77 Commits
Author SHA1 Message Date
Valiantsin Dzerakh 9fcd7766f9 Up version 0.5.1-rc2 2026-11-25 22:17:53 +03:00
Valiantsin DzerakhandClaude Opus 5.5 a81324ce51 Merge task/plugself: Zonai Fieldworks switches its members on and off in play without a crash or freeze, and Challenge Mode's plugins that call their own functions build in (#1388, #1451, #1422, #1461)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:12:09 +03:00
Valiantsin DzerakhandClaude Opus 5.5 9cf4d060d1 A plugin loop that spins on a yield with no call in its body gets a spin line, so its back-edges go through rt_spin_gate and hand the virtual core to a waiting thread (#1388)
Zonai Fieldworks guards its hook wrappers with an exclusive byte lock (plugin+0xe3ff4 on 1.4.3). On the Switch the
holder has its own core; here a spinner kept the virtual core the holder waited for, and the game froze when a member
was switched off. exefs_plugins.py now finds such loops by word (a direct back-edge of at most 512 bytes to a head
whose body holds a yield and no bl, blr or svc): 21 in Fieldworks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:11:19 +03:00
Valiantsin DzerakhandClaude Opus 5.5 fc2863a15c nvnCommandBufferFenceSync is implemented: the sync waits for the fence of the submit that carries the record (#1388)
Zonai Fieldworks' native-font renderer (Cryonis in its BotW Abilities member) records it, and the weak stub ended the
game with "NVN nvnCommandBufferFenceSync is not implemented". The record is a new op, OP_FENCE_SYNC, that every replay
skips; at QueueSubmitCommands the syncs named in the submitted handles get that submit's fence value, which completes
no earlier than the console's point. The game itself never records the op, so its submits pay one flag load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 21:23:19 +03:00
Valiantsin DzerakhandClaude Opus 5.5 4fccaa5bef Each exlaunch inline stub a plugin writes back to back at init is a lift entry, with its callback (#1388, #1451)
Zonai Fieldworks writes one stub per member hook in a row at init and points a gate slot at it when the player switches
the member on. init_code took only the first stub of the row as a start and read the 8-byte callback after it as more
code, so the other stubs (Hookshot at plugin2+0x135048, Fleet Sync at plugin2+0x1350f0) were never lifted and switching
them on ended the game with "no function at guest pc".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 21:19:50 +03:00
Valiantsin DzerakhandClaude Opus 5.5 340da7c6e6 A plugin hook on main's module header gets only its expect line, not a lift site (#1422, #1461)
exlaunch adds a table offset to main's base, so an update the plugin's table lacks hooks main+0x0 (Challenge
Mode's Enemy Health Regeneration names 1.0.0 to 1.4.1). Nothing runs there, on the Switch either; the site line
made the generator refuse the lift ("patched instruction is a trap") and the installer dropped every plugin. The
report notes such a hook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 21:06:28 +03:00
Valiantsin DzerakhandClaude Opus 5.5 5c5c6d1dd0 With a mod plugin on, read-only module data stays writable on the host, so Zonai Fieldworks can swap main's RELRO entries when a member is switched on in play (#1451)
QueryMemory still reports the permission the game asked for. Material Columns swaps 11 dispatch slots in main's
RELRO from its own code at switch time; on the platforms the mod is made for that write goes through, here it
faulted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 21:06:27 +03:00
Valiantsin DzerakhandClaude Opus 5.5 fe0e44117c Merge task/f1rows: sync_ahead and host_checkpoint get rows in the settings menu's Advanced tab, in all twelve menu languages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:59:53 +03:00
Valiantsin DzerakhandClaude Opus 5.5 f56ae3ffb2 The Advanced tab of the settings menu has rows for sync_ahead and host_checkpoint under Scheduling, with their text in all twelve menu languages; both are on by default and take effect at the next start
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:59:45 +03:00
Valiantsin DzerakhandClaude Opus 5.5 272d1d3d09 Merge task/idle: a thread asked to give up its virtual core does so as soon as it leaves a port function (host_checkpoint, on by default), about 5% shorter frames on a 4-core Ryzen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:56:10 +03:00
Valiantsin DzerakhandClaude Opus 5.5 59f14012c1 host_checkpoint is on by default: a thread asked to give its virtual core to a better one gives it up when it returns from a host call or SVC to game code, so an interrupt refused inside a port function no longer leaves the core held until the next SVC or interrupt; on machine A (7900X, 4 cores, islands) the frame went from 13.71 to 13.04 ms over 5 clean runs each
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:56:10 +03:00
Valiantsin Dzerakh 3087e9fe27 Merge branch 'dev' into task/idle 2026-11-25 20:54:41 +03:00
Valiantsin Dzerakh d4794238d4 Merge branch 'dev' into task/plugself 2026-11-25 20:44:52 +03:00
Valiantsin DzerakhandClaude Opus 5.5 08284c107d Merge task/sadef: sync_ahead is on by default and frame generation runs with it (#1129, #1192)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:41:47 +03:00
Valiantsin DzerakhandClaude Opus 5.5 e7439d4f9e sync_ahead is on by default, and frame generation runs with it: the replay and the presents keep their order with the frame wait one frame late, and each submission waits until the present thread submitted the blit, so the two alternating generated pictures stay safe (#1129, #1192)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:41:46 +03:00
Valiantsin DzerakhandClaude Opus 5.5 6841675942 Merge pull request #1459: the UI is laid out for any screen shape from 4:3 to 32:9, 4:3, 7680x2160 and phone sizes join the list, the Purah Pad frame, the map and the loading screen fill wide screens; vert_plus (the 16:9 width at narrower shapes) is off by default with a row under the field of view (itaskaev2) (#632, #1453)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:40:36 +03:00
Valiantsin DzerakhandClaude Opus 5.5 519d6628a2 Merge pull request #1442: with dlaa_effects_after = 1 the upscaler runs after the fog layer and the clouds, so distant ridges no longer get a bright outline; the option is named Particles after DLAA (codexx-dev)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:33:29 +03:00
Valiantsin DzerakhandClaude Opus 5.5 abadb60861 Merge pull request #1466: the gameplay map zoom works with menu_cursor = 0, the map is still found while gameplay_map_zoom is on (ShannoonRuaaa) (#1376)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:33:27 +03:00
Valiantsin DzerakhandClaude Opus 5.5 6c76ca86ed Merge pull request #1465: under Steam on Linux the gamepad pauses while the window has no focus, so Steam's overlay and menus get its presses alone; pad_background = 1 keeps it playing, Windows unchanged (ShannoonRuaaa) (#1462)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:33:26 +03:00
Valiantsin DzerakhandClaude Opus 5.5 b13875340e Merge pull request #1467: the Linux setup names a system library the game cannot start without and the package that has it, before the lift and after a start the loader stopped (ShannoonRuaaa) (#1428, #1315, #1419)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:33:25 +03:00
Valiantsin DzerakhandClaude Opus 5.5 b51dccd969 The Steam check of pad_background is left out on Windows, where the game window is not SDL's: the hint stays on there as before (#1462)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:32:57 +03:00
Valiantsin DzerakhandClaude Opus 5.5 f69d170484 Ship vert_plus off by default and give it a row under the field of view in the Display tab
A new setting starts off: on by default, Steam Deck (1280x800) and other 16:10, 3:2 and 4:3 players would get a
wider view than the game's with a GPU cost nobody measured on the weakest target. The toggle is live, as
resolution.c res_fov_live re-reads it. res_fov_live starts from the game's own view (shown_vp 0), so at 16:9 the
first present writes nothing and logs nothing, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:29:01 +03:00
Valiantsin Dzerakh 1b366cac61 Merge pull request #1442 2026-11-25 16:22:43 +03:00
Valiantsin Dzerakh a7d5a6159f Merge pull request #1466 2026-11-25 16:22:37 +03:00
Valiantsin DzerakhandClaude Opus 5.5 73aafc3c12 Merge pull request #1459: lay the UI out for screen shapes from 4:3 to 32:9, offer 4:3 and phone sizes, keep the 16:9 width at narrower shapes (itaskaev2) (#632, #1453)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:22:24 +03:00
Valiantsin Dzerakh 9aec84889c Merge pull request #1465 2026-11-25 16:22:22 +03:00
Valiantsin Dzerakh ba6e22cf5c Merge pull request #1467 2026-11-25 16:22:16 +03:00
Valiantsin DzerakhandClaude Opus 5.5 20e27a2d33 Merge task/drs: with sync_ahead, timestamps the late frame wait did not cover read as the newest one written at that wait, so dynamic resolution no longer drops to its lowest level for half a second at a time (#1123)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:17:45 +03:00
Valiantsin DzerakhandClaude Opus 5.5 912adc2965 Count the cores given up at host call returns in the asynchronous preemption line
With TOTK_HOST_CHECKPOINT=1 the line logged every 600 frames ends with the number of cores kern_host_left gave up, so
a log shows the switch at work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:16:33 +03:00
Valiantsin DzerakhandClaude Opus 5.5 6f97dca93a A plugin's call to a function it defines itself is its own code, not an import (#1422, #1461)
A plugin built with default visibility calls its own exported functions
through its PLT. Challenge Mode's Enemy Health Regeneration plugin
(exefs subsdk8) does so for the std::vector<const char*> constructor it
carries, and the service run counted that as a library call outside the
reviewed list, so the plugin was refused and its whole mod stayed off.

runtime/loader.c resolve binds such a JUMP_SLOT straight to the plugin's
own definition (a host override still wins and stays counted), and
tools/exefs_plugins.py plt_imports maps the PLT stub to that code, so
the reach check follows into it instead of naming an import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:06:54 +03:00
Valiantsin DzerakhandClaude Opus 5.5 e85a5ffc48 Switches for the preemption timing of virtual cores: TOTK_AP_FIRST_US and TOTK_HOST_CHECKPOINT
TOTK_AP_FIRST_US sets how long a waiter spins before it first interrupts a worse owner (default 250 as before).
TOTK_HOST_CHECKPOINT=1 makes an owner with a pending preempt request give its core up when a host call or SVC
returns to game code, instead of at its next SVC or indirect call. Both off by default; for timing on the islands
bench (critical path: worse owners hold a better thread's core 0.70 ms a frame there).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:57:38 +03:00
Valiantsin DzerakhandClaude Opus 5.5 47eb44d1b2 With sync_ahead, a timestamp the frame wait did not cover reads as the newest one written at that wait, so the dynamic resolution controller never reads a wrapped GPU time (#1123)
The game converts the end and then the begin report of a pair and subtracts them unsigned. With the frame wait one
frame late the end could be unwritten (0) or hold the value of the report before it, and the difference wrapped to
about 2^64: an over-budget frame for the controller, two in a row drop the game to its lowest quality level. Reads of
a report that holds 0, a time after the bound, or whose newest replayed report is not done read the bound instead,
so a pair in submission order never reads end < begin. Guest memory, RENDER_COND and samples-passed counts are
unchanged. TOTK_SYNC_AHEAD_TIMESTAMPS=0 turns it off, =check counts without replacing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:46:45 +03:00
itaskaev2andClaude Opus 5.5 c03fffd7cd Give the camera's album window the screen's shape and keep the inn's clock under its choices at shapes narrower than 16:9
The "save to the album?" window showed a 4:3 or 16:10 photo in a 16:9 frame, stretched across: N_FirstOut_00's
scale_y k, there for the compendium's square photos, also undid N_InOut_00's taller frame for the album photo under
it. The scale goes on N_PictureBook_00 and the album's question and buttons (N_AlbumCon_00) instead, and those move
out by the frame's extra half height. The clock of an inn's choices (Time_00) stayed in the middle 16:9 while
MessageDialog_00 went to the bottom edge, so it covered the last choices; it goes to the bottom edge too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 11:29:22 +01:00
itaskaev2andClaude Opus 5.5 f51308cb8f Fill shapes narrower than 16:9 with the map instead of black above and below it
AppMap_00's capture, cut, backing and shadow panes are 1080 high, the height of a 16:9 layout, in the layout and in the full map's keys of AppMap_00_MiniMap, which win over the layout's sizes. On a 4:3 or 16:10 canvas they now take the screen's height, 1080 / k, so the map reaches the Purah Pad frame at the top and bottom.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:58:40 +01:00
itaskaev2andClaude Opus 5.5 24662dbf60 List ultrawide monitors and the other screen shapes in the README's features
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:43:34 +01:00
ShannoonRuaaaandClaude Opus 5.5 b0990047b4 The Linux setup names a system library the game cannot start without, before the lift and after a start the loader stopped (#1428)
The libSDL3.so.0 the release puts next to the game links system libraries a minimal system may lack (libXss.so.1 on AnataseOS in #1315 and #1428, libdecor-0.so.0 on Batocera in #1419). The loader then stopped totk --prepare-shaders with exit code 127 after the half hour of lift and compile, and the setup reported only that preparing the shaders failed.

The check step now runs ldd on the release's libraries (Linux, not in a repository build) and stops with check.libraries_missing, naming the missing files and, for the common ones, the package that provides them on Fedora, Debian/Ubuntu and Arch (LIBRARY_PACKAGES). When the game still fails to start in the prepare step, the loader's "error while loading shared libraries" lines in its log give prepare.libraries_missing in place of prepare.shaders_failed. Both messages are in all twelve catalogs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:16:20 -08:00
ShannoonRuaaaandClaude Opus 5.5 3b7c4bea3c The gameplay map zoom works with the menu cursor off: the map is still found while gameplay_map_zoom is on (#1376)
gameplay_tweaks.c map_zoom_allowed zooms only on the map that menu_cursor.c finds in eui's open screens, and with menu_cursor = 0 that scan did not run, so the scroll wheel neither zoomed the map nor did the mouse move its cursor, with gameplay_map_zoom = 1 set. menu_cursor_poll now scans for the map while that zoom is on, as it scans for the dialogue box for dialogue_click; the pointer, the menus, the strips and the camera stay off with menu_cursor = 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:11:37 -08:00
ShannoonRuaaaandClaude Opus 5.5 58fd4f6f68 The gamepad pauses while the window has no focus in a game Steam started, so Steam's overlay and menus get its presses alone (#1462)
Since #971, SDL passes gamepad events to the game while its window has no focus (SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS). On Linux the window is SDL's, and under Steam the focus goes to Steam's overlay and menus while they are open (the Quick Access menu in SteamOS's Game Mode): the game took the presses meant for them too, which 0.4.1 did not.

The new setting pad_background (auto, 1, 0; read at start) decides the hint. auto, the default, keeps it on unless Steam started the game (SteamGameId or SteamOverlayGameId in the environment, set for Steam games and non-Steam shortcuts alike); 1 keeps the gamepad playing behind other windows under Steam too, 0 pauses it everywhere. input_map.c input_pad_background_pick holds the decision and cfg_probe checks it. On Windows the game window is not SDL's, and nothing changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:08:22 -08:00
itaskaev2andClaude Opus 5.5 9932ac2892 Fill wide screens with the map and the loading screen instead of black bars
The full map's width was held at 2250 by AppMap_00_MiniMap's size keys (they win over the layout's sizes): wide_anim sets them to 2250 / k, so the map is drawn across a 32:9 screen; the layer tabs and the time and position move to the screen's edges. The loading map is a capture of the 3 x 3 world map tiles of 840 units around the player's tile (TOTK_DUMP: nine 840x840 tile draws into the capture), so a capture wider than about 1680 shows black where the player stands near a tile's edge: loading_map keeps it at most 1660 wide from the screen's left edge, moves the map's slide keys (LoadingFade_00_BarIn and BarOut) with it, and widens the side panel, a window whose frame keeps its proportions, to the screen's right edge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 23:47:01 +01:00
itaskaev2andClaude Opus 5.5 66bb3c749a Keep the Purah Pad frame's width and an unstretched loading map at wide shapes
AppMenuOverlay_00 keeps a full-width root, so the stone and light pieces of the map's side frame (N_Frame_00, P_Frame{L,R}*) were stretched across a 21:9 or 32:9 screen; they now take scale k at the edges. The loading screen widened N_Base_00 back to the screen, which stretched the map capture inside it; instead the capture panes and their pictures get a size of 1920/k - 450 (1470 at 16:9), so more map shows unstretched, and the side panel stays at the right edge at its own width. The map's cut and backing panes (AppMap_00 N_Cut_00 and the others) take 2250/k as a size. ultrawide_layout.py gains the pane width field (+76); tests/hud_layout_test.py leaves these three layouts out of its byte comparison with the older implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 23:30:47 +01:00
itaskaev2andClaude Opus 5.5 463af9cb14 Offer 7680x2160, the 32:9 size of 57-inch dual-4K monitors
It takes the 32:9 layout folder (3840x1080's, cfg.c cfg_shape_size); totk.ini.example names the common 21:9 and 32:9 sizes and hud_width for the HUD in the middle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 23:10:34 +01:00
itaskaev2andClaude Opus 5.5 ce156ff76b Keep the 16:9 width of the view at shapes narrower than 16:9 (vert_plus) (#632)
The camera kept the game's vertical view angle at every shape, so 16:10, 3:2 and 4:3 showed less of the world at the sides than 16:9. res_fov_live now also multiplies the fov patch's factor by 2 atan(tan(v/2) k) / v, k = 16:9 over the aspect and v = 51.2 degrees, the game's default vertical angle measured from a 4:3 frame at fov 130 against 16:9 (scale 0.730). Measured after: 4:3 frames are 16:9 ones scaled by 0.752 (0.750 is exact), 16:10 by 1.000 (1.106 without). vert_plus = 0 keeps the game's vertical view; it multiplies with fov.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 23:02:37 +01:00
itaskaev2andClaude Opus 5.5 13b4b0ca9b Lay the UI out for any screen shape from 4:3 to 32:9, and offer 4:3 and phone sizes (#632, #1453)
A game resolution whose shape the fifteen listed sizes did not cover (13:6 on a phone streamed to, 4:3) drew 16:9 with bars: neither the setup's Shapes step (installer/screens.py shape_size) nor the game's background generator (runtime/romfs.c romfs_folders_prepare) made a layout for it, though tools/ultrawide_layout.py handles any aspect ratio and runtime/romfs.c overlay_init already loads a folder of the exact size. cfg.c cfg_shape_size and screens.py shape_size now give an unlisted shape from 4:3 to 32:9 its own size, so both make romfs-patches-<w>x<h> for it; a display of an unlisted shape still keeps the 1920x1080 default and gets no folder. The list gains 4:3 (1440x1080, 1600x1200, 2048x1536, 2732x2048) and 19.5:9 and 20:9 phone sizes (2340x1080, 3120x1440, 2400x1080, 3200x1440), in the menu's game resolution row too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:50:55 +01:00
Valiantsin DzerakhandClaude Opus 5.5 ed8fa04034 Merge task/plugstale: a mod plugin whose start-up writes a value into the game's data that redirects nothing (Zonai Fieldworks' Self Recall and its memory pool size) no longer goes stale when render_scale grows the pool, and a plugin the game found stale makes the rebuild lift and compile again instead of looping (#1437, #1388)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 23:00:15 +03:00
Valiantsin DzerakhandClaude Opus 5.5 6205940caf Merge pull request #1448: skip_cs leaves out the dispatches of listed compute shaders, a bisecting tool for the Intel 1.2.1 boot freeze (ShannoonRuaaa) (#1402, #994)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:12:15 +03:00
Valiantsin DzerakhandClaude Opus 5.5 c91046781f skip_cs names the offending entry when it is not 1 to 16 hex digits, not the whole value
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:12:06 +03:00
Valiantsin DzerakhandClaude Opus 5.5 28d8a43bfe A plugin the game found stale makes the rebuild run the lift and the compile (#1437, #1388)
build-cache/plugins.stale changes no input of the lift or compile key, so the rebuild the game started planned only
check and cleanup, never ran the plugin's service run again, and the plugin stayed stale. A non-empty plugins.stale
now makes Lift and Compile not current (installer/steps.py plugins_stale); Compile too, since the transient lift runs
only with the step after it. Lift.run clears the file, so the next start plans nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 21:46:41 +03:00
Valiantsin DzerakhandClaude Opus 5.5 cc749d8679 A plugin's write into main's data that points at no plugin code is matched by place only at start (#1437, #1388)
The expect line of such a word says `* *` (tools/exefs_plugins.py plugin_lines), recomp/patches.py carries it into
RT_PLUGIN_WRITES as a flag, and runtime/plugin_init.c check_writes accepts any value there through
runtime/plugin_writes.h plugin_write_find. Hook branches in .text and pointers into a plugin's .text keep the exact
match. Zonai Fieldworks' Self Recall takes its storage off a pool size at main+0x3ad6eb8 that grows with the texture
heap of render_scale, so its plugin went off at every start with a grown heap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 21:46:33 +03:00
Valiantsin Dzerakh 453e83f564 Merge branch 'pr1448' into task/pr1448 2026-11-24 21:30:20 +03:00
ShannoonRuaaaandClaude Opus 5.5 1910ffb609 The skip_cs setting leaves out every dispatch of the compute shaders it lists, named by the id the pass marks print.
Issue #1402 reports a GPU hang on Intel (Mesa ANV) right after the startup logo on game 1.2.1, which the pass marks put in one dispatch of cs 75be3722f62cb67e. #994 reports the same freeze on Intel's Windows driver with 1.2.1, while 1.4.3 boots. The cause is not found yet. skip_cs takes the named dispatches out so a tester can confirm the shader is the cause and get past it, at the cost of what the shader would write. An id shorter than 16 hex digits matches every shader whose id starts with it. The log names each listed id and the first dispatch skipped of each. The setting is registered in cfg.c, documented as Risky in docs/settings.md, and docs/agents/symptoms.md gets a row for the freeze.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 22:59:15 -08:00
Valiantsin DzerakhandClaude Opus 5.5 7da078d1ab Merge task/bmerge: barrier_merge is on by default and ends the pass when a draw samples a target written in the pass that it does not write itself, as Savage Wind does; shrine passes 581 -> 128 a frame on an RDNA2 iGPU with the GPU time unchanged on AMD's Windows driver, RADV waterfall GPU 8.3 -> 4.1 ms (#1237)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:15:52 +03:00
Valiantsin DzerakhandClaude Opus 5.5 dca69306fb barrier_merge is on by default
With the unwritten-read rule every read that stays merged comes from a draw that samples a target it also writes,
the case Savage Wind runs the same way on every GPU. Shrine on the RDNA2 iGPU (AMD Windows driver, 1080p): passes
581 -> 128 a frame, GPU time unchanged (37.2 ms off, 38.0 and 36.5 ms on), the picture the same. PR #1237 measured
the waterfall on RADV at 1105 -> 117 passes and GPU 8.3 -> 4.1 ms, and an RTX 4080 shrine at +3% mean fps with the
1% low 83 -> 98. barrier_merge = 0 brings back a full barrier at each such Barrier.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:15:23 +03:00
Valiantsin DzerakhandClaude Opus 5.5 3c977bf78c Merge pull request #1435: Linux opens a text entry window for the software keyboard (horse naming) with keyboard and controller grid input, and falls back to the default name when no window opens (cheat45681) (#401)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:07:57 +03:00
Valiantsin DzerakhandClaude Opus 5.5 c3cd1e31c2 Text entry on SDL: hint lines come from the catalog, a password shows stars, a surrogate pair goes in and out whole and obeys the length limit, TOTK_SWKBD_TEST=ok presses OK, and the window redraws when exposed (#401)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:07:09 +03:00
Valiantsin DzerakhandClaude Opus 5.5 5aaa718eb6 barrier_merge ends the pass when a draw samples a target written in the pass that it does not write itself
The by-region barrier inside a merged pass orders only the pixel a fragment writes. A draw that reads a target other
draws wrote, without writing it, may read neighbouring pixels (blur, ambient occlusion, light composites), which only
the game's full Barrier orders on every driver. Such a draw now ends the pass, as Savage Wind does for the same case.
TOTK_TRACE=gfx counts these restarts by colour and depth. Shrine, town and field on 1.4.3: 0 restarts; every read
after a merged Barrier comes from a draw that writes the target it samples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:04:48 +03:00
cheat45681 37551aedad Linux text entry: controller letter grid (D-pad, bottom add, right delete, Start OK, top cancel); keyboard unchanged 2026-11-24 09:03:38 +03:00
cheat45681 a5c95fb971 Linux: add a text entry window for the software keyboard (horse naming, #401) 2026-11-24 09:03:38 +03:00
Valiantsin DzerakhandClaude Opus 5.5 be7ca2c275 Merge task/demoteini: on AMD's Windows driver a discarded pixel keeps running only in shaders that take a derivative after the discard, so grass, foliage and other alpha-tested draws no longer pay for their discarded pixels; demote is a totk.ini key (#1365, #164)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:57:41 +03:00
Valiantsin DzerakhandClaude Opus 5.5 c8b88f7428 Demote a discard only where a derivative follows it, and read demote from the ini (#164, #1365)
spirv_demote turned every OpKill inside a selection into OpDemoteToHelperInvocation on AMD's Windows driver. A
demoted fragment runs the rest of the shader, so every alpha-tested draw (grass, foliage, hair) paid for its
discarded pixels. The cloud fringe of #164 came from OpImageQueryLod after the discard. Now a discard is demoted only
when an OpImageQueryLod, an explicit derivative or a function call follows it in its function; the rest keep the
plain discard, as before 0.4.1. On the field save 1 of 128 shaders with a discard is demoted, and the picture keeps
the fix.

demote has a row in the settings table and a description in totk.ini.example, so demote = 0 or 1 in the ini no
longer logs an unknown key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:56:03 +03:00
Valiantsin DzerakhandClaude Opus 5.5 4f5a9d4754 Merge task/pr1369: heap_lazy = 1 commits the game heap on first use on Windows, off by default; the Vulkan import also commits the chunks its alignment widens into, and the commit census shows the heap's faults (ShannoonRuaaa)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:50:35 +03:00
Valiantsin DzerakhandClaude Opus 5.5 de0b1f899f heap_lazy adds the committed heap and the first-use faults with their total time to the commit census lines, so a log shows what the setting saved and cost
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:44:45 +03:00
Valiantsin DzerakhandClaude Opus 5.5 a0587b59e7 heap_lazy also commits the chunks a Vulkan import widens into when the driver's host pointer alignment is above 4 KiB, and the memory.c comment names mem_heap_commit for save writes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:39:29 +03:00
Valiantsin DzerakhandClaude Opus 5.5 d66aeef75c Merge pull request #1369: heap_lazy = 1 commits the game heap on first use on Windows, off by default (ShannoonRuaaa)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:35:07 +03:00
Valiantsin DzerakhandClaude Opus 5.5 011b80c948 Merge pull request #1408: the IPC probe's request helper clears its reply when the kernel call fails (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:34:47 +03:00
Valiantsin DzerakhandClaude Opus 5.5 a073e6d3c6 Merge pull request #1407: the custom cursor's sampler writes zero colour where it returns zero coverage (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:34:47 +03:00
codexx-devandClaude Opus 5.5 3d2cec5e18 The menu option dlaa_effects_after is named Particles after DLAA, and its description in every menu language says the fog and the clouds still go through DLSS
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:07:52 -03:00
codexx-devandClaude Opus 5.5 6a2941859f Running the upscaler after the fog layer and the clouds is what dlaa_effects_after = 1 does, with DLSS as with FSR, instead of a separate dlaa_fx_composite switch
The option draws the particles and the dust over the upscaler's picture; the fog layer and the clouds' composite
before them decide sky or surface from the jittered scene depth and belong under the upscaler with either engine.
DLSS is not yet checked on NVIDIA hardware.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:03:25 -03:00
codexx-devandClaude Opus 5.5 7f09910809 The symptoms row for the ridge outline names the option it needs, Fog and particles after DLAA
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:46:57 -03:00
codexx-devandClaude Opus 5.5 9444f4ea5a totk.ini.example describes dlaa_fx_composite, the switch that runs FSR after the fog layer and the clouds
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:33:18 -03:00
codexx-devandClaude Opus 5.5 7bd579d370 With FSR the upscaler waits for the first composite without depth after the lighting, so the fog layer and the clouds go through it and distant ridges no longer get a flickering bright outline at night and at dawn
The upscaler ran at the first pass into the light target after the lighting. The fog layer and the half-size clouds'
composite that follow it decide per pixel from the scene depth, still jittered, whether a pixel is sky; over the
upscaler's steady picture a sky pixel on a silhouette took the surface's side in some frames and got no clouds there,
a bright dot that the upscaler never resolved. effects_point now waits for the first full-size pass without depth into
the light target and runs before the next pass with a depth (the particles), behind TOTK_DLAA_FX_COMPOSITE: on by
default with FSR, off with DLSS until measured on NVIDIA hardware. Frame dumps at 2560x1440 with FSR 4: ridge pixels
brighter than both sides fall from 34 % of the columns to 15 %.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:23:36 -03:00
Ruan Shannon 7ddb883992 Merge remote-tracking branch 'fork/perf/heap-lazy-commit' into perf/heap-lazy-commit 2026-11-23 13:39:47 -08:00
Ruan ShannonandClaude Opus 5.5 ab356192d7 heap_lazy: the docs say 1 MiB chunks, and with the setting off ipc, svc and save writes are as before
Review of #1369: the settings row still said 64 KiB though LAZY_CHUNK is 1 MiB, and two changes ran for every player.
ipc.c and svc.c readable() ask the OS again unless TOTK_HEAP_LAZY is on (mem_heap_lazy), and fs_host.c write_file calls
mem_heap_commit, which commits the buffer's reserved heap chunks in lazy mode and does nothing otherwise, instead of
mem_thaw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:38:10 -08:00
Ruan Shannon 54b2975d98 Merge remote-tracking branch 'origin/dev' into perf/heap-lazy-commit
# Conflicts:
#	runtime/cfg.c
2026-11-23 13:37:39 -08:00
ShannoonRuaaa fe45b876e0 Merge current dev while preserving heap and lightning settings 2026-11-22 15:23:19 -08:00
ICUMADETHIS 2ec4b3f04b Clear IPC probe replies after kernel failures 2026-11-22 21:34:13 +00:00
ICUMADETHIS 362fcfb3b7 Initialize transparent custom cursor samples 2026-11-22 21:24:54 +00:00
Ruan Shannon 6370c7c0b6 heap_lazy = 1 commits the game's heap a 1 MiB chunk at a time on first use (Windows, opt-in)
SetHeapSize takes the game's whole heap at boot (2.1 GiB on 1.4.3) and Windows charges all of it against the commit
limit, although a sky-island run touched about two thirds. With TOTK_HEAP_LAZY=1 the heap stays reserved: the first
read or write of a chunk faults and memory.c heap_fault commits it; read faults reach the hook only in this mode
(plat_mem_fault_reads). A byte per chunk (lazy_map) answers without asking the OS, so frozen-region write faults pay
nothing for it, and only clear chunks are committed, never pages a freeze made read-only. mem_thaw, which file reads,
save writes and Vulkan imports call before the kernel or driver touches guest memory, commits its range's chunks
first; ipc.c and svc.c check readability by the layout; vk_mem_host_room counts the uncommitted heap as taken. Default
off: the heap path is unchanged unless set.

Sky island, 120 s, this laptop (Iris Xe): peak commit 6345-6536 MiB on dev, 5736-5821 MiB with heap_lazy = 1; about
600 first-use faults, 8 ms in all.
2026-11-22 04:49:58 -08:00
76 changed files with 2030 additions and 275 deletions

No files matched your search

+6 -1
View File
@@ -26,7 +26,12 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
modes as DLSS: for FSR 4 the setup downloads AMD's signed FSR SDK libraries
(github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK, AMD FSR SDK license), ticked by default with an AMD GPU
- HDR10 output with peak, game and HUD brightness settings
- 16:10 (Steam Deck, handhelds), 3:2 (Surface, Framework), 21:9 and 32:9 (ultrawide) game resolutions, with the camera and the interface in that shape
- Ultrawide monitors, 21:9 and 32:9 (2560x1080, 3440x1440, 3840x1600, 5120x2160, 3840x1080, 5120x1440, 7680x2160):
the camera sees the whole width, the map and the loading screen fill it without bars or stretching, and the HUD sits
at the screen's edges or in the middle 21:9 or 16:9 (`hud_width`)
- Other screen shapes from 4:3 to 32:9, each with the camera and the interface in that shape: 16:10 (Steam Deck,
handhelds), 3:2 (Surface, Framework), 4:3 (iPads, CRT monitors) and phones (19.5:9, 20:9) for streaming; on shapes
narrower than 16:9 the view can keep the 16:9 width (`vert_plus`, off by default)
- Anisotropic texture filtering up to 16x, for sharp ground into the distance
- In-game settings menu (F1) and performance overlay (F10)
- Play time across runs on the Game tab of the settings menu, kept in `playtime.txt` next to the saves
+1 -1
View File
@@ -1 +1 @@
0.5.1-rc1
0.5.1-rc2
+4 -2
View File
@@ -32,7 +32,8 @@ GPU semantics behind the graphics rows: [maxwell.md](../maxwell.md). The method
| with DLAA on, the world behind the inventory smears into horizontal streaks on the right half, from the second time the inventory is opened (when Link's model is drawn there) | the camera jitter's read-back took the inventory camera's own off-centre projection (P[0][2] about -0.6) for a jitter and gave DLSS an offset of about 1152 pixels (fixed: `vk_dlaa.c` `cam_offset` takes only an offset it gave that block) | `TOTK_DLAA_CAM_JITTER=0` makes it go; a `--capture` run over the opened inventory: the background's horizontal gradient against its vertical one |
| with DLAA/DLSS on, large distant blocks behind the fog (the Depths) turn darker or lighter for a frame while the camera moves | DLSS created with AutoExposure estimated the exposure of the dark scene itself, and the estimate moved from frame to frame (fixed with `dlss_fixed_exposure = 1`: `vk_dlaa.c` evaluate creates the feature without it) | a flat fogged patch in `capture.py` frames: one value without DLAA, jumps with it |
| flicker or a texture swapped with a similar one | the newest texture picked at shared storage instead of the one with the matching view | texture lookup by id in the dump |
| with DLAA on, dust and small particles in fog (shrines) vanish, smear or behave oddly; the fog looks processed | DLSS ran at the bloom, after the fog and the particles, which have no motion vectors or jitter of their own (fixed: `vk_dlaa.c` effects_point runs DLSS at the first pass into the light target after the lighting, and the effects go over its picture) | `dlaa_effects_after = 0` (Screen tab) brings the old point back; the count "before the effects" in the `dlaa:` log line against the frames anti-aliased |
| with DLAA on, dust and small particles in fog (shrines) vanish, smear or behave oddly; the fog looks processed | DLSS ran at the bloom, after the fog and the particles, which have no motion vectors or jitter of their own (fixed: `vk_dlaa.c` effects_point runs DLSS after the lighting, before the particles, and they go over its picture) | `dlaa_effects_after = 0` (Screen tab) brings the old point back; the count "before the effects" in the `dlaa:` log line against the frames anti-aliased |
| with FSR or DLSS on and "Particles after DLAA" (formerly "Fog and particles after DLAA") on (`dlaa_effects_after = 1`), a white or bright dotted outline along distant mountains and other silhouettes against the sky, most visible at night and at dawn against clouds; gone with that option off; `TOTK_DEMOTE` makes no difference | the upscaler ran at the first pass after the lighting, and the fog layer and the half-size clouds' composite that follow it decide per pixel from the scene depth, still jittered, whether it is sky: over the upscaler's steady picture a sky pixel on a ridge took the mountain's side in some frames and got no clouds (fixed: `vk_dlaa.c` `effects_point` waits for the first composite without depth and runs the upscaler before the particles) | `TOTK_DLAA_JITTER=0` or `dlaa_effects_after = 0` make it go; frame dump: ridge pixels brighter than the sky and the mountain in the composite pass into the light target |
| with DLAA on, the picture flickers from frame to frame: a little outdoors; the whole scene in a fogged shrine with an ability's targeting view (Ultrahand) open, where the fog also goes back under DLSS | DLSS ran before some effects in one frame and after them in the next: their order changes from frame to frame (the yard's half-size effects pass is in some frames only; the ability highlight, drawn into the light target with a D16 depth of its own, comes before or after the fog layer), and a rule that waited for one of them or took any D16 pass for the lighting followed it (fixed: `vk_dlaa.c` effects_point knows the lighting by its depth and runs DLSS right after it) | the `dlaa:` log line: "before the effects" must equal the frames anti-aliased in the world; a log of the passes into the light target per frame |
## Timing and frame pacing
@@ -68,7 +69,8 @@ GPU semantics behind the graphics rows: [maxwell.md](../maxwell.md). The method
|---|---|---|
| device lost a few frames in, GPU writes to address 0 (older NVIDIA) | present from another thread or queue | every submit and present on one queue under one lock |
| device lost or garbage on one AMD generation | views the driver branch mishandles (BC block views of 3D textures) | `vk: pass marks`, validation; the formats in the pass |
| device lost on one scene, every run, one vendor | a shader or pass that driver cannot run | pass marks name the pass; skip shaders by hash to bisect |
| device lost on one scene, every run, one vendor | a shader or pass that driver cannot run | pass marks name the pass; `skip_cs = <id>` (docs/settings.md) leaves out the dispatch the marks name, to bisect |
| freeze on "Nintendo presents", then device lost, every run, Intel GPU (Windows driver and Mesa ANV), game 1.2.1 only; 1.4.3 boots (#994, #1402) | on ANV the pass marks put it in one compute dispatch of 1.2.1 after the startup logo (`dispatch 10 of submission 430`, `cs 75be3722f62cb67e`, absent from a 1.4.3 shader cache); the Windows driver has no pass marks, so the same dispatch there is a guess; the shader and why it hangs are not found yet | pass marks; `skip_cs = 75be3722f62cb67e`; game 1.4.3 |
| GPU timeout after 1-2 min, single frames over 2 s | first-time shader stalls or a huge one-shot submission on a slow GPU | prepared shaders; submission sizes at boot |
| GPU hang at boot with pipeline libraries | point lists without a point size | the shader writes point size or the device clamps it |
| black window after a driver update | caches from another driver | the log line `vk_pipeline: ... written by another device or driver`; delete the caches next to `totk.exe` |
+1 -1
View File
@@ -91,7 +91,7 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app
- Memory pools. Apple's unified memory let MacNativeGames use the game's pools zero-copy. The back end imports the pools as host memory (`VK_EXT_external_memory_host`); under Wine, or on a GPU without the extension, CPU-visible pools get shadow storage instead (host-visible copies, `vk_memory.c` `mirror_mode`). On a discrete GPU, pools bound as buffers are mirrored in device-local memory and the pages the CPU wrote (write watch, above) are uploaded before a replay; idle pool regions are made read-only so the write-watch queries skip them (`vk_memory.c`). GPU-rendered textures are written back when the CPU reads them: on a pool invalidate, on a CPU copy, and for small targets once the CPU waits for a fence (`vk_texture.c`).
- Replay thread. `TOTK_REPLAY_ASYNC=1` moves the replay off the submitting thread onto a queue at most one frame behind the game; reads of GPU results wait for the newest writer instead of draining the queue (`vk_backend.c`). It is off by default. Where the game waits for the GPU it overlaps the replay with the game threads (a GTX 1650 in the Depths, issue #88), a gain measured only there; while it was the default, a GTX 1660 Ti at the 60 fps cap with the GPU at 26 % reported uneven motion (#659). It adds up to a frame of latency; `replay_async = 1` turns it on.
- Chunked replay. A large submission is recorded in chunks by several threads (`TOTK_REPLAY_WORKERS`, 0 by default: the sequential replay; 4 is a good value from 8 logical processors) and the chunks go to the queue in order (`vk_exec.c`). A sequential scan keeps a copy of the queue state where each chunk starts and lists what a chunk would otherwise learn from the chunks before it: inline uniform updates, conditions, contact shadow marches, uniform drops. It also makes render targets live in replay order and notes the op, since a chunk can sample a storage before the chunk that renders it got there or after the scan went past a later target there: a chunk's texture slots resolve as of its own op, and the chunks after a texture with no entry yet wait for the chunk that makes it. DLSS's decisions (the G-buffer, the light target, the end of the scene, the scaling pass) are the scan's too, and its copy of the lit scene and its evaluation are records of the chunk that holds the op; a chunk's draws are jittered while they come before the scan's end of the scene. The evaluation waits until the chunks before it are recorded, as it reads what their draws noted (the camera block, the jitter, the per-object motion list, which chunks add to under one lock), and the chunks after it wait for it, as they sample its output. `TOTK_REPLAY_STATE_CHECK=1` compares the state after the last chunk with the scan's.
- Frame ahead. `TOTK_SYNC_AHEAD=1` (`sync_ahead`, off by default) makes the one `nvnSyncWait` per frame that waits for the frame presented last wait for the frame before it, so the game builds the next frame while the GPU still runs the previous one (`nvn_api_core.c`, `nvnSyncWait`). The game then writes memory that in-flight work still reads. Two forms guard that. With shadow storage (`vk_memory.c`, the CPU-visible pools are host-visible copies of guest memory, on by default on Linux and Wine, `shadow = 1` (`TOTK_SHADOW=1`) on native Windows) a CPU write reaches the GPU only through the shadow copy made before each submit (`vk_mem_shadow_sync`), and a copy that would overwrite bytes an unfinished submission reads is queued as a GPU copy in the prologue command buffer of the part submitted next (`vk_mem_shadow_prologue`, `TOTK_SHADOW_DEFER=1`, the default with the feature) or, with `=0`, waited for on the replay thread (`shadow_reader_wait`). Only that one wait lags (identified by its call site, known for 1.1.0, 1.2.1 and 1.4.3). GPU writes into pool storage come back with their fence, so a buffer the game reads back every frame after that wait holds the result of the frame before; a buffer it has not read lately holds none, and its `nvnMemoryPoolInvalidateMappedRange` waits for the write (`vk_mem_shadow_read`): TotK reads single pixels through a buffer per request, and in the Depths zeros in one of them put Link in gloom. The exit line `mem: the game waited for a GPU write it reads` counts these waits and their time. On 1.4.3 the patch set `qstamp` (`recomp/patches-v143.txt`) lets the game take its depth query results one frame older; it follows the switch and is off when the switch is refused. The fence write-back of small render targets (`vk_texture.c`, `write_back_n`) does not wait for the GPU with `TOTK_WB_EAGER=1` (`wb_eager`, the default, but only while frame-ahead is in effect: with `sync_ahead` off or refused the setting does nothing and the write-back reads the image when it runs): `vk_sync_submit` has `vk_texture_eager_record` copy the targets that value rendered into staging buffers inside the same command buffer, so once the value has passed the write-back only copies from staging into the target's storage. Only a target that was written back within the last 64 timeline values is copied (the first write-back of a target takes the blocking path), and the staging of a target past that window, no longer wanted or released goes through the deferred free (`vk_defer_buffer_until`). A snapshot is used only when its value is the one that last rendered the target, nothing recorded a write to the image since (`wr_fence`) and the GPU has finished it; otherwise the write-back reads the image as before, and the exit line `vk: wb_eager:` counts the reasons. With frame-ahead in effect the exit line `vk: fence write-backs waited for the GPU` counts the write-backs that waited for a copy and the time they waited, for every value of the setting. `check` also reads the old way and compares.
- Frame ahead. `TOTK_SYNC_AHEAD=1` (`sync_ahead`, on by default) makes the one `nvnSyncWait` per frame that waits for the frame presented last wait for the frame before it, so the game builds the next frame while the GPU still runs the previous one (`nvn_api_core.c`, `nvnSyncWait`). The game then writes memory that in-flight work still reads. Two forms guard that. With shadow storage (`vk_memory.c`, the CPU-visible pools are host-visible copies of guest memory, on by default on Linux and Wine, `shadow = 1` (`TOTK_SHADOW=1`) on native Windows) a CPU write reaches the GPU only through the shadow copy made before each submit (`vk_mem_shadow_sync`), and a copy that would overwrite bytes an unfinished submission reads is queued as a GPU copy in the prologue command buffer of the part submitted next (`vk_mem_shadow_prologue`, `TOTK_SHADOW_DEFER=1`, the default with the feature) or, with `=0`, waited for on the replay thread (`shadow_reader_wait`). Only that one wait lags (identified by its call site, known for 1.1.0, 1.2.1 and 1.4.3). GPU writes into pool storage come back with their fence, so a buffer the game reads back every frame after that wait holds the result of the frame before; a buffer it has not read lately holds none, and its `nvnMemoryPoolInvalidateMappedRange` waits for the write (`vk_mem_shadow_read`): TotK reads single pixels through a buffer per request, and in the Depths zeros in one of them put Link in gloom. The exit line `mem: the game waited for a GPU write it reads` counts these waits and their time. On 1.4.3 the patch set `qstamp` (`recomp/patches-v143.txt`) lets the game take its depth query results one frame older; it follows the switch and is off when the switch is refused. The fence write-back of small render targets (`vk_texture.c`, `write_back_n`) does not wait for the GPU with `TOTK_WB_EAGER=1` (`wb_eager`, the default, but only while frame-ahead is in effect: with `sync_ahead` off or refused the setting does nothing and the write-back reads the image when it runs): `vk_sync_submit` has `vk_texture_eager_record` copy the targets that value rendered into staging buffers inside the same command buffer, so once the value has passed the write-back only copies from staging into the target's storage. Only a target that was written back within the last 64 timeline values is copied (the first write-back of a target takes the blocking path), and the staging of a target past that window, no longer wanted or released goes through the deferred free (`vk_defer_buffer_until`). A snapshot is used only when its value is the one that last rendered the target, nothing recorded a write to the image since (`wr_fence`) and the GPU has finished it; otherwise the write-back reads the image as before, and the exit line `vk: wb_eager:` counts the reasons. With frame-ahead in effect the exit line `vk: fence write-backs waited for the GPU` counts the write-backs that waited for a copy and the time they waited, for every value of the setting. `check` also reads the old way and compares.
- Frame ahead in place. Without shadow storage the GPU reads the game's own memory, as in Savage Wind's overlap, and `vk_ahead_init` (`runtime/vk_ahead.c`) turns on guards for what the GPU reads or writes there after the recording, each with a switch `TOTK_SYNC_AHEAD_<NAME>` (1 by default unless noted) for A/B runs. `MSYNC`: the VRAM mirrors' sync copies take the synced pages from a staging copy the replay thread makes at submit (`vk_memory.c` `stage_ranges`), not from guest memory when the GPU runs them; the frame wait returns only after the replay submitted the asked value, so those are that frame's bytes. A synced range that an earlier value still writes back into waits for that value first, or the copy would drop its GPU words. `WBMERGE`: every GPU write into a mirror goes back through the word merge (`wb_merge_record`), so a write-back that lands after the game wrote the range for the next frame puts back only the words the GPU changed. `DESWZ`: a texture the CPU rewrote after its last upload is deswizzled on the CPU (`upload_gpu`, reason `frame ahead`). `READS`: GPU writes into CPU-visible memory are listed with their value until it completes (bounded, `aw_add`), and an invalidate of a range not read lately waits for the writer's own value (`ahead_read`). `ONESHOT`: the frame wait waits up to the value that rendered a dirty small target not written back within the last 16 frames (Savage Wind's one-off rule, `vk_texture_oneshot`), so a photo or a pick reads its own frame, while targets read every frame or in turns get the frame before. `QUERIES` (0 by default): the same for samples-passed reports; TotK reads those two updates after it asks (1.2.1 `f_70010c3298`). With import memory (`TOTK_MEMORY=import`, the integrated-GPU mode) the GPU reads vertex, index and storage data in place, which no guard covers (a check run saw the game rewrite about 10 KiB of them a frame after the wait, particles mostly), so the switch is refused there without shadow storage. The exit lines `mem: sync-ahead in place` and `sync-ahead: frame waits made exact` give the guards' waits and copies. `TOTK_SYNC_AHEAD_CHECK=1` runs the detector below with the late wait itself.
- Frame-ahead check. `TOTK_SYNC_AHEAD=check` keeps the frame wait exact and measures what a one-frame-late wait without shadow storage would race (`runtime/vk_ahead.c`). The replay notes, with each submission's value, every access of guest memory the GPU makes after the recording: in-place bindings of imported pools without a VRAM mirror (`VK_AHEAD_READ`), the mirror's sync copies (`vk_mem_mirror_prologue`), GPU deswizzle sources (`vk_texture.c` `upload_gpu`) and the mirror write-backs (`vk_mem_mirror_end`). At the frame wait for value A, whose late form would have waited for L, the notes of values in (L, A] form the frame's read set: merged per class, gap-joined into at most 512 write-watch queries that stamp the writes made so far into the shared page generations (`vk_mem_ahead_observe`). At the next frame-wait entry the queries run again, and every page of the set stamped since is a CPU write the late wait would have raced; memory without a write watch is compared by page hashes. GPU writes into CPU-visible memory and reports are listed with their value: an invalidate of a range written by a value in (L, A] of the last frame wait, and the fence write-back of a small target rendered by one, count as stale readbacks. One line `sync-ahead check:` per second of host time and a run summary with the largest offenders by pool at exit. `--probe-vkmem` checks the detector on a watched pool (`vk_ahead_selftest`); `tests/sync_ahead_check.py` checks that the wait stays exact.
- Recorder thread. The Vulkan calls the replay makes into its command buffer are made by a thread of their own (`vk_rec.c`, after Savage Wind Recomp and LAS Recomp): each `vkCmd*` copies its arguments into a packet of a ring and the recorder makes the calls in order; calls into other command buffers are made at once; the recorder also ends the command buffer, and the submit waits until it has. In the town on an RX 9070 the replay takes 17% less time on the submitting thread. It is off by default on AMD GPUs, where the driver loses the device or hangs the GPU at startup with it (`TOTK_VK_RECORDER=1` forces it on, `=0` makes every call on the submitting thread).
+8 -1
View File
@@ -294,7 +294,7 @@ With `gameplay_tweaks_enabled = 1` (`TOTK_GAMEPLAY_TWEAKS_ENABLED=1`, live; off
- **Ultrahand distance**: holding the right mouse button while scrolling pushes or pulls the held object closer or farther (`gameplay_ultrahand_distance = 1`, sensitivity `gameplay_distance_sensitivity = 1`).
- **Free-roam weapon switching**: scrolling the mouse wheel in free roam steps through equipped weapons (`gameplay_weapon_wheel = 1`, sensitivity `gameplay_weapon_sensitivity = 1`). Press E to confirm the chosen weapon; right click or pressing B cancels.
- **Quick-selection menus**: scrolling the mouse wheel browses items while a quick-selection menu (weapons, bows, shields, materials) is open (`gameplay_item_wheel = 1`, sensitivity `gameplay_item_sensitivity = 1`). A and D keys step left and right through the strip (`gameplay_item_ad = 1`).
- **Smooth map zoom**: the mouse wheel performs continuous inertial zooming on the Purah Pad map (`gameplay_map_zoom = 1`, sensitivity `gameplay_map_zoom_sensitivity = 1`).
- **Smooth map zoom**: the mouse wheel performs continuous inertial zooming on the Purah Pad map (`gameplay_map_zoom = 1`, sensitivity `gameplay_map_zoom_sensitivity = 1`). It works with `menu_cursor = 0` too: the map is still found then, and the mouse moves the map's cursor there as with the menu cursor on, while the game's other menus stay without the pointer.
All sub-toggles default to 1 and sensitivities to 1 (range 0.25 to 4.0), so enabling `gameplay_tweaks_enabled` activates the full suite immediately while allowing individual features to be toggled or tuned.
@@ -324,6 +324,13 @@ gyro all the time. Pick an activation the game does not need (a back button), or
of the game's own motion. Under Steam the Steam Controller's gyro arrives already corrected, so it keeps a bias of its
own (`gyro_bias_pad` ends in "(under Steam)").
On Linux the gamepad keeps playing while the game window has no focus (#971), except in a game Steam started: the
Steam overlay and Steam's menus (the Quick Access menu and the Steam menu in SteamOS's Game Mode) take the focus while
they are open, and the presses meant for them must not reach the game too (#1462). Steam sets `SteamGameId` for its
own games and for non-Steam shortcuts; the log then says `input: the gamepad pauses while the window has no focus`.
`pad_background = 1` keeps the gamepad playing behind other windows under Steam too, `0` pauses it everywhere
(`runtime/input.c`, `start`; read at start). On Windows the game window is not SDL's, and the gamepad always plays.
## Scripted input
`TOTK_INPUT_SCRIPT=<file>` replays presses. It is ORed with real input and still applies under `TOTK_INPUT=none`. One event per line, `#` starts a comment:
+3 -1
View File
@@ -109,7 +109,9 @@ loads the saves 1.4.3 wrote.
file but the UI archive; for `pc` with the same `--binds` as the PC prompts step, whose key the step follows). The shapes are those of every connected display (Windows: `EnumDisplayDevices`; Linux:
`xrandr`, else the DRM connectors), of the `output_res` the game defaults to on each, and of the `totk.ini`
`output_res` (`installer/screens.py`). One folder per shape, named after the shape's size in `ASPECT_SIZES` (the
closest within 1%; `5120x2160` uses `2560x1080`); `runtime/romfs.c` `overlay_init` maps the game resolution the
closest within 1%; `5120x2160` uses `2560x1080`), or for an unlisted shape from 4:3 to 32:9 its own size (a
`totk.ini` `output_res` of `2560x1200`, say; a display of an unlisted shape gets none, as the game keeps 1920x1080
there); `runtime/romfs.c` `overlay_init` maps the game resolution the
same way, and a folder of the exact size from an older setup still wins. A 16:9 player gets none. The step runs
again when the displays, the prompts or the patches change. At a game resolution whose shape has no folder the
game draws 16:9 with bars and starts the generator itself, in the background, for the next start: at start and
+1 -1
View File
@@ -81,7 +81,7 @@ Source shorthands:
| 3.2 | **FMZ multiply mode** (`FMUL/FFMA/...` field `Fmz`, `.FMZ`): 0 × anything = 0, including Inf/NaN (DX9 rule). | IEEE: 0 × Inf = NaN. | Ryujinx decodes `Fmz` (`Decoders/InstDecoders.cs:306-309, 1901`) but no emitter reads it. Ours: same. Census needed (check 13). | RYU-SH |
| 3.3 | **Denormals**: per-instruction `.FTZ`. | AMD flushes fp32 denormals by default; `VK_KHR_shader_float_controls` sets it per shader. | Ryujinx ignores `.FTZ`. Low risk. | RYU-SH (no `Ftz` use in `Instructions/`) |
| 3.4 | **Warp size 32**: `SHFL`, `VOTE`, `S2R LANEID`, ballots are 32-bit. | AMD RDNA runs wave32 or wave64 per shader (the driver chooses; RADV fragment default wave64); `VK_EXT_subgroup_size_control` `requiredSubgroupSize = 32` fixes it. | Ryujinx adapts lane masks to `QueryHostSubgroupSize()` (default 32, `IGpuAccessor.cs:218`; `Instructions/InstEmitWarp.cs:72, 106`, `InstEmitMove.cs:175-185`). Ours: not overridden, no required size (check 6). | <https://docs.mesa3d.org/envvars.html> (`RADV_PERFTEST=pswave32`) |
| 3.5 | **Discard (`KIL`)** keeps the quad's derivatives valid (demote semantics). | `OpKill` terminates; later derivatives in the quad undefined. | Ryujinx emits `OpKill` (`CodeGen/Spirv/Instructions.cs:508`). Ours: on AMD's own drivers (`vk_caps.amd` without `mesa`) `vk_pipeline.c` `spirv_demote` turns each `OpKill` that a selection header branches to into `OpDemoteToHelperInvocation` plus a branch to the selection's merge block; `TOTK_DEMOTE` overrides. TotK's cloud shader discards and then takes `OpImageQueryLod`: with `OpKill` AMD's Windows driver lost fog in the fragments sharing a quad with a discarded one (#164). | <https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/EXT/SPV_EXT_demote_to_helper_invocation.asciidoc> |
| 3.5 | **Discard (`KIL`)** keeps the quad's derivatives valid (demote semantics). | `OpKill` terminates; later derivatives in the quad undefined. | Ryujinx emits `OpKill` (`CodeGen/Spirv/Instructions.cs:508`). Ours: on AMD's own drivers (`vk_caps.amd` without `mesa`) `vk_pipeline.c` `spirv_demote` turns each `OpKill` that a selection header branches to, and that an `OpImageQueryLod`, an explicit derivative or a call follows in its function, into `OpDemoteToHelperInvocation` plus a branch to the selection's merge block; other kills stay `OpKill`, since a demoted fragment runs the rest of the shader and alpha-tested draws paid for every discarded pixel. `TOTK_DEMOTE` (ini `demote`) overrides. TotK's cloud shader discards and then takes `OpImageQueryLod`: with `OpKill` AMD's Windows driver lost fog in the fragments sharing a quad with a discarded one (#164). | <https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/EXT/SPV_EXT_demote_to_helper_invocation.asciidoc> |
| 3.6 | **Implicit-LOD sampling in divergent control flow** works on Maxwell (TEX unit uses quad neighbours). | Undefined in non-uniform control flow; AMD whole-quad mode usually works. | — | VKSPEC (derivatives) |
| 3.7 | **Integer division** does not exist (compiled to `XMAD`/`IMAD` sequences); MUFU.RCP(0) = +Inf, LG2(0) = -Inf. | Same IEEE edge cases through `1/x`, `Log2`. | Low risk. | — |
| 3.8 | **FP64** in some TotK cutscene shaders. | No FP64 on some hosts. | yuzu FP64 → FP32 (YZ-2306, PR 10693); ours: `softfloat64` job flag (`tools/xlate/Program.cs` `QueryHostSupportsShaderFloat64`). | — |
+7 -3
View File
@@ -112,8 +112,10 @@ ahead of time, after the design in [#845](https://github.com/valentderah/totk-pc
reason, and the other plugins are built in.
2. At every start each plugin's start-up runs again, before the game's own start-up code, in the same setting: it
sees the game's own instructions, as in its service run. Its redirects are compared with the record of the
rebuild. When they match, the mod's code sites go on. When they do not, the plugin stays off for this run, the
mod's row says why, and the next start runs the rebuild.
rebuild. A value it writes into the game's data that redirects nothing (a size, a counter) only has to land at
the recorded place, since the game may hold another value there at this start, for example a memory pool that
grows with `render_scale`. When they match, the mod's code sites go on. When they do not, the plugin stays off for
this run, the mod's row says why, and the next start runs the rebuild, which runs the plugin's service run again.
3. The plugin keeps what its start-up made (its memory, its tables), so its code works as on the Switch. The start
costs about 50 ms per plugin; the game runs no differently without a plugin.
4. Removing a plugin mod from the mods folder starts the rebuild at the next start, which builds the game without
@@ -126,7 +128,9 @@ The rebuild refuses a plugin when its start-up or the code its redirects reach n
system calls other than the few its start-up needs (memory queries and maps, the heap size, the clock, debug output),
or a library call the game itself never makes and a reviewed list does not hold (memory and string functions, the heap,
text formatting, mutexes, the clock, the system language, the SD card's files), such as network sockets or the module
loader. A library call the game makes (threads, input, time, its files) runs on the path the game runs on. A start-up
loader. A library call the game makes (threads, input, time, its files) runs on the path the game runs on. A call to a
function the plugin itself holds counts as its own code, even when it goes through the plugin's import table (C++
library templates such as `std::vector` built into it). A start-up
still gets only the system calls above, so it cannot start a thread or open a service; a redirect that is not one of exlaunch's hook shapes
(inline hook, replace hook, call-site rewrite, a branch into its code from inside a game function, a pointer in the
game's data swapped for one into its code); a write into the game's read-only data or into another module; two runs of
+5 -3
View File
@@ -28,7 +28,7 @@ Many rows below are developer tools that only act together with another setting
| `bind_stats` | `1` counts bindings and descriptors per draw of each stage and how much of the bound state changes between draws. | Adds per-draw bookkeeping to the render thread and extra log output; frames get slower. | Caution |
| `contact_debug` | `1` draws the contact-shadow factor in grey in place of the picture; `2` draws the sun visibility the shadows are scaled by (white in the sun, black in shade and underground). | The frame shows a grey debug image while it is set; has no effect when contact shadows are off. | Caution |
| `core_diag` | `1` records why ready guest threads wait for a virtual core and for how long, with a histogram every 60 presents. | Turns on host-call and SVC depth tracking and writes many log lines (one per present over 25 ms); frames get slower. | Caution |
| `barrier_merge` (default `0`) | Experimental. `1` keeps a render pass open through the game's Barrier calls that ask only for fragment ordering and texture invalidation, when no draw of the pass can write a storage buffer or image; the next draw that samples a written target gets a by-region barrier in the pass (the feedback layout). In scenes with about a thousand such barriers a frame this cuts the passes from about 1200 to 130 and the GPU time from 24.5 to 7.8 ms. | The game's barrier orders every pixel, the in-pass by-region barrier only the pixel a draw writes: a driver that runs it per screen tile can show flicker or squares at the edges of water, decals or particles. | Caution |
| `barrier_merge` (default `1`) | `1` keeps a render pass open through the game's Barrier calls that ask only for fragment ordering and texture invalidation, when no draw of the pass can write a storage buffer or image; the next draw that samples a target it also writes gets a by-region barrier in the pass (the feedback layout), and a draw that samples a written target without writing it ends the pass. In scenes with about a thousand such barriers a frame this cuts the passes from about 1200 to 130 and, on RADV, the GPU time from 24.5 to 7.8 ms; AMD's Windows driver shows no GPU time change. `0` ends the pass at every such Barrier. | The game's barrier orders every pixel, the in-pass by-region barrier only the pixel a draw writes: a driver that runs it per screen tile could show flicker or squares at the edges of water, decals or particles; `0` rules that out. | Caution |
| `menu_cursor_log` | `1` logs what the menu cursor code reads at every screen change. | Only adds log lines. | Safe |
| `plugin_tick_offset` (default `0`) | Added to every GetSystemTick in the plugin service run (`totk.exe --plugin-init DIR`), so `tools/exefs_plugins.py` can run a plugin's init twice with other ticks and compare the records. | Has no effect outside `--plugin-init`; a plugin's init at the start of the game gets the plain ticks. | Safe |
| `plugin_trace` (default `0`) | `1` logs the first call of each entry of a mod plugin's hooks (its callbacks, replace and call targets) as `plugins: hook entry ... reached`. | Each such call goes through a counting step; nothing changes without a mod plugin. | Safe |
@@ -36,6 +36,7 @@ Many rows below are developer tools that only act together with another setting
| `perf_slow_ms` (default `50`) | Frames at least this many milliseconds long get a `perf: slow frame` log line with the time blocked per cause. | Changes how many frames are logged; a small value fills the log. | Safe |
| `replay_check` | `1` reads every texture read-back a second time after a full drain of the replay queue and compares the two. | Stalls the replay queue at every read-back, so frames get much slower; mismatches are only counted and logged. | Caution |
| `resolve_check` | `1` compares every cached pool lookup with the locked lookup and stops on a difference. | Slows every pool lookup; the game stops if the two ever differ. | Caution |
| `skip_cs` | Leaves out every dispatch of the compute shaders it names: up to 16 ids, separated by commas or spaces, each the 16 hex digits after `cs` in a `vk: last started ...: dispatch ...` pass-mark line of a lost device (fewer digits match every id that starts with them). At the first dispatch the log names each listed id, and then the first dispatch it skipped of each. For finding the shader behind a GPU hang that the pass marks put in one dispatch, such as the hang after the startup logo on Intel GPUs with game 1.2.1 (#1402). | Whatever the skipped shader writes is missing, so parts of the picture can be wrong or black, and a shader whose results the game reads back can change what it does; remove the line once the test is done. | Risky |
| `speed_probe` | `1` adds the player's position and ground speed to the frame-rate line that `TOTK_TRACE=perf` prints every 120 presents. | Only adds log text; has no effect without `TOTK_TRACE=perf`. | Safe |
## Profiling and measurement
@@ -146,7 +147,7 @@ Many rows below are developer tools that only act together with another setting
| `dyn_delta` (default `1`) | Records only the pipeline dynamic states (cull mode, depth and stencil tests, vertex input, blend enables, equations and write masks, ...) whose values changed since the last draw in the command buffer, also across pipeline changes; `0` records the full set at every change of pipeline state, as before; `ab` alternates with the `ab` blocks. | Fewer commands per pipeline change on the render and recorder threads; a driver that loses dynamic state across pipeline binds would draw with stale state. `TOTK_TRACE=perf` prints the calls and commands per submission. | Caution |
| `feedback` | `0` samples a target that an earlier draw of the same pass wrote with no barrier; `restart` ends and restarts the pass behind a full barrier; otherwise the feedback-loop layout is used when the GPU supports it. | `0` brings back the old behaviour that the barrier fixed, so the picture can break in passes that read a target they draw into; `restart` costs extra passes. | Risky |
| `flush_span` (default `0`) | `1` copies one span from the lowest to the highest flushed address of a pool, as an older version did. | Copies far more data to the GPU in crowded towns: an estimated 30-50 ms of GPU time per large copy over PCIe 3.0 x8. | Caution |
| `frame_gen` (default `off`) | The frame generator: `off`, or `fsr3`, which brings up AMD FSR 3 frame interpolation and optical flow (FidelityFX SDK 1.1.4) at start; with DLSS off the replay follows the scene and records the motion vectors (the camera's and the moving objects', `fg_objects`), the picture before the HUD and the interpolation of a frame between each two the game draws (`runtime/vk_fg.cpp`). Each frame then goes out as two presents: the generated picture once the GPU has drawn the frame (a timeline wait, not before the pacer's time), the game's half the smoothed interval later (`runtime/vk_backend.c` `present_pair`); `fps_limit` counts the pictures shown and the game draws half, 30 at least (`runtime/frame_rate.c` `frame_step_cap_ns`). Off with DLSS or FSR 3.1 (`scene_upscaler`), `replay_workers` above 0, `sync_ahead = 1` or HDR output, and while a menu background or a loading or event fade is open; the game then draws at the whole limit. The swapchain gets one image more. Applies at once: turned on in the menu, the contexts are made at the next frame (a hitch of about 0.1 s once); turned off, they stay until exit. | The controls answer at the drawn rate, about half a frame later. Costs about 1.5 ms of GPU and 0.6 ms of the replay thread per drawn frame at 1080p (RX 9070, 7900X on 4 cores: 94 drawn without it, 86 drawn and 169 shown with it, no limit). For displays of 120 Hz and more. | Caution |
| `frame_gen` (default `off`) | The frame generator: `off`, or `fsr3`, which brings up AMD FSR 3 frame interpolation and optical flow (FidelityFX SDK 1.1.4) at start; with DLSS off the replay follows the scene and records the motion vectors (the camera's and the moving objects', `fg_objects`), the picture before the HUD and the interpolation of a frame between each two the game draws (`runtime/vk_fg.cpp`). Each frame then goes out as two presents: the generated picture once the GPU has drawn the frame (a timeline wait, not before the pacer's time), the game's half the smoothed interval later (`runtime/vk_backend.c` `present_pair`); `fps_limit` counts the pictures shown and the game draws half, 30 at least (`runtime/frame_rate.c` `frame_step_cap_ns`). Off with DLSS or FSR 3.1 (`scene_upscaler`), `replay_workers` above 0 or HDR output, and while a menu background or a loading or event fade is open; the game then draws at the whole limit. The swapchain gets one image more. Applies at once: turned on in the menu, the contexts are made at the next frame (a hitch of about 0.1 s once); turned off, they stay until exit. | The controls answer at the drawn rate, about half a frame later. Costs about 1.5 ms of GPU and 0.6 ms of the replay thread per drawn frame at 1080p (RX 9070, 7900X on 4 cores: 94 drawn without it, 86 drawn and 169 shown with it, no limit). For displays of 120 Hz and more. | Caution |
| `fg_test` | Frame generation checks: `1` presents the generated frame in place of the game's, `2` the picture before the HUD. Read at start. | Shows the frames out of their order: for checks only. | Caution |
| `fg_debug` | `1`: the generated frames hold the SDK's debug view (motion fields, optical flow, disocclusion). Read at start. | For checks only. | Caution |
| `fg_objects` (default `1`) | Frame generation's motion vectors get the per-object pass DLSS uses over the camera's: the moving scene draws (characters, enemies, objects) are drawn again with last frame's blocks (`runtime/vk_exec_draw.c` `vk_mvobj_execute`, `runtime/vk_mvprev.c`). `0`: the camera's motion alone; Link, whom the camera follows, then carries the world's motion and the generated pictures show him twice. Read at start. `dlaa_objmv = 0` also turns the object pass off. | About 0.04 ms of GPU and 0.8 ms of the replay thread per drawn frame (RX 9070, 7900X on 4 cores, field, 1080p: 85.6 drawn with `0`, 80.0 with `1`), half of it the host copy of the uniform snapshot the object pass reads. | Safe |
@@ -221,6 +222,7 @@ Many rows below are developer tools that only act together with another setting
| --- | --- | --- | --- |
| `app_pool` | Size in bytes of the guest application memory pool; accepts decimal or `0x` hex. | The default depends on the resolution settings; `0` stops the start with a message, and too small a pool leaves the game without memory. | Risky |
| `audio_off` | Any value mixes audio without opening an output device. | The game runs in silence and reports two channels; same as `audio = none`. | Caution |
| `heap_lazy` (default `0`) | The game's heap is committed a 1 MiB chunk at a time when the game first touches it, instead of all at once when the game sets its size (about 2.1 GiB at boot on 1.4.3). File reads, save writes and Vulkan imports commit their pages first. Windows only; Linux already backs pages on first use. | `1` lowers the game's committed memory (RAM plus page file) by the heap the game never touches (sky island: peak commit about 6.4 to 5.8 GiB), which helps PCs whose commit limit is near the game's needs; each first touch of a 1 MiB chunk costs a fault and a commit (about 600 a run, 8 ms in all). | Caution |
| `kspin_us` (default `20`) | Microseconds a guest wait or a wait for a virtual core polls before it sleeps; `0` turns the poll off; `ab` polls only in the B blocks of `ab`. Off with fewer than 6 logical processors. | A wake within the poll costs no OS wake-up; a longer poll takes more CPU time from other threads. | Caution |
| `mem_reserve_mib` (default `1536`) | MiB of system memory kept free for Windows, other programs and the game's own heap when the renderer sizes what it keeps in device memory, where device memory takes system memory (integrated GPUs, and discrete GPUs whose driver charges it to the process). | A larger value keeps fewer released textures and spare blocks when the system runs short; a smaller one lets the game use more before it holds back. | Caution |
| `one_per_core` (default `0`) | `1` keeps the process on the first logical processor of each physical core; `ab` switches it with the `ab` blocks. | Busy threads stop sharing a core with a sibling thread, which can help or hurt on the CPU; it only applies when the CPU has hyperthreads. | Caution |
@@ -248,7 +250,7 @@ These names are code patch sets built into the generated game code (`recomp/patc
| `audio_drain_fix` (default `1`) | Patch set that sends the game's audio thread back to its command ring after each list (1.2.1 main+0x883780, 1.4.3 main+0x149244), so it takes every queued list per 5 ms audio frame instead of one (#337). Game 1.1.0 has no site and keeps the game's code. | `0` runs the game's code as shipped: above about 200 game updates a second the ring fills, and the game's guard (1.2.1 main+0x9bcdc4) switches the sound commands off until the game is restarted once 300 updates in a row find it full. The guard starts over whenever two audio frames fall between two updates, so by the code it fires only while the audio frames come evenly, 5 ms apart: with `audio = none`, or while the audio device takes nothing and the mixer keeps time by its own timer. The guard's count and the switch have not been read in a run. With a device playing the game kept its sound in every run on Linux with PipeWire and 1024-frame device periods, where the frames come in bursts after each period; on Windows the bursts are read from the code (`gap_ns = 0` in `runtime/audren.c`), not measured; a device with periods of 240 frames or less was not tried and may pace as evenly as the timer. The set acts only when more than one list is queued, so below that rate it seldom changes anything. Measured at `fps_limit = 240` (Linux, PipeWire), seconds with sound with `0` and with `1`. On 1.2.1: without a device 6 of 119 and 111 of 119; with a device 111 of 119 and 112 of 119; with the game's stream paused for 5 s from outside (`pw-cli`, not a real device stalling) 4 of 120 (silent from the pause on, also after the device resumed) and 113 of 119; a pause of 2 s silenced the game with `0`, a pause of 1 s did not. On 1.4.3: without a device 3 of 119 and 113 of 120; with a device 111 of 119 with `0`; with the stream paused for 5 s, in 60 s runs, 3 of 59 and 51 of 59; a pause of 2 s with `0`, 4 of 59. | Safe |
| `fixed_res_patch` (default `0`) | Patch set that holds the game's dynamic resolution at 100 percent (the scene tier). | The resolution code switches this set from `dynamic_res` (on at `0`); a manual value is replaced. | Unknown |
| `freecam_patch` (default `0`) | Patch set of the hook in the camera component update behind the free camera (`freecam_pad`, `freecam_key`) on game 1.4.3; the *Free camera* row of the Controls tab. Read at start. | `1` puts the hook in the camera update: while the free camera is off it runs the game's own load and one compare. `0` runs the game's code as shipped: the combo and the key do nothing and the game gets the combo's buttons. | Safe |
| `fov_patch` (default `0`) | Patch set that scales the camera's vertical view angle by the field-of-view setting. | The resolution code switches this set itself whenever the field of view is not 100 percent; a manual value is replaced. | Unknown |
| `fov_patch` (default `0`) | Patch set that scales the camera's vertical view angle by the field-of-view setting. | The resolution code switches this set itself whenever the field of view is not 100 percent or `vert_plus` widens the view; a manual value is replaced. | Unknown |
| `lightning_fix` (default `1`) | Patch set on 1.2.1 and 1.4.3 (set `lightning`; 1.4.3 main+0x62b1fc, main+0x62b3d8, main+0x62b51c; 1.2.1 main+0xab8d50, main+0xab9014, main+0xab8f90): in a thunderstorm the world manager's lightning update runs once per frame and draws, each update, a random number for each of three fixed chances, 0.013333 for a distant bolt and 0.01 for a near strike and for the environment's lightning flag that near strikes also set (#1287). The set multiplies each chance by the frame ratio, at most 1, so above 30 fps a storm has as much lightning per second as at 30 fps; at 30 fps and below the chances are the game's own. Game 1.1.0 has no site and keeps the game's code. | `0` runs the game's code: the higher the frame rate, the more distant bolts and lightning flags. Counted on 1.4.3 in one storm (205 s, the reporter's save) with a local build that logs each draw that succeeds: distant bolts 22, 52 and 94 to 96 a minute at 30, 60 and 120 fps with `0`, and 26, 27 and 20 to 24 with `1`; the lightning flag 19, 34 and 64 to 80 a minute of the storm's lightning phase with `0`, 12 to 17 with `1`. Near strikes stayed at 14 to 18 per run at every rate with either value. On 1.2.1 counted from screenshots only (no logging build; a storm in Hyrule Field, one screenshot every 0.2 s, each counted bolt checked by eye): 19 screenshots with a distant bolt a minute at 30 fps, about 61 at 120 fps with `0`, 15 with `1`; the same count on 1.4.3 gives 25 to 26, 65 to 68 and 16 to 20. | Safe |
| `mouse_direct_patch` (default `1`) | Patch set of the hooks in the game's camera code behind `mouse_mode = direct` on game 1.4.3. | `0` stops `mouse_mode = direct` from taking effect; other mouse modes are unaffected. | Safe |
| `optref_guard` (default `1`) | Patch set that treats a negative value in the optional reference at object +0x6b0 (1.4.3 main+0x1bd01c0, 1.2.1 main+0x1622bec) as absent instead of loading through it (#1005). | `0` runs the game's code as shipped: the random crash reading `0xffffffffffffffff` after minutes to hours of play can return. | Risky |
+25 -9
View File
@@ -16,22 +16,28 @@ from pathlib import Path
# The game resolutions of another shape than 16:9 that runtime/ui/menu.cpp row_output_res lists, in the order of
# runtime/cfg.c SHAPED: 21:9 and 32:9 monitors, 16:10 screens (the Steam Deck's 1280x800, handhelds and laptops) and 3:2
# screens (Surface and Framework laptops and tablets)
ASPECT_SIZES = ('2560x1080', '3440x1440', '3840x1600', '5120x2160', '3840x1080', '5120x1440',
# screens (Surface and Framework laptops and tablets), 4:3 screens (CRT monitors, iPads) and 19.5:9 and 20:9 phone screens
# (streamed to a phone)
ASPECT_SIZES = ('2560x1080', '3440x1440', '3840x1600', '5120x2160', '3840x1080', '5120x1440', '7680x2160',
'1280x800', '1680x1050', '1920x1200', '2560x1600',
'1920x1280', '2160x1440', '2256x1504', '2880x1920', '3000x2000')
'1920x1280', '2160x1440', '2256x1504', '2880x1920', '3000x2000',
'1440x1080', '1600x1200', '2048x1536', '2732x2048',
'2340x1080', '3120x1440', '2400x1080', '3200x1440')
SHAPED = tuple(tuple(int(v) for v in s.split('x')) for s in ASPECT_SIZES)
TOLERANCE = 0.01 # cfg.c and resolution.c res_is_16x9: shapes within 1% are the same
# cfg.c SHAPE_MIN / SHAPE_MAX: the aspect ratios a UI layout can be made for (tools/ultrawide_layout.py), 4:3 to 32:9
SHAPE_MIN, SHAPE_MAX = 4 / 3 * 0.99, 32 / 9 * 1.01
def is_16x9(w, h):
return abs((w / h) / (16 / 9) - 1) <= TOLERANCE
def shape_size(w, h):
def shape_size(w, h, listed=False):
"""The folder size of w x h's shape: of ASPECT_SIZES within 1% of its aspect ratio, the closest, the first of equal
ones (5120x2160 is 2560x1080's shape). None for 16:9 and for a shape the setup has no layout for. The same rule as
runtime/cfg.c cfg_shape_size."""
ones (5120x2160 is 2560x1080's shape); another shape from 4:3 to 32:9 its own size (an output_res of a phone's
3120x1440, say), unless listed. None for 16:9 and for a shape no layout can be made for (portrait, narrower than
4:3, wider than 32:9). The same rule as runtime/cfg.c cfg_shape_size."""
if not w or not h or is_16x9(w, h):
return None
r, best, err = w / h, None, None
@@ -39,7 +45,15 @@ def shape_size(w, h):
e = abs(sw / sh / r - 1)
if e <= TOLERANCE and (err is None or e < err):
best, err = f'{sw}x{sh}', e
return best
if best or listed or not SHAPE_MIN <= r <= SHAPE_MAX:
return best
return f'{w}x{h}'
def size_order(size):
"""Sort key: the ASPECT_SIZES order, then the sizes of unlisted shapes by width and height."""
w, h = (int(v) for v in size.split('x'))
return (ASPECT_SIZES.index(size), 0, 0) if size in ASPECT_SIZES else (len(ASPECT_SIZES), w, h)
def default_size(w, h):
@@ -199,8 +213,10 @@ def wanted(dest, screens=None):
text = ''
sizes = set()
for w, h in screens:
# A display of an unlisted shape keeps the 1920x1080 default (cfg.c screen_default): no folder for it unless
# output_res asks for its size.
w, h = max(w, h), min(w, h)
sizes.add(shape_size(w, h))
sizes.add(shape_size(w, h, listed=True))
d = default_size(w, h)
if d:
sizes.add(shape_size(*(int(v) for v in d.split('x'))))
@@ -208,4 +224,4 @@ def wanted(dest, screens=None):
if m:
sizes.add(shape_size(int(m.group(1)), int(m.group(2))))
sizes.discard(None)
return sorted(sizes, key=ASPECT_SIZES.index), prompts_style(text)
return sorted(sizes, key=size_order), prompts_style(text)
+80 -1
View File
@@ -218,6 +218,60 @@ def linux_glibc():
# GLIBC_FLOOR); on an older one they cannot start
GLIBC_NEEDED = (2, 34)
# The libraries the release puts next to the game (libSDL3.so.0 from the Steam Runtime sysroot) link system libraries
# that a minimal system may lack: libXss.so.1 on AnataseOS (#1315, #1428), libdecor-0.so.0 on Batocera (#1419). The
# loader then stops the game before it runs, after the half hour of lift and compile, as `totk --prepare-shaders`
# with exit code 127. The package that provides a common one, by distribution family.
LIBRARY_PACKAGES = {
'libXss.so.1': ('libXScrnSaver', 'libxss1', 'libxss'),
'libdecor-0.so.0': ('libdecor', 'libdecor-0-0', 'libdecor'),
'libXi.so.6': ('libXi', 'libxi6', 'libxi'),
'libXrandr.so.2': ('libXrandr', 'libxrandr2', 'libxrandr'),
'libXcursor.so.1': ('libXcursor', 'libxcursor1', 'libxcursor'),
'libXinerama.so.1': ('libXinerama', 'libxinerama1', 'libxinerama'),
'libXext.so.6': ('libXext', 'libxext6', 'libxext'),
'libXfixes.so.3': ('libXfixes', 'libxfixes3', 'libxfixes'),
'libX11.so.6': ('libX11', 'libx11-6', 'libx11'),
'libxkbcommon.so.0': ('libxkbcommon', 'libxkbcommon0', 'libxkbcommon'),
'libwayland-client.so.0': ('libwayland-client', 'libwayland-client0', 'wayland'),
'libasound.so.2': ('alsa-lib', 'libasound2', 'alsa-lib'),
}
LDD_NOT_FOUND = re.compile(r'^\s*(\S+) => not found', re.M)
LOADER_NOT_FOUND = re.compile(r'error while loading shared libraries: (\S+?): cannot open shared object file')
def library_packages(libraries):
"""The packages that provide the known ones of libraries, as " (Fedora: ..., Debian/Ubuntu: ..., Arch: ...)" for
the message; "" when none is known."""
known = [LIBRARY_PACKAGES[n] for n in libraries if n in LIBRARY_PACKAGES]
if not known:
return ''
return ' (' + ', '.join(f'{family}: {" ".join(p[i] for p in known)}'
for i, family in enumerate(('Fedora', 'Debian/Ubuntu', 'Arch'))) + ')'
def loader_missing(log):
"""The libraries the system's loader could not find in a tool's log ("error while loading shared libraries"), in
order, each once."""
log = Path(log)
text = log.read_text(encoding='utf-8', errors='replace') if log.is_file() else ''
return list(dict.fromkeys(LOADER_NOT_FOUND.findall(text)))
def missing_libraries(paths):
"""Linux: the shared libraries `ldd` reports as not found for paths, in order, each once; [] elsewhere, when ldd
cannot run, or when nothing is missing."""
if not sys.platform.startswith('linux'):
return []
found = []
for p in paths:
try:
r = subprocess.run(['ldd', str(p)], capture_output=True, text=True, errors='replace', timeout=60)
except (OSError, subprocess.SubprocessError):
return []
found += [n for n in LDD_NOT_FOUND.findall(r.stdout) if n not in found]
return found
def linux_kernel():
"""(major, minor) of the running Linux kernel, None elsewhere."""
@@ -537,6 +591,12 @@ class Check(Step):
host = self.probe_host(ctx, exe)
if not host['x86_64_v2']:
raise InstallError('check.cpu_too_old')
# Before lift and compile: the game would not start without these (LIBRARY_PACKAGES); a repository build links
# the system's own libraries
missing = [] if layout.dev else missing_libraries(layout.dlls)
if missing:
raise InstallError('check.libraries_missing', libraries=', '.join(missing),
packages=library_packages(missing))
# v3 is the faster build; v2 runs on CPUs without AVX2/FMA (runtime/fma.c supplies the fused multiply-add).
ctx.cpu = 'v3' if host['x86_64_v3'] else 'v2'
if not host['loader']:
@@ -1141,6 +1201,17 @@ def plugins_status(ctx):
return ctx.dest / 'build-cache' / 'plugins.status'
def plugins_stale(ctx):
"""True when the game listed a plugin whose start differed from the build (build-cache/plugins.stale, runtime/mods.c
mods_plugin_off): the plugin's record comes from the lift's service run and the exe's patch sets from the compile,
so both are out of date, while their keys, made of the files the steps read, are unchanged. Only Lift.run clears
the file."""
try:
return bool((ctx.dest / 'build-cache' / 'plugins.stale').read_text(encoding='utf-8', errors='replace').strip())
except OSError:
return False
def built_plugins(status, files, mods):
"""The files of the plugins the status file lists as built (kind `plugin`), in the order of files. The key is
FNV-1a 32 of "<mod folder>/<path in the mod>", as tools/exefs_plugins.py and runtime/mods.c compute it."""
@@ -1194,7 +1265,8 @@ class Lift(Step):
def current(self, ctx, record):
gen = ctx.temp / 'gen'
stamp = gen / STAMP
return (gen / 'layout.json').is_file() and stamp.is_file() and stamp.read_text().strip() == ctx.keys['lift']
return ((gen / 'layout.json').is_file() and stamp.is_file() and stamp.read_text().strip() == ctx.keys['lift']
and not plugins_stale(ctx))
def run(self, ctx):
# gen/ of the last run stays: gen.py lifts again only the chunks whose inputs changed
@@ -1369,6 +1441,8 @@ class Compile(Step):
exe = ctx.dest / ('totk' + EXE)
if not exe.is_file() or not (ctx.dest / 'romfs-index.bin').is_file():
return False
if plugins_stale(ctx): # the lift runs (Lift.current), and a transient step runs only with the step after it
return False
if not all((ctx.dest / d.name).is_file() for d in ctx.layout.dlls):
return False
return file_sha256(exe) == record.get('exe_sha256')
@@ -1505,6 +1579,11 @@ class Prepare(Step):
[dest, '--version', version_tag(game_version(ctx)), '--romfs', dest / 'romfs', '--exefs',
dest / 'exefs', '--list', shader_list], parse)
if code or not (dest / 'shader-prepared.bin').is_file():
# The loader stopped the game before it ran: name the library rather than exit code 127
missing = loader_missing(log)
if missing:
raise InstallError('prepare.libraries_missing', libraries=', '.join(missing),
packages=library_packages(missing), log=str(log))
raise InstallError('prepare.shaders_failed', code=code, log=str(log))
if skipped[0]:
rep.warning('warn.shaders_skipped', count=skipped[0], log=str(log))
+2
View File
@@ -64,6 +64,7 @@
"check.vulkan_missing": "Es ist kein Vulkan-Treiber installiert. Installiere den neuesten Treiber für deine Grafikkarte.",
"check.vulkan_no_device": "Vulkan findet keine Grafikkarte. Installiere den neuesten Treiber für deine Grafikkarte.",
"check.vulkan_too_old": "Das Spiel braucht eine Grafikkarte mit Vulkan 1.3; gefunden: {devices}. Aktualisiere den Grafiktreiber.",
"check.libraries_missing": "Das Spiel kann auf diesem System nicht starten: Es braucht {libraries}, das dem System fehlt. Installiere das Paket, das es bereitstellt, mit dem Paketmanager des Systems{packages} und starte das Setup dann erneut.",
"check.no_display": "Zum Vorbereiten der Shader wird ein Bildschirm gebraucht. Starte das Setup aus der Desktop-Sitzung oder setze DISPLAY=:0 (auf einem Steam Deck im Spielmodus zusätzlich XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "Die Spieldateien werden gebraucht: wähle das Hauptspiel, das Update 1.1.0, 1.2.1 oder 1.4.3 und prod.keys.",
"check.input_missing": "Datei nicht gefunden ({input}): {path}",
@@ -106,6 +107,7 @@
"prepare.shader_list_missing": "Die Shader-Liste fehlt.",
"prepare.romfs_patches_failed": "Das Schreiben der Spieldaten-Patches ist fehlgeschlagen (Exit-Code {code}). Details: {log}",
"prepare.shaders_failed": "Das Vorbereiten der Shader ist fehlgeschlagen (Exit-Code {code}). Details: {log}",
"prepare.libraries_missing": "Das Spiel wurde gebaut, kann aber nicht starten: Dem System fehlt {libraries}. Installiere das Paket, das es bereitstellt, mit dem Paketmanager des Systems{packages} und starte das Setup dann erneut. Details: {log}",
"cleanup.romfs_unreadable": "Die Spieldaten in {path} fehlen nach der Installation oder können nicht gelesen werden. Starte Windows neu und führe das Installationsprogramm erneut auf demselben Ordner aus: Es entpackt die Spieldaten erneut und behält den Rest.",
"prepare.pack_failed": "Das Packen des Shader-Caches ist fehlgeschlagen (Exit-Code {code}). Details: {log}",
"cleanup.ini_failed": "totk.ini kann nicht geschrieben werden: {detail}",
+2
View File
@@ -67,6 +67,7 @@
"check.vulkan_missing": "No Vulkan driver is installed. Install the latest driver for your graphics card.",
"check.vulkan_no_device": "Vulkan finds no graphics card. Install the latest driver for your graphics card.",
"check.vulkan_too_old": "The game needs a graphics card with Vulkan 1.3; found: {devices}. Update the graphics driver.",
"check.libraries_missing": "The game cannot start on this system: it needs {libraries}, which the system does not have. Install the package that provides it with the system's package manager{packages}, then run the setup again.",
"check.no_display": "Preparing the shaders needs a display. Run the setup from the desktop session, or export DISPLAY=:0 (on a Steam Deck in Game Mode also XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "The game files are needed: choose the base game, the 1.1.0 or 1.2.1 or 1.4.3 update and prod.keys.",
"check.input_missing": "File not found ({input}): {path}",
@@ -110,6 +111,7 @@
"prepare.shader_list_missing": "The shader list is missing.",
"prepare.romfs_patches_failed": "Writing the game data patches failed (exit code {code}). Details: {log}",
"prepare.shaders_failed": "Preparing the shaders failed (exit code {code}). Details: {log}",
"prepare.libraries_missing": "The game was built but cannot start: the system does not have {libraries}. Install the package that provides it with the system's package manager{packages}, then run the setup again. Details: {log}",
"cleanup.romfs_unreadable": "The game data in {path} is missing or cannot be read after the install. Restart Windows, then run the installer again on the same folder: it extracts the game data again and keeps the rest.",
"prepare.pack_failed": "Packing the shader cache failed (exit code {code}). Details: {log}",
"cleanup.ini_failed": "totk.ini cannot be written: {detail}",
+2
View File
@@ -64,6 +64,7 @@
"check.vulkan_missing": "No hay ningún controlador Vulkan instalado. Instala el controlador más reciente de tu tarjeta gráfica.",
"check.vulkan_no_device": "Vulkan no encuentra ninguna tarjeta gráfica. Instala el controlador más reciente de tu tarjeta gráfica.",
"check.vulkan_too_old": "El juego necesita una tarjeta gráfica con Vulkan 1.3; encontrado: {devices}. Actualiza el controlador gráfico.",
"check.libraries_missing": "El juego no puede iniciarse en este sistema: necesita {libraries}, que el sistema no tiene. Instala el paquete que lo proporciona con el gestor de paquetes del sistema{packages} y vuelve a ejecutar el instalador.",
"check.no_display": "Preparar los shaders necesita una pantalla. Ejecuta el instalador desde la sesión de escritorio o exporta DISPLAY=:0 (en una Steam Deck en modo Juego, también XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "Se necesitan los archivos del juego: elige el juego base, la actualización 1.1.0, 1.2.1 o 1.4.3 y prod.keys.",
"check.input_missing": "Archivo no encontrado ({input}): {path}",
@@ -106,6 +107,7 @@
"prepare.shader_list_missing": "Falta la lista de shaders.",
"prepare.romfs_patches_failed": "Falló la escritura de los parches de datos del juego (código de salida {code}). Detalles: {log}",
"prepare.shaders_failed": "Falló la preparación de los shaders (código de salida {code}). Detalles: {log}",
"prepare.libraries_missing": "El juego se compiló pero no puede iniciarse: el sistema no tiene {libraries}. Instala el paquete que lo proporciona con el gestor de paquetes del sistema{packages} y vuelve a ejecutar el instalador. Detalles: {log}",
"cleanup.romfs_unreadable": "Los datos del juego en {path} faltan o no se pueden leer tras la instalación. Reinicia Windows y vuelve a ejecutar el instalador en la misma carpeta: extrae de nuevo los datos del juego y conserva el resto.",
"prepare.pack_failed": "Falló el empaquetado de la caché de shaders (código de salida {code}). Detalles: {log}",
"cleanup.ini_failed": "No se puede escribir totk.ini: {detail}",
+2
View File
@@ -64,6 +64,7 @@
"check.vulkan_missing": "Aucun pilote Vulkan n'est installé. Installez le dernier pilote de votre carte graphique.",
"check.vulkan_no_device": "Vulkan ne trouve aucune carte graphique. Installez le dernier pilote de votre carte graphique.",
"check.vulkan_too_old": "Le jeu demande une carte graphique avec Vulkan 1.3 ; trouvé : {devices}. Mettez à jour le pilote graphique.",
"check.libraries_missing": "Le jeu ne peut pas démarrer sur ce système : il a besoin de {libraries}, absent du système. Installez le paquet qui le fournit avec le gestionnaire de paquets du système{packages}, puis relancez l'installation.",
"check.no_display": "La préparation des shaders a besoin d'un écran. Lancez l'installation depuis la session de bureau, ou exportez DISPLAY=:0 (sur un Steam Deck en mode Jeu, aussi XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "Les fichiers du jeu sont nécessaires : choisissez le jeu de base, la mise à jour 1.1.0, 1.2.1 ou 1.4.3 et prod.keys.",
"check.input_missing": "Fichier introuvable ({input}) : {path}",
@@ -106,6 +107,7 @@
"prepare.shader_list_missing": "La liste des shaders est manquante.",
"prepare.romfs_patches_failed": "L'écriture des correctifs de données du jeu a échoué (code de sortie {code}). Détails : {log}",
"prepare.shaders_failed": "La préparation des shaders a échoué (code de sortie {code}). Détails : {log}",
"prepare.libraries_missing": "Le jeu a été compilé mais ne peut pas démarrer : {libraries} est absent du système. Installez le paquet qui le fournit avec le gestionnaire de paquets du système{packages}, puis relancez l'installation. Détails : {log}",
"cleanup.romfs_unreadable": "Les données du jeu dans {path} sont manquantes ou illisibles après l'installation. Redémarrez Windows, puis relancez l'installateur sur le même dossier : il extrait à nouveau les données du jeu et conserve le reste.",
"prepare.pack_failed": "Le regroupement du cache de shaders a échoué (code de sortie {code}). Détails : {log}",
"cleanup.ini_failed": "totk.ini ne peut pas être écrit : {detail}",
+2
View File
@@ -64,6 +64,7 @@
"check.vulkan_missing": "Non è installato alcun driver Vulkan. Installa il driver più recente della tua scheda grafica.",
"check.vulkan_no_device": "Vulkan non trova alcuna scheda grafica. Installa il driver più recente della tua scheda grafica.",
"check.vulkan_too_old": "Il gioco richiede una scheda grafica con Vulkan 1.3; trovato: {devices}. Aggiorna il driver grafico.",
"check.libraries_missing": "Il gioco non può avviarsi su questo sistema: richiede {libraries}, che il sistema non ha. Installa il pacchetto che lo fornisce con il gestore di pacchetti del sistema{packages}, poi esegui di nuovo l'installazione.",
"check.no_display": "La preparazione degli shader richiede uno schermo. Avvia l'installazione dalla sessione desktop oppure esporta DISPLAY=:0 (su uno Steam Deck in modalità Gioco anche XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "Servono i file del gioco: scegli il gioco base, l'aggiornamento 1.1.0, 1.2.1 o 1.4.3 e prod.keys.",
"check.input_missing": "File non trovato ({input}): {path}",
@@ -106,6 +107,7 @@
"prepare.shader_list_missing": "Manca l'elenco degli shader.",
"prepare.romfs_patches_failed": "La scrittura delle patch dei dati di gioco non è riuscita (codice di uscita {code}). Dettagli: {log}",
"prepare.shaders_failed": "La preparazione degli shader non è riuscita (codice di uscita {code}). Dettagli: {log}",
"prepare.libraries_missing": "Il gioco è stato compilato ma non può avviarsi: il sistema non ha {libraries}. Installa il pacchetto che lo fornisce con il gestore di pacchetti del sistema{packages}, poi esegui di nuovo l'installazione. Dettagli: {log}",
"cleanup.romfs_unreadable": "I dati di gioco in {path} mancano o non sono leggibili dopo l'installazione. Riavvia Windows, poi esegui di nuovo il programma di installazione sulla stessa cartella: estrae di nuovo i dati di gioco e mantiene il resto.",
"prepare.pack_failed": "La raccolta della cache degli shader non è riuscita (codice di uscita {code}). Dettagli: {log}",
"cleanup.ini_failed": "Impossibile scrivere totk.ini: {detail}",
+2
View File
@@ -64,6 +64,7 @@
"check.vulkan_missing": "Vulkan ドライバーがインストールされていません。グラフィックカードの最新ドライバーをインストールしてください。",
"check.vulkan_no_device": "Vulkan がグラフィックカードを見つけられません。グラフィックカードの最新ドライバーをインストールしてください。",
"check.vulkan_too_old": "このゲームには Vulkan 1.3 対応のグラフィックカードが必要です。見つかったもの: {devices}。グラフィックドライバーを更新してください。",
"check.libraries_missing": "このシステムではゲームを起動できません: {libraries} が必要ですが、システムにありません。システムのパッケージマネージャーでそれを含むパッケージをインストールし{packages}、セットアップをもう一度実行してください。",
"check.no_display": "シェーダーの準備にはディスプレイが必要です。デスクトップのセッションからセットアップを実行するか、DISPLAY=:0 を export してください(Steam Deck のゲームモードでは XDG_RUNTIME_DIR=/run/user/1000 も)。",
"check.inputs_needed": "ゲームファイルが必要です。本編、1.1.0・1.2.1・1.4.3 のいずれかのアップデート、prod.keys を選んでください。",
"check.input_missing": "ファイルが見つかりません ({input}): {path}",
@@ -106,6 +107,7 @@
"prepare.shader_list_missing": "シェーダーの一覧がありません。",
"prepare.romfs_patches_failed": "ゲームデータパッチの書き出しに失敗しました (終了コード {code})。詳細: {log}",
"prepare.shaders_failed": "シェーダーの準備に失敗しました (終了コード {code})。詳細: {log}",
"prepare.libraries_missing": "ゲームはビルドされましたが起動できません: システムに {libraries} がありません。システムのパッケージマネージャーでそれを含むパッケージをインストールし{packages}、セットアップをもう一度実行してください。詳細: {log}",
"cleanup.romfs_unreadable": "インストール後、{path} のゲームデータが見つからないか読み取れません。Windows を再起動し、同じフォルダーでインストーラーをもう一度実行してください。ゲームデータだけを再展開し、それ以外は保持します。",
"prepare.pack_failed": "シェーダーキャッシュのまとめに失敗しました (終了コード {code})。詳細: {log}",
"cleanup.ini_failed": "totk.ini を書き込めません: {detail}",
+2
View File
@@ -64,6 +64,7 @@
"check.vulkan_missing": "Vulkan 드라이버가 설치되어 있지 않습니다. 그래픽 카드의 최신 드라이버를 설치하세요.",
"check.vulkan_no_device": "Vulkan이 그래픽 카드를 찾지 못했습니다. 그래픽 카드의 최신 드라이버를 설치하세요.",
"check.vulkan_too_old": "게임에는 Vulkan 1.3을 지원하는 그래픽 카드가 필요합니다. 발견된 장치: {devices}. 그래픽 드라이버를 업데이트하세요.",
"check.libraries_missing": "이 시스템에서는 게임을 시작할 수 없습니다: {libraries}이(가) 필요하지만 시스템에 없습니다. 시스템의 패키지 관리자로 이를 제공하는 패키지를 설치한 뒤{packages} 설치 프로그램을 다시 실행하세요.",
"check.no_display": "셰이더를 준비하려면 디스플레이가 필요합니다. 데스크톱 세션에서 설치 프로그램을 실행하거나 DISPLAY=:0 을 export 하세요(게임 모드의 Steam Deck에서는 XDG_RUNTIME_DIR=/run/user/1000 도).",
"check.inputs_needed": "게임 파일이 필요합니다. 기본 게임, 1.1.0 또는 1.2.1 또는 1.4.3 업데이트, prod.keys를 선택하세요.",
"check.input_missing": "파일을 찾을 수 없음({input}): {path}",
@@ -106,6 +107,7 @@
"prepare.shader_list_missing": "셰이더 목록이 없습니다.",
"prepare.romfs_patches_failed": "게임 데이터 패치 작성에 실패했습니다(종료 코드 {code}). 자세히: {log}",
"prepare.shaders_failed": "셰이더 준비에 실패했습니다(종료 코드 {code}). 자세히: {log}",
"prepare.libraries_missing": "게임은 빌드되었지만 시작할 수 없습니다: 시스템에 {libraries}이(가) 없습니다. 시스템의 패키지 관리자로 이를 제공하는 패키지를 설치한 뒤{packages} 설치 프로그램을 다시 실행하세요. 자세히: {log}",
"cleanup.romfs_unreadable": "설치 후 {path}의 게임 데이터가 없거나 읽을 수 없습니다. Windows를 다시 시작한 다음 같은 폴더로 설치 프로그램을 다시 실행하세요. 게임 데이터만 다시 추출하고 나머지는 유지합니다.",
"prepare.pack_failed": "셰이더 캐시 묶기에 실패했습니다(종료 코드 {code}). 자세히: {log}",
"cleanup.ini_failed": "totk.ini를 쓸 수 없습니다: {detail}",
+2
View File
@@ -64,6 +64,7 @@
"check.vulkan_missing": "Er is geen Vulkan-stuurprogramma geïnstalleerd. Installeer het nieuwste stuurprogramma voor je videokaart.",
"check.vulkan_no_device": "Vulkan vindt geen videokaart. Installeer het nieuwste stuurprogramma voor je videokaart.",
"check.vulkan_too_old": "Het spel heeft een videokaart met Vulkan 1.3 nodig; gevonden: {devices}. Werk het grafische stuurprogramma bij.",
"check.libraries_missing": "Het spel kan op dit systeem niet starten: het heeft {libraries} nodig, dat het systeem niet heeft. Installeer het pakket dat het levert met de pakketbeheerder van het systeem{packages} en voer de installatie daarna opnieuw uit.",
"check.no_display": "Voor het voorbereiden van de shaders is een scherm nodig. Start de installatie vanuit de bureaubladsessie of exporteer DISPLAY=:0 (op een Steam Deck in de Gamemodus ook XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "De spelbestanden zijn nodig: kies het basisspel, de update 1.1.0, 1.2.1 of 1.4.3 en prod.keys.",
"check.input_missing": "Bestand niet gevonden ({input}): {path}",
@@ -106,6 +107,7 @@
"prepare.shader_list_missing": "De shaderlijst ontbreekt.",
"prepare.romfs_patches_failed": "Het schrijven van de spelgegevenspatches is mislukt (afsluitcode {code}). Details: {log}",
"prepare.shaders_failed": "Het voorbereiden van de shaders is mislukt (afsluitcode {code}). Details: {log}",
"prepare.libraries_missing": "Het spel is gebouwd maar kan niet starten: het systeem heeft {libraries} niet. Installeer het pakket dat het levert met de pakketbeheerder van het systeem{packages} en voer de installatie daarna opnieuw uit. Details: {log}",
"cleanup.romfs_unreadable": "De spelgegevens in {path} ontbreken of kunnen na de installatie niet worden gelezen. Start Windows opnieuw en voer het installatieprogramma opnieuw uit op dezelfde map: het pakt de spelgegevens opnieuw uit en behoudt de rest.",
"prepare.pack_failed": "Het verpakken van de shadercache is mislukt (afsluitcode {code}). Details: {log}",
"cleanup.ini_failed": "totk.ini kan niet worden geschreven: {detail}",
+2
View File
@@ -67,6 +67,7 @@
"check.vulkan_missing": "Nenhum driver Vulkan está instalado. Instale o driver mais recente da sua placa de vídeo.",
"check.vulkan_no_device": "O Vulkan não encontra nenhuma placa de vídeo. Instale o driver mais recente da sua placa de vídeo.",
"check.vulkan_too_old": "O jogo precisa de uma placa de vídeo com Vulkan 1.3; encontrado: {devices}. Atualize o driver de vídeo.",
"check.libraries_missing": "O jogo não pode iniciar neste sistema: ele precisa de {libraries}, que o sistema não tem. Instale o pacote que o fornece com o gerenciador de pacotes do sistema{packages} e execute o instalador de novo.",
"check.no_display": "Preparar os shaders exige uma tela. Execute a instalação na sessão da área de trabalho ou use export DISPLAY=:0 (no Steam Deck em Game Mode, também XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "Os arquivos do jogo são necessários: escolha o jogo base, a atualização 1.1.0, 1.2.1 ou 1.4.3 e o prod.keys.",
"check.input_missing": "Arquivo não encontrado ({input}): {path}",
@@ -110,6 +111,7 @@
"prepare.shader_list_missing": "A lista de shaders está faltando.",
"prepare.romfs_patches_failed": "Falha ao gravar os patches nos dados do jogo (código de saída {code}). Detalhes: {log}",
"prepare.shaders_failed": "Falha ao preparar os shaders (código de saída {code}). Detalhes: {log}",
"prepare.libraries_missing": "O jogo foi compilado, mas não pode iniciar: o sistema não tem {libraries}. Instale o pacote que o fornece com o gerenciador de pacotes do sistema{packages} e execute o instalador de novo. Detalhes: {log}",
"cleanup.romfs_unreadable": "Os dados do jogo em {path} estão faltando ou não podem ser lidos depois da instalação. Reinicie o Windows e execute o instalador de novo na mesma pasta: ele extrai os dados do jogo outra vez e mantém o resto.",
"prepare.pack_failed": "Falha ao juntar o cache de shaders (código de saída {code}). Detalhes: {log}",
"cleanup.ini_failed": "Não foi possível gravar o totk.ini: {detail}",
+2
View File
@@ -67,6 +67,7 @@
"check.vulkan_missing": "Драйвер Vulkan не установлен. Установите свежий драйвер видеокарты.",
"check.vulkan_no_device": "Vulkan не находит видеокарту. Установите свежий драйвер видеокарты.",
"check.vulkan_too_old": "Игре нужна видеокарта с Vulkan 1.3; найдено: {devices}. Обновите драйвер видеокарты.",
"check.libraries_missing": "Игра не может запуститься в этой системе: ей нужна библиотека {libraries}, которой в системе нет. Установите пакет с ней через менеджер пакетов системы{packages} и запустите установку снова.",
"check.no_display": "Для подготовки шейдеров нужен дисплей. Запустите установку из сеанса рабочего стола или выполните export DISPLAY=:0 (на Steam Deck в игровом режиме ещё XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "Нужны игровые файлы: выберите базовую игру, обновление 1.1.0 или 1.2.1 или 1.4.3 и prod.keys.",
"check.input_missing": "Файл не найден ({input}): {path}",
@@ -110,6 +111,7 @@
"prepare.shader_list_missing": "Нет списка шейдеров.",
"prepare.romfs_patches_failed": "Не удалось записать патчи данных игры (код выхода {code}). Подробности: {log}",
"prepare.shaders_failed": "Не удалось подготовить шейдеры (код выхода {code}). Подробности: {log}",
"prepare.libraries_missing": "Игра собрана, но не может запуститься: в системе нет библиотеки {libraries}. Установите пакет с ней через менеджер пакетов системы{packages} и запустите установку снова. Подробности: {log}",
"cleanup.romfs_unreadable": "Данные игры в {path} пропали или не читаются после установки. Перезагрузите Windows и запустите установщик снова на ту же папку: он заново распакует данные игры, остальное сохранится.",
"prepare.pack_failed": "Не удалось упаковать кэш шейдеров (код выхода {code}). Подробности: {log}",
"cleanup.ini_failed": "Не удаётся записать totk.ini: {detail}",
+2
View File
@@ -64,6 +64,7 @@
"check.vulkan_missing": "Chưa cài đặt trình điều khiển Vulkan nào. Hãy cài đặt trình điều khiển mới nhất cho card đồ họa của bạn.",
"check.vulkan_no_device": "Vulkan không tìm thấy card đồ họa nào. Hãy cài đặt trình điều khiển mới nhất cho card đồ họa của bạn.",
"check.vulkan_too_old": "Trò chơi cần card đồ họa hỗ trợ Vulkan 1.3; tìm thấy: {devices}. Hãy cập nhật trình điều khiển đồ họa.",
"check.libraries_missing": "Trò chơi không thể khởi động trên hệ thống này: cần {libraries}, nhưng hệ thống không có. Hãy cài gói cung cấp thư viện đó bằng trình quản lý gói của hệ thống{packages}, rồi chạy lại trình cài đặt.",
"check.no_display": "Cần có màn hình hiển thị để chuẩn bị shader. Hãy chạy trình cài đặt từ phiên làm việc trên màn hình nền (desktop), hoặc export DISPLAY=:0 (trên Steam Deck ở Game Mode thì thêm XDG_RUNTIME_DIR=/run/user/1000).",
"check.inputs_needed": "Cần có các tệp trò chơi: hãy chọn trò chơi gốc, bản cập nhật 1.1.0 hoặc 1.2.1 hoặc 1.4.3 và prod.keys.",
"check.input_missing": "Không tìm thấy tệp ({input}): {path}",
@@ -106,6 +107,7 @@
"prepare.shader_list_missing": "Thiếu danh sách shader.",
"prepare.romfs_patches_failed": "Ghi các bản vá dữ liệu trò chơi không thành công (mã thoát {code}). Chi tiết: {log}",
"prepare.shaders_failed": "Chuẩn bị shader không thành công (mã thoát {code}). Chi tiết: {log}",
"prepare.libraries_missing": "Trò chơi đã được biên dịch nhưng không thể khởi động: hệ thống không có {libraries}. Hãy cài gói cung cấp thư viện đó bằng trình quản lý gói của hệ thống{packages}, rồi chạy lại trình cài đặt. Chi tiết: {log}",
"cleanup.romfs_unreadable": "Dữ liệu trò chơi trong {path} bị thiếu hoặc không đọc được sau khi cài đặt. Hãy khởi động lại Windows, rồi chạy lại trình cài đặt trên cùng thư mục đó: trình cài đặt sẽ trích xuất lại dữ liệu trò chơi và giữ nguyên phần còn lại.",
"prepare.pack_failed": "Đóng gói bộ nhớ đệm shader không thành công (mã thoát {code}). Chi tiết: {log}",
"cleanup.ini_failed": "Không thể ghi totk.ini: {detail}",
+2
View File
@@ -67,6 +67,7 @@
"check.vulkan_missing": "未安装 Vulkan 驱动。请为你的显卡安装最新的驱动程序。",
"check.vulkan_no_device": "Vulkan 找不到显卡。请为你的显卡安装最新的驱动程序。",
"check.vulkan_too_old": "游戏需要支持 Vulkan 1.3 的显卡;检测到:{devices}。请更新显卡驱动程序。",
"check.libraries_missing": "游戏无法在此系统上启动:它需要 {libraries},但系统中没有。请用系统的软件包管理器安装提供它的软件包{packages},然后重新运行安装程序。",
"check.no_display": "准备着色器需要显示器。请在桌面会话中运行安装程序,或执行 export DISPLAY=:0(Steam Deck 游戏模式下还需 XDG_RUNTIME_DIR=/run/user/1000)。",
"check.inputs_needed": "需要游戏文件:请选择游戏本体、1.1.0、1.2.1 或 1.4.3 更新以及 prod.keys。",
"check.input_missing": "找不到文件({input}):{path}",
@@ -110,6 +111,7 @@
"prepare.shader_list_missing": "缺少着色器列表。",
"prepare.romfs_patches_failed": "写入游戏数据补丁失败(退出代码 {code})。详情:{log}",
"prepare.shaders_failed": "准备着色器失败(退出代码 {code})。详情:{log}",
"prepare.libraries_missing": "游戏已编译,但无法启动:系统中没有 {libraries}。请用系统的软件包管理器安装提供它的软件包{packages},然后重新运行安装程序。详情:{log}",
"cleanup.romfs_unreadable": "安装完成后,{path} 中的游戏数据缺失或无法读取。请重启 Windows,然后对同一文件夹再次运行安装程序:它会重新提取游戏数据,其余内容保留。",
"prepare.pack_failed": "打包着色器缓存失败(退出代码 {code})。详情:{log}",
"cleanup.ini_failed": "无法写入 totk.ini:{detail}",
+13 -6
View File
@@ -60,7 +60,8 @@ run's record; the design follows #845 by itaskaev2):
sha256> is that .text's hash: the runtime compares it with the .text its own run of the init leaves, and keeps the
set off when they differ.
- `expect`: one word the init writes into a game module (the hook branches into main's .text); the runtime compares
the words its run of the init wrote with these, all or nothing per plugin.
the words its run of the init wrote with these, all or nothing per plugin. `*` for <old> and <new> matches the word
by place only: a word of main's .data or .bss that shapes no lifted code and may differ at play.
- `stub`: an exlaunch inline-hook entry stub (stur x30; bl impl; ldur x30; b trampoline; .quad callback). Its fourth
word is lifted as a `ret`: the generated site calls the stub and runs its own original instruction after it
(`@call` below), so the trampoline (the original relocated, b site+4) never runs.
@@ -119,7 +120,8 @@ class Table:
self.spins = spins or {} # {module: {back-edge offset: head offset}}
self.hooks = hooks or {} # {module: {function offset}}; empty: FN_ENTER in every function
self.ordered = set(ordered)
# {module: {'set', 'sha256', 'image', 'expect': [(module, offset, old, new)], 'stubs': {offset},
# {module: {'set', 'sha256', 'image', 'expect': [(module, offset, old, new)] (old and new None for `* *`),
# 'stubs': {offset},
# 'seeds': {offset}, 'origs': {trampoline offset: (function module, function offset)}}}; empty without
# plugin lines
self.plugins = plugins or {}
@@ -296,7 +298,10 @@ def plugin_line(f, where, index, bases, plugins):
owner = [p for p in plugins.values() if p['set'] == index[f[1]]]
if not owner:
raise PatchError(f'{where}: set {f[1]} owns no plugin')
owner[0]['expect'].append((f[2], int(f[3], 16), int(f[4], 16), int(f[5], 16)))
if (f[4] == '*') != (f[5] == '*'):
raise PatchError(f'{where}: `*` for one of old and new only')
words = (None, None) if f[4] == '*' else (int(f[4], 16), int(f[5], 16))
owner[0]['expect'].append((f[2], int(f[3], 16), *words))
elif f[0] == 'stub' and len(f) == 3:
plugin(f[1])['stubs'].add(int(f[2], 16))
elif f[0] == 'seed' and len(f) >= 3:
@@ -345,14 +350,16 @@ def header_text(table, marker):
enumerate(table.sets)), '']
if table.plugins: # none: the header is what it was before plugins
names = sorted(table.plugins)
writes = [f'X({i}, "{m}", {o:#x}, {old:#010x}u, {new:#010x}u)' for i, n in enumerate(names)
for m, o, old, new in sorted(table.plugins[n]['expect'])]
writes = [f'X({i}, "{m}", {o:#x}, {old or 0:#010x}u, {new or 0:#010x}u, {int(old is None)})'
for i, n in enumerate(names)
for m, o, old, new in sorted(table.plugins[n]['expect'], key=lambda e: e[:2])]
lines += [f'#define RT_PLUGIN_COUNT {len(names)}',
'// X(index, module, its set, SHA-256 of its .text after the init)',
'#define RT_PLUGINS(X) ' + ' '.join(f'X({i}, "{n}", {table.plugins[n]["set"]}, '
f'"{table.plugins[n]["sha256"]}")' for i, n in enumerate(names)),
f'#define RT_PLUGIN_WRITE_COUNT {len(writes)}',
'// X(plugin index, module, offset, old word, new word): what the init writes into game modules',
'// X(plugin index, module, offset, old word, new word, 1: any words, matched by place only): what '
'the init writes into game modules',
'#define RT_PLUGIN_WRITES(X) ' + ' '.join(writes),
'// X(module, offset): the hook entries (seed lines) TOTK_PLUGIN_TRACE counts (runtime/plugin_init.c)',
'#define RT_PLUGIN_ROOTS(X) ' + ' '.join(f'X("{n}", {o:#x})' for n in names
+34 -17
View File
@@ -33,7 +33,7 @@ static int save_ok = 1; // the last cfg_save_to wrote (o
// logged as unknown. A new variable goes here too, or its ini key logs a harmless "unknown key" line, and gets a
// description in totk.ini.example or docs/settings.md (tests/settings_doc_check.py checks both).
static const char *const known[] = {
"AB", "ABILITY_GUARD", "ADDR_REPORT", "AMIIBO_DIR", "ANISO", "ANV_VS_BARRIER", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_CHANNELS", "AUDIO_DEVICE", "AUDIO_DRAIN_FIX", "AUDIO_OFF", "AUDIO_PREFILL_MS",
"AB", "ABILITY_GUARD", "ADDR_REPORT", "AMIIBO_DIR", "ANISO", "ANV_VS_BARRIER", "AP_FIRST_US", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_CHANNELS", "AUDIO_DEVICE", "AUDIO_DRAIN_FIX", "AUDIO_OFF", "AUDIO_PREFILL_MS",
"BACKGROUND_WINDOW", "BIND_A", "BIND_B", "BIND_DOWN", "BIND_L", "BIND_LCLICK", "BIND_LEFT", "BIND_LSTICK_DOWN", "BIND_LSTICK_LEFT",
"BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS",
"BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP",
@@ -41,7 +41,7 @@ static const char *const known[] = {
"BIND_INC", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y",
"BIND_ZL", "BIND_ZR", "BARRIER_MERGE", "BLOCK_VIEWS_3D", "CLIMB_FIX", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA",
"COLOR_PRESET", "COLOR_SATURATION", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT",
"DESC_TEMPLATE", "DESWIZZLE", "DEVICE_PROFILE", "DIALOGUE_CLICK", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_CAM_JITTER", "DLAA_EFFECTS_AFTER", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_FIXED_EXPOSURE", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR",
"DEMOTE", "DESC_TEMPLATE", "DESWIZZLE", "DEVICE_PROFILE", "DIALOGUE_CLICK", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_CAM_JITTER", "DLAA_EFFECTS_AFTER", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_FIXED_EXPOSURE", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR",
"DUMP_LOG", "DYNAMIC_RES", "DYN_DELTA", "EXEFS", "FEEDBACK", "FG_DEBUG", "FG_OBJECTS", "FG_SHOT", "FG_SHOT_DIR", "FG_TEST", "FG_TIMES", "FIXED_RES_PATCH", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES",
"FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FLUSH_SPAN", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FRAME_GEN", "FRAME_QUEUE", "FREECAM_KEY", "FREECAM_PAD", "FREECAM_PATCH",
"FREEZE_IDLE", "FREE_CORES", "FSR3_DEBUG", "FSR3_VIEW", "FSR4_DEBUG", "FSR_SHARPNESS",
@@ -52,21 +52,21 @@ static const char *const known[] = {
"GAMEPLAY_WEAPON_WHEEL",
"GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "GRASS_RANGE",
"GYRO_AUTO_BIAS", "GYRO_BIAS_PAD", "GYRO_BIAS_X", "GYRO_BIAS_Y", "GYRO_BIAS_Z", "GYRO_CALIBRATION", "HDR", "HDR_GAME_NITS", "HDR_HUE",
"HDR_PEAK_NITS", "HDR_UI_NITS", "HIGHFPS_FIX", "HUD_WIDTH", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "KSPIN_US", "LANG", "LIB_PREBUILD",
"HOST_CHECKPOINT", "HDR_PEAK_NITS", "HDR_UI_NITS", "HEAP_LAZY", "HIGHFPS_FIX", "HUD_WIDTH", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "KSPIN_US", "LANG", "LIB_PREBUILD",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LIGHTNING_FIX", "LOCALE", "LOD_GUARD", "LOD_STEADY", "LSTICK_DEADZONE", "MAP_CLICK", "MEMORY", "MEMX", "MENU_LANG", "MENU_TEST", "MENU_FONT_FONTCONFIG",
"MEM_RESERVE_MIB", "MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_NO_CODE", "MODS_ORDER", "MODS_REBUILD", "MODS_WITHOUT_CODE", "MOTION", "MOUSE_AIM_SCALE", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_ASPECT", "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", "NULL_ATTACH",
"ONE_PER_CORE", "OPERATION_MODE", "OPTREF_GUARD", "OUTPUT_RES", "PAD_LAYOUT", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_SCENE", "PCORE", "PCSS", "PCSS_K", "PERF_CENSUS", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PLUGIN_TICK_OFFSET", "PLUGIN_TRACE", "POINTER_IMAGE",
"ONE_PER_CORE", "OPERATION_MODE", "OPTREF_GUARD", "OUTPUT_RES", "PAD_BACKGROUND", "PAD_LAYOUT", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_SCENE", "PCORE", "PCSS", "PCSS_K", "PERF_CENSUS", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PLUGIN_TICK_OFFSET", "PLUGIN_TRACE", "POINTER_IMAGE",
"PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_BENCH", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES",
"PROFILE_MAIN", "PROFILE_RENDER", "PROMPTS", "PUSH_SKIP", "PUSH_STAGE", "QUICKLOAD_KEY", "QUICKSAVE", "QUICKSAVE_KEY", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_ASYNC", "REC_END", "REC_SPIN_US", "REEXEC", "REFLEX",
"RENDER_SCALE", "REPLAY_ASYNC", "REPLAY_CHUNKS", "REPLAY_CHUNK_DRAWS", "REPLAY_SKEW_US", "REPLAY_STATE_CHECK", "REPLAY_WORKERS",
"REPLAY_CHECK", "REPORT_GUARD", "RESOLVE_CHECK", "RESTART_WAIT", "RESTBL_CACHE", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
"ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RSTICK_DEADZONE", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SCENE_UPSCALER", "SHADER_CACHE",
"SHADER_MEMO", "SHADOW", "SHADOW_DEFER", "SHADOW_RANGE", "SHADOW_RES", "SHADOW_SCALE", "SHADOW_SNAP", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHUTTER_FIX",
"SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "STICK_SENS",
"SHOTS_FULL", "SKIP_CS", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "STICK_SENS",
"SWKBD_ANSWER", "SYNC_AHEAD",
"SWKBD_TEST", "TEST_OOM", "TEST_PAD", "TEST_PAD_RUMBLE_MS", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_BLOCK_MIB", "TEX_HEAP_EXTRA_MB", "TEX_MEMO", "TEX_RELEASED_MIB", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "UB_OVERLAY", "UB_OVERLAY_OUT", "UPSCALER", "VB_USED", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64", "VK_NO_HOST_IMPORT",
"SWKBD_TEST", "TEST_OOM", "TEST_PAD", "TEST_PAD_RUMBLE_MS", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_BLOCK_MIB", "TEX_HEAP_EXTRA_MB", "TEX_MEMO", "TEX_RELEASED_MIB", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "UB_OVERLAY", "UB_OVERLAY_OUT", "UPSCALER", "VB_USED", "VERT_PLUS", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64", "VK_NO_HOST_IMPORT",
"VK_PRESENT", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VMA_BLOCK_MIB", "VOLUME", "VOLUME_MASK_BIAS", "VOLUME_MUSIC", "VOLUME_SFX", "VOLUME_VOICE", "VRAM_HEADROOM", "VRAM_LIMIT_MIB", "VS_OUTS",
"WALK_KEY", "WALK_SCALE", "WB_EAGER", "WB_EXACT", "WB_FENCE_LIMIT", "WB_MERGE", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_KEEP", "XLATE_PROCS",
"ZSTD_CHECK", "ZSTD_NATIVE",
@@ -81,7 +81,7 @@ static const struct { const char *key, *section; } sections[] = {
{"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"},
{"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"},
{"HUD_WIDTH", "display"},
{"SHARPNESS", "display"}, {"DYNAMIC_RES", "display"}, {"ASPECT", "display"}, {"MOVIE_ASPECT", "display"}, {"FOV", "display"}, {"ANISO", "display"},
{"SHARPNESS", "display"}, {"DYNAMIC_RES", "display"}, {"ASPECT", "display"}, {"MOVIE_ASPECT", "display"}, {"FOV", "display"}, {"VERT_PLUS", "display"}, {"ANISO", "display"},
{"LOD_STEADY", "display"}, {"COLOR_PRESET", "display"},
{"COLOR_BRIGHTNESS", "display"}, {"COLOR_CONTRAST", "display"}, {"COLOR_SATURATION", "display"},
{"COLOR_GAMMA", "display"}, {"HDR", "display"}, {"HDR_PEAK_NITS", "display"}, {"HDR_GAME_NITS", "display"},
@@ -98,7 +98,7 @@ static const struct { const char *key, *section; } sections[] = {
{"AUDIO_DEVICE", "audio"},
{"MOTION", "input"}, {"GYRO_CALIBRATION", "input"}, {"GYRO_AUTO_BIAS", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"},
{"GYRO_BIAS_X", "input"}, {"GYRO_BIAS_Y", "input"}, {"GYRO_BIAS_Z", "input"}, {"GYRO_BIAS_PAD", "input"},
{"PAD_LAYOUT", "input"}, {"PROMPTS", "input"}, {"STICK_DEADZONE", "input"}, {"LSTICK_DEADZONE", "input"}, {"RSTICK_DEADZONE", "input"},
{"PAD_BACKGROUND", "input"}, {"PAD_LAYOUT", "input"}, {"PROMPTS", "input"}, {"STICK_DEADZONE", "input"}, {"LSTICK_DEADZONE", "input"}, {"RSTICK_DEADZONE", "input"},
{"STICK_SENS", "input"},
{"MENU_CURSOR", "input"}, {"MAP_CLICK", "input"}, {"DIALOGUE_CLICK", "input"}, {"POINTER_IMAGE", "input"}, {"QUICKSAVE", "input"}, {"QUICKSAVE_KEY", "input"}, {"QUICKLOAD_KEY", "input"}, {"MOUSE_MODE", "input"}, {"MOUSE_SENS", "input"}, {"MOUSE_AIM_SCALE", "input"}, {"WALK_KEY", "input"}, {"WALK_SCALE", "input"}, {"FREECAM_PATCH", "input"}, {"FREECAM_PAD", "input"}, {"FREECAM_KEY", "input"}, {"INPUT_RECORD", "input"},
{"BIND_A", "input"}, {"BIND_B", "input"}, {"BIND_X", "input"}, {"BIND_Y", "input"}, {"BIND_LCLICK", "input"},
@@ -107,11 +107,11 @@ static const struct { const char *key, *section; } sections[] = {
{"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_SHAKE", "input"},
{"ASYNC_PREEMPT", "performance"}, {"REPLAY_ASYNC", "performance"}, {"REPLAY_WORKERS", "performance"}, {"FREE_CORES", "performance"},
{"ASYNC_PREEMPT", "performance"}, {"HOST_CHECKPOINT", "performance"}, {"REPLAY_ASYNC", "performance"}, {"REPLAY_WORKERS", "performance"}, {"FREE_CORES", "performance"},
{"TIMER_1MS", "performance"}, {"PIPE_WAIT", "performance"}, {"PIPE_SKIP", "performance"},
{"BARRIER_MERGE", "performance"}, {"LIB_PREBUILD", "performance"}, {"LIB_PREBUILD_THREADS", "performance"}, {"PIPE_PREBUILD", "performance"},
{"PREWARM_XLATE", "performance"}, {"GPL", "performance"}, {"ASTC", "performance"}, {"MEMORY", "performance"},
{"TEX_ALIAS", "performance"}, {"TEX_VRAM_PRESSURE", "performance"}, {"TEX_RELEASED_MIB", "performance"}, {"TEX_BLOCK_MIB", "performance"}, {"VMA_BLOCK_MIB", "performance"}, {"ASTC_BC", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"},
{"TEX_ALIAS", "performance"}, {"TEX_VRAM_PRESSURE", "performance"}, {"TEX_RELEASED_MIB", "performance"}, {"TEX_BLOCK_MIB", "performance"}, {"VMA_BLOCK_MIB", "performance"}, {"ASTC_BC", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"}, {"DEMOTE", "performance"},
{"BIND_SKIP", "performance"}, {"SHADER_MEMO", "performance"}, {"PIPE_MEMO", "performance"}, {"MEMX", "performance"}, {"BIND_INC", "performance"}, {"TEX_MEMO", "performance"}, {"VB_USED", "performance"}, {"DESC_TEMPLATE", "performance"},
{"SYNC_AHEAD", "performance"}, {"SHADOW_DEFER", "performance"}, {"PUSH_SKIP", "performance"}, {"SPLIT_DRAWS", "performance"}, {"SPLIT_US", "performance"}, {"VK_VALIDATION", "performance"},
{"VK_DYN_VERTEX", "performance"}, {"VK_DYN_A2C", "performance"}, {"VK_SUBGROUP_PIN", "performance"},
@@ -149,6 +149,7 @@ static const CfgMeta metas[] = {
{"DLSS_CHAR_MASK", "65", "0|35|65|100", LIVE}, {"REFLEX", "off", "off|auto|on|boost", RESTART}, {"FXAA", "1", "0|1", LIVE},
{"LOD_STEADY", "0", "0|1", RESTART}, // sets steady
{"ASPECT", "fit", "fit|stretch", LIVE}, {"MOVIE_ASPECT", "keep", "keep|stretch", LIVE}, {"FOV", "100", "70..140", LIVE},
{"VERT_PLUS", "0", "0|1", LIVE}, // resolution.c res_fov_live
{"ANISO", "game", "game|2|4|8|16", RESTART}, // vk_texture.c sampler_features
// colour adjustment (vk_color.c); the preset is the menu's, the four values are what the present uses
{"COLOR_PRESET", "default", "default|vivid|clarity|custom", LIVE}, {"COLOR_BRIGHTNESS", "0", "-30..30", LIVE},
@@ -183,6 +184,7 @@ static const CfgMeta metas[] = {
{"GYRO_BIAS_X", "", NULL, RESTART}, {"GYRO_BIAS_Y", "", NULL, RESTART}, {"GYRO_BIAS_Z", "", NULL, RESTART},
{"GYRO_BIAS_PAD", "", NULL, RESTART},
{"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox", LIVE},
{"PAD_BACKGROUND", "auto", "auto|0|1", RESTART}, // input.c start: SDL's background joystick events (#971, #1462)
{"PROMPTS", "nintendo", "nintendo|xbox|playstation|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},
@@ -214,15 +216,16 @@ static const CfgMeta metas[] = {
{"DISCORD_APP_ID", "1567232599846293504", NULL, LIVE},
{"DISCORD_IMAGE", "totk_512x512", NULL, LIVE},
// Advanced: scheduling
{"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "0", "0|1", RESTART},
{"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"HOST_CHECKPOINT", "1", "0|1", RESTART},
{"REPLAY_ASYNC", "0", "0|1", RESTART},
{"REPLAY_WORKERS", "0", "0..16", RESTART}, {"REPLAY_CHUNKS", "0", "0..64", RESTART},
{"REPLAY_CHUNK_DRAWS", "128", "1..100000", RESTART}, {"REPLAY_STATE_CHECK", "0", "0|1", RESTART},
{"REPLAY_SKEW_US", "0", "0..100000", RESTART},
{"SYNC_AHEAD", "0", "0|1|check", RESTART}, {"SHADOW_DEFER", "1", "0|1", RESTART},
{"SYNC_AHEAD", "1", "0|1|check", RESTART}, {"SHADOW_DEFER", "1", "0|1", RESTART},
{"FREE_CORES", "0", "0|1", RESTART}, {"TIMER_1MS", "1", "0|1", RESTART},
// shaders and pipelines
{"PIPE_WAIT", "default", "default|draw", RESTART}, {"PIPE_SKIP", "fullscreen", "strict|any|fullscreen", RESTART},
{"BARRIER_MERGE", "0", "0|1", RESTART}, {"LIB_PREBUILD", "1", "0|1", RESTART}, {"LIB_PREBUILD_THREADS", "", "1..64", RESTART},
{"BARRIER_MERGE", "1", "0|1", RESTART}, {"LIB_PREBUILD", "1", "0|1", RESTART}, {"LIB_PREBUILD_THREADS", "", "1..64", RESTART},
{"PIPE_PREBUILD", "1", "0|1", RESTART}, {"PREWARM_XLATE", "", "1..64", RESTART}, {"GPL", "1", "0|1", RESTART},
// textures and memory
{"ASTC", "auto", "auto|gpu|native|cpu", RESTART}, {"MEMORY", "auto", "auto|import|mirror|verify", RESTART},
@@ -232,6 +235,7 @@ static const CfgMeta metas[] = {
{"OPTREF_GUARD", "1", "0|1", RESTART}, {"ABILITY_GUARD", "1", "0|1", RESTART}, {"REPORT_GUARD", "1", "0|1", RESTART},
// render fixes
{"LOD_GUARD", "1", "0|1", RESTART}, {"FIX_C0", "1", "0|1", RESTART}, {"FIX_ZERO", "1", "0|1", RESTART},
{"DEMOTE", "", "0|1", RESTART}, // vk_pipeline.c spirv_demote: 1 on AMD's own driver, else 0
{"BIND_SKIP", "1", "0|1", RESTART}, {"SHADER_MEMO", "1", "0|1", RESTART}, {"PIPE_MEMO", "1", "0|1", RESTART}, {"MEMX", "1", "0|1|check", RESTART}, {"BIND_INC", "0", "0|1|check", RESTART}, {"TEX_MEMO", "1", "0|1", RESTART},
{"VB_USED", "1", "0|1", RESTART},
{"DESC_TEMPLATE", "1", "0|1", RESTART},
@@ -406,15 +410,24 @@ static const char *raw_get(const char *name) {
// the Switch ones.
static const unsigned SHAPED[][2] = {
{2560, 1080}, {3440, 1440}, {3840, 1600}, {5120, 2160}, // 21:9
{3840, 1080}, {5120, 1440}, // 32:9
{3840, 1080}, {5120, 1440}, {7680, 2160}, // 32:9
{1280, 800}, {1680, 1050}, {1920, 1200}, {2560, 1600}, // 16:10
{1920, 1280}, {2160, 1440}, {2256, 1504}, {2880, 1920}, {3000, 2000}, // 3:2
{1440, 1080}, {1600, 1200}, {2048, 1536}, {2732, 2048}, // 4:3 (CRT monitors, iPads)
{2340, 1080}, {3120, 1440}, {2400, 1080}, {3200, 1440}, // 19.5:9 and 20:9 (phones, streamed)
};
// The shapes a UI layout can be made for (tools/ultrawide_layout.py works on any aspect ratio between these): from 4:3
// to 32:9, 1% either side. A shape between them that SHAPED does not list takes a folder of its own exact size.
#define SHAPE_MIN (4.0 / 3.0 * 0.99)
#define SHAPE_MAX (32.0 / 9.0 * 1.01)
// The folder size of w x h's shape: of SHAPED within 1% of its aspect ratio, the closest, the first of equal ones
// (5120x2160 takes 2560x1080). The UI layout depends on the aspect ratio alone (tools/ultrawide_layout.py apply), so
// the setup writes one romfs-patches-<w>x<h> per shape, named after this size (installer/screens.py shape_size, the
// same rule), and romfs.c overlay_init looks for it. 0 for 16:9 and for a shape without a layout.
// same rule), and romfs.c overlay_init looks for it. A shape SHAPED does not list but within SHAPE_MIN..SHAPE_MAX (a
// phone's 13:6 screen streamed to, say) is its own folder, w x h itself, which the setup and the game's background
// generator make as they make the listed ones. 0 for 16:9 and outside that range (portrait screens).
int cfg_shape_size(unsigned w, unsigned h, unsigned out[2]) {
if (!w || !h) return 0;
double r = (double)w / h, err = 0;
@@ -424,8 +437,12 @@ int cfg_shape_size(unsigned w, unsigned h, unsigned out[2]) {
double e = fabs((double)SHAPED[i][0] / SHAPED[i][1] / r - 1);
if (e <= 0.01 && (best < 0 || e < err)) best = i, err = e;
}
if (best < 0) return 0;
out[0] = SHAPED[best][0], out[1] = SHAPED[best][1];
if (best >= 0) {
out[0] = SHAPED[best][0], out[1] = SHAPED[best][1];
return 1;
}
if (r < SHAPE_MIN || r > SHAPE_MAX) return 0;
out[0] = w, out[1] = h;
return 1;
}
+3 -2
View File
@@ -23,8 +23,9 @@ unsigned cfg_version(void);
int cfg_from_env(const char *name);
// 1 when the player set name (the environment or totk.ini), 0 when cfg_get gives a device profile's default or NULL.
int cfg_is_set(const char *name);
// The folder size of w x h's shape (cfg.c SHAPED: the closest aspect ratio within 1%, the first of equal ones), the
// one romfs-patches-<w>x<h> the setup writes for it. 0 for 16:9 and for a shape without a UI layout.
// The folder size of w x h's shape (cfg.c SHAPED: the closest aspect ratio within 1%, the first of equal ones; an
// unlisted shape from 4:3 to 32:9 keeps w x h), the one romfs-patches-<w>x<h> the setup writes for it. 0 for 16:9 and
// for a shape without a UI layout (portrait, narrower than 4:3, wider than 32:9).
int cfg_shape_size(unsigned w, unsigned h, unsigned out[2]);
// The size output_res defaults to on this display (its shape, cfg.c screen_default) while the player set no
// output_res, also when the default stays 1920x1080 because that shape lacks the prompts' folder. The generator the game
+21 -4
View File
@@ -146,6 +146,8 @@ int probe_cfg(void) {
CHECK(m && EQ(m->def, "130") && EQ(m->values, "0..300"), "meta: rumble strength 130 in 0..300");
m = cfg_meta("PERF_OVERLAY");
CHECK(m && EQ(m->def, "off") && EQ(m->values, "off|fps|full") && m->live, "meta: perf_overlay is live, off by default");
m = cfg_meta("VERT_PLUS");
CHECK(m && EQ(m->def, "0") && m->live, "meta: vert_plus is live, off by default");
CHECK(cfg_meta("BIND_A") == NULL && cfg_meta("FPS_COUNTER") == NULL && cfg_meta("NO_SUCH") == NULL,
"meta: keys the menu does not show are NULL");
@@ -315,6 +317,12 @@ int probe_cfg(void) {
CHECK(input_pad_layout_pick("xbox_prompts", 0) == PAD_LAYOUT_NINTENDO &&
input_pad_layout_pick("Xbox_Prompts", 1) == PAD_LAYOUT_NINTENDO,
"pad layout: 0.1.9's xbox_prompts keeps the Nintendo positions (only the prompts change, romfs.c overlay_init)");
// Gamepad events behind other windows (input_map.c, input.c start)
CHECK(input_pad_background_pick("auto", 0) && !input_pad_background_pick("auto", 1) &&
input_pad_background_pick(NULL, 0) && !input_pad_background_pick(NULL, 1),
"pad background: automatic is on, off when Steam started the game (its overlay takes the gamepad, #1462)");
CHECK(input_pad_background_pick("1", 1) && !input_pad_background_pick("0", 0),
"pad background: 1 and 0 win over the Steam check");
// Button prompts (input_map.c)
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,
@@ -357,16 +365,25 @@ int probe_cfg(void) {
"prompts: the PlayStation folder puts A on the circle exactly when the layout puts A on the east button");
}
// One folder per screen shape (cfg.c cfg_shape_size, installer/screens.py shape_size): the closest aspect ratio of
// SHAPED within 1%, the first of equal ones; 16:9 and unlisted shapes have none.
// SHAPED within 1%, the first of equal ones; an unlisted shape from 4:3 to 32:9 its own size; 16:9, portrait and
// shapes narrower than 4:3 none.
unsigned sz[2] = {0, 0};
CHECK(cfg_shape_size(5120, 2160, sz) && sz[0] == 2560 && sz[1] == 1080, "shape: 5120x2160 takes 2560x1080's folder");
CHECK(cfg_shape_size(3440, 1440, sz) && sz[0] == 3440 && sz[1] == 1440, "shape: 3440x1440 keeps its own (0.8% off 2560x1080)");
CHECK(cfg_shape_size(1920, 800, sz) && sz[0] == 3840 && sz[1] == 1600, "shape: 1920x800 takes 3840x1600's folder");
CHECK(cfg_shape_size(2560, 1600, sz) && sz[0] == 1280 && sz[1] == 800 && cfg_shape_size(3000, 2000, sz) &&
sz[0] == 1920 && sz[1] == 1280 && cfg_shape_size(5120, 1440, sz) && sz[0] == 3840 && sz[1] == 1080,
sz[0] == 1920 && sz[1] == 1280 && cfg_shape_size(5120, 1440, sz) && sz[0] == 3840 && sz[1] == 1080 &&
cfg_shape_size(7680, 2160, sz) && sz[0] == 3840 && sz[1] == 1080,
"shape: 16:10, 3:2 and 32:9 take their first size");
CHECK(!cfg_shape_size(1920, 1080, sz) && !cfg_shape_size(2560, 1440, sz) && !cfg_shape_size(1024, 768, sz),
"shape: none for 16:9 and 4:3");
CHECK(cfg_shape_size(1024, 768, sz) && sz[0] == 1440 && sz[1] == 1080 && cfg_shape_size(2048, 1536, sz) &&
sz[0] == 1440 && sz[1] == 1080 && cfg_shape_size(3120, 1440, sz) && sz[0] == 2340 && sz[1] == 1080,
"shape: 4:3 and 19.5:9 take their first size");
CHECK(cfg_shape_size(2560, 1200, sz) && sz[0] == 2560 && sz[1] == 1200 && cfg_shape_size(2000, 1080, sz) &&
sz[0] == 2000 && sz[1] == 1080,
"shape: an unlisted shape between 4:3 and 32:9 keeps its own size");
CHECK(!cfg_shape_size(1920, 1080, sz) && !cfg_shape_size(2560, 1440, sz) && !cfg_shape_size(1280, 1024, sz) &&
!cfg_shape_size(1080, 1920, sz) && !cfg_shape_size(7680, 1440, sz),
"shape: none for 16:9, narrower than 4:3, portrait and wider than 32:9");
// romfs.c shaped_name: the exact size's folder (an older setup wrote every size) wins, else the shape's
{
char dir[1100], f[1200];
+1
View File
@@ -62,6 +62,7 @@ static float sample(V p, float *r, float *g, float *b) {
float a = ds < -0.8f ? 1 : (0.8f - ds) / 1.6f;
return 0.38f * a;
}
*r = *g = *b = 0;
return 0;
}
+1
View File
@@ -1024,6 +1024,7 @@ static uint32_t write_file(uint64_t h, int64_t offset, const void *buffer, uint6
if (!plat_file_id(f, &id)) rt_fatal("fs: host save size");
if ((uint64_t)offset + size > id.size && !(mode & FS_OPEN_APPEND)) return FS_R_APPEND_REQUIRED;
if (file->save) save_touched();
mem_heap_commit((uintptr_t)buffer, size); // TOTK_HEAP_LAZY: the kernel reads the buffer, so its chunks must exist
for (uint64_t done = 0; done < size;) {
uint32_t chunk = size - done > 0x40000000 ? 0x40000000 : (uint32_t)(size - done);
int64_t put = plat_file_pwrite(f, (const uint8_t *)buffer + done, chunk, (uint64_t)offset + done);
+3
View File
@@ -27,6 +27,8 @@
#include "vk.h"
#include "platform/platform.h"
int swkbd_sdl_event(const SDL_Event *e); // swkbd_sdl.c: the text entry window's events
static SDL_Window *g_win;
static uint32_t g_ev_base; // SDL_RegisterEvents: the user events below
enum { EV_RUN, EV_SETTINGS, EV_CLOSE, EV_COUNT };
@@ -158,6 +160,7 @@ static void handle(const SDL_Event *e) {
}
if (e->type == g_ev_base + EV_CLOSE) gfx_window_closed();
if (!g_win) return;
if (swkbd_sdl_event(e)) return;
input_sdl_event(e);
menu_sdl_event(e);
switch (e->type) {
+10
View File
@@ -148,6 +148,8 @@ void mem_init(void); // reserve every regi
const RtGuestLayout *mem_layout(void);
uint32_t mem_set_heap_size(uint64_t size, uint64_t *addr); // 0x01
uint32_t mem_set_permission(uint64_t a, uint64_t n, uint32_t perm); // 0x02
extern int mem_plugin_writes; // plugin_init.c plugins_start: a mod plugin is on; read-only module data stays writable
// on the host (mem_set_permission)
uint32_t mem_set_attribute(uint64_t a, uint64_t n, uint32_t mask, uint32_t at); // 0x03
uint32_t mem_map(uint64_t dst, uint64_t src, uint64_t n); // 0x04
uint32_t mem_unmap(uint64_t dst, uint64_t src, uint64_t n); // 0x05
@@ -177,6 +179,14 @@ void mem_thaw(uint64_t a, uint64_t n); // makes the frozen r
void mem_freeze_stats(uint64_t *frozen, uint64_t *freezes, uint64_t *fault_thaws, uint64_t *other_thaws);
// regions frozen now; freezes and thaws since the last call
void mem_kernel_free(void *p, uint64_t size); // TLR/TLS reuse after thread exit
int mem_heap_lazy(void); // TOTK_HEAP_LAZY is on (Windows): heap pages commit on first use
void mem_heap_commit(uint64_t a, uint64_t n); // commits the not yet committed heap chunks of [a, a+n) before
// the kernel reads them; nothing when mem_heap_lazy is 0
void mem_heap_lazy_stats(uint64_t *faults, uint64_t *ns, uint64_t *committed, uint64_t *size);
// TOTK_HEAP_LAZY: first-use faults and their time since
// the start, committed heap bytes, heap size
uint64_t mem_heap_uncommitted(void); // heap bytes set by SetHeapSize but not committed yet
// (TOTK_HEAP_LAZY): commit the game can still claim
int mem_guest_readable(uint64_t a, uint64_t n); // [a, a+n) can be read without a fault: inside a loaded
// module or the committed heap answered from the layout,
// anything else by plat_mem_readable (an OS query)
+17 -3
View File
@@ -671,9 +671,23 @@ static void start(void) {
// window lacks keyboard focus (SDL_PrivateJoystickShouldIgnoreEvent in SDL_joystick.c; centring and releases
// pass). That applies where the window is SDL's (Linux); the Win32 window on Windows is not an SDL window. The
// game keeps running out of focus by default (TOTK_ASSUME_FOCUS, ov_system.c oe_set_focus), so the gamepad has to
// keep working there. With the setting off the game's main thread waits while unfocused and reads no input, so
// the hint can stay on for the whole run.
SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
// keep working there (#971). With the setting off the game's main thread waits while unfocused and reads no input,
// so the hint can stay on for the whole run. A game Steam started is the exception (input_pad_background_pick):
// Steam's overlay and menus take the focus while they are open, and the presses meant for them reached the game
// too (#1462). Steam sets SteamGameId for its own games and for non-Steam shortcuts, SteamOverlayGameId with the
// overlay. TOTK_PAD_BACKGROUND = 1 or 0 decides it either way. On Windows the game window is not SDL's, so SDL never
// drops events for focus there and the Steam check is left out: the hint stays as it was.
#ifdef _WIN32
int under_steam = 0;
#else
const char *gid = getenv("SteamGameId"), *ogid = getenv("SteamOverlayGameId");
int under_steam = (gid && *gid) || (ogid && *ogid);
#endif
const char *bg = cfg_value("TOTK_PAD_BACKGROUND");
if (input_pad_background_pick(bg, under_steam)) SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
else
rt_log("input: the gamepad pauses while the window has no focus (%s)",
strcmp(bg, "0") ? "Steam started the game; pad_background = 1 keeps it" : "pad_background = 0");
if (!SDL_Init(SDL_INIT_GAMEPAD)) { state = -1; rt_log("input: SDL gamepad init failed (%s), keyboard only", SDL_GetError()); }
else state = 1;
if (state == 1) test_pad_attach();
+6
View File
@@ -305,6 +305,12 @@ int input_pad_layout_pick(const char *setting, int east_labelled_a) {
return east_labelled_a ? PAD_LAYOUT_NINTENDO : PAD_LAYOUT_XBOX;
}
int input_pad_background_pick(const char *setting, int under_steam) {
if (setting && !strcmp(setting, "1")) return 1;
if (setting && !strcmp(setting, "0")) return 0;
return !under_steam;
}
int input_prompts_pick(const char *prompts, const char *pad_layout) {
if (prompts && *prompts)
return !strcasecmp(prompts, "xbox") ? PROMPTS_XBOX
+6
View File
@@ -91,6 +91,12 @@ void input_map_configure(void);
// pad's east button is labelled A (a Switch Pro Controller, a GuliKit) and Xbox otherwise.
int input_pad_layout_pick(const char *setting, int east_labelled_a);
// Whether SDL passes gamepad presses and stick movements to the game while its window has no focus (TOTK_PAD_BACKGROUND,
// input.c start): "1" on, "0" off. Anything else ("auto", NULL) is on unless Steam started the game: then the focus
// goes to Steam's overlay and menus (the Quick Access menu in SteamOS's Game Mode), whose gamepad it is while they are
// open (#1462); elsewhere the gamepad keeps playing while another window has the focus (#971).
int input_pad_background_pick(const char *setting, int under_steam);
// 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). PlayStation: the
+7 -2
View File
@@ -66,7 +66,11 @@ void ipc_handle_closed(int kind, void *obj) {
}
// ---- helpers for services
static int readable(uint64_t a, uint64_t n) { return plat_mem_readable(a, n); }
// With TOTK_HEAP_LAZY the heap by the layout (its pages may not be committed before first use), anything else by
// the OS; without it the OS for everything, as before.
static int readable(uint64_t a, uint64_t n) {
return mem_heap_lazy() ? mem_guest_readable(a, n) : plat_mem_readable(a, n);
}
void ipc_backtrace(void) {
const Cpu *c = t_req;
@@ -422,11 +426,12 @@ static void msg_parse(const uint32_t *m, int tipc, Reply *r) {
}
// One request on the TLR message buffer; the kernel result of SendSyncRequest, the service result in r->result.
// A kernel failure has no reply: clear it before the probe reads fields in a failure diagnostic.
static uint32_t call(Cpu *c, uint32_t h, const Msg *q, Reply *r) {
uint32_t *m = (uint32_t *)(uintptr_t)c->tpidrro;
msg_build(m, q);
uint32_t k = sv(c, 0x21, h, 0, 0, 0);
if (k) return k;
if (k) { memset(r, 0, sizeof *r); return k; }
msg_parse(m, q->type >= T_TIPC_BASE, r);
return 0;
}
+29 -7
View File
@@ -389,6 +389,13 @@ static int core_allowed(const RtThread *t, int c) { return (int)((t->mask >> c)
// inheritance and the preemption disable without interrupting owners.
#define AP_FIRST_NS 250000ull // the waiter spins this long before the first interruption (most waits end sooner)
#define AP_GAP_NS 1000000ull // and interrupts the same owner at most this often
// TOTK_AP_FIRST_US replaces AP_FIRST_NS (10..1000 us). TOTK_HOST_CHECKPOINT (on by default): an owner with a pending preempt request
// that returns from a host call or SVC to game code gives its core up there (kern_host_left), as at its next SVC or
// indirect call, instead of running on until one or until a waiter interrupts it.
static uint64_t g_ap_first_ns = AP_FIRST_NS;
static int g_host_cp;
static uint64_t g_hcp_taken; // cores given up at a host call or SVC return (atomic)
static int checkpoint(void);
static int g_ap = -1, g_ap_int; // g_ap_int: interrupt owners (TOTK_ASYNC_PREEMPT=2: inheritance and disable only)
static int g_ap_log; // redirects logged so far (AP_LOG_N)
#define AP_LOG_N 40
@@ -401,6 +408,12 @@ static void ap_init(void) {
const char *e = cfg_value("TOTK_ASYNC_PREEMPT");
g_ap = strcmp(e, "0") != 0;
g_ap_int = g_ap && strcmp(e, "2") != 0;
const char *f = cfg_get("TOTK_AP_FIRST_US");
if (f && *f) {
long long us = atoll(f);
g_ap_first_ns = (uint64_t)(us < 10 ? 10 : us > 1000 ? 1000 : us) * 1000;
}
g_host_cp = cfg_bool("TOTK_HOST_CHECKPOINT");
if (g_ap) {
RtModule m[16];
int n = rt_linked_modules(m, 16);
@@ -425,8 +438,12 @@ static void ap_init(void) {
kern_host_track = 1;
}
}
rt_log("kernel: asynchronous preemption of virtual cores %s, priority inheritance and preemption disable %s; lifted "
"code exe+%#llx-exe+%#llx", g_ap_int ? "on" : "off", g_ap ? "on (TOTK_ASYNC_PREEMPT=0 turns all off)" : "off",
if (g_ap && g_host_cp) kern_host_track = 1;
rt_log("kernel: asynchronous preemption of virtual cores %s (first after %llu us, TOTK_AP_FIRST_US), priority "
"inheritance and preemption disable %s; preempt requests honoured at host call returns %s "
"(TOTK_HOST_CHECKPOINT); lifted code exe+%#llx-exe+%#llx",
g_ap_int ? "on" : "off", (unsigned long long)(g_ap_first_ns / 1000),
g_ap ? "on (TOTK_ASYNC_PREEMPT=0 turns all off)" : "off", g_ap && g_host_cp ? "on" : "off",
(unsigned long long)(g_gen_lo ? g_gen_lo - plat_exe_base() : 0),
(unsigned long long)(g_gen_hi ? g_gen_hi - plat_exe_base() : 0));
}
@@ -733,6 +750,7 @@ int kern_core_diag_on(void) { return g_diag > 0; }
void kern_host_left(void *thread) {
RtThread *t = thread;
if (g_diag > 0 && t->dg_kick && t->dg_host_kick && !t->dg_host_end) t->dg_host_end = kern_now_ns();
if (g_host_cp && g_ap > 0 && t == tcur && checkpoint()) __atomic_add_fetch(&g_hcp_taken, 1, __ATOMIC_RELAXED);
}
static int dg_in_host(const RtThread *o) { return __atomic_load_n(&o->host_depth, __ATOMIC_RELAXED) > 0; }
@@ -833,10 +851,10 @@ void kern_core_diag_frame(uint64_t frame, uint64_t interval_ns) {
unlock();
rt_log("kernel: frame %llu: asynchronous preemption: %llu interrupted, %llu cores given up there; refused: "
"%llu in a host call, %llu outside game code, %llu preemption disabled, %llu failed; %llu waits ended "
"in the first spin; SVC 0x36 %llu",
"in the first spin; SVC 0x36 %llu; cores given up at host call returns %llu",
(unsigned long long)frame, (unsigned long long)v[0], (unsigned long long)v[1], (unsigned long long)v[2],
(unsigned long long)v[3], (unsigned long long)v[4], (unsigned long long)v[5], (unsigned long long)v[6],
(unsigned long long)v[7]);
(unsigned long long)v[7], (unsigned long long)__atomic_load_n(&g_hcp_taken, __ATOMIC_RELAXED));
}
if (g_diag <= 0) return;
DgWindow w;
@@ -1026,7 +1044,7 @@ static void core_take(RtThread *t) {
core_kick();
if (g_diag > 0) t->dg_cls = dg_class0(t);
if (g_ap_int && t->target && t->cur_core < 0) { // most waits end within microseconds: spin before interrupting
uint64_t end = kern_now_ns() + AP_FIRST_NS;
uint64_t end = kern_now_ns() + g_ap_first_ns;
unlock();
while (__atomic_load_n(&t->cur_core, __ATOMIC_RELAXED) < 0 && kern_now_ns() < end) plat_pause();
lock();
@@ -1138,9 +1156,10 @@ void rt_spin_gate(Cpu *c, uint64_t head) {
// A pending preempt request, at an SVC or an indirect call. The core goes over only if a better thread still waits
// for it, so core_put grants it to a waiter better than t; a stale request (that waiter got another core) is dropped.
void kern_checkpoint(void) {
// checkpoint: 1 if the core was given up (holding G inside).
static int checkpoint(void) {
RtThread *t = tcur;
if (!t || !__atomic_load_n(&t->preempt, __ATOMIC_RELAXED)) return;
if (!t || !__atomic_load_n(&t->preempt, __ATOMIC_RELAXED)) return 0;
lock();
if (g_diag > 0 && t->cur) {
t->dg_pc = t->cur->pc;
@@ -1162,8 +1181,11 @@ void kern_checkpoint(void) {
g_pre_stale++;
}
unlock();
return better;
}
void kern_checkpoint(void) { checkpoint(); }
// kern_ap_stub, on the interrupted owner: where to jump back to, then the core given up as at a checkpoint.
uint64_t kern_ap_rip(void) { return tcur->ap_rip; }
+7 -1
View File
@@ -397,7 +397,13 @@ static Res resolve(Mod *m, uint32_t si, int jump) {
uint64_t guest = sym_defined(m, si) ? m->pub.base + m->syms[si].value : find_symbol(name, NULL);
GuestFn f;
Res r;
if (jump && m->pub.plugin && ldr_plugin_import) { // the plugin service run counts the plugin's calls by name
// A plugin's calls out of its own code are counted by name (plugin_init.c plugin_import), so the plugin check can
// judge what its init reached. A JUMP_SLOT whose symbol the plugin defines itself is no call out: a plugin built
// with default visibility calls its own exported functions through its PLT, such as the std::vector<const char*>
// constructor of Challenge Mode's Enemy Health Regeneration (exefs subsdk8), and it binds to that definition as
// any other own symbol. A host override of the name still wins and stays counted.
int own_code = sym_defined(m, si) && !hostfn_override(name);
if (jump && m->pub.plugin && ldr_plugin_import && !own_code) {
uint64_t to = (f = hostfn_override(name)) ? hostfn_register(name, f) : guest;
if (!to) to = hostfn_register(name, unresolved_stub);
r = (Res){hostfn_register_observer(name, ldr_plugin_import, to), RES_OBSERVER};
+136 -6
View File
@@ -108,10 +108,13 @@ static void thaw_range_locked(uint64_t a, uint64_t n, int why) {
for (uint64_t r = r0; r <= r1; r++) thaw_locked(r, why);
}
static void heap_commit_range(uint64_t a, uint64_t n);
void mem_thaw(uint64_t a, uint64_t n) {
plat_mutex_lock(&frz_lock); // also when nothing is frozen: the hold keeps a read's buffer writable
thaw_range_locked(a, n, 2);
plat_mutex_unlock(&frz_lock);
heap_commit_range(a, n);
}
// frz_lock held exclusively. Makes the committed pages of region r read-only when every one of them is read-write;
@@ -200,6 +203,105 @@ static void commit(uint64_t a, uint64_t n, const char *what) {
rt_fatal("memory: commit %s %#llx+%#llx failed", what, (unsigned long long)a, (unsigned long long)n);
}
// ---- heap pages committed on first use (Windows)
// SetHeapSize asks for the game's whole heap at once (1.4.3: about 2.1 GiB at boot), and Windows charges every
// committed page against the system's commit limit, backed by RAM or the page file, whether the game touches it or not.
// In a sky-island scene it had touched about two thirds. With TOTK_HEAP_LAZY=1 (Windows, off by default) the part
// SetHeapSize adds stays reserved: the first read or write of a reserved page faults, and heap_fault commits its
// LAZY_CHUNK and retries. Freshly committed pages read as zero, as the Switch's heap does. Access by the kernel or the GPU
// driver does not fault: a file read into the heap, a save written from it and a Vulkan import of it would fail on a
// reserved page. File reads and Vulkan imports call mem_thaw first, so mem_thaw commits the reserved chunks of its
// range too (heap_commit_range); save writes only need the pages to exist and call mem_heap_commit. Linux backs mprotect'ed pages on first use by itself and keeps committing eagerly.
//
// lazy_map holds one byte per chunk, set once the chunk is committed, so neither path asks the OS for the page state:
// a VirtualQuery costs tens of microseconds here, and the write faults of frozen pool regions (thaw_fault) come through
// heap_fault first. Only whole chunks are committed and only when their byte is clear: VirtualAlloc(MEM_COMMIT) over
// committed pages would set them read-write again and undo a freeze.
#ifndef LAZY_CHUNK
#define LAZY_CHUNK 0x100000ull // divides the 2 MiB granularity of SetHeapSize
#endif
static int heap_lazy;
static uint8_t *lazy_map; // per chunk of L.heap: 1 committed; written under lazy_lock
static PlatMutex lazy_lock = PLAT_MUTEX_INIT; // commits and the heap's shrink; never held across a guest access
static volatile uint64_t heap_committed; // bytes of committed chunks (lazy mode), exact
static volatile int64_t lazy_faults, lazy_ns;
// Commits the clear chunks among [i0, i1) of the heap's first `size` bytes, runs of them in one call.
static void heap_commit_chunks(uint64_t i0, uint64_t i1, uint64_t size, const char *what) {
uint64_t base = L.heap.base, top = base + size;
plat_mutex_lock(&lazy_lock);
for (uint64_t i = i0; i < i1;) {
if (lazy_map[i]) { i++; continue; }
uint64_t j = i;
while (j < i1 && !lazy_map[j]) j++;
uint64_t lo = base + i * LAZY_CHUNK, hi = base + j * LAZY_CHUNK;
if (hi > top) hi = top;
commit(lo, hi - lo, what);
__atomic_add_fetch(&heap_committed, hi - lo, __ATOMIC_RELAXED);
for (uint64_t k = i; k < j; k++) __atomic_store_n(&lazy_map[k], 1, __ATOMIC_RELEASE);
i = j;
}
plat_mutex_unlock(&lazy_lock);
}
static void heap_commit_range(uint64_t a, uint64_t n) {
if (!heap_lazy || !n) return;
uint64_t base = L.heap.base, size = __atomic_load_n(&heap_size, __ATOMIC_ACQUIRE), top = base + size;
uint64_t lo = a > base ? a : base, hi = a + n < a || a + n > top ? top : a + n;
if (lo >= hi) return;
uint64_t i0 = (lo - base) / LAZY_CHUNK, i1 = (hi - base + LAZY_CHUNK - 1) / LAZY_CHUNK, i = i0;
while (i < i1 && __atomic_load_n(&lazy_map[i], __ATOMIC_ACQUIRE)) i++; // the usual case: all committed, no lock
if (i < i1) heap_commit_chunks(i, i1, size, "heap pages for a file, save or import");
}
// The platform's fault hook, ahead of thaw_fault: 1 retries the access. A committed chunk's fault is not this one's
// (a frozen page, or a guest error); heap_fault_raced catches a chunk committed by another thread in between.
static int heap_fault(uint64_t a) {
if (!heap_lazy) return 0;
uint64_t base = L.heap.base, size = __atomic_load_n(&heap_size, __ATOMIC_ACQUIRE);
if (a < base || a - base >= size) return 0;
uint64_t i = (a - base) / LAZY_CHUNK;
if (__atomic_load_n(&lazy_map[i], __ATOMIC_ACQUIRE)) return 0;
uint64_t t0 = plat_now_ns();
heap_commit_chunks(i, i + 1, size, "heap on first use");
int64_t ns = (int64_t)__atomic_add_fetch(&lazy_ns, (int64_t)(plat_now_ns() - t0), __ATOMIC_RELAXED);
int64_t n = (int64_t)plat_inc64(&lazy_faults);
if (!(n % (int64_t)((512ull << 20) / LAZY_CHUNK))) // every 512 MiB of chunks: how often and at what cost
rt_log("memory: heap committed on first use: %lld faults, %.1f ms in all (%.1f us each); heap %llu of %llu MiB "
"committed", (long long)n, (double)ns / 1e6, (double)ns / 1e3 / (double)n,
(unsigned long long)(__atomic_load_n(&heap_committed, __ATOMIC_RELAXED) >> 20),
(unsigned long long)(size >> 20));
return 1;
}
// Last, after thaw_fault declined: a chunk another thread committed between this thread's fault and heap_fault's read
// of lazy_map. Asks the OS, which only the faults no hook takes (a crash on its way) pay for.
static int heap_fault_raced(uint64_t a) {
uint64_t base = L.heap.base, size = __atomic_load_n(&heap_size, __ATOMIC_ACQUIRE), end;
if (!heap_lazy || a < base || a - base >= size) return 0;
return plat_mem_state(a & ~(PAGE - 1), (a & ~(PAGE - 1)) + PAGE, &end) == PLAT_PROT_RW;
}
int mem_heap_lazy(void) { return heap_lazy; }
void mem_heap_commit(uint64_t a, uint64_t n) { heap_commit_range(a, n); }
void mem_heap_lazy_stats(uint64_t *faults, uint64_t *ns, uint64_t *committed, uint64_t *size) {
*faults = (uint64_t)__atomic_load_n(&lazy_faults, __ATOMIC_RELAXED);
*ns = (uint64_t)__atomic_load_n(&lazy_ns, __ATOMIC_RELAXED);
*committed = __atomic_load_n(&heap_committed, __ATOMIC_RELAXED);
*size = __atomic_load_n(&heap_size, __ATOMIC_ACQUIRE);
}
uint64_t mem_heap_uncommitted(void) {
if (!heap_lazy) return 0;
uint64_t size = __atomic_load_n(&heap_size, __ATOMIC_ACQUIRE), done = __atomic_load_n(&heap_committed, __ATOMIC_RELAXED);
return size > done ? size - done : 0;
}
static int thaw_fault(uint64_t a);
static int mem_fault(uint64_t a) { return heap_fault(a) || thaw_fault(a) || heap_fault_raced(a); }
static void decommit(uint64_t a, uint64_t n, const char *what) {
plat_mutex_lock(&frz_lock);
thaw_range_locked(a, n, 3);
@@ -253,12 +355,17 @@ void mem_init(void) {
if (reserve_at(at, ALIAS_SIZE, 1)) alias = at;
if (!alias) reexec_or_fail("a 64 GiB alias region below 2^39");
plat_mem_fault_hook(thaw_fault); // before the crash handler
plat_mem_fault_hook(mem_fault); // before the crash handler
alias_pages = calloc(ALIAS_PAGES, 1);
if (!alias_pages) rt_fatal("memory: cannot allocate the alias page map");
// totk.ini is read here, once the address space is claimed and before the first setting: the pool size below
// depends on TOTK_APP_POOL and on the resolution settings (resolution.c decides them once, on this first call).
cfg_init();
#ifdef _WIN32
const char *lazy = cfg_get("TOTK_HEAP_LAZY");
heap_lazy = lazy && atoi(lazy) != 0; // opt-in: an untouched heap page then faults on its first read too
plat_mem_fault_reads(heap_lazy);
#endif
const char *pool = cfg_get("TOTK_APP_POOL");
L = (RtGuestLayout){
.aslr = {low, RT_ADDRESS_LIMIT - low},
@@ -271,6 +378,8 @@ void mem_init(void) {
: DEFAULT_POOL + res_heap_extra_bytes() + res_tex_heap_extra_bytes() + res_grass_heap_extra_bytes(),
};
if (!L.pool) rt_fatal("memory: TOTK_APP_POOL is 0");
if (heap_lazy && !(lazy_map = calloc(L.heap.size / LAZY_CHUNK + 1, 1)))
rt_fatal("memory: cannot allocate the heap chunk map");
}
const RtGuestLayout *mem_layout(void) { return &L; }
@@ -306,8 +415,21 @@ uint32_t mem_set_heap_size(uint64_t size, uint64_t *addr) {
plat_mutex_unlock(&lock);
return R_INVALID_STATE;
}
if (size > heap_size) commit(L.heap.base + heap_size, size - heap_size, "heap");
if (size < heap_size) decommit(L.heap.base + size, heap_size - size, "heap");
if (size > heap_size && !heap_lazy) commit(L.heap.base + heap_size, size - heap_size, "heap"); // else heap_fault
if (size < heap_size && heap_lazy) { // the chunks above the new size go back to reserved
plat_mutex_lock(&lazy_lock);
for (uint64_t i = size / LAZY_CHUNK, end = (heap_size + LAZY_CHUNK - 1) / LAZY_CHUNK; i < end; i++)
if (lazy_map[i]) {
uint64_t lo = L.heap.base + i * LAZY_CHUNK, hi = lo + LAZY_CHUNK;
if (hi > L.heap.base + heap_size) hi = L.heap.base + heap_size;
decommit(lo, hi - lo, "heap");
__atomic_sub_fetch(&heap_committed, hi - lo, __ATOMIC_RELAXED);
__atomic_store_n(&lazy_map[i], 0, __ATOMIC_RELEASE);
}
plat_mutex_unlock(&lazy_lock);
} else if (size < heap_size) {
decommit(L.heap.base + size, heap_size - size, "heap");
}
heap_size = size;
plat_mutex_unlock(&lock);
if (addr) *addr = L.heap.base;
@@ -378,6 +500,8 @@ static int module_data(uint64_t a, uint64_t n) {
return off >= m->data_off && n <= m->size - off ? i : -1;
}
int mem_plugin_writes;
uint32_t mem_set_permission(uint64_t a, uint64_t n, uint32_t perm) {
if (a & (PAGE - 1)) return R_INVALID_ADDRESS;
if (!n || (n & (PAGE - 1))) return R_INVALID_SIZE;
@@ -393,10 +517,16 @@ uint32_t mem_set_permission(uint64_t a, uint64_t n, uint32_t perm) {
return R_INVALID_STATE;
}
memset(t, (int)perm, n / PAGE);
protect(a, n, perm == PERM_RW ? PLAT_PROT_RW : perm == PERM_R ? PLAT_PROT_READ : PLAT_PROT_NONE, "module data");
// With a mod plugin on, a read-only run (the RELRO the SDK seals in each module's DT_INIT, after the plugins'
// inits) stays writable on the host while QueryMemory reports what the game asked. Zonai Fieldworks swaps entries
// of main's RELRO tables from its own code when a member is switched on in play (#1451), writing main's address
// directly; on the platforms the mod is made for that write goes through, here it faulted.
int keep_rw = perm == PERM_R && mem_plugin_writes;
protect(a, n, perm == PERM_RW || keep_rw ? PLAT_PROT_RW : perm == PERM_R ? PLAT_PROT_READ : PLAT_PROT_NONE,
"module data");
plat_mutex_unlock(&lock);
rt_log("%s data permission +%#llx size %#llx perm %u", m->name, (unsigned long long)(a - m->base),
(unsigned long long)n, perm);
rt_log("%s data permission +%#llx size %#llx perm %u%s", m->name, (unsigned long long)(a - m->base),
(unsigned long long)n, perm, keep_rw ? " (kept writable on the host: a mod plugin is on)" : "");
return R_OK;
}
+14 -4
View File
@@ -22,7 +22,8 @@
// TOTK_MENU_CURSOR (live, default 1): 0 leaves the menus to the keys and the pad.
//
// With TOTK_MAP_CLICK=1 (live, default 0: one key per controller button) input.c makes the left mouse button A on the
// map (menu_cursor_map), so a click acts at the map's cursor. The map is found only while TOTK_MENU_CURSOR is on.
// map (menu_cursor_map), so a click acts at the map's cursor. The map is found while TOTK_MENU_CURSOR is on, and with
// it off while the gameplay tweaks' map zoom is on (TOTK_GAMEPLAY_MAP_ZOOM), which acts only on the map found here.
//
// The same read of the open screens tells input.c when a dialogue box is on screen (menu_cursor_dialogue), where the
// left mouse button presses B (it advances the text and skips its scroll) and the right one A, instead of their
@@ -34,6 +35,7 @@
#include <string.h>
#include "cfg.h"
#include "gameplay_tweaks.h"
#include "gfx.h"
#include "host.h"
#include "input.h"
@@ -377,8 +379,11 @@ void menu_cursor_poll(uint64_t *buttons) {
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)");
}
int cursor = enabled(), talk = dialogue_enabled();
if (!cursor && !talk) {
// The map zoom of the gameplay tweaks (gameplay_tweaks.c map_zoom_allowed) acts only on the map found here, so with
// the menu cursor off and that zoom on, the map is still looked for, as the dialogue is for dialogue_click; the
// pointer and the menus stay off (#1376).
int cursor = enabled(), talk = dialogue_enabled(), zoom = !cursor && RT_V143 && gameplay_tweaks_map_zoom();
if (!cursor && !talk && !zoom) {
set_pointer(0);
__atomic_store_n(&g_map, 0, __ATOMIC_RELAXED);
__atomic_store_n(&g_dialogue, 0, __ATOMIC_RELAXED);
@@ -414,7 +419,12 @@ void menu_cursor_poll(uint64_t *buttons) {
__atomic_store_n(&g_dialogue, dialogue, __ATOMIC_RELAXED);
if (!cursor) {
set_pointer(0);
__atomic_store_n(&g_map, 0, __ATOMIC_RELAXED);
if (zoom && map && !map_logged) {
map_logged = 1;
rt_log("menu_cursor: the map is open: the mouse moves its cursor and the scroll wheel zooms "
"(gameplay_map_zoom; menu_cursor = 0 leaves the menus alone)");
}
__atomic_store_n(&g_map, zoom ? map : 0, __ATOMIC_RELAXED);
__atomic_store_n(&g_menu, 0, __ATOMIC_RELAXED);
__atomic_store_n(&g_strip, 0, __ATOMIC_RELAXED);
__atomic_store_n(&g_camera, 0, __ATOMIC_RELAXED);
+12
View File
@@ -50,6 +50,11 @@ uint64_t nvn_new_serial(void); // next tex_t / prog_
void nvn_sync_ahead_present(void);
uint64_t nvn_sync_ahead_guard(void);
int nvn_sync_ahead_on(void); // 1 when the frame-ahead wait is in effect: TOTK_SYNC_AHEAD=1 and a wait site known for this version
// vk_exec_xfer.c, TOTK_SYNC_AHEAD: at the game's frame wait the newest timestamp written becomes the bound; the value
// the game reads for the timestamp t of the report at addr (t, or the bound for a report its frame wait did not cover)
void vk_counter_frame(void);
uint64_t vk_counter_timestamp(uint64_t addr, uint64_t t);
void vk_counter_log(void); // the run total, once (gfx_exit_log)
int vk_mem_shadow_on(void); // vk_memory.c: 1 with shadow storage on (valid once the Vulkan back end is up)
int vk_mem_mirror_on(void); // vk_memory.c: 1 when pools used as buffers get VRAM mirrors (memory = mirror or auto on a discrete GPU)
void vk_mem_shadow_fence(void); // vk_memory.c: returns once every shadow sync that read the old guard is done
@@ -67,6 +72,10 @@ void nvn_submit_prepare(const uint64_t *handles, int n); // weak no-op; the co
// Asynchronous replay: as nvn_submit_prepare, writing the handles to replay to out (a clone where a still queued
// submission uses the same recording with other deferred binds)
void nvn_submit_prepare_async(const uint64_t *handles, uint64_t *out, int n);
// After the back end took a submission as fence value `fence`: every sync an OP_FENCE_SYNC of the game's handles names
// is fenced at that value. Returns at once while no recording ever held the op (the game records none; mod plugins do).
void nvn_submit_fence_syncs(const uint64_t *handles, int n, uint64_t fence);
void nvn_sync_fence(sync_t *s, uint64_t fence); // nvn_api_core.c: an initialized sync now waits for fence
int gfx_replay_async(void); // 1: the back end replays submissions on its own thread
uint64_t gfx_replayed_submits(void); // newest submit number (nvn_submit_count) replayed
#define NVN_HANDLE_TEX(h) ((int)((h) & 0xfffff)) // combined texture handle = texture id | sampler id << 20
@@ -105,6 +114,9 @@ typedef struct { int32_t prim, itype; uint64_t ibuf, ind; } p_draw_idx_ind;
typedef struct { uint64_t ind, caller; } p_dispatch_ind; // OP_DISPATCH_IND: ind = GPU address of the 3 group counts
// OP_CLEAR_BUF: size bytes at addr filled with the 32-bit value in GPU order (ClearBuffer; ReportValue is a 4-byte one)
typedef struct { uint64_t addr, size; uint32_t value, pad; } p_clear_buf;
// OP_FENCE_SYNC: CommandBufferFenceSync. The front end, not the replay, signals the sync: at the submit that carries
// the record it gets that submit's fence value (nvn_submit_fence_syncs). Every replay skips the record.
typedef struct { sync_t *sync; } p_fence_sync;
_Static_assert(sizeof(p_signal_event) == 16 && sizeof(p_report_counter) == 16 && sizeof(p_copy_b2b) == 24 &&
sizeof(p_update_ub) == 16, "op payload layouts of hle_nvn.c");
static inline const op_hdr *nvn_op_first(uint64_t handle) { return (const op_hdr *)(uintptr_t)handle; } // OP_BEGIN
+31 -4
View File
@@ -414,8 +414,9 @@ void nvn_pins_stats(uint64_t *live, uint64_t *freed) {
// deferred: 0 unknown, 1 none, 2 some; pins: texture pins its ops name, counted in their refs; pin_v: those pins, in
// record order, or NULL (then pin_refs walks the records); cap: bytes of the block from the large-block cache
// (copy_block), 0 for a plain heap block; hw: the recording's command memory as the real driver counts it (set at
// EndRecording), what CopyCommands of it adds to nvnCommandBufferGetCommandMemoryUsed (inline_recording)
typedef struct { uint64_t magic, bytes, made_at, used_at, deferred, pins, cap, hw; const tex_t **pin_v; } copy_prefix;
// EndRecording), what CopyCommands of it adds to nvnCommandBufferGetCommandMemoryUsed (inline_recording); fsync: 1 when
// the records hold an OP_FENCE_SYNC (flatten_recording), which nvn_submit_fence_syncs signals at submit
typedef struct { uint64_t magic, bytes, made_at, used_at, deferred, pins, cap, hw, fsync; const tex_t **pin_v; } copy_prefix;
_Static_assert(sizeof(copy_prefix) % 8 == 0, "records stay 8-byte aligned");
typedef struct { uintptr_t lo, hi; uint8_t *copy; } cmd_copy;
typedef struct { cmd_copy *v; uint32_t n, cap; } copy_bucket;
@@ -423,6 +424,7 @@ static PlatMutex copy_lock = PLAT_MUTEX_INIT; // guards the two maps, the cou
static nvn_hmap copy_pages = {.klen = 8}; // page -> copy_bucket
static nvn_hmap copy_live = {.klen = 8}; // handle -> copy_prefix of a live copy
static uint64_t ncopies, copy_bytes, copies_made;
static int fence_sync_recorded; // 1 once nvnCommandBufferFenceSync recorded an op (never set by the game itself)
// Asynchronous replay: copies released by the game, and per-submission clones, that a queued submission still reads.
// Freed once gfx_replayed_submits() reaches their used_at. Empty with synchronous replay.
static copy_prefix **zombies;
@@ -598,6 +600,8 @@ static uint8_t *flatten_recording(const uint8_t *p, size_t n) {
static __thread struct { const tex_t **v; uint64_t cap; } named; // the pins of this recording, reused
uint64_t pins_named = 0;
int listed = 1; // 0 after a failed growth: the copy goes without a list
// Looked for only once some recording held the op (fence_sync_recorded): the game's own recordings never do.
int find_fsync = __atomic_load_n(&fence_sync_recorded, __ATOMIC_RELAXED), fsync = 0;
for (size_t at = 0;;) { // the records stay checked: a corrupt one stops here, not in the replay
op_hdr h;
memcpy(&h, p + at, sizeof h);
@@ -616,6 +620,7 @@ static uint8_t *flatten_recording(const uint8_t *p, size_t n) {
}
if (k && listed) memcpy((void *)(named.v + pins_named), pinned, sizeof *pinned * (size_t)k);
pins_named += (uint64_t)k;
fsync |= find_fsync && h.op == OP_FENCE_SYNC;
at += h.size;
if (h.op == OP_END) {
if (at != n) rt_fatal("nvn: recording at %p ends at %zu of %zu bytes", (const void *)p, at, n);
@@ -625,7 +630,8 @@ static uint8_t *flatten_recording(const uint8_t *p, size_t n) {
const tex_t **pin_v = NULL;
if (pins_named && listed && (pin_v = malloc(sizeof *pin_v * pins_named)))
memcpy((void *)pin_v, (const void *)named.v, sizeof *pin_v * pins_named);
*block = (copy_prefix){.magic = COPY_MAGIC, .bytes = n, .pins = pins_named, .cap = block->cap, .pin_v = pin_v};
*block = (copy_prefix){.magic = COPY_MAGIC, .bytes = n, .pins = pins_named, .cap = block->cap, .fsync = (uint64_t)fsync,
.pin_v = pin_v};
return out + sizeof(copy_prefix);
}
@@ -1260,6 +1266,15 @@ NVN_API(nvnCommandBufferWaitEvent) { (void)c; }
NVN_API(nvnCommandBufferSetShaderScratchMemory) { (void)c; }
NVN_API(nvnCommandBufferSetPatchSize) { (void)c; }
// void nvnCommandBufferFenceSync(NVNcommandBuffer *cmd, NVNsync *sync, NVNsyncCondition condition, int flags): the sync
// is signaled once the GPU ran every command before it. Here it is fenced at the value of the whole submit that carries
// the record (nvn_submit_fence_syncs), which completes no earlier than the console's point. The game never calls it;
// mod plugins do (Zonai Fieldworks' native-font renderer).
NVN_API(nvnCommandBufferFenceSync) {
__atomic_store_n(&fence_sync_recorded, 1, __ATOMIC_RELAXED);
REC(cmd_of(c), OP_FENCE_SYNC, p_fence_sync)->sync = arg_p(c, 1);
}
// ---------- submit
// What the console reads at the submit call is read here, on the game thread: every handle must be a live recording,
// and deferred binds take the handles the game's arrays hold now (the game fills its tables for the next frame as soon
@@ -1353,6 +1368,18 @@ void nvn_submit_prepare_async(const uint64_t *handles, uint64_t *out, int n) {
(unsigned long long)now, (unsigned long long)__atomic_load_n(&n_clones, __ATOMIC_RELAXED), nzombies);
}
// The game's handles, not the per-submission clones of nvn_submit_prepare_async: a clone may be freed as soon as the
// replay is done with it, and the handles stay live while the game is in QueueSubmitCommands. Copies hold no OP_CALL
// or OP_JUMP (flatten_recording), so each is one run of records to OP_END.
void nvn_submit_fence_syncs(const uint64_t *handles, int n, uint64_t fence) {
if (!__atomic_load_n(&fence_sync_recorded, __ATOMIC_RELAXED)) return;
for (int i = 0; i < n; i++) {
if (!((const copy_prefix *)(uintptr_t)handles[i] - 1)->fsync) continue;
for (const op_hdr *h = nvn_op_first(handles[i]); h->op != OP_END; h = nvn_op_next(h))
if (h->op == OP_FENCE_SYNC) nvn_sync_fence(((const p_fence_sync *)nvn_op_payload(h))->sync, fence);
}
}
uint64_t nvn_submit_count(void) { return __atomic_load_n(&nsubmits, __ATOMIC_RELAXED); }
const char *nvn_op_name(uint32_t op) {
@@ -1362,7 +1389,7 @@ const char *nvn_op_name(uint32_t op) {
"BIND_VSTREAM", "BIND_VBUF", "BIND_UBO", "BIND_SSBO", "BIND_TEX", "BIND_SAMP", "STENCIL", "POLY_OFFSET", "DRAW",
"DRAW_IDX", "DISPATCH", "BARRIER", "SET_TEX_POOL", "SET_SAMP_POOL", "COPY_B2T", "COPY_STRIDE", "BLEND_COLOR",
"COPY_T2B", "BIND_IMG", "COPY_T2T", "RESET_COUNTER", "CLEAR_TEX", "DEPTH_CLAMP", "RENDER_ENABLE",
"RASTER_DISCARD", "RENDER_COND", "PRIM_RESTART", "DRAW_IDX_IND", "DISPATCH_IND", "CLEAR_BUF",
"RASTER_DISCARD", "RENDER_COND", "PRIM_RESTART", "DRAW_IDX_IND", "DISPATCH_IND", "CLEAR_BUF", "FENCE_SYNC",
};
_Static_assert(sizeof names / sizeof *names == OP_COUNT_, "one name per op");
return op < OP_COUNT_ ? names[op] : "?";
+12 -1
View File
@@ -463,7 +463,8 @@ NVN_API(nvnBufferFlushMappedRange) {
}
// ---------- Sync and events
// A sync is a fence value: fenced = 1 after QueueFenceSync (the newest submit), 3 after WindowAcquireTexture (fence 0).
// A sync is a fence value: fenced = 1 after QueueFenceSync (the newest submit) or the submit of a CommandBufferFenceSync
// record (that submit), 3 after WindowAcquireTexture (fence 0).
// NVNboolean nvnSyncInitialize(NVNsync *s, NVNdevice *d)
NVN_API(nvnSyncInitialize) {
*(sync_t *)arg_p(c, 0) = (sync_t){SYNC_MAGIC, 0, 0};
@@ -478,6 +479,13 @@ NVN_API(nvnQueueFenceSync) {
s->fenced = 1;
s->fence = nvn_fence_last();
}
// CommandBufferFenceSync at its submit (nvn_api_cmd.c nvn_submit_fence_syncs): the value first, then fenced, so a
// thread that sees fenced waits for this value or a newer one. A sync finalized since the record is left alone.
void nvn_sync_fence(sync_t *s, uint64_t fence) {
if (!s || s->magic != SYNC_MAGIC) return;
__atomic_store_n(&s->fence, fence, __ATOMIC_RELAXED);
__atomic_store_n(&s->fenced, 1, __ATOMIC_RELEASE);
}
// TOTK_SYNC_AHEAD=1: one more frame in flight. Each frame the game waits (one nvnSyncWait, frame_wait_lr) for
// the frame it presented last; on the Switch that work is long done by then, here it is still in the replay and on the
// GPU (about 11 ms from the submit), and the wait sets the frame time. With the switch on, that wait, and only that
@@ -581,6 +589,7 @@ NVN_API(nvnSyncWait) {
if (det) vk_ahead_frame_lag(s->fence, lag, behind);
b->cpu_synced(want == s->fence ? s->fence : b->fence_done());
if (det) vk_ahead_frame_done(1);
if (mode == 1) vk_counter_frame();
ret_x(c, NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED);
return;
}
@@ -592,6 +601,7 @@ NVN_API(nvnSyncWait) {
if (det) vk_ahead_frame_lag(s->fence, lag, behind);
if (ok) b->cpu_synced(want == s->fence ? s->fence : b->fence_done());
if (det) vk_ahead_frame_done(ok);
if (mode == 1) vk_counter_frame();
ret_x(c, ok ? NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED : NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED);
}
// void nvnEventBuilderSetDefaults(NVNeventBuilder *b)
@@ -718,6 +728,7 @@ NVN_API(nvnQueueSubmitCommands) {
nvn_submit_prepare(h, n);
f = gfx_backend()->submit(h, n);
}
nvn_submit_fence_syncs(h, n, f); // the syncs this submit's CommandBufferFenceSync records name wait for f
uint64_t prev = __atomic_load_n(&last_fence, __ATOMIC_RELAXED);
while (f > prev && !__atomic_compare_exchange_n(&last_fence, &prev, f, 1, __ATOMIC_RELEASE, __ATOMIC_RELAXED)) {}
__atomic_store_n(&lod_fence[no % LOD_RING], f, __ATOMIC_RELAXED);
+6 -2
View File
@@ -60,8 +60,12 @@ NVN_API(nvnDeviceSetAutomaticCheckpointsMask) { (void)c; }
static uint64_t ticks_to_ns(uint64_t t) { return t / 12 * 625 + t % 12 * 625 / 12; }
// uint64_t nvnDeviceGetCurrentTimestampInNanoseconds(const NVNdevice *d)
NVN_API(nvnDeviceGetCurrentTimestampInNanoseconds) { ret_x(c, ticks_to_ns(rt_ticks())); }
// uint64_t nvnDeviceGetTimestampInNanoseconds(const NVNdevice *d, const NVNcounterData *counter)
NVN_API(nvnDeviceGetTimestampInNanoseconds) { ret_x(c, ticks_to_ns(((const NVNcounterData *)arg_p(c, 1))->timestamp)); }
// uint64_t nvnDeviceGetTimestampInNanoseconds(const NVNdevice *d, const NVNcounterData *counter): with the frame wait
// one frame late, a report that wait did not cover reads as the newest one written by then (vk_exec_xfer.c)
NVN_API(nvnDeviceGetTimestampInNanoseconds) {
const NVNcounterData *d = arg_p(c, 1);
ret_x(c, ticks_to_ns(vk_counter_timestamp((uintptr_t)d, d->timestamp)));
}
// ---------- memory pools and buffers
// size_t nvnMemoryPoolGetSize(const NVNmemoryPool *p)
+1 -1
View File
@@ -128,7 +128,7 @@ enum {
OP_BIND_PROGRAM, OP_BIND_STATE, OP_BIND_VATTR, OP_BIND_VSTREAM, OP_BIND_VBUF,
OP_BIND_UBO, OP_BIND_SSBO, OP_BIND_TEX, OP_BIND_SAMP,
OP_STENCIL, OP_POLY_OFFSET, OP_DRAW, OP_DRAW_IDX, OP_DISPATCH, OP_BARRIER,
OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_DEPTH_CLAMP, OP_RENDER_ENABLE, OP_RASTER_DISCARD, OP_RENDER_COND, OP_PRIM_RESTART, OP_DRAW_IDX_IND, OP_DISPATCH_IND, OP_CLEAR_BUF, OP_COUNT_
OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_DEPTH_CLAMP, OP_RENDER_ENABLE, OP_RASTER_DISCARD, OP_RENDER_COND, OP_PRIM_RESTART, OP_DRAW_IDX_IND, OP_DISPATCH_IND, OP_CLEAR_BUF, OP_FENCE_SYNC, OP_COUNT_
};
// Payload (immediately follows op_hdr)
typedef struct { int32_t n; const tex_t *color[8]; view_t cview[8]; uint8_t has_cview[8]; const tex_t *depth; view_t dview; uint8_t has_dview; } p_set_rt;
+15 -1
View File
@@ -319,6 +319,7 @@ static void probe_samplers(void) {
// ---- sync and events
OBJ(NVNsync, syncs);
OBJ(NVNsync, sync_future);
OBJ(NVNsync, sync_cmd); // CommandBufferFenceSync's sync (record_all, probe_null_effects)
OBJ(NVNevent, ev);
OBJ(NVNevent, ev2);
OBJ(NVNeventBuilder, evb);
@@ -326,6 +327,7 @@ OBJ(NVNeventBuilder, evb);
static void probe_sync_events(void) {
CHECK((uint8_t)CALL(nvnSyncInitialize, U(&syncs), U(&dev)) == 1, "SyncInitialize");
CHECK(CALL(nvnSyncWait, U(&syncs), 1000) == NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED, "a sync never fenced times out at once");
CALL(nvnSyncInitialize, U(&sync_cmd), U(&dev));
CALL(nvnSyncInitialize, U(&sync_future), U(&dev));
sync_t *sf = (sync_t *)(void *)&sync_future;
sf->fenced = 1;
@@ -461,6 +463,7 @@ static uint64_t record_all(void) {
CALL(nvnCommandBufferSetColorReductionEnable, U(c), 1); // hints: nothing recorded
CALL(nvnCommandBufferSetColorReductionThresholds, U(c), 0, U(thresholds));
REC(OP_COPY_T2T, CALL(nvnCommandBufferDownsample, U(c), U(&tex1), U(&tex2)));
REC(OP_FENCE_SYNC, CALL(nvnCommandBufferFenceSync, U(c), U(&sync_cmd), NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0));
CHECK((uint8_t)CALL(nvnCommandBufferIsRecording, U(c)) == 1, "IsRecording while recording");
uint64_t h = CALL(nvnCommandBufferEndRecording, U(c));
CHECK((uint8_t)CALL(nvnCommandBufferIsRecording, U(c)) == 0, "IsRecording after EndRecording");
@@ -681,6 +684,7 @@ static void parse_all(uint64_t h) {
(p->addr == 0xc300 && p->size == 4 && p->value == 0x1234), "CLEAR_BUF payload (ClearBuffer, ReportValue)");
break;
}
case OP_FENCE_SYNC: CHECK(((const p_fence_sync *)a)->sync == (sync_t *)(void *)&sync_cmd, "FENCE_SYNC payload"); break;
default: CHECK(0, "unexpected op %s", nvn_op_name(o->op)); break;
}
}
@@ -815,6 +819,7 @@ static void probe_null_effects(void) {
CALL(nvnCommandBufferUpdateUniformBuffer, U(c), gbase, 64, 8, 8, U(d2));
CALL(nvnCommandBufferDrawArrays, U(c), NVN_DRAW_PRIMITIVE_TRIANGLES, 0, 3); // ignored
CALL(nvnCommandBufferBarrier, U(c), 1);
CALL(nvnCommandBufferFenceSync, U(c), U(&sync_cmd), NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
uint64_t ha = CALL(nvnCommandBufferEndRecording, U(c));
begin(&cmd2, ctlmem2, 0x38000);
@@ -824,6 +829,9 @@ static void probe_null_effects(void) {
CHECK(*(uint32_t *)ev_val == 0 && !pmem[OFF_UB + 4] && !pmem[OFF_DST] && pmem[OFF_COUNTER_B] == 0xaa,
"recording has no side effects");
// record_all and the call that inlined it recorded a FenceSync of sync_cmd too, and neither was submitted
CHECK(CALL(nvnSyncWait, U(&sync_cmd), 1000) == NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED,
"a CommandBufferFenceSync recorded but not submitted leaves the sync unsignaled");
uint64_t t0 = rt_ticks(), subs = nvn_submit_count(), fence0 = nvn_fence_last();
uint64_t hs[2] = {ha, hb};
@@ -835,6 +843,12 @@ static void probe_null_effects(void) {
(unsigned long long)wait);
CHECK(nvn_submit_count() == subs + 1 && nvn_fence_last() == fence0 + 1 && gfx_backend()->fence_done() == nvn_fence_last(),
"one submit advances the fence once (%llu -> %llu)", (unsigned long long)fence0, (unsigned long long)nvn_fence_last());
const sync_t *sc = (const sync_t *)(const void *)&sync_cmd;
uint64_t wait_cmd = CALL(nvnSyncWait, U(&sync_cmd), 1000000000ull);
CHECK(sc->fenced == 1 && sc->fence == nvn_fence_last() &&
(wait_cmd == NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED || wait_cmd == NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED),
"CommandBufferFenceSync: the submit fenced the sync at its value (fenced %u, fence %llu of %llu), SyncWait %llu",
sc->fenced, (unsigned long long)sc->fence, (unsigned long long)nvn_fence_last(), (unsigned long long)wait_cmd);
// event: WRITE 0x11, ADD 5, then handle 2's WRITE 0x99
CHECK((uint32_t)CALL(nvnEventGetValue, U(&ev)) == 0x99, "event value %#x after the stream, expected 0x99", *(uint32_t *)ev_val);
@@ -852,7 +866,7 @@ static void probe_null_effects(void) {
CHECK(cb[0] == 0 && cb[1] + 1 >= t0 && cb[1] <= t1 + 1, "samples-passed counter {%llu, %llu}", (unsigned long long)cb[0],
(unsigned long long)cb[1]);
CHECK(!memcmp(pmem + OFF_B2B_DST, keep, 16), "a copy out of the GPU window left the target alone");
n_effects = 6;
n_effects = 7;
CALL(nvnCommandBufferFinalize, U(&cmd2));
CALL(nvnCommandBufferFinalize, U(&cmd));
+2
View File
@@ -985,6 +985,8 @@ void plat_mem_fault_hook(int (*fn)(uint64_t addr)) {
fault_install();
}
void plat_mem_fault_reads(int on) { (void)on; }
void plat_crash_hook(void (*fn)(const PlatCrash *c)) {
crash_fn = fn;
fault_install();
+3
View File
@@ -220,6 +220,9 @@ uint64_t plat_mem_written(uint64_t addr, uint64_t n, uint64_t *pages, uint64_t m
// A write that faulted on a read-only page at addr goes to fn first; fn returns 1 when it made the page writable and
// the write should run again, 0 to let the fault go on (to the crash handler). One hook per process.
void plat_mem_fault_hook(int (*fn)(uint64_t addr));
// Read faults go to the hook too (memory.c heap_fault, TOTK_HEAP_LAZY): Windows only, before the game starts; a no-op
// on Linux, which commits on first use by itself.
void plat_mem_fault_reads(int on);
// Starts this program again with the same arguments and ends this process with the new one's exit code (Windows), or
// replaces this process with it (Linux). Environment changes made before the call are passed on.
_Noreturn void plat_reexec(void);
+10 -2
View File
@@ -721,10 +721,16 @@ uint64_t plat_mem_written(uint64_t addr, uint64_t n, uint64_t *pages, uint64_t m
static int (*fault_hook)(uint64_t addr);
// A write access violation (ExceptionInformation[0] == 1) goes to the hook; registered first, before the crash handler.
static ULONG_PTR fault_kinds = 1; // highest ExceptionInformation[0] the hook takes: 1 writes, 0 also reads
// A write access violation (ExceptionInformation[0] == 1) goes to the hook, and a read (0) too once
// plat_mem_fault_reads asked for it; registered first, before the crash handler. Writes thaw frozen regions; with
// TOTK_HEAP_LAZY reads and writes both commit heap pages on first use (memory.c, heap_fault). An execute fault (8) is
// never the hook's.
static LONG CALLBACK fault_veh(EXCEPTION_POINTERS *ep) {
const EXCEPTION_RECORD *er = ep->ExceptionRecord;
if (er->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || er->NumberParameters < 2 || er->ExceptionInformation[0] != 1)
ULONG_PTR kind = er->NumberParameters >= 2 ? er->ExceptionInformation[0] : 8;
if (er->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || kind > 1 || (kind == 0 && fault_kinds != 0))
return EXCEPTION_CONTINUE_SEARCH;
return fault_hook((uint64_t)er->ExceptionInformation[1]) ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH;
}
@@ -734,6 +740,8 @@ void plat_mem_fault_hook(int (*fn)(uint64_t addr)) {
AddVectoredExceptionHandler(1, fault_veh);
}
void plat_mem_fault_reads(int on) { fault_kinds = on ? 0 : 1; }
static void (*crash_fn)(const PlatCrash *c);
// The faulting thread's general registers, for the report to tie the faulting instruction to its operands.
+9 -13
View File
@@ -62,6 +62,7 @@
#include "kernel.h"
#include "mods.h"
#include "platform/platform.h"
#include "plugin_writes.h"
#if __has_include("patches.h")
#include "patches.h"
@@ -523,11 +524,7 @@ static const struct { const char *module; int set; const char *sha256; } plugin_
RT_PLUGINS(X)
#undef X
};
static const struct { int plugin; const char *module; uint64_t off; uint32_t old, now; } write_tab[] = {
#define X(p, mod, off, old, now) {p, mod, off, old, now},
RT_PLUGIN_WRITES(X)
#undef X
};
static const PluginWrite write_tab[] = {RT_PLUGIN_WRITES(PLUGIN_WRITE)};
#define NWRITES ((int)(sizeof write_tab / sizeof *write_tab))
#ifdef RT_PLUGIN_ROOTS
static const struct { const char *module; uint64_t off; } root_tab[] = {
@@ -590,7 +587,9 @@ static void restore_page(const RtLoaded *m, uint64_t off, const uint8_t *was) {
}
// After plugin i's init: what it wrote into the game modules, word by word, against the record of the build (its
// entries of RT_PLUGIN_WRITES). The first difference goes into why (unless a reason is there already). Then the game
// entries of RT_PLUGIN_WRITES, plugin_writes.h plugin_write_find). A recorded word the init did not change counts as
// missing, unless the record takes any value there (the init may have written the value the word held). The first
// difference goes into why (unless a reason is there already). Then the game
// modules are made what they were before the init: the sealed part (.text, .rodata) gets the game's bytes back, a
// write elsewhere stays and goes into pre, so the next plugin's init is compared only with what it writes itself.
// The aliases this init mapped (from first_alias on) are flushed first; an earlier init's were flushed after it.
@@ -612,12 +611,8 @@ static void check_writes(int plugin, int first_alias, char *why, size_t cap) {
memcpy(&a, pre[i] + w, 4);
memcpy(&b, now + w, 4);
if (a == b) continue;
int k = 0;
while (k < NWRITES && !(write_tab[k].plugin == plugin && write_tab[k].off == w &&
!strcmp(write_tab[k].module, m->name) && write_tab[k].old == a &&
write_tab[k].now == b))
k++;
if (k < NWRITES) {
int k = plugin_write_find(write_tab, NWRITES, plugin, m->name, w, a, b);
if (k >= 0) {
seen[k] = 1;
} else if (!unexpected++) {
snprintf(first, sizeof first, "%s+%#llx %08x -> %08x", m->name, (unsigned long long)w, a, b);
@@ -627,7 +622,7 @@ static void check_writes(int plugin, int first_alias, char *why, size_t cap) {
else memcpy(pre[i] + off, now + off, PAGE);
}
}
for (int k = 0; k < NWRITES; k++) missing += write_tab[k].plugin == plugin && !seen[k];
for (int k = 0; k < NWRITES; k++) missing += write_tab[k].plugin == plugin && !seen[k] && !write_tab[k].any;
if (why[0]) return;
if (unexpected)
snprintf(why, cap, "its init wrote %d words the build did not record (first %s)", unexpected, first);
@@ -713,6 +708,7 @@ int plugins_start(Cpu *c, const RtLoaded *sdk) {
for (int i = 0; i < naliases; i++) live += aliases[i].live;
rt_log("plugins: %d of %d plugins on in %llu ms (%d process-memory maps, %d kept)", on, nrun,
(unsigned long long)(plat_now_ms() - t0), naliases, live);
mem_plugin_writes = on > 0; // before main's DT_INIT seals its RELRO (memory.c mem_set_permission)
if (on && cfg_bool("TOTK_PLUGIN_TRACE")) trace_entries();
return 1;
#else
+31
View File
@@ -0,0 +1,31 @@
// The build's record of what a mod plugin's init writes into the game modules (patches.h RT_PLUGIN_WRITES, from the
// `expect` lines of recomp/patches.py), and the lookup plugin_init.c check_writes makes for every word an init changed
// at the start of the game.
#pragma once
#include <stdint.h>
#include <string.h>
// any: the expect line said `* *`, a word of main's .data or .bss that shapes no lifted code (tools/exefs_plugins.py
// plugin_lines). The game may hold another value there at play than in the service run (Zonai Fieldworks' Self Recall
// takes its storage off a pool size that grows with the resolution's texture heap), so it matches by place only. A
// hook branch in .text and a pointer into a plugin's .text match by place and both words.
typedef struct {
int plugin;
const char *module;
uint64_t off;
uint32_t old, now;
int any;
} PluginWrite;
// The X of RT_PLUGIN_WRITES for a table of PluginWrite.
#define PLUGIN_WRITE(p, mod, off, old, now, any) {p, mod, off, old, now, any},
// The index of the entry of plugin that records the write of module+off from old to now, or -1.
static inline int plugin_write_find(const PluginWrite *tab, int n, int plugin, const char *module, uint64_t off,
uint32_t old, uint32_t now) {
for (int k = 0; k < n; k++)
if (tab[k].plugin == plugin && tab[k].off == off && !strcmp(tab[k].module, module) &&
(tab[k].any || (tab[k].old == old && tab[k].now == now)))
return k;
return -1;
}
+34 -9
View File
@@ -44,6 +44,8 @@
#include "ov.h"
#include "platform/platform.h"
static void vert_plus_init(double ratio_over_16x9);
#define BASE_W 1920
#define BASE_H 1080
#define SCENE_W 1600
@@ -643,6 +645,7 @@ void res_init(void) {
memcpy(page + 56, &r, sizeof r);
rt_patch_switch(aspect, 1);
rt_log("resolution: camera aspect ratio %.4f (16:9 is %.4f)", ratio, game);
if (ratio < game) vert_plus_init(ratio / game);
}
} else {
rt_patch_switch(aspect, 0); // the page holds no ratio
@@ -673,25 +676,47 @@ int res_wants_wide_overlay(const unsigned out[2]) {
// Field of view (TOTK_FOV, percent of the game's own, 70..140, live): the camera's vertical view angle times the factor
// on page +60 (recomp/patches-v110.txt, patches-v121.txt and patches-v143.txt, set fov). The horizontal angle follows
// through the aspect ratio. 100 switches the set off, so the camera code is the game's own. Runs on a settings change
// (gfx_present.c window_settings_live), the first time at the first present.
// through the aspect ratio. A factor of 1 switches the set off, so the camera code is the game's own. Runs on a settings
// change (gfx_present.c window_settings_live), the first time at the first present.
//
// Vert+ (TOTK_VERT_PLUS, off by default; the Display tab's row under the field of view): the camera keeps the game's vertical view angle at every shape, so a shape
// narrower than 16:9 (16:10, 3:2, 4:3) showed less of the world at the sides than 16:9 does. The factor is then also
// multiplied by the one that gives the game's default view the horizontal angle it has at 16:9: tan(v'/2) = tan(v/2)
// * (16/9) / aspect, so v' / v = 2 atan(tan(v/2) k) / v with k = 16:9 over the aspect. v is the game's default
// vertical angle, 51.2 degrees, measured on 1.4.3 at Lookout Landing: a 4:3 frame at TOTK_FOV=130 is a 16:9 frame of
// the same moment scaled by 0.730 about its middle (tan(v/2) / tan(1.3 v/2) = 0.730 gives v = 51.2). The patch scales
// the angle linearly, so a zoomed view (the bow, the scope) gets the same factor, a few percent short of the exact one.
#define FOV_MIN 70
#define FOV_MAX 140
#define VERT_PLUS_V (51.2 * 3.14159265358979 / 180)
static float vert_plus_k = 1; // set by res_init (vert_plus_init) for a camera narrower than 16:9
static void vert_plus_init(double ratio_over_16x9) {
double k = 1 / ratio_over_16x9, v = VERT_PLUS_V;
vert_plus_k = (float)(2 * atan(tan(v / 2) * k) / v);
}
void res_fov_live(void) {
static int set = -2, shown = 100;
static int set = -2, shown = 100, shown_vp = 0; // the game's own view: nothing to write until one changes
if (set == -2) set = rt_patch_set("fov");
int pct = cfg_int("TOTK_FOV");
pct = pct < FOV_MIN ? FOV_MIN : pct > FOV_MAX ? FOV_MAX : pct;
if (pct == shown) return;
shown = pct;
int vp = vert_plus_k != 1 && cfg_bool("TOTK_VERT_PLUS");
if (pct == shown && vp == shown_vp) return;
shown = pct, shown_vp = vp;
if (set < 0) {
rt_log("resolution: this game version has no field-of-view patch; TOTK_FOV=%d does nothing", pct);
if (pct != 100 || vp)
rt_log("resolution: this game version has no field-of-view patch; TOTK_FOV=%d and Vert+ do nothing", pct);
return;
}
float k = pct / 100.0f;
float k = pct / 100.0f * (vp ? vert_plus_k : 1);
memcpy((uint8_t *)rt_patch_page() + 60, &k, sizeof k); // before the switch: a site that sees it on reads k
rt_patch_switch(set, pct != 100);
rt_log("resolution: field of view %d%% of the game's", pct);
rt_patch_switch(set, k != 1);
if (vp)
rt_log("resolution: field of view %d%% of the game's, times %.4f for Vert+ (the 16:9 width at this narrower "
"shape)", pct, vert_plus_k);
else
rt_log("resolution: field of view %d%% of the game's", pct);
}
// TOTK_DYNAMIC_RES = 0 holds the game's dynamic resolution at 100 % (patches-v110.txt, patches-v121.txt and patches-v143.txt,
+5 -1
View File
@@ -31,7 +31,11 @@ RtStats rt_stats(void) {
return (RtStats){__atomic_load_n(&g_svcs, __ATOMIC_RELAXED), kern_threads_created(), hostfn_calls()};
}
static int readable(uint64_t a, uint64_t n) { return plat_mem_readable(a, n); }
// With TOTK_HEAP_LAZY the heap by the layout (its pages may not be committed before first use), anything else by
// the OS; without it the OS for everything, as before.
static int readable(uint64_t a, uint64_t n) {
return mem_heap_lazy() ? mem_guest_readable(a, n) : plat_mem_readable(a, n);
}
void kern_backtrace(const Cpu *c) {
char d[160];
+235 -10
View File
@@ -1,21 +1,246 @@
// The software keyboard's front end for SDL windows (swkbd.h). Until the in-game text field exists (an ImGui entry in
// the menu overlay, which SDL_StartTextInput can pair with the Steam Deck's on-screen keyboard), the text entry takes
// the starting text at once, as TOTK_SWKBD_ANSWER=<initial> does: the game's initial text, else the default name from
// the catalog. TotK asks only for a horse's name. TOTK_SWKBD_TEST=cancel stands for Cancel pressed, as in the Win32
// window.
// The software keyboard's front end for SDL windows (swkbd.h): a text window of its own, opened on the window thread
// (gfx_window_sdl_run) and fed by that thread's events. The keyboard types, Backspace deletes, Enter is OK and Escape
// cancels. The controller moves a letter grid: D-pad moves the cursor, the bottom button adds the letter, the right
// button deletes, Start is OK and the top button cancels. The guest thread waits for the answer. Without a game window
// it takes the starting text at once.
#include <stdio.h>
#include <string.h>
#include <SDL3/SDL.h>
#include "cfg.h"
#include "host.h"
#include "input_sdl.h"
#include "platform/platform.h"
#include "swkbd.h"
#include "ui_text.h"
#define GRID_COLS 10
static const char grid_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.";
#define GRID_N ((int)(sizeof grid_chars - 1))
typedef struct {
const SwkbdRequest *req;
uint16_t text[KB_LIMIT + 1];
size_t n;
int sel; // the grid cell the controller's cursor is on
int result; // 1 OK, -1 Cancel, 0 still open
int open;
SDL_Window *win;
SDL_Renderer *ren;
Uint32 id;
PlatEvent done;
} Box;
static Box *g_box; // one text entry at a time (swkbd.c holds the lock)
static void draw(const Box *b) {
char prompt[0x101 * 3 + 1], text[KB_LIMIT * 3 + 2], line[KB_LIMIT * 3 + 2];
size_t pl = 0;
while (pl < 0x100 && b->req->prompt[pl]) pl++;
if (pl) swkbd_utf16_to_utf8(b->req->prompt, pl, prompt, sizeof prompt);
else snprintf(prompt, sizeof prompt, "%s", ui_text(UI_SWKBD_PROMPT));
if (b->req->password) { // one star per character, not per UTF-16 unit
size_t k = 0;
for (size_t i = 0; i < b->n && k < KB_LIMIT; i++)
if (b->text[i] < 0xdc00 || b->text[i] >= 0xe000) text[k++] = '*';
text[k] = 0;
} else {
swkbd_utf16_to_utf8(b->text, b->n, text, sizeof text);
}
snprintf(line, sizeof line, "%s_", text);
SDL_SetRenderDrawColor(b->ren, 24, 24, 32, 255);
SDL_RenderClear(b->ren);
SDL_SetRenderScale(b->ren, 4.0f, 4.0f);
SDL_SetRenderDrawColor(b->ren, 240, 240, 240, 255);
SDL_RenderDebugText(b->ren, 4, 4, prompt);
SDL_RenderDebugText(b->ren, 4, 20, line);
for (int i = 0; i < GRID_N; i++) {
float x = 4.0f + (float)(i % GRID_COLS) * 14.0f, y = 40.0f + (float)(i / GRID_COLS) * 18.0f;
char c[2] = {grid_chars[i], 0};
if (i == b->sel) {
SDL_FRect cell = {x - 2.0f, y - 2.0f, 12.0f, 12.0f};
SDL_SetRenderDrawColor(b->ren, 200, 160, 40, 255);
SDL_RenderFillRect(b->ren, &cell);
SDL_SetRenderDrawColor(b->ren, 24, 24, 32, 255);
}
SDL_RenderDebugText(b->ren, x, y, c);
SDL_SetRenderDrawColor(b->ren, 240, 240, 240, 255);
}
// the debug font draws ASCII: the hints are the catalog's English text whatever the game's language
SDL_RenderDebugText(b->ren, 4, 116, ui_text_in("en", UI_SWKBD_SDL_KEYS_HINT));
SDL_RenderDebugText(b->ren, 4, 130, ui_text_in("en", UI_SWKBD_SDL_PAD_HINT1));
SDL_RenderDebugText(b->ren, 4, 144, ui_text_in("en", UI_SWKBD_SDL_PAD_HINT2));
SDL_RenderPresent(b->ren);
}
static void close_box(Box *b);
static void open_box(void *arg) {
Box *b = arg;
b->win = SDL_CreateWindow(ui_text(UI_SWKBD_TITLE), 1280, 720, 0);
if (!b->win) {
rt_log("swkbd: cannot open the text entry window (%s)", SDL_GetError());
return;
}
b->ren = SDL_CreateRenderer(b->win, NULL);
if (!b->ren) {
rt_log("swkbd: no renderer for the text entry (%s)", SDL_GetError());
SDL_DestroyWindow(b->win);
b->win = NULL;
return;
}
b->id = SDL_GetWindowID(b->win);
b->open = 1;
g_box = b;
SDL_StartTextInput(b->win);
SDL_RaiseWindow(b->win);
draw(b);
const char *test = cfg_get("TOTK_SWKBD_TEST");
if (test && !strcmp(test, "ok")) { // as the Win32 window: OK pressed at once
b->result = 1;
close_box(b);
}
}
static void close_box(Box *b) {
SDL_StopTextInput(b->win);
SDL_DestroyRenderer(b->ren);
SDL_DestroyWindow(b->win);
b->win = NULL;
b->ren = NULL;
g_box = NULL;
plat_event_set(&b->done);
}
// Appends typed UTF-16 within the game's limits: a surrogate pair goes in whole or not at all (as clean in swkbd.c),
// and a number pad takes digits only.
static void add_text(Box *b, const uint16_t *u, size_t k) {
const SwkbdRequest *r = b->req;
size_t max = (size_t)r->max_len < KB_LIMIT ? (size_t)r->max_len : KB_LIMIT;
for (size_t i = 0; i < k; i++) {
int pair = u[i] >= 0xd800 && u[i] < 0xdc00 && i + 1 < k && u[i + 1] >= 0xdc00 && u[i + 1] < 0xe000;
if (pair) {
if (!r->numeric && b->n + 2 <= max) b->text[b->n++] = u[i], b->text[b->n++] = u[i + 1];
i++;
} else if (b->n < max && swkbd_allowed(u[i], r->disabled, r->numeric)) {
b->text[b->n++] = u[i];
}
}
}
static void delete_last(Box *b) {
if (!b->n) return;
int pair = b->n >= 2 && b->text[b->n - 1] >= 0xdc00 && b->text[b->n - 1] < 0xe000 && b->text[b->n - 2] >= 0xd800 &&
b->text[b->n - 2] < 0xdc00;
b->n -= pair ? 2 : 1;
}
static void pad_button(Box *b, Uint8 button) {
switch (button) {
case SDL_GAMEPAD_BUTTON_DPAD_LEFT:
if (b->sel % GRID_COLS) b->sel--;
break;
case SDL_GAMEPAD_BUTTON_DPAD_RIGHT:
if (b->sel + 1 < GRID_N && (b->sel + 1) % GRID_COLS) b->sel++;
break;
case SDL_GAMEPAD_BUTTON_DPAD_UP:
if (b->sel >= GRID_COLS) b->sel -= GRID_COLS;
break;
case SDL_GAMEPAD_BUTTON_DPAD_DOWN:
if (b->sel + GRID_COLS < GRID_N) b->sel += GRID_COLS;
break;
case SDL_GAMEPAD_BUTTON_SOUTH: {
uint16_t one = (uint16_t)grid_chars[b->sel];
add_text(b, &one, 1);
break;
}
case SDL_GAMEPAD_BUTTON_EAST:
delete_last(b);
break;
case SDL_GAMEPAD_BUTTON_START:
if ((int)b->n >= b->req->min_len) b->result = 1;
break;
case SDL_GAMEPAD_BUTTON_NORTH:
b->result = -1;
break;
default:
break;
}
}
// The window thread's events for the text entry; returns 1 when the event was the text entry's.
int swkbd_sdl_event(const SDL_Event *e) {
Box *b = g_box;
if (!b) return 0;
if (e->type == SDL_EVENT_GAMEPAD_BUTTON_DOWN) {
pad_button(b, e->gbutton.button);
if (b->result) close_box(b);
else draw(b);
return 1;
}
Uint32 id;
switch (e->type) {
case SDL_EVENT_TEXT_INPUT: id = e->text.windowID; break;
case SDL_EVENT_KEY_DOWN: id = e->key.windowID; break;
case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
case SDL_EVENT_WINDOW_EXPOSED: id = e->window.windowID; break;
default: return 0;
}
if (id != b->id) return 0;
const SwkbdRequest *r = b->req;
if (e->type == SDL_EVENT_WINDOW_CLOSE_REQUESTED) {
b->result = -1;
} else if (e->type == SDL_EVENT_WINDOW_EXPOSED) {
draw(b); // the compositor dropped the contents
return 1;
} else if (e->type == SDL_EVENT_TEXT_INPUT) {
uint16_t u[KB_LIMIT + 1];
size_t k = swkbd_utf8_to_utf16(e->text.text, u, KB_LIMIT + 1);
add_text(b, u, k);
} else {
switch (e->key.scancode) {
case SDL_SCANCODE_BACKSPACE:
delete_last(b);
break;
case SDL_SCANCODE_RETURN:
case SDL_SCANCODE_KP_ENTER:
if ((int)b->n >= r->min_len) b->result = 1;
break;
case SDL_SCANCODE_ESCAPE:
b->result = -1;
break;
default:
break;
}
}
if (b->result) close_box(b);
else draw(b);
return 1;
}
int text_entry_run(const SwkbdRequest *req, uint16_t *out, size_t cap, size_t *n) {
const char *test = cfg_get("TOTK_SWKBD_TEST");
if (test && !strcmp(test, "cancel")) { *n = 0; return 0; }
Box b = {.req = req};
size_t k = 0;
while (k < cap && req->initial[k]) k++;
memcpy(out, req->initial, k * 2);
*n = k;
rt_log("swkbd: no text entry window on this host yet: the %s name is taken", req->game_initial ? "game's" : "default");
return k > 0;
while (k < KB_LIMIT && req->initial[k]) k++;
memcpy(b.text, req->initial, k * 2);
b.n = k;
if (gfx_window_sdl()) {
plat_event_init(&b.done, 1, 0);
gfx_window_sdl_run(open_box, &b);
}
if (!b.open) {
rt_log("swkbd: no text entry window on this host: the %s name is taken", req->game_initial ? "game's" : "default");
size_t f = b.n < cap ? b.n : cap;
memcpy(out, b.text, f * 2);
*n = f;
return f > 0;
}
plat_event_wait(&b.done);
if (b.result != 1) { *n = 0; return 0; }
*n = b.n < cap ? b.n : cap;
memcpy(out, b.text, *n * 2);
return 1;
}
+12 -6
View File
@@ -571,15 +571,18 @@ static void folders_retry(const char *id, int need) {
}
// The game resolution (resolution.c): 16:9 sizes from its smallest, 1280x720 (for weak GPUs), up, the common 21:9 and
// 32:9 monitor sizes, the 16:10 screens of the Steam Deck, handhelds and laptops and the 3:2 screens of laptops and
// tablets (Surface, Framework; the camera and the HUD follow
// another shape, resolution.c res_init; the installer lays the HUD out for each, installer/steps.py ASPECT_SIZES), and
// the current value when it is another size.
// 32:9 monitor sizes (7680x2160: the 57-inch dual-4K ones), the 16:10 screens of the Steam Deck, handhelds and laptops, the 3:2 screens of laptops and
// tablets (Surface, Framework), the 4:3 screens of CRT monitors and iPads and the 19.5:9 and 20:9 screens of phones a
// game is streamed to (the camera and the HUD follow another shape, resolution.c res_init; the installer lays the HUD
// out for each, installer/screens.py ASPECT_SIZES), and the current value when it is another size: any shape from 4:3
// to 32:9 gets a layout of its own (cfg.c cfg_shape_size).
static void row_output_res(void) {
static const char *const vals[] = {"1280x720", "1600x900", "1920x1080", "2560x1440", "3200x1800", "3840x2160",
"2560x1080", "3440x1440", "3840x1600", "5120x2160", "3840x1080", "5120x1440",
"2560x1080", "3440x1440", "3840x1600", "5120x2160", "3840x1080", "5120x1440", "7680x2160",
"1280x800", "1680x1050", "1920x1200", "2560x1600",
"1920x1280", "2160x1440", "2256x1504", "2880x1920", "3000x2000"};
"1920x1280", "2160x1440", "2256x1504", "2880x1920", "3000x2000",
"1440x1080", "1600x1200", "2048x1536", "2732x2048",
"2340x1080", "3120x1440", "2400x1080", "3200x1440"};
enum { N = sizeof vals / sizeof *vals };
char shown[N][32];
const char *names[N];
@@ -822,6 +825,7 @@ static void tab_screen(float scale) {
static const UiTextId movie_aspect[] = {UI_MENU_MOVIE_ASPECT_KEEP, UI_MENU_MOVIE_ASPECT_STRETCH};
opt_choice("TOTK_MOVIE_ASPECT", UI_MENU_MOVIE_ASPECT, movie_aspect, 2, UI_MENU_MOVIE_ASPECT_DESC);
opt_slider("TOTK_FOV", UI_MENU_FOV, 70, 140, UI_MENU_FOV_DESC, 5, "%.0f %%");
opt_toggle("TOTK_VERT_PLUS", UI_MENU_VERT_PLUS, UI_MENU_VERT_PLUS_DESC);
static const char *const aniso[] = {"game", "2", "4", "8", "16"};
const char *aniso_names[] = {menu_text(UI_MENU_ANISO_GAME), "2x", "4x", "8x", "16x"};
opt_choice_list("TOTK_ANISO", UI_MENU_ANISO, aniso, aniso_names, 5, UI_MENU_ANISO_DESC);
@@ -1276,6 +1280,8 @@ static void tab_advanced(float scale) {
opt_group(UI_MENU_GROUP_SCHED);
static const UiTextId preempt[] = {UI_MENU_PREEMPT_OFF, UI_MENU_PREEMPT_ON, UI_MENU_PREEMPT_INHERIT}; // 0|1|2
opt_choice("TOTK_ASYNC_PREEMPT", UI_MENU_ASYNC_PREEMPT, preempt, 3, UI_MENU_ASYNC_PREEMPT_DESC);
opt_toggle("TOTK_HOST_CHECKPOINT", UI_MENU_HOST_CHECKPOINT, UI_MENU_HOST_CHECKPOINT_DESC);
opt_toggle("TOTK_SYNC_AHEAD", UI_MENU_SYNC_AHEAD, UI_MENU_SYNC_AHEAD_DESC);
opt_toggle("TOTK_REPLAY_ASYNC", UI_MENU_REPLAY_ASYNC, UI_MENU_REPLAY_ASYNC_DESC);
row_replay_workers();
opt_toggle("TOTK_TIMER_1MS", UI_MENU_TIMER_1MS, UI_MENU_TIMER_1MS_DESC);
+156 -64
View File
@@ -40,6 +40,11 @@ typedef struct { const char *lang; const char *const *text; } Row;
static const char *const text_en[UI_TEXT_COUNT] = {
SWKBD("Text entry", "Enter a name", "Horse", "OK", "Cancel", "Controller: A = OK, B = Cancel"),
// The SDL text entry draws with SDL's ASCII debug font, so these three exist in English only (the other rows fall
// back to it).
[UI_SWKBD_SDL_KEYS_HINT] = "Keys: type, Enter OK, Esc cancel",
[UI_SWKBD_SDL_PAD_HINT1] = "Pad: D-pad move, bottom add, right del",
[UI_SWKBD_SDL_PAD_HINT2] = "Start OK, top cancel",
[UI_MENU_TITLE] = "Settings",
[UI_MENU_TAB_SCREEN] = "Screen", [UI_MENU_TAB_GAME] = "Game", [UI_MENU_TAB_MODS] = "Mods", [UI_MENU_TAB_SOUND] = "Sound",
@@ -96,6 +101,8 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_MENU_MOVIE_ASPECT_KEEP] = "Black bars", [UI_MENU_MOVIE_ASPECT_STRETCH] = "Stretch",
[UI_MENU_FOV] = "Field of view",
[UI_MENU_FOV_DESC] = "How much of the world the camera shows, in percent of the game's own. Game versions 1.1.0, 1.2.1 and 1.4.3.",
[UI_MENU_VERT_PLUS] = "Keep the 16:9 width",
[UI_MENU_VERT_PLUS_DESC] = "On screens narrower than 16:9 (Steam Deck, 16:10, 4:3) the camera shows the same width of the world as at 16:9, and more above and below. No effect at 16:9 or wider.",
[UI_MENU_SHADOW_RES] = "Shadow map size",
[UI_MENU_SHADOW_RES_DESC] = "Size of the sun's shadow map. The game's own size changes with the view, down to about 400 "
"near the ground, so leaf shadows look blocky and jump; a fixed size keeps them still and "
@@ -527,6 +534,10 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_MENU_REPLAY_WORKERS_NOW] = "now: %s",
[UI_MENU_TIMER_1MS] = "1 ms Windows timer",
[UI_MENU_TIMER_1MS_DESC] = "Raises the system timer resolution to 1 ms for steadier frame pacing.",
[UI_MENU_SYNC_AHEAD] = "One frame ahead of the GPU",
[UI_MENU_SYNC_AHEAD_DESC] = "The game builds the next frame while the graphics card still draws the previous one. More frames per second, one frame more input delay.",
[UI_MENU_HOST_CHECKPOINT] = "Quick core hand-over",
[UI_MENU_HOST_CHECKPOINT_DESC] = "A game thread gives its virtual core to a more important one as soon as it leaves the port's own code, not at its next system call.",
[UI_MENU_PIPE_WAIT] = "Waiting draw handling",
[UI_MENU_PIPE_WAIT_DESC] = "Default keeps the current scheduling with a reserved worker for waiting draws; Old (draw) uses the previous scheduling.",
[UI_MENU_PIPE_WAIT_DEFAULT] = "Default", [UI_MENU_PIPE_WAIT_DRAW] = "Old (draw)",
@@ -558,12 +569,13 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_MENU_FIX_C0_DESC] = "Fills the driver-reserved constant bank c0 (storage sizes, dispatch size, point size, base instance) instead of reading zeros.",
[UI_MENU_FIX_ZERO] = "Zero new GPU memory",
[UI_MENU_FIX_ZERO_DESC] = "New GPU memory pools start zero-filled, as Switch memory does.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Fog and particles after DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "With DLAA, fog, dust and other particles are drawn over the picture DLSS has"
" already smoothed, as the game draws them without DLSS: small particles in "
"fog (shrines) no longer vanish or leave trails. Off: DLSS also processes "
"these effects, as before. DLAA mode only; the upscaling DLSS modes always "
"process them. Applies at once.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Particles after DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "With DLAA, dust and other particles are drawn over the picture DLSS has "
"already smoothed, as the game draws them without DLSS: small particles in "
"fog (shrines) no longer vanish or leave trails. The fog and the clouds still "
"go through DLSS, so distant edges against the sky stay clean. Off: DLSS also "
"processes the particles, as before. DLAA mode only; the upscaling DLSS modes "
"always process them. Applies at once.",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Fixed DLSS exposure",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS takes the brightness of the game's picture as it is instead of "
"estimating the exposure from each frame: in dark scenes (the Depths) large "
@@ -744,6 +756,8 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_MOVIE_ASPECT_KEEP] = "Чёрные полосы", [UI_MENU_MOVIE_ASPECT_STRETCH] = "Растянуть",
[UI_MENU_FOV] = "Поле зрения",
[UI_MENU_FOV_DESC] = "Сколько мира показывает камера, в процентах от игрового. Для версий игры 1.1.0, 1.2.1 и 1.4.3.",
[UI_MENU_VERT_PLUS] = "Ширина обзора как в 16:9",
[UI_MENU_VERT_PLUS_DESC] = "На экранах уже 16:9 (Steam Deck, 16:10, 4:3) камера показывает мир той же ширины, что и в 16:9, и больше сверху и снизу. На 16:9 и шире ничего не меняет.",
[UI_MENU_SHADOW_RES] = "Размер карты теней",
[UI_MENU_SHADOW_RES_DESC] = "Размер карты теней от солнца. Собственный размер игры меняется вместе с видом, у земли до "
"примерно 400, поэтому тени листвы выглядят квадратными и дёргаются; постоянный размер делает "
@@ -1180,6 +1194,10 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_REPLAY_WORKERS_NOW] = "сейчас: %s",
[UI_MENU_TIMER_1MS] = "Таймер Windows 1 мс",
[UI_MENU_TIMER_1MS_DESC] = "Повышает точность системного таймера до 1 мс для ровного темпа кадров.",
[UI_MENU_SYNC_AHEAD] = "На кадр впереди видеокарты",
[UI_MENU_SYNC_AHEAD_DESC] = "Игра готовит следующий кадр, пока видеокарта рисует предыдущий. Больше кадров в секунду, на один кадр больше задержка ввода.",
[UI_MENU_HOST_CHECKPOINT] = "Быстрая передача ядра",
[UI_MENU_HOST_CHECKPOINT_DESC] = "Поток игры отдаёт виртуальное ядро более важному потоку сразу при выходе из кода порта, а не на следующем системном вызове.",
[UI_MENU_PIPE_WAIT] = "Обработка ожидающих отрисовок",
[UI_MENU_PIPE_WAIT_DESC] = "«По умолчанию» — текущее планирование с отдельным потоком для ожидающих отрисовок; «Старый способ» — прежнее планирование.",
[UI_MENU_PIPE_WAIT_DEFAULT] = "По умолчанию", [UI_MENU_PIPE_WAIT_DRAW] = "Старый способ",
@@ -1211,12 +1229,13 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_FIX_C0_DESC] = "Заполняет зарезервированный драйвером банк констант c0 (размеры хранилищ, размер запуска, размер точки, базовый экземпляр) вместо чтения нулей.",
[UI_MENU_FIX_ZERO] = "Обнулять новую память GPU",
[UI_MENU_FIX_ZERO_DESC] = "Новые пулы памяти GPU заполняются нулями, как память Switch.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Туман и частицы после DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "С DLAA туман, пыль и другие частицы рисуются поверх картинки, уже сглаженной"
" DLSS, как игра рисует их без DLSS: мелкие частицы в тумане (святилища) "
"больше не пропадают и не оставляют шлейфов. Выкл.: DLSS обрабатывает и эти "
"эффекты, как раньше. Только в режиме DLAA; режимы DLSS с повышением "
"разрешения обрабатывают их всегда. Применяется сразу.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Частицы после DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "С DLAA пыль и другие частицы рисуются поверх картинки, уже сглаженной DLSS, "
"как игра рисует их без DLSS: мелкие частицы в тумане (святилища) больше не "
"пропадают и не оставляют шлейфов. Туман и облака по-прежнему проходят через "
"DLSS, поэтому далёкие края на фоне неба остаются чистыми. Выкл.: DLSS "
"обрабатывает и частицы, как раньше. Только в режиме DLAA; режимы DLSS с "
"повышением разрешения обрабатывают их всегда. Применяется сразу.",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Фиксированная экспозиция DLSS",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS берёт яркость картинки игры как есть, а не оценивает экспозицию по "
"каждому кадру: в тёмных сценах (Глубины) большие участки в тумане больше не "
@@ -1633,6 +1652,10 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
[UI_MENU_REPLAY_WORKERS_NOW] = "agora: %s",
[UI_MENU_TIMER_1MS] = "Timer do Windows de 1 ms",
[UI_MENU_TIMER_1MS_DESC] = "Aumenta a resolução do timer do sistema para 1 ms, para um ritmo de quadros mais estável.",
[UI_MENU_SYNC_AHEAD] = "Um quadro à frente da GPU",
[UI_MENU_SYNC_AHEAD_DESC] = "O jogo prepara o próximo quadro enquanto a placa de vídeo ainda desenha o anterior. Mais quadros por segundo, um quadro a mais de atraso na entrada.",
[UI_MENU_HOST_CHECKPOINT] = "Troca rápida de núcleo",
[UI_MENU_HOST_CHECKPOINT_DESC] = "Uma thread do jogo cede seu núcleo virtual a uma mais importante assim que sai do código do port, e não na próxima chamada de sistema.",
[UI_MENU_PIPE_WAIT] = "Tratamento de desenhos em espera",
[UI_MENU_PIPE_WAIT_DESC] = "Padrão mantém o agendamento atual, com um worker reservado para desenhos em espera; Antigo (draw) usa o agendamento anterior.",
[UI_MENU_PIPE_WAIT_DEFAULT] = "Padrão", [UI_MENU_PIPE_WAIT_DRAW] = "Antigo (draw)",
@@ -1666,12 +1689,14 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
[UI_MENU_FIX_C0_DESC] = "Preenche o banco de constantes c0 reservado ao driver (tamanhos de armazenamento, tamanho do dispatch, tamanho do ponto, instância base) em vez de ler zeros.",
[UI_MENU_FIX_ZERO] = "Zerar memória nova da GPU",
[UI_MENU_FIX_ZERO_DESC] = "Novos pools de memória da GPU começam zerados, como a memória do Switch.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Névoa e partículas após o DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Com DLAA, a névoa, a poeira e outras partículas são desenhadas sobre a "
"imagem já suavizada pelo DLSS, como o jogo as desenha sem DLSS: partículas "
"pequenas na névoa (santuários) não somem mais nem deixam rastros. Desligado:"
" o DLSS também processa esses efeitos, como antes. Só no modo DLAA; os modos"
" de DLSS que aumentam a resolução sempre os processam. Aplica-se na hora.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Partículas após o DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Com DLAA, a poeira e outras partículas são desenhadas sobre a imagem já "
"suavizada pelo DLSS, como o jogo as desenha sem DLSS: partículas pequenas na "
"névoa (santuários) não somem mais nem deixam rastros. A névoa e as nuvens "
"continuam passando pelo DLSS, então as bordas distantes contra o céu ficam "
"limpas. Desligado: o DLSS também processa as partículas, como antes. Só no "
"modo DLAA; os modos de DLSS que aumentam a resolução sempre as processam. "
"Aplica-se na hora.",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Exposição fixa do DLSS",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "O DLSS usa o brilho da imagem do jogo como ele é, em vez de estimar a "
"exposição a cada quadro: em cenas escuras (as Profundezas), grandes áreas com "
@@ -1740,6 +1765,8 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
[UI_MENU_FOV] = "Campo de visão",
[UI_MENU_FOV_DESC] = "Quanto do mundo a câmera mostra, em porcentagem do original do jogo. Nas versões 1.1.0, 1.2.1 e 1.4.3 "
"do jogo.",
[UI_MENU_VERT_PLUS] = "Manter a largura de 16:9",
[UI_MENU_VERT_PLUS_DESC] = "Em telas mais estreitas que 16:9 (Steam Deck, 16:10, 4:3), a câmera mostra a mesma largura do mundo que em 16:9, e mais acima e abaixo. Sem efeito em 16:9 ou mais largo.",
[UI_MENU_SHADOW_RES] = "Tamanho do mapa de sombras",
[UI_MENU_SHADOW_RES_DESC] = "Tamanho do mapa de sombras do sol. O tamanho do jogo muda com a vista, até cerca de "
"400 perto do chão, então as sombras das folhas ficam quadriculadas e pulam; um "
@@ -2140,6 +2167,8 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_MENU_FOV] = "视野",
[UI_MENU_FOV_DESC] = "镜头能看到多大范围,以游戏自身视野的百分比表示。"
"支持游戏版本 1.1.0、1.2.1 和 1.4.3。",
[UI_MENU_VERT_PLUS] = "保持 16:9 宽度",
[UI_MENU_VERT_PLUS_DESC] = "在比 16:9 更窄的屏幕上(Steam Deck、16:10、4:3),镜头显示与 16:9 相同宽度的世界,上下显示更多。16:9 或更宽的屏幕没有变化。",
[UI_MENU_SHARPNESS] = "FSR 锐度",
[UI_MENU_SHARPNESS_DESC] = "FSR 缩放后的锐化强度;0 为关闭。",
[UI_MENU_COLOR] = "色彩",
@@ -2416,6 +2445,10 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
[UI_MENU_REPLAY_WORKERS_NOW] = "当前:%s",
[UI_MENU_TIMER_1MS] = "1 ms Windows 计时器",
[UI_MENU_TIMER_1MS_DESC] = "将系统计时器精度提高到 1 ms,使帧间隔更平稳。",
[UI_MENU_SYNC_AHEAD] = "领先 GPU 一帧",
[UI_MENU_SYNC_AHEAD_DESC] = "游戏在显卡仍在绘制上一帧时就开始准备下一帧。帧率更高,输入延迟多一帧。",
[UI_MENU_HOST_CHECKPOINT] = "快速交出核心",
[UI_MENU_HOST_CHECKPOINT_DESC] = "游戏线程一离开移植层代码就把虚拟核心让给更重要的线程,而不是等到下一次系统调用。",
[UI_MENU_PIPE_WAIT] = "等待中绘制的处理",
[UI_MENU_PIPE_WAIT_DESC] = "默认保留当前调度,并为等待中的绘制预留一个工作线程;"
"旧版(绘制)沿用先前的调度。",
@@ -2467,10 +2500,10 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
"基础实例),而不是读取零值。",
[UI_MENU_FIX_ZERO] = "清零新的 GPU 内存",
[UI_MENU_FIX_ZERO_DESC] = "新的 GPU 内存池初始内容为零,与 Switch 内存一致。",
[UI_MENU_DLAA_EFFECTS_AFTER] = "DLAA 之后绘制雾和粒子",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "开启 DLAA 时,雾、灰尘和其他粒子绘制在 DLSS 已平滑的画面之上,与游戏不用 DLSS 时的"
"绘制方式相同:雾中的细小粒子(神庙中)不再消失,也不再留下拖影。关闭:DLSS 也处理这些效果,与以"
"前相同。仅用于 DLAA 模式;提升分辨率的 DLSS 模式始终处理它们。立即生效。",
[UI_MENU_DLAA_EFFECTS_AFTER] = "DLAA 之后绘制粒子",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "开启 DLAA 时,灰尘和其他粒子绘制在 DLSS 已平滑的画面之上,与游戏不用 DLSS "
"时的绘制方式相同:雾中的细小粒子(神庙中)不再消失,也不再留下拖影。雾和云仍由 DLSS 处理,因此远处与天空相接的边缘保持干净。关闭:DLSS "
"也处理这些粒子,与以前相同。仅用于 DLAA 模式;提升分辨率的 DLSS 模式始终处理它们。立即生效。",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "固定 DLSS 曝光",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS 直接使用游戏画面的亮度,而不是逐帧自行估算曝光:在暗场景(地底)中,"
"镜头移动时大片雾中区域不再忽暗忽亮一帧。关闭:DLSS 自行估算曝光,与以前相同。立即生效。",
@@ -2852,6 +2885,8 @@ static const char *const text_de[UI_TEXT_COUNT] = {
[UI_MENU_MOVIE_ASPECT_STRETCH] = "Strecken",
[UI_MENU_FOV] = "Sichtfeld",
[UI_MENU_FOV_DESC] = "Wie viel von der Welt die Kamera zeigt, in Prozent des Spielwerts. Nur Spielversion 1.4.3.",
[UI_MENU_VERT_PLUS] = "16:9-Breite behalten",
[UI_MENU_VERT_PLUS_DESC] = "Auf Bildschirmen, die schmaler als 16:9 sind (Steam Deck, 16:10, 4:3), zeigt die Kamera dieselbe Breite der Welt wie bei 16:9 und mehr darüber und darunter. Bei 16:9 oder breiter ohne Wirkung.",
[UI_MENU_SHADOW_RES] = "Größe der Schattenkarte",
[UI_MENU_SHADOW_RES_DESC] = "Größe der Schattenkarte der Sonne. Die Größe des Spiels ändert sich mit der Ansicht, "
"bis etwa 400 nahe am Boden, daher wirken Blätterschatten klotzig und springen; eine "
@@ -3451,6 +3486,10 @@ static const char *const text_de[UI_TEXT_COUNT] = {
[UI_MENU_REPLAY_WORKERS_NOW] = "jetzt: %s",
[UI_MENU_TIMER_1MS] = "Windows-Timer mit 1 ms",
[UI_MENU_TIMER_1MS_DESC] = "Erhöht die Auflösung des Systemtimers auf 1 ms für gleichmäßigere Bildzeiten.",
[UI_MENU_SYNC_AHEAD] = "Ein Bild vor der GPU",
[UI_MENU_SYNC_AHEAD_DESC] = "Das Spiel baut das nächste Bild, während die Grafikkarte noch das vorige zeichnet. Mehr Bilder pro Sekunde, ein Bild mehr Eingabeverzögerung.",
[UI_MENU_HOST_CHECKPOINT] = "Schnelle Kernübergabe",
[UI_MENU_HOST_CHECKPOINT_DESC] = "Ein Spiel-Thread gibt seinen virtuellen Kern an einen wichtigeren ab, sobald er den Code des Ports verlässt, nicht erst beim nächsten Systemaufruf.",
[UI_MENU_PIPE_WAIT] = "Umgang mit wartenden Draws",
[UI_MENU_PIPE_WAIT_DESC] = "Standard behält die aktuelle Zeitplanung mit einem reservierten Worker für wartende "
"Draws; Alt (Draw) verwendet die vorherige Zeitplanung.",
@@ -3503,13 +3542,14 @@ static const char *const text_de[UI_TEXT_COUNT] = {
"Punktgröße, Basisinstanz), statt Nullen zu lesen.",
[UI_MENU_FIX_ZERO] = "Neuen GPU-Speicher nullen",
[UI_MENU_FIX_ZERO_DESC] = "Neue GPU-Speicherpools beginnen mit Nullen gefüllt, wie Switch-Speicher.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Nebel und Partikel nach DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Mit DLAA werden Nebel, Staub und andere Partikel über das bereits von DLSS "
[UI_MENU_DLAA_EFFECTS_AFTER] = "Partikel nach DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Mit DLAA werden Staub und andere Partikel über das bereits von DLSS "
"geglättete Bild gezeichnet, so wie das Spiel sie ohne DLSS zeichnet: Kleine "
"Partikel im Nebel (Schreine) verschwinden nicht mehr und ziehen keine Spuren "
"mehr. Aus: DLSS verarbeitet auch diese Effekte, wie bisher. Nur im "
"DLAA-Modus; die hochskalierenden DLSS-Modi verarbeiten sie immer. Wirkt "
"sofort.",
"mehr. Nebel und Wolken gehen weiterhin durch DLSS, sodass ferne Kanten vor "
"dem Himmel sauber bleiben. Aus: DLSS verarbeitet auch die Partikel, wie "
"bisher. Nur im DLAA-Modus; die hochskalierenden DLSS-Modi verarbeiten sie "
"immer. Wirkt sofort.",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Feste DLSS-Belichtung",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS nimmt die Helligkeit des Spielbilds, wie sie ist, statt die Belichtung "
"aus jedem Bild zu schätzen: In dunklen Szenen (Untergrund) werden große "
@@ -3756,6 +3796,8 @@ static const char *const text_fr[UI_TEXT_COUNT] = {
[UI_MENU_FOV] = "Champ de vision",
[UI_MENU_FOV_DESC] = "La part du monde que montre la caméra, en pourcentage de celle du jeu. Version 1.4.3 du jeu "
"uniquement.",
[UI_MENU_VERT_PLUS] = "Garder la largeur 16:9",
[UI_MENU_VERT_PLUS_DESC] = "Sur les écrans plus étroits que 16:9 (Steam Deck, 16:10, 4:3), la caméra montre la même largeur du monde qu'en 16:9, et davantage au-dessus et en dessous. Sans effet en 16:9 ou plus large.",
[UI_MENU_SHADOW_RES] = "Taille de la carte d'ombres",
[UI_MENU_SHADOW_RES_DESC] = "Taille de la carte d'ombres du soleil. La taille du jeu change avec la vue, jusqu'à "
"environ 400 près du sol, si bien que les ombres des feuilles paraissent pixelisées "
@@ -4369,6 +4411,10 @@ static const char *const text_fr[UI_TEXT_COUNT] = {
[UI_MENU_REPLAY_WORKERS_NOW] = "actuel : %s",
[UI_MENU_TIMER_1MS] = "Minuteur Windows de 1 ms",
[UI_MENU_TIMER_1MS_DESC] = "Porte la résolution du minuteur système à 1 ms pour un rythme d'images plus régulier.",
[UI_MENU_SYNC_AHEAD] = "Une image d'avance sur le GPU",
[UI_MENU_SYNC_AHEAD_DESC] = "Le jeu prépare l'image suivante pendant que la carte graphique dessine encore la précédente. Plus d'images par seconde, une image de latence d'entrée en plus.",
[UI_MENU_HOST_CHECKPOINT] = "Cession rapide du cœur",
[UI_MENU_HOST_CHECKPOINT_DESC] = "Un thread du jeu cède son cœur virtuel à un thread plus important dès qu'il quitte le code du portage, et non à son prochain appel système.",
[UI_MENU_PIPE_WAIT] = "Gestion des draws en attente",
[UI_MENU_PIPE_WAIT_DESC] = "Par défaut garde l'ordonnancement actuel avec un worker réservé aux draws en attente "
"; Ancien (draw) utilise l'ordonnancement précédent.",
@@ -4425,13 +4471,15 @@ static const char *const text_fr[UI_TEXT_COUNT] = {
[UI_MENU_FIX_ZERO] = "Remettre à zéro la nouvelle mémoire GPU",
[UI_MENU_FIX_ZERO_DESC] = "Les nouveaux pools de mémoire GPU commencent remplis de zéros, comme la mémoire de la "
"Switch.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Brouillard et particules après DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Avec DLAA, le brouillard, la poussière et les autres particules sont "
"dessinés par-dessus l'image déjà lissée par DLSS, comme le jeu les dessine "
"sans DLSS : les petites particules dans le brouillard (sanctuaires) ne "
"disparaissent plus et ne laissent plus de traînées. Désactivé : DLSS traite "
"aussi ces effets, comme avant. Mode DLAA uniquement ; les modes DLSS avec "
"mise à l'échelle les traitent toujours. S'applique immédiatement.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Particules après DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Avec DLAA, la poussière et les autres particules sont dessinées par-dessus "
"l'image déjà lissée par DLSS, comme le jeu les dessine sans DLSS : les "
"petites particules dans le brouillard (sanctuaires) ne disparaissent plus et "
"ne laissent plus de traînées. Le brouillard et les nuages passent toujours "
"par DLSS, donc les bords lointains sur le ciel restent nets. Désactivé : "
"DLSS traite aussi les particules, comme avant. Mode DLAA uniquement ; les "
"modes DLSS avec mise à l'échelle les traitent toujours. S'applique "
"immédiatement.",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Exposition DLSS fixe",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS prend la luminosité de l'image du jeu telle quelle au lieu d'estimer "
"l'exposition à chaque image : dans les scènes sombres (les Profondeurs), "
@@ -4680,6 +4728,8 @@ static const char *const text_es[UI_TEXT_COUNT] = {
[UI_MENU_FOV] = "Campo de visión",
[UI_MENU_FOV_DESC] = "Cuánto del mundo muestra la cámara, en porcentaje del propio del juego. Solo la versión "
"1.4.3 del juego.",
[UI_MENU_VERT_PLUS] = "Mantener el ancho de 16:9",
[UI_MENU_VERT_PLUS_DESC] = "En pantallas más estrechas que 16:9 (Steam Deck, 16:10, 4:3), la cámara muestra el mismo ancho del mundo que en 16:9, y más por arriba y por abajo. Sin efecto en 16:9 o más ancho.",
[UI_MENU_SHADOW_RES] = "Tamaño del mapa de sombras",
[UI_MENU_SHADOW_RES_DESC] = "Tamaño del mapa de sombras del sol. El tamaño del juego cambia con la vista, hasta "
"unos 400 cerca del suelo, por lo que las sombras de las hojas se ven pixeladas y "
@@ -5281,6 +5331,10 @@ static const char *const text_es[UI_TEXT_COUNT] = {
[UI_MENU_TIMER_1MS] = "Temporizador de Windows de 1 ms",
[UI_MENU_TIMER_1MS_DESC] = "Sube la resolución del temporizador del sistema a 1 ms para un ritmo de fotogramas "
"más estable.",
[UI_MENU_SYNC_AHEAD] = "Un fotograma por delante de la GPU",
[UI_MENU_SYNC_AHEAD_DESC] = "El juego prepara el siguiente fotograma mientras la tarjeta gráfica aún dibuja el anterior. Más fotogramas por segundo, un fotograma más de retraso de entrada.",
[UI_MENU_HOST_CHECKPOINT] = "Cesión rápida del núcleo",
[UI_MENU_HOST_CHECKPOINT_DESC] = "Un hilo del juego cede su núcleo virtual a uno más importante en cuanto sale del código del port, no en su siguiente llamada al sistema.",
[UI_MENU_PIPE_WAIT] = "Gestión de draws en espera",
[UI_MENU_PIPE_WAIT_DESC] = "Predeterminado mantiene la planificación actual con un worker reservado para draws en "
"espera; Antiguo (draw) usa la planificación anterior.",
@@ -5336,12 +5390,14 @@ static const char *const text_es[UI_TEXT_COUNT] = {
"tamaño de dispatch, tamaño de punto, instancia base) en lugar de leer ceros.",
[UI_MENU_FIX_ZERO] = "Poner a cero la memoria GPU nueva",
[UI_MENU_FIX_ZERO_DESC] = "Los nuevos bloques de memoria GPU empiezan llenos de ceros, como la memoria de Switch.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Niebla y partículas tras DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Con DLAA, la niebla, el polvo y otras partículas se dibujan sobre la imagen "
"que DLSS ya ha suavizado, como las dibuja el juego sin DLSS: las partículas "
"pequeñas en la niebla (santuarios) ya no desaparecen ni dejan estelas. No: "
"DLSS también procesa estos efectos, como antes. Solo en el modo DLAA; los "
"modos DLSS con escalado siempre los procesan. Se aplica al momento.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Partículas tras DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Con DLAA, el polvo y otras partículas se dibujan sobre la imagen que DLSS ya "
"ha suavizado, como las dibuja el juego sin DLSS: las partículas pequeñas en "
"la niebla (santuarios) ya no desaparecen ni dejan estelas. La niebla y las "
"nubes siguen pasando por DLSS, así que los bordes lejanos contra el cielo "
"quedan limpios. No: DLSS también procesa las partículas, como antes. Solo en "
"el modo DLAA; los modos DLSS con escalado siempre los procesan. Se aplica al "
"momento.",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Exposición fija de DLSS",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS toma el brillo de la imagen del juego tal cual en lugar de estimar la "
"exposición en cada fotograma: en escenas oscuras (el Subsuelo) las grandes "
@@ -5589,6 +5645,8 @@ static const char *const text_it[UI_TEXT_COUNT] = {
[UI_MENU_FOV] = "Campo visivo",
[UI_MENU_FOV_DESC] = "Quanta parte del mondo mostra la telecamera, in percentuale di quella del gioco. Solo "
"versione 1.4.3 del gioco.",
[UI_MENU_VERT_PLUS] = "Mantieni la larghezza 16:9",
[UI_MENU_VERT_PLUS_DESC] = "Sugli schermi più stretti di 16:9 (Steam Deck, 16:10, 4:3) la telecamera mostra la stessa larghezza del mondo che in 16:9, e di più sopra e sotto. Nessun effetto a 16:9 o più largo.",
[UI_MENU_SHADOW_RES] = "Dimensione della mappa delle ombre",
[UI_MENU_SHADOW_RES_DESC] = "Dimensione della mappa delle ombre del sole. Quella del gioco cambia con la visuale, "
"fino a circa 400 vicino al suolo, quindi le ombre delle foglie sembrano squadrate e "
@@ -6194,6 +6252,10 @@ static const char *const text_it[UI_TEXT_COUNT] = {
[UI_MENU_TIMER_1MS] = "Timer di Windows a 1 ms",
[UI_MENU_TIMER_1MS_DESC] = "Porta la risoluzione del timer di sistema a 1 ms per un ritmo dei fotogrammi più "
"regolare.",
[UI_MENU_SYNC_AHEAD] = "Un fotogramma avanti alla GPU",
[UI_MENU_SYNC_AHEAD_DESC] = "Il gioco prepara il fotogramma successivo mentre la scheda video disegna ancora il precedente. Più fotogrammi al secondo, un fotogramma in più di ritardo dell'input.",
[UI_MENU_HOST_CHECKPOINT] = "Cessione rapida del core",
[UI_MENU_HOST_CHECKPOINT_DESC] = "Un thread del gioco cede il suo core virtuale a uno più importante appena esce dal codice del port, non alla sua prossima chiamata di sistema.",
[UI_MENU_PIPE_WAIT] = "Gestione dei draw in attesa",
[UI_MENU_PIPE_WAIT_DESC] = "Predefinito mantiene la pianificazione attuale con un worker riservato ai draw in "
"attesa; Vecchio (draw) usa la pianificazione precedente.",
@@ -6248,12 +6310,13 @@ static const char *const text_it[UI_TEXT_COUNT] = {
"del dispatch, dimensione dei punti, istanza base) invece di leggere zeri.",
[UI_MENU_FIX_ZERO] = "Azzera la nuova memoria GPU",
[UI_MENU_FIX_ZERO_DESC] = "I nuovi pool di memoria GPU partono riempiti di zeri, come la memoria di Switch.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Nebbia e particelle dopo DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Con DLAA, nebbia, polvere e altre particelle vengono disegnate sopra "
"l'immagine già levigata da DLSS, come le disegna il gioco senza DLSS: le "
"piccole particelle nella nebbia (sacrari) non spariscono più né lasciano "
"scie. No: DLSS elabora anche questi effetti, come prima. Solo in modalità "
"DLAA; le modalità DLSS con upscaling li elaborano sempre. Si applica subito.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Particelle dopo DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Con DLAA, polvere e altre particelle vengono disegnate sopra l'immagine già "
"levigata da DLSS, come le disegna il gioco senza DLSS: le piccole particelle "
"nella nebbia (sacrari) non spariscono più né lasciano scie. Nebbia e nuvole "
"passano ancora per DLSS, così i bordi lontani contro il cielo restano "
"puliti. No: DLSS elabora anche le particelle, come prima. Solo in modalità "
"DLAA; le modalità DLSS con upscaling le elaborano sempre. Si applica subito.",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Esposizione DLSS fissa",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS prende la luminosità dell'immagine del gioco così com'è invece di "
"stimare l'esposizione da ogni fotogramma: nelle scene buie (il Sottosuolo) "
@@ -6500,6 +6563,8 @@ static const char *const text_nl[UI_TEXT_COUNT] = {
[UI_MENU_FOV] = "Gezichtsveld",
[UI_MENU_FOV_DESC] = "Hoeveel van de wereld de camera toont, in procenten van dat van het spel. Alleen spelversie "
"1.4.3.",
[UI_MENU_VERT_PLUS] = "16:9-breedte behouden",
[UI_MENU_VERT_PLUS_DESC] = "Op schermen die smaller zijn dan 16:9 (Steam Deck, 16:10, 4:3) toont de camera dezelfde breedte van de wereld als bij 16:9, en meer erboven en eronder. Geen effect bij 16:9 of breder.",
[UI_MENU_SHADOW_RES] = "Grootte van de schaduwkaart",
[UI_MENU_SHADOW_RES_DESC] = "Grootte van de schaduwkaart van de zon. De grootte van het spel verandert met het "
"zicht, tot ongeveer 400 dicht bij de grond, waardoor bladschaduwen blokkerig ogen en "
@@ -7086,6 +7151,10 @@ static const char *const text_nl[UI_TEXT_COUNT] = {
[UI_MENU_REPLAY_WORKERS_NOW] = "nu: %s",
[UI_MENU_TIMER_1MS] = "Windows-timer van 1 ms",
[UI_MENU_TIMER_1MS_DESC] = "Verhoogt de resolutie van de systeemtimer naar 1 ms voor een gelijkmatiger beeldritme.",
[UI_MENU_SYNC_AHEAD] = "Eén beeld voor op de GPU",
[UI_MENU_SYNC_AHEAD_DESC] = "Het spel bouwt het volgende beeld terwijl de videokaart het vorige nog tekent. Meer beelden per seconde, één beeld meer invoervertraging.",
[UI_MENU_HOST_CHECKPOINT] = "Snelle kernoverdracht",
[UI_MENU_HOST_CHECKPOINT_DESC] = "Een spelthread geeft zijn virtuele kern aan een belangrijkere thread zodra hij de code van de port verlaat, niet pas bij zijn volgende systeemaanroep.",
[UI_MENU_PIPE_WAIT] = "Afhandeling van wachtende draws",
[UI_MENU_PIPE_WAIT_DESC] = "Standaard houdt de huidige planning met een gereserveerde worker voor wachtende "
"draws; Oud (draw) gebruikt de vorige planning.",
@@ -7140,12 +7209,14 @@ static const char *const text_nl[UI_TEXT_COUNT] = {
"dispatchgrootte, puntgrootte, basisinstantie) in plaats van nullen te lezen.",
[UI_MENU_FIX_ZERO] = "Nieuw GPU-geheugen op nul zetten",
[UI_MENU_FIX_ZERO_DESC] = "Nieuwe GPU-geheugenpools beginnen gevuld met nullen, zoals Switch-geheugen.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Mist en deeltjes na DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Met DLAA worden mist, stof en andere deeltjes over het beeld getekend dat "
"DLSS al heeft gladgestreken, zoals het spel ze zonder DLSS tekent: kleine "
"deeltjes in mist (heiligdommen) verdwijnen niet meer en laten geen sporen "
"meer achter. Uit: DLSS verwerkt deze effecten ook, zoals voorheen. Alleen in "
"DLAA-modus; de upscalingmodi van DLSS verwerken ze altijd. Werkt meteen.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Deeltjes na DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Met DLAA worden stof en andere deeltjes over het beeld getekend dat DLSS al "
"heeft gladgestreken, zoals het spel ze zonder DLSS tekent: kleine deeltjes "
"in mist (heiligdommen) verdwijnen niet meer en laten geen sporen meer "
"achter. Mist en wolken gaan nog steeds door DLSS, zodat verre randen tegen "
"de lucht schoon blijven. Uit: DLSS verwerkt ook de deeltjes, zoals voorheen. "
"Alleen in DLAA-modus; de upscalingmodi van DLSS verwerken ze altijd. Werkt "
"meteen.",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Vaste DLSS-belichting",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS neemt de helderheid van het spelbeeld zoals ze is, in plaats van de "
"belichting per beeld te schatten: in donkere scènes (de Diepten) worden "
@@ -7380,6 +7451,8 @@ static const char *const text_ja[UI_TEXT_COUNT] = {
[UI_MENU_MOVIE_ASPECT_STRETCH] = "引き伸ばし",
[UI_MENU_FOV] = "視野角",
[UI_MENU_FOV_DESC] = "カメラが映す範囲を、ゲーム本来の視野に対するパーセントで指定します。ゲームのバージョン 1.4.3 のみ。",
[UI_MENU_VERT_PLUS] = "16:9 の横幅を保つ",
[UI_MENU_VERT_PLUS_DESC] = "16:9 より横幅の狭い画面(Steam Deck、16:10、4:3)で、カメラが 16:9 と同じ横幅の世界を映し、上下はより広く映します。16:9 以上の横長の画面では変わりません。",
[UI_MENU_SHADOW_RES] = "シャドウマップのサイズ",
[UI_MENU_SHADOW_RES_DESC] = "太陽のシャドウマップの大きさです。ゲーム本来のサイズは視点によって変わり、地面近くでは約 400 まで下がるため、葉の影がブロック状になって跳ねます。固定サイ"
"ズにすると影が安定し、くっきりします。1024 を超えると GPU 時間とビデオメモリが増えます。",
@@ -7871,6 +7944,10 @@ static const char *const text_ja[UI_TEXT_COUNT] = {
[UI_MENU_REPLAY_WORKERS_NOW] = "現在: %s",
[UI_MENU_TIMER_1MS] = "1 ms の Windows タイマー",
[UI_MENU_TIMER_1MS_DESC] = "システムタイマーの分解能を 1 ms に上げ、フレーム間隔を安定させます。",
[UI_MENU_SYNC_AHEAD] = "GPU より 1 フレーム先行",
[UI_MENU_SYNC_AHEAD_DESC] = "グラフィックカードが前のフレームを描いている間に、ゲームが次のフレームを組み立てます。フレームレートが上がり、入力遅延が 1 フレーム増えます。",
[UI_MENU_HOST_CHECKPOINT] = "コアの素早い受け渡し",
[UI_MENU_HOST_CHECKPOINT_DESC] = "ゲームのスレッドは、移植側のコードを抜けた時点で、より重要なスレッドに仮想コアを譲ります。次のシステムコールまで待ちません。",
[UI_MENU_PIPE_WAIT] = "待機中の描画の扱い",
[UI_MENU_PIPE_WAIT_DESC] = "「既定」は待機中の描画用にワーカーを確保した現在のスケジューリングを使い、「旧方式 (draw)」は以前のスケジューリングを使います。",
[UI_MENU_PIPE_WAIT_DEFAULT] = "既定",
@@ -7915,9 +7992,10 @@ static const char *const text_ja[UI_TEXT_COUNT] = {
[UI_MENU_FIX_C0_DESC] = "ドライバー予約の定数バンク c0 (ストレージサイズ、ディスパッチサイズ、ポイントサイズ、ベースインスタンス) を、ゼロを読む代わりに埋めます。",
[UI_MENU_FIX_ZERO] = "新しい GPU メモリをゼロで埋める",
[UI_MENU_FIX_ZERO_DESC] = "Switch のメモリと同じく、新しい GPU メモリプールをゼロで埋めた状態から始めます。",
[UI_MENU_DLAA_EFFECTS_AFTER] = "DLAA の後に霧とパーティクル",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "DLAA 使用時、霧、ちり、その他のパーティクルを、DLSS が滑らかにした後の映像の上に描きます。DLSS なしでゲームが描くのと同じです: "
"霧の中の小さなパーティクル (祠) が消えたり残像を残したりしなくなります。オフ: これまでどおり DLSS がこれらのエフェクトも処理します。DLAA "
[UI_MENU_DLAA_EFFECTS_AFTER] = "DLAA の後にパーティクル",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "DLAA 使用時、ちりやその他のパーティクルを、DLSS が滑らかにした後の映像の上に描きます。DLSS なしでゲームが描くのと同じです: "
"霧の中の小さなパーティクル (祠) が消えたり残像を残したりしなくなります。霧と雲は引き続き DLSS "
"を通るため、空を背にした遠くの輪郭はきれいなままです。オフ: これまでどおり DLSS がパーティクルも処理します。DLAA "
"モードのみ。アップスケーリングする DLSS モードでは常に処理されます。すぐに反映されます。",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "DLSS の露出を固定",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS が各フレームから露出を推定せず、ゲームの映像の明るさをそのまま使います: 暗い場面 (地底) "
@@ -8129,6 +8207,8 @@ static const char *const text_ko[UI_TEXT_COUNT] = {
[UI_MENU_MOVIE_ASPECT_STRETCH] = "늘리기",
[UI_MENU_FOV] = "시야각",
[UI_MENU_FOV_DESC] = "카메라가 보여 주는 범위를 게임 원래 시야에 대한 퍼센트로 지정합니다. 게임 버전 1.4.3 전용입니다.",
[UI_MENU_VERT_PLUS] = "16:9 너비 유지",
[UI_MENU_VERT_PLUS_DESC] = "16:9보다 좁은 화면(Steam Deck, 16:10, 4:3)에서 카메라가 16:9와 같은 너비의 세계를 보여 주고 위아래는 더 많이 보여 줍니다. 16:9 이상 넓은 화면에서는 효과가 없습니다.",
[UI_MENU_SHADOW_RES] = "그림자 맵 크기",
[UI_MENU_SHADOW_RES_DESC] = "태양 그림자 맵의 크기입니다. 게임 원래 크기는 시점에 따라 바뀌며 지면 가까이에서는 약 400까지 내려가서 나뭇잎 그림자가 각지고 튀게 됩니다. 고정 "
"크기로 하면 그림자가 안정되고 선명해집니다. 1024를 넘으면 GPU 시간과 비디오 메모리가 늘어납니다.",
@@ -8621,6 +8701,10 @@ static const char *const text_ko[UI_TEXT_COUNT] = {
[UI_MENU_REPLAY_WORKERS_NOW] = "현재: %s",
[UI_MENU_TIMER_1MS] = "1 ms Windows 타이머",
[UI_MENU_TIMER_1MS_DESC] = "시스템 타이머 해상도를 1 ms로 올려 프레임 간격을 고르게 합니다.",
[UI_MENU_SYNC_AHEAD] = "GPU보다 한 프레임 앞서기",
[UI_MENU_SYNC_AHEAD_DESC] = "그래픽 카드가 이전 프레임을 그리는 동안 게임이 다음 프레임을 만듭니다. 프레임이 늘고 입력 지연이 한 프레임 늘어납니다.",
[UI_MENU_HOST_CHECKPOINT] = "빠른 코어 넘기기",
[UI_MENU_HOST_CHECKPOINT_DESC] = "게임 스레드가 포트 코드를 벗어나는 즉시 더 중요한 스레드에 가상 코어를 넘깁니다. 다음 시스템 호출까지 기다리지 않습니다.",
[UI_MENU_PIPE_WAIT] = "대기 중인 그리기 처리",
[UI_MENU_PIPE_WAIT_DESC] = "'기본값'은 대기 중인 그리기용 워커를 둔 현재 스케줄링을, '이전 방식(draw)'은 예전 스케줄링을 사용합니다.",
[UI_MENU_PIPE_WAIT_DEFAULT] = "기본값",
@@ -8666,10 +8750,11 @@ static const char *const text_ko[UI_TEXT_COUNT] = {
[UI_MENU_FIX_C0_DESC] = "드라이버 예약 상수 뱅크 c0(저장소 크기, 디스패치 크기, 포인트 크기, 기본 인스턴스)을 0을 읽는 대신 채웁니다.",
[UI_MENU_FIX_ZERO] = "새 GPU 메모리를 0으로 채우기",
[UI_MENU_FIX_ZERO_DESC] = "Switch 메모리처럼 새 GPU 메모리 풀을 0으로 채운 상태에서 시작합니다.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "DLAA 후 안개와 파티클",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "DLAA 사용 시 안개, 먼지 등 파티클을 DLSS가 이미 부드럽게 한 영상 위에 그립니다. DLSS 없이 게임이 그리는 방식과 "
"같습니다. 안개 속의 작은 파티클(사당)이 더 이상 사라지거나 잔상을 남기지 않습니다. 끄기: 예전처럼 DLSS가 이 효과도 처리합니다. "
"DLAA 모드 전용이며, 업스케일링 DLSS 모드는 항상 이 효과를 처리합니다. 즉시 적용됩니다.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "DLAA 후 파티클",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "DLAA 사용 시 먼지 등 파티클을 DLSS가 이미 부드럽게 한 영상 위에 그립니다. DLSS 없이 게임이 그리는 방식과 같습니다. 안개 "
"속의 작은 파티클(사당)이 더 이상 사라지거나 잔상을 남기지 않습니다. 안개와 구름은 계속 DLSS를 거치므로 하늘을 배경으로 한 먼 "
"윤곽이 깨끗하게 유지됩니다. 끄기: 예전처럼 DLSS가 파티클도 처리합니다. DLAA 모드 전용이며, 업스케일링 DLSS 모드는 항상 이 "
"효과를 처리합니다. 즉시 적용됩니다.",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "DLSS 노출 고정",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS가 프레임마다 노출을 추정하지 않고 게임 영상의 밝기를 그대로 사용합니다. 어두운 장면(지저)에서 안개 낀 넓은 영역이 카메라가 "
"움직일 때 한 프레임 동안 어두워지거나 밝아지지 않습니다. 끄기: 예전처럼 DLSS가 노출을 직접 추정합니다. 즉시 적용됩니다.",
@@ -8864,6 +8949,8 @@ static const char *const text_vi[UI_TEXT_COUNT] = {
[UI_MENU_MOVIE_ASPECT_KEEP] = "Dải đen", [UI_MENU_MOVIE_ASPECT_STRETCH] = "Kéo giãn",
[UI_MENU_FOV] = "Góc nhìn",
[UI_MENU_FOV_DESC] = "Camera cho thấy bao nhiêu thế giới, tính theo phần trăm của game gốc. Game phiên bản 1.1.0, 1.2.1 và 1.4.3.",
[UI_MENU_VERT_PLUS] = "Giữ bề ngang 16:9",
[UI_MENU_VERT_PLUS_DESC] = "Trên màn hình hẹp hơn 16:9 (Steam Deck, 16:10, 4:3), camera cho thấy thế giới rộng ngang như ở 16:9, và nhiều hơn ở phía trên và dưới. Không có tác dụng ở 16:9 hoặc rộng hơn.",
[UI_MENU_SHADOW_RES] = "Kích thước bản đồ bóng",
[UI_MENU_SHADOW_RES_DESC] = "Kích thước bản đồ bóng của mặt trời. Kích thước của game đổi theo tầm nhìn, xuống còn khoảng "
"400 khi gần mặt đất, nên bóng lá trông bị vỡ ô và nhảy; kích thước cố định giữ chúng đứng "
@@ -9283,6 +9370,10 @@ static const char *const text_vi[UI_TEXT_COUNT] = {
[UI_MENU_REPLAY_WORKERS_NOW] = "hiện tại: %s",
[UI_MENU_TIMER_1MS] = "Bộ hẹn giờ Windows 1 ms",
[UI_MENU_TIMER_1MS_DESC] = "Nâng độ phân giải bộ hẹn giờ hệ thống lên 1 ms để nhịp khung hình đều hơn.",
[UI_MENU_SYNC_AHEAD] = "Đi trước GPU một khung hình",
[UI_MENU_SYNC_AHEAD_DESC] = "Game dựng khung hình tiếp theo trong khi card đồ họa vẫn vẽ khung hình trước. Nhiều khung hình mỗi giây hơn, thêm một khung hình độ trễ điều khiển.",
[UI_MENU_HOST_CHECKPOINT] = "Nhường lõi nhanh",
[UI_MENU_HOST_CHECKPOINT_DESC] = "Một luồng game nhường lõi ảo cho luồng quan trọng hơn ngay khi rời khỏi mã của bản port, không đợi đến lời gọi hệ thống tiếp theo.",
[UI_MENU_PIPE_WAIT] = "Xử lý lệnh vẽ đang chờ",
[UI_MENU_PIPE_WAIT_DESC] = "Mặc định giữ cách lập lịch hiện tại, có một luồng xử lý dành riêng cho các lệnh vẽ đang chờ; Cũ (lệnh vẽ) dùng cách lập lịch trước đó.",
[UI_MENU_PIPE_WAIT_DEFAULT] = "Mặc định", [UI_MENU_PIPE_WAIT_DRAW] = "Cũ (lệnh vẽ)",
@@ -9314,11 +9405,12 @@ static const char *const text_vi[UI_TEXT_COUNT] = {
[UI_MENU_FIX_C0_DESC] = "Điền bảng hằng số c0 mà trình điều khiển dành riêng (kích thước vùng lưu trữ, kích thước điều phối, kích thước điểm, thực thể gốc) thay vì đọc ra số không.",
[UI_MENU_FIX_ZERO] = "Xóa sạch bộ nhớ GPU mới",
[UI_MENU_FIX_ZERO_DESC] = "Các vùng nhớ GPU mới bắt đầu với toàn số không, như bộ nhớ Switch.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Sương mù và hạt sau DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Với DLAA, sương mù, bụi và các hạt khác được vẽ đè lên hình DLSS đã làm mịn, như game "
"vẽ chúng khi không có DLSS: các hạt nhỏ trong sương mù (đền thờ) không còn biến mất "
"hay để lại vệt. Tắt: DLSS cũng xử lý các hiệu ứng này, như trước. Chỉ ở chế độ "
"DLAA; các chế độ phóng to DLSS luôn xử lý chúng. Áp dụng ngay.",
[UI_MENU_DLAA_EFFECTS_AFTER] = "Hạt sau DLAA",
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Với DLAA, bụi và các hạt khác được vẽ đè lên hình DLSS đã làm mịn, như game "
"vẽ chúng khi không có DLSS: các hạt nhỏ trong sương mù (đền thờ) không còn "
"biến mất hay để lại vệt. Sương mù và mây vẫn đi qua DLSS, nên các cạnh ở xa "
"trên nền trời vẫn sạch. Tắt: DLSS cũng xử lý các hạt này, như trước. Chỉ ở "
"chế độ DLAA; các chế độ phóng to DLSS luôn xử lý chúng. Áp dụng ngay.",
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Phơi sáng DLSS cố định",
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS lấy độ sáng của hình game như nó vốn có thay vì ước lượng phơi sáng từ từng "
"khung hình: trong cảnh tối (Depths) các vùng sương lớn không còn tối hoặc sáng đi "
+5
View File
@@ -10,6 +10,9 @@ typedef enum {
UI_SWKBD_OK,
UI_SWKBD_CANCEL,
UI_SWKBD_PAD_HINT, // how a controller answers
UI_SWKBD_SDL_KEYS_HINT, // the SDL window's key line; English only: its debug font draws ASCII (swkbd_sdl.c)
UI_SWKBD_SDL_PAD_HINT1, // the SDL window's controller lines, the letter grid's buttons
UI_SWKBD_SDL_PAD_HINT2,
// Menu: window, tabs, bottom row. UI_MENU_FIRST..UI_MENU_LAST_ID carry English, Russian, Brazilian Portuguese,
// Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese, Korean and Vietnamese texts.
@@ -42,6 +45,7 @@ typedef enum {
UI_MENU_ASPECT, UI_MENU_ASPECT_DESC, UI_MENU_ASPECT_FIT, UI_MENU_ASPECT_STRETCH,
UI_MENU_MOVIE_ASPECT, UI_MENU_MOVIE_ASPECT_DESC, UI_MENU_MOVIE_ASPECT_KEEP, UI_MENU_MOVIE_ASPECT_STRETCH,
UI_MENU_FOV, UI_MENU_FOV_DESC,
UI_MENU_VERT_PLUS, UI_MENU_VERT_PLUS_DESC,
UI_MENU_SHADOW_RES, UI_MENU_SHADOW_RES_DESC, UI_MENU_SHADOW_RES_GAME,
UI_MENU_ANISO, UI_MENU_ANISO_DESC, UI_MENU_ANISO_GAME,
UI_MENU_LOD_STEADY, UI_MENU_LOD_STEADY_DESC,
@@ -240,6 +244,7 @@ typedef enum {
UI_MENU_REPLAY_ASYNC, UI_MENU_REPLAY_ASYNC_DESC,
UI_MENU_REPLAY_WORKERS, UI_MENU_REPLAY_WORKERS_DESC, UI_MENU_REPLAY_WORKERS_NOW,
UI_MENU_TIMER_1MS, UI_MENU_TIMER_1MS_DESC,
UI_MENU_SYNC_AHEAD, UI_MENU_SYNC_AHEAD_DESC, UI_MENU_HOST_CHECKPOINT, UI_MENU_HOST_CHECKPOINT_DESC,
UI_MENU_PIPE_WAIT, UI_MENU_PIPE_WAIT_DESC, UI_MENU_PIPE_WAIT_DEFAULT, UI_MENU_PIPE_WAIT_DRAW,
UI_MENU_PIPE_SKIP, UI_MENU_PIPE_SKIP_DESC, UI_MENU_PIPE_SKIP_STRICT, UI_MENU_PIPE_SKIP_ANY,
UI_MENU_PIPE_SKIP_FULLSCREEN,
+1
View File
@@ -480,6 +480,7 @@ void gfx_exit_log(void) {
vk_mem_shadow_read_log();
vk_ahead_log_final();
vk_ahead_log_guards();
vk_counter_log();
if (gfx_replay_async() && r_started && !plat_xchg32(&done, 1)) replay_log(game_frames, 1);
}
+18 -2
View File
@@ -327,6 +327,7 @@ static struct {
VkImage light_z; // this frame: the D16 depth the lighting draws into the light target with
int fx_on; // dlaa_effects_after, read at each present while DLSS runs
int fx_seen, fx_open, fx_bad; // this frame: the point found / the scene not ended since / drawn on after it
int fx_comp; // this frame: a full-size pass into the light target without depth after the lighting
uint32_t fx_steady; // DLSS frames in a row with the point found and nothing of the scene after it
// jitter (vk_dlaa_viewport)
VkImage jdepth; // the scene depth of the last frame DLAA ran on: passes drawing with it are jittered
@@ -1617,6 +1618,19 @@ static void gbuf_light(const VkExec *ex) {
// breaks it puts DLSS back at the bloom until it holds again, so a frame the rule does not fit changes the picture at
// most once a second instead of from frame to frame.
// dlaa_effects_after = 0 (the Screen tab, read each frame): DLSS at the bloom, effects included.
// The point waits for the first full-size pass into the light target without depth after the lighting (the composite
// of the half-size clouds outdoors, of the volumetric fog in shrines, of the field's effects in the yard) and runs DLSS
// before the next pass with a depth, the particles or the dust. Run at the first pass after the lighting, it left the
// fog layer and those composites over its picture: they decide per pixel from the scene depth whether a pixel is sky
// or a surface, and that depth is still this frame's jittered one while DLSS's picture is not, so on a silhouette
// against clouds or fog a pixel the picture shows as sky took the surface's side of the test in some frames. No clouds
// or fog there that frame: a brighter dot along distant ridges at night and at dawn, flickering with the jitter's
// phase and never resolved, since it came after DLSS. Measured at 2560x1440 with FSR 4 (frame dumps, a ridge against
// the night sky): a ridge pixel brighter than the sky and the mountain beside it in 34 % of the columns with the point
// before the fog layer, 15 % with it after the composite (6 % with the upscaler off). These layers are smooth and
// follow the scene, so DLSS takes them with the scene's motion; the particles and the dust still go over its picture.
// A frame without such a composite before the bloom runs DLSS at the bloom, and the FX_STEADY count holds the point
// back as for any frame the rule does not fit.
#define FX_STEADY 60u
static int effects_point(const VkExec *ex) {
@@ -1630,6 +1644,8 @@ static int effects_point(const VkExec *ex) {
unsigned o[2], s[2];
res_sizes(o, s);
if (c->width < o[0] || !scene_shaped(c) || !scene_large(c)) return 0;
if (!z->image) D.fx_comp = 1; // asked again at the same pass: the same answer
if (!D.fx_comp || !z->image) return 0;
D.fx_seen = D.fx_open = 1;
return D.fx_steady >= FX_STEADY;
}
@@ -1948,7 +1964,7 @@ void vk_dlaa_frame(void) {
D.on = on, D.fg = vk_dlaa_fg_on = fg, D.fsr = fsr;
// either way the next DLAA frame starts a new history from an unjittered frame
D.reset = 1, D.cam_prev_ok = 0, D.jit_ok = D.jit_used = D.armed = D.done = D.gbuf = D.ended = D.up = 0;
D.fx_seen = D.fx_open = D.fx_bad = 0, D.fx_steady = 0;
D.fx_seen = D.fx_open = D.fx_bad = D.fx_comp = 0, D.fx_steady = 0;
D.nodepth = D.glight = D.light_z = VK_NULL_HANDLE;
D.hold = 0;
return;
@@ -1957,7 +1973,7 @@ void vk_dlaa_frame(void) {
D.fx_on = dl_active() && cfg_bool("TOTK_DLAA_EFFECTS_AFTER"); // DLSS's point alone
if (!D.done) D.frames_missed++;
else D.fx_steady = D.fx_seen ? D.fx_steady + (D.fx_steady < FX_STEADY) : 0;
D.fx_seen = D.fx_open = D.fx_bad = 0;
D.fx_seen = D.fx_open = D.fx_bad = D.fx_comp = 0;
if (D.jit_used && !D.done) D.hold = 60, D.holds++; // jittered but not resolved: that frame shook
else if (D.hold) D.hold--;
if (!D.done) D.jit_ok = 0;
+13 -9
View File
@@ -90,12 +90,12 @@ void vk_exec_frame_log(const tex_t *p, uint64_t frame) {
fw[i].h, fw[i].fmt, fw[i].n);
}
rt_log("frame %llu: submits %llu passes %llu draws %llu/%llu clears %llu copies %llu dispatches %llu; present %p "
"%ux%u/%#x written %d; pass ends: targets %llu barrier %llu (%llu merged, %llu undone) bits %llu/%llu/%llu/%llu/%llu/%llu/%llu/%llu; feedback draws %llu barriers %llu restarts %llu layouts %llu; targets%s",
"%ux%u/%#x written %d; pass ends: targets %llu barrier %llu (%llu merged, %llu undone, unwritten reads %llu colour %llu depth) bits %llu/%llu/%llu/%llu/%llu/%llu/%llu/%llu; feedback draws %llu barriers %llu restarts %llu layouts %llu; targets%s",
(unsigned long long)frame, (unsigned long long)f->submits,
(unsigned long long)f->passes, (unsigned long long)f->draws, (unsigned long long)f->draws_seen,
(unsigned long long)f->clears, (unsigned long long)f->copies, (unsigned long long)f->dispatches,
p ? (const void *)p->mem : NULL, p ? p->d.width : 0, p ? p->d.height : 0, p ? (uint32_t)p->d.format : 0,
hit, (unsigned long long)f->pass_end_rt, (unsigned long long)f->pass_end_barrier, (unsigned long long)f->barrier_merged, (unsigned long long)f->barrier_undone, (unsigned long long)f->barrier_bit[0], (unsigned long long)f->barrier_bit[1], (unsigned long long)f->barrier_bit[2], (unsigned long long)f->barrier_bit[3], (unsigned long long)f->barrier_bit[4], (unsigned long long)f->barrier_bit[5], (unsigned long long)f->barrier_bit[6], (unsigned long long)f->barrier_bit[7], (unsigned long long)f->fb_draws, (unsigned long long)f->fb_barriers, (unsigned long long)f->fb_restarts,
hit, (unsigned long long)f->pass_end_rt, (unsigned long long)f->pass_end_barrier, (unsigned long long)f->barrier_merged, (unsigned long long)f->barrier_undone, (unsigned long long)f->undone_color, (unsigned long long)f->undone_depth, (unsigned long long)f->barrier_bit[0], (unsigned long long)f->barrier_bit[1], (unsigned long long)f->barrier_bit[2], (unsigned long long)f->barrier_bit[3], (unsigned long long)f->barrier_bit[4], (unsigned long long)f->barrier_bit[5], (unsigned long long)f->barrier_bit[6], (unsigned long long)f->barrier_bit[7], (unsigned long long)f->fb_draws, (unsigned long long)f->fb_barriers, (unsigned long long)f->fb_restarts,
(unsigned long long)f->fb_layouts, list);
memset(f, 0, sizeof *f);
nfw = 0;
@@ -984,7 +984,7 @@ static void clear_ds(VkExec *ex, const p_clear_ds *c) {
// ---- the op loop
// barrier_merge (TOTK_BARRIER_MERGE, off by default): TotK calls Barrier(ORDER_FRAGMENTS | INVALIDATE_TEXTURE) about
// barrier_merge (TOTK_BARRIER_MERGE, on by default): TotK calls Barrier(ORDER_FRAGMENTS | INVALIDATE_TEXTURE) about
// 1200 times a frame in some scenes (water, decals): the next draw reads the render targets the last one wrote. A full
// barrier there ends the Vulkan pass and flips every target's layout. What such a barrier asks for, an attachment write
// made visible to a later fragment shader read of the open pass, feedback_prepare / feedback_barrier already do before the
@@ -992,10 +992,14 @@ static void clear_ds(VkExec *ex, const p_clear_ds *c) {
// that may write a storage buffer or image (pass_storage), which only a full barrier makes visible, or the barrier asks for
// more than those two bits, or the feedback layout is not in use, or a target is a 3D BC stand-in (its texture gets the
// pass's writes only at the pass end, bc_copy_back). The reads the by-region barrier does not cover end the pass at the
// draw that makes them (vk_exec_draw.c merge_guard). The by-region barrier orders only reads of the pixel a fragment
// writes; NVN's ORDER_FRAGMENTS orders every pixel (ORDER_FRAGMENTS_TILED is the per-region one), so a draw that reads a
// neighbouring pixel of a target written in the pass relies on the driver running the barrier for the whole target, as
// RADV does; hence experimental.
// draw that makes them (vk_exec_draw.c merge_guard), and so do reads of a target the draw does not write itself
// (vk_exec_draw.c merge_unwritten_reads): the by-region barrier orders only reads of the pixel a fragment writes, while
// NVN's ORDER_FRAGMENTS orders every pixel (ORDER_FRAGMENTS_TILED is the per-region one). What stays merged is a draw
// that samples a target it also writes, which Savage Wind runs the same way on every GPU. If such a draw read a
// neighbouring pixel, it would rely on the driver running the barrier for the whole target, as RADV and the desktop
// drivers do. On 1.4.3 every read after a merged Barrier in the shrine, the town and the field is of that kind. Passes
// a frame in the shrine: 581 -> 128 on an RDNA2 iGPU with no GPU time change on AMD's Windows driver; the waterfall
// on RADV: 1105 -> 117, GPU 8.3 -> 4.1 ms.
int vk_exec_barrier_merge_on(void) {
static int on = -1;
if (on < 0) on = cfg_bool("TOTK_BARRIER_MERGE");
@@ -1171,7 +1175,7 @@ static int walk(VkExec *ex, const op_hdr *h, int depth, const op_hdr *stop) {
if (ex->wpos_i < ex->wpos_end && ex->wpos[ex->wpos_i] == ex->pos) ex->drop_n++, ex->wpos_i++;
}
switch (h->op) {
case OP_BEGIN: break;
case OP_BEGIN: case OP_FENCE_SYNC: break; // FENCE_SYNC: the front end signals it at submit (p_fence_sync)
case OP_JUMP: h = (const op_hdr *)(uintptr_t)((const p_jump *)a)->target; continue;
case OP_CALL:
if (depth >= CALL_DEPTH) rt_fatal("vk: command buffer calls nested deeper than %d", CALL_DEPTH);
@@ -1745,7 +1749,7 @@ static void scan(VkExec *s, int hi, const op_hdr *h, int depth) {
if (vk_exec_xfer_revive(h->op, a, s->pos)) scan_hold(HOLD_TEX);
SC.open = 0;
break;
case OP_SIGNAL_EVENT: break;
case OP_SIGNAL_EVENT: case OP_FENCE_SYNC: break;
case OP_RENDER_COND: SC.cond[SC.ncond++] = (uint8_t)vk_exec_xfer_scan(s, h->op, a); break;
case OP_REPORT_COUNTER: case OP_RESET_COUNTER: case OP_RENDER_ENABLE: vk_exec_xfer_scan(s, h->op, a); break;
default: state_op(s, h->op, a); // walk stops on an op without a handler
+2
View File
@@ -57,6 +57,8 @@ typedef struct {
uint64_t barrier_bit[8]; // the game's Barrier calls that carry NVN barrier bit 0..7 (TOTK_TRACE=gfx)
uint64_t barrier_merged; // the game's Barrier calls the open pass went on through (barrier_merge)
uint64_t barrier_undone; // passes a draw then ended for a read the merge cannot order (merge_guard)
uint64_t undone_color, undone_depth; // of those, for sampling a colour target / the depth target the draw does
// not write itself (vk_exec_draw.c merge_unwritten_reads)
uint64_t pass_end_rt, pass_end_barrier; // passes ended by other render targets, by the game's own Barrier (TOTK_TRACE=gfx)
uint64_t fb_draws, fb_barriers, fb_restarts, fb_layouts; // feedback loops: draws sampling a written target of
// their pass, in-pass barriers, pass restarts, layout
+99 -2
View File
@@ -3128,6 +3128,23 @@ static int merge_guard(VkExec *ex, const GfxShader *vs, const GfxShader *fs) {
return m != 0;
}
// barrier_merge: the attachments of fbl (sampled in the feedback layout) that a draw with state s reads after other
// draws of the pass wrote them, without writing them itself. A read of a target the draw also writes (G-buffer bits
// ORed in, blending in the shader) is a read of its own pixel, which the by-region barrier orders. A read of a target
// the draw leaves alone is a read of what earlier draws left there, often at neighbouring pixels (blur, ambient
// occlusion, light composites over the G-buffer, depth-based effects), which only the game's Barrier, a full one,
// orders on every driver; the caller ends the pass for it. The rule is Savage Wind's (runtime/nvn/vulkan/exec.c, the
// sampled-texture loop of the draw: a colour target the draw does not write ends the pass when it was written in the
// pass, a read-only depth target when depth was), which that port runs on every GPU. A colour target counts as
// written when the pipeline's write mask for it is not zero, depth as feedback_written counts it.
static uint32_t merge_unwritten_reads(const VkExec *ex, const VkPipeState *s, uint32_t fbl) {
uint32_t r = fbl & ex->fb_dirty;
for (uint32_t i = 0; r & 0xff && i < ex->pass_ncolor && i < 8; i++)
if ((r >> i & 1) && vk_pipeline_target_wmask(s, (int)i)) r &= ~(1u << i);
if ((r & 0x100) && ((s->ds.dt && s->ds.dw) || s->ds.st)) r &= ~0x100u;
return r;
}
// ---- incremental draw preparation (TOTK_BIND_INC)
// A draw is prepared from what changed since the context's last prepared draw in the same command buffer: the bind
// ops mark the slots whose bytes they changed (VkExec.dirt, vk_exec_bind), every write that changes the pipeline state
@@ -3450,6 +3467,18 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) {
if (memcmp(&s, &D->PM.s, sizeof s)) bi_mismatch(ex, BIM_PIPE, "pipeline memo: state differs from the memo its generation matched");
}
}
// barrier_merge: a read of a target this draw does not write, made after a merged Barrier, ends the pass; nothing of
// the draw is recorded yet, and the new pass keeps the targets and their feedback layout, so fbl and the state hold.
if (ex->pass_merged && fbl & ex->fb_dirty) {
uint32_t r = merge_unwritten_reads(ex, sp, fbl);
if (r) {
vk_exec_pass_end(ex);
vk_exec_pass_begin(ex);
ex->fr.barrier_undone++;
if (r & 0xff) ex->fr.undone_color++;
else ex->fr.undone_depth++;
}
}
const VkPipeInfo *info = NULL;
int pending;
// A draw of at most 6 vertices over half the render area or more (a full-screen triangle or quad, a tile) waits for
@@ -4484,6 +4513,74 @@ static void op_draw_idx_ind(VkExec *ex, const p_draw_idx_ind *d) {
// ---- dispatch and uniform buffer updates
// skip_cs (TOTK_SKIP_CS): compute shaders whose dispatches are left out, named by the id the pass marks print for a
// dispatch ("cs 75be3722f62cb67e": the first 8 bytes of the shader's input id, vk_crumbs.c shader_id). Up to
// SKIP_CS_MAX ids of 1 to 16 hex digits, separated by commas or spaces; an id shorter than 16 digits matches every
// shader whose id starts with it. When the pass marks put a GPU hang in one dispatch, as on Intel GPUs on game 1.2.1
// after the startup logo (#1402), this takes that dispatch out: the device survives if the shader was the cause, at the
// cost of whatever the shader would have written. A bisecting tool and a stopgap, not a fix.
#define SKIP_CS_MAX 16
static struct { unsigned long long id, mask; } skip_cs[SKIP_CS_MAX];
static int n_skip_cs;
static PlatOnce skip_cs_once = PLAT_ONCE_INIT;
static void skip_cs_read(void *arg) {
(void)arg;
const char *v = cfg_get("TOTK_SKIP_CS");
if (!v) return;
for (const char *p = v; *p;) {
while (*p == ',' || *p == ' ' || *p == '\t') p++;
if (!*p) break;
unsigned long long id = 0;
int digits = 0;
const char *entry = p;
for (; *p && *p != ',' && *p != ' ' && *p != '\t'; p++) {
int c = (unsigned char)*p, h = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10
: c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;
if (h < 0 || digits == 16) { // not an id: skip the rest of this entry
digits = -1;
while (*p && *p != ',' && *p != ' ' && *p != '\t') p++;
break;
}
id = id << 4 | (unsigned)h, digits++;
}
if (digits <= 0) {
int len = 0;
while (entry[len] && entry[len] != ',' && entry[len] != ' ' && entry[len] != '\t') len++;
rt_log("vk: skip_cs: \"%.*s\" is not 1 to 16 hex digits; ignored", len, entry);
continue;
}
if (n_skip_cs == SKIP_CS_MAX) {
rt_log("vk: skip_cs: more than %d ids; the rest are ignored", SKIP_CS_MAX);
break;
}
int shift = 4 * (16 - digits); // 0..60: digits is 1..16
skip_cs[n_skip_cs].id = id << shift;
skip_cs[n_skip_cs].mask = ~0ull << shift;
n_skip_cs++;
}
for (int i = 0; i < n_skip_cs; i++)
rt_log("vk: skip_cs: dispatches of compute shaders whose id starts with %0*llx are skipped (TOTK_SKIP_CS)",
16 - __builtin_ctzll(skip_cs[i].mask) / 4, skip_cs[i].id >> __builtin_ctzll(skip_cs[i].mask));
}
// 1 when skip_cs names cs; logs the first skipped dispatch of each listed id.
static int cs_skipped(const GfxShader *cs) {
plat_once(&skip_cs_once, skip_cs_read, NULL);
if (!n_skip_cs) return 0;
const uint8_t *iid = gfx_shader_input_id(cs);
unsigned long long v = 0;
for (int i = 0; i < 8; i++) v = v << 8 | iid[i];
static uint32_t logged; // bit i: entry i was logged
for (int i = 0; i < n_skip_cs; i++) {
if ((v & skip_cs[i].mask) != skip_cs[i].id) continue;
if (!(__atomic_fetch_or(&logged, 1u << i, __ATOMIC_RELAXED) & 1u << i))
rt_log("vk: skip_cs: skipped a dispatch of cs %016llx (TOTK_SKIP_CS); later ones are not logged", v);
return 1;
}
return 0;
}
static void op_dispatch(VkExec *ex, const p_dispatch *d) {
VkExecDraw *D = ex->draw;
if (d->x <= 0 || d->y <= 0 || d->z <= 0) return;
@@ -4493,7 +4590,7 @@ static void op_dispatch(VkExec *ex, const p_dispatch *d) {
dummies_init();
int present;
const GfxShader *cs = shader_for(ex, NVN_STAGE_CS, &present, NULL, 0); // synchronous: a skipped dispatch changes results
if (!cs) return;
if (!cs || cs_skipped(cs)) return;
const VkPipeInfo *info = NULL;
VkPipeline p = vk_pipeline_compute(cs, &info);
if (!p || !info) return warn_once(W_PIPELINE, "a compute pipeline could not be created: dispatches with it are skipped");
@@ -4522,7 +4619,7 @@ static void op_dispatch_ind(VkExec *ex, const p_dispatch_ind *d) {
dummies_init();
int present;
const GfxShader *cs = shader_for(ex, NVN_STAGE_CS, &present, NULL, 0);
if (!cs) return;
if (!cs || cs_skipped(cs)) return;
const VkPipeInfo *info = NULL;
VkPipeline p = vk_pipeline_compute(cs, &info);
if (!p || !info) return warn_once(W_PIPELINE, "a compute pipeline could not be created: dispatches with it are skipped");
+5
View File
@@ -758,6 +758,10 @@ static int test_xfer(const GfxBackend *b, uint8_t *guest, int *bytes) {
p = put(p, OP_CLEAR_TEX, &ct, sizeof ct);
const p_signal_event ev1 = {event, NVN_EVENT_SIGNAL_MODE_WRITE, 7}, ev2 = {event, NVN_EVENT_SIGNAL_MODE_ADD, 5};
p = put(p, OP_SIGNAL_EVENT, &ev1, sizeof ev1);
// CommandBufferFenceSync's record: the replay passes over it (the front end signals the sync at submit)
static sync_t fs_sync;
const p_fence_sync fs = {&fs_sync};
p = put(p, OP_FENCE_SYNC, &fs, sizeof fs);
p = put(p, OP_SIGNAL_EVENT, &ev2, sizeof ev2);
const p_report_counter rc = {NVN_COUNTER_TYPE_TIMESTAMP, (uint64_t)(uintptr_t)ctr};
p = put(p, OP_REPORT_COUNTER, &rc, sizeof rc);
@@ -786,6 +790,7 @@ static int test_xfer(const GfxBackend *b, uint8_t *guest, int *bytes) {
memcpy(&clv, cl, 4);
for (int i = 0; i < XF_W * XF_H; i++) CHECK(px[i] == clv, "CLEAR_TEX texel %d is %08x, expected %08x", i, px[i], clv);
CHECK(*event == 12, "event word is %u after WRITE 7 and ADD 5", *event);
CHECK(!fs_sync.fenced && !fs_sync.fence, "the replay left the FENCE_SYNC record's sync alone");
CHECK(ctr->counter == 0 && ctr->timestamp != 0, "counter report is {%llu, %llu}", (unsigned long long)ctr->counter,
(unsigned long long)ctr->timestamp);
CHECK(sp->counter == 0 && sp->timestamp != 0, "samples-passed report after a reset and no draw is {%llu, %llu}",
+93 -3
View File
@@ -38,6 +38,7 @@
#include <stdlib.h>
#include <string.h>
#include "cfg.h"
#include "host.h"
#include "nvn_api.h"
#include "nvn_tex.h"
@@ -92,9 +93,11 @@ static void event_cb(void *arg) {
}
// NVNcounterData = {counter, timestamp}; timestamps are Tegra 19.2 MHz ticks (the base of GetSystemTick).
static uint64_t counter_last; // the newest timestamp written (completion thread), for the bound below
static void write_counter(uint64_t addr, uint64_t counter) {
uint64_t rec[2] = {counter, (uint64_t)((unsigned __int128)kern_now_ns() * 12 / 625)};
memcpy((void *)(uintptr_t)addr, rec, sizeof rec);
__atomic_store_n(&counter_last, rec[1], __ATOMIC_RELEASE);
}
static void counter_cb(void *arg) {
@@ -104,11 +107,21 @@ static void counter_cb(void *arg) {
}
// Reports queued by the replay that the GPU has not finished. The condition of RENDER_COND reads a timestamp one as 0
// and a samples-passed one as unknown.
// and a samples-passed one as unknown. The replay thread writes the ring; game threads read it too
// (vk_counter_timestamp): an entry's fence is stored before its address, so a reader that finds the address sees its
// fence or a newer one, and an entry caught in between is judged by the newer fence (pending, the safe side).
#define PENDING 256
static struct { uint64_t addr, fence; int unknown; } pending[PENDING];
static unsigned pending_head;
static void pending_add(uint64_t addr, uint64_t fence, int unknown) {
unsigned i = pending_head % PENDING;
__atomic_store_n(&pending[i].fence, fence, __ATOMIC_RELAXED);
pending[i].unknown = unknown;
__atomic_store_n(&pending[i].addr, addr, __ATOMIC_RELEASE);
__atomic_store_n(&pending_head, pending_head + 1, __ATOMIC_RELEASE);
}
// ---- occlusion counts (samples passed)
//
// After a SAMPLES_PASSED reset, the first draw of a pass begins an occlusion query (precise when the device has
@@ -300,7 +313,84 @@ static void report_counter(VkExec *ex, const p_report_counter *p) {
*a = p->addr;
vk_completion_add(ex->fence, counter_cb, a);
}
if (!ex->chunked) pending[pending_head++ % PENDING] = (typeof(pending[0])){p->addr, ex->fence, samples}; // else the scan's
if (!ex->chunked) pending_add(p->addr, ex->fence, samples); // else the scan's
}
// ---- timestamps read one frame early (TOTK_SYNC_AHEAD)
//
// A report lands in guest memory when its submission's fence completes (write_counter). With the frame wait one frame
// late the game reads timestamps of work the GPU may not have finished. TotK's GPU time for its dynamic resolution
// controller (1.4.3 main+0xa1a50, 1.2.1 main+0x972bac) converts the end and then the begin report of a pair it issued
// two updates before, subtracts them unsigned and zeroes both reports. An end not written yet reads 0, and one written
// after the zeroing leaves the value of the report before it for the next read: either way the difference wraps to
// about 2^64, the controller sees an over-budget frame, and two of those in a row drop the game to its lowest quality
// level until 60 good frames bring it back (the half-second blur of #1123). Measured on 1.4.3 (islands): 12-20
// wrapped pairs in 40 s with the late wait, none without it.
//
// Every read is kept consistent with the order of the reports. At each frame wait the bound B becomes the newest
// timestamp written so far. A read of a report that holds 0, holds a time after B, or whose newest replayed report is
// not done yet reads B instead. Every report done before B was taken is written and holds at most B, so of two reports
// in submission order the first never reads later than the second: the difference lies between 0 and what the exact
// wait gives, never wrapped. Reports the exact wait would also have covered read as they are. Only the converted value
// changes (nvnDeviceGetTimestampInNanoseconds); guest memory, RENDER_COND and samples-passed counts stay as they were.
// TOTK_SYNC_AHEAD_TIMESTAMPS: 1 (default; acts only with the frame wait late), 0 off, check: counts what it would
// replace and leaves the reads as they are.
static uint64_t ts_bound; // 0: off
static int ts_mode = -1; // 0 off, 1 on, 2 check
static struct { uint64_t reads, zero, later, pending, last_log; } ts_stat; // game threads, approximate counts
static int ts_on(void) {
if (ts_mode < 0) {
const char *v = cfg_get("TOTK_SYNC_AHEAD_TIMESTAMPS");
ts_mode = !v || !*v ? 1 : !strcmp(v, "check") ? 2 : strcmp(v, "0") != 0;
rt_log("sync-ahead: timestamps the game reads before their frame is done read as the newest one written at "
"the frame wait: %s", ts_mode == 2 ? "check (counted, not replaced)" : ts_mode ? "on" : "off");
}
return ts_mode;
}
void vk_counter_frame(void) {
if (ts_on()) __atomic_store_n(&ts_bound, __atomic_load_n(&counter_last, __ATOMIC_ACQUIRE), __ATOMIC_RELEASE);
}
// 1: the newest replayed report to addr is not done
static int report_pending(uint64_t addr) {
uint64_t done = vk_sync_fence_done();
unsigned head = __atomic_load_n(&pending_head, __ATOMIC_ACQUIRE);
for (unsigned k = 1; k <= PENDING; k++) { // newest first: the last report to addr decides
unsigned i = (head - k) % PENDING;
if (__atomic_load_n(&pending[i].addr, __ATOMIC_ACQUIRE) == addr)
return __atomic_load_n(&pending[i].fence, __ATOMIC_RELAXED) > done;
}
return 0;
}
static void ts_log(const char *when) {
rt_log("sync-ahead: timestamps %s: %llu reads, %s %llu (zero %llu, after the bound %llu, report not done %llu)", when,
(unsigned long long)ts_stat.reads, ts_mode == 2 ? "would be replaced" : "replaced",
(unsigned long long)(ts_stat.zero + ts_stat.later + ts_stat.pending), (unsigned long long)ts_stat.zero,
(unsigned long long)ts_stat.later, (unsigned long long)ts_stat.pending);
}
uint64_t vk_counter_timestamp(uint64_t addr, uint64_t t) {
uint64_t b = __atomic_load_n(&ts_bound, __ATOMIC_ACQUIRE);
if (!b) return t;
ts_stat.reads++;
int why = !t ? 1 : t > b ? 2 : report_pending(addr) ? 3 : 0;
if (why == 1) ts_stat.zero++;
else if (why == 2) ts_stat.later++;
else if (why == 3) ts_stat.pending++;
uint64_t now = kern_now_ns();
if (now - ts_stat.last_log > 30000000000ull) { // every 30 s of host time
if (ts_stat.last_log) ts_log("so far");
ts_stat.last_log = now;
}
return why && ts_mode == 1 ? b : t;
}
void vk_counter_log(void) {
static int once;
if (ts_mode > 0 && !__atomic_exchange_n(&once, 1, __ATOMIC_RELAXED)) ts_log("over the run");
}
// ---- conditional rendering
@@ -694,7 +784,7 @@ int vk_exec_xfer_scan(VkExec *ex, uint32_t op, const void *payload) {
VkMemSpan m;
if (!nvn_gpu_only(p->addr) && !vk_mem_resolve(p->addr, sizeof(NVNcounterData), &m)) break; // the recording stops
if (samples) oq_report_state(ex);
if (!nvn_gpu_only(p->addr)) pending[pending_head++ % PENDING] = (typeof(pending[0])){p->addr, ex->fence, samples};
if (!nvn_gpu_only(p->addr)) pending_add(p->addr, ex->fence, samples);
break;
}
}
+7 -6
View File
@@ -103,7 +103,7 @@ static struct {
unsigned toggle;
uint64_t frame_id, last_prep_ns, made;
// settings read at start (vk_fg_init)
int workers, sync_ahead, hdr, test, debug, times;
int workers, hdr, test, debug, times;
uint64_t shot_at; // TOTK_FG_SHOT: the first present shot, or (shot_w) the first after that world time
int64_t shot_w;
char shot_dir[260];
@@ -295,7 +295,6 @@ static void start(void) {
}
g.win_fmt = VK_FORMAT_R8G8B8A8_UNORM;
g.workers = cfg_int("TOTK_REPLAY_WORKERS");
g.sync_ahead = cfg_bool("TOTK_SYNC_AHEAD") && strcmp(cfg_value("TOTK_SYNC_AHEAD"), "check") != 0; // check: exact
g.hdr = vk_hdr_wanted();
g.test = knob_int("TOTK_FG_TEST");
g.debug = knob_int("TOTK_FG_DEBUG");
@@ -329,14 +328,16 @@ extern "C" int vk_fg_wanted(int dlss) {
if (vk_fg_engine() != VK_FG_FSR3) return 0;
if (!started) start(); // turned on in the menu: the contexts now; the first prepare makes them for the scene
if (!g.live || g.failed) return 0;
// the inputs are this frame's, recorded in replay order: one frame in flight more or chunks recording side by
// side are not handled yet
int why = dlss ? 1 : g.workers > 0 ? 2 : g.sync_ahead ? 3 : g.hdr ? 4 : 0;
// the inputs are this frame's, recorded in replay order: chunks recording side by side are not handled yet.
// sync_ahead only moves the game's frame wait; the replay and the presents keep their order, and the replay's
// next submission waits until the present thread submitted the blit (vk_backend.c submit_sync, vk_present_drain),
// so out[] and hl[] alternate safely with it on.
int why = dlss ? 1 : g.workers > 0 ? 2 : g.hdr ? 3 : 0;
if (why) {
if (!(g.said & 1u << why)) {
g.said |= 1u << why;
static const char *const r[] = {"", "DLSS runs (dlaa = 1)", "the replay records in chunks (replay_workers > 0)",
"sync_ahead = 1", "HDR output (hdr = 1)"};
"HDR output (hdr = 1)"};
rt_log("fg: frame generation off while %s", r[why]);
}
return 0;
+1 -1
View File
@@ -28,7 +28,7 @@ int vk_fg_active(void);
void vk_fg_release(void);
// vk_dlaa.c vk_dlaa_frame, once per present: 1 when frame generation follows the scene in the next frame. 0 while
// DLSS runs (dlss), with replay workers or sync_ahead = 1 (the inputs are per frame and recorded in replay order),
// DLSS runs (dlss), with replay workers (the inputs are per frame and recorded in replay order),
// with HDR output, or while the game shows a menu without its world (vk_fg_menu); each reason is logged once.
int vk_fg_wanted(int dlss);
// vk_dlaa.c, the game's thread at each present: 1 while the map or a loading or event fade is open (sampled there,
+14
View File
@@ -128,6 +128,9 @@ static int import_pool(VkCtx *c, PoolRec *r, uint64_t addr, uint64_t size) {
r->import_lo = addr & ~(al - 1);
r->import_hi = (addr + size + al - 1) & ~(al - 1);
uint64_t n = r->import_hi - r->import_lo;
// TOTK_HEAP_LAZY: the caller's mem_thaw committed the pool's own chunks; an alignment above 4 KiB can widen the
// import into a neighbouring chunk the game never touched, and the driver refuses reserved pages.
mem_heap_commit(r->import_lo, n);
VkMemoryHostPointerPropertiesEXT hp = {.sType = VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT};
VkResult res = p_host_props ? p_host_props(c->device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,
(void *)(uintptr_t)r->import_lo, &hp)
@@ -582,6 +585,13 @@ void vk_mem_census(uint64_t frame) {
rt_log("mem: commit at frame %llu: this process %.0f MB, the system %.0f of %.0f MB; room for device memory %s%.0f MiB",
(unsigned long long)frame, proc, used, limit, room == UINT64_MAX ? "not counted " : "",
room == UINT64_MAX ? 0.0 : room / 1048576.0);
if (mem_heap_lazy()) { // what the heap's first-use commits (memory.c heap_fault) cost and saved so far
uint64_t nf, ns, hc, hs;
mem_heap_lazy_stats(&nf, &ns, &hc, &hs);
rt_log("mem: heap at frame %llu: %llu of %llu MiB committed, %llu first-use faults, %.1f ms in all",
(unsigned long long)frame, (unsigned long long)(hc >> 20), (unsigned long long)(hs >> 20),
(unsigned long long)nf, ns / 1e6);
}
// Per heap, what VMA holds (blocks, and the allocations inside them) beside what the driver counts for the process:
// usage above VMA's blocks is the driver's own memory (pipelines, command buffers, descriptor pools).
VkCtx *vc = vk_ctx();
@@ -643,6 +653,10 @@ uint64_t vk_mem_host_room(void) {
if (at && now - at < 250) return __atomic_load_n(&room_cached, __ATOMIC_RELAXED); // a query costs a system call
uint64_t commit, phys;
plat_mem_room(&commit, &phys);
// The game's heap commits on first use (memory.c, heap_fault): the part it has not touched yet is commit it can
// still claim, which an eagerly committed heap had already taken. Its physical memory was never taken either way.
uint64_t later = mem_heap_uncommitted();
if (commit != UINT64_MAX) commit = commit > later ? commit - later : 0;
uint64_t r = host_backed == HB_UMA && phys < commit ? phys : commit;
r = r == UINT64_MAX ? r : r > room_reserve ? r - room_reserve : 0;
__atomic_store_n(&room_cached, r, __ATOMIC_RELAXED);
+54 -17
View File
@@ -879,37 +879,72 @@ out:
// undefined. Mesa keeps computing after a discard; AMD's Windows compiler does not, and TotK's cloud shader, which
// discards where the scene is in front and then takes OpImageQueryLod for its noise textures, lost fog in the pixels
// sharing a quad with a discarded one: a light fringe round every silhouette against clouds (issue #164).
// Each OpKill whose block is a direct target of a selection header becomes OpDemoteToHelperInvocation plus a branch to
// that selection's merge block, so the fragment goes on computing and writes nothing. An OpKill anywhere else (the end
// of a function, a switch case) stays. NULL: nothing to change.
// Each OpKill whose block is a direct target of a selection header, and which an explicit derivative follows (below),
// becomes OpDemoteToHelperInvocation plus a branch to that selection's merge block, so the fragment goes on computing
// and writes nothing. An OpKill anywhere else (the end of a function, a switch case) stays. NULL: nothing to change.
// Only kills that an OpImageQueryLod, an OpDPdx..OpFwidthCoarse or an OpFunctionCall (whose callee may take one)
// follows later in the same function change: the cloud shader's fringe came from OpImageQueryLod. A demoted fragment
// runs the rest of the shader, so demoting every kill made each alpha-tested draw (grass, foliage, hair) pay for its
// discarded pixels; implicit-LOD samples after a kill, which nearly every alpha-tested shader takes, kept the OpKill
// they had before demote existed, without a report. Program order stands for "after": a derivative in the other arm
// of the kill's selection demotes too (harmless), one reached only by a loop's back edge does not (that kill keeps
// its OpKill, as before demote).
// On by default on AMD's own drivers, where the fringe shows; other drivers keep the translator's OpKill, their output
// unchanged. TOTK_DEMOTE=1 or 0 overrides on any driver that enables shaderDemoteToHelperInvocation (vk_caps.demote,
// set in vk_device.c create_device); without the feature the module keeps OpKill, since the capability would be invalid.
// unchanged. TOTK_DEMOTE=1 or 0 (ini: demote) overrides on any driver that enables shaderDemoteToHelperInvocation
// (vk_caps.demote, set in vk_device.c create_device); without the feature the module keeps OpKill, since the
// capability would be invalid.
static uint64_t demote_mods, demote_kept; // modules with an OpKill: some kill demoted, every kill kept (atomics)
// Logs the split of modules with an OpKill at each power of two of their count.
static void demote_note(int demoted) {
uint64_t d = demoted ? __atomic_add_fetch(&demote_mods, 1, __ATOMIC_RELAXED) : __atomic_load_n(&demote_mods, __ATOMIC_RELAXED);
uint64_t k = demoted ? __atomic_load_n(&demote_kept, __ATOMIC_RELAXED) : __atomic_add_fetch(&demote_kept, 1, __ATOMIC_RELAXED);
uint64_t t = d + k;
if (!(t & (t - 1)))
rt_log("vk_pipeline: discard as demote: %llu shaders with a discard demote it, %llu keep it (no derivative after)",
(unsigned long long)d, (unsigned long long)k);
}
static uint32_t *spirv_demote(const uint32_t *w, uint64_t n, uint64_t *out_n) {
enum { OP_EXTENSION = 10, OP_CAPABILITY = 17, OP_SELECTION_MERGE = 247, OP_LABEL = 248, OP_BRANCH = 249,
enum { OP_EXTENSION = 10, OP_CAPABILITY = 17, OP_FUNCTION_END = 56, OP_FUNCTION_CALL = 57, OP_IMAGE_QUERY_LOD = 105,
OP_DPDX = 207, OP_FWIDTH_COARSE = 215, OP_SELECTION_MERGE = 247, OP_LABEL = 248, OP_BRANCH = 249,
OP_BRANCH_CONDITIONAL = 250, OP_KILL = 252, OP_DEMOTE = 5380, CAP_DEMOTE = 5379 };
static const char ext_name[36] = "SPV_EXT_demote_to_helper_invocation"; // 35 characters and the terminator: 9 words
static int on = -1;
if (on < 0) {
on = vk_caps.demote && rt_knob("DEMOTE", vk_caps.amd && !vk_caps.mesa ? "1" : "0");
rt_log("vk_pipeline: discard as demote: %s (shaderDemoteToHelperInvocation %d, TOTK_DEMOTE)", on ? "on" : "off",
vk_caps.demote);
rt_log("vk_pipeline: discard as demote: %s, for discards a derivative follows (shaderDemoteToHelperInvocation "
"%d, TOTK_DEMOTE)", on ? "on" : "off", vk_caps.demote);
}
if (!on || n < 5) return NULL;
uint64_t kills = 0;
// Pass 1: check the words, count the kills, and note each function's last derivative (or call) by function order.
uint64_t kills = 0, nfn = 0, cap_fn = 8, last = 0;
uint64_t *fn_deriv = malloc(cap_fn * sizeof *fn_deriv);
if (!fn_deriv) return NULL;
for (uint64_t i = 5; i < n;) {
uint32_t op = w[i] & 0xffff, l = w[i] >> 16;
if (!l || i + l > n) return NULL;
if (op == OP_KILL) kills++;
if (op == OP_CAPABILITY && l >= 2 && w[i + 1] == CAP_DEMOTE) return NULL; // already demotes
if (!l || i + l > n || (op == OP_CAPABILITY && l >= 2 && w[i + 1] == CAP_DEMOTE)) { // malformed, or demotes already
free(fn_deriv);
return NULL;
}
kills += op == OP_KILL;
if (op == OP_IMAGE_QUERY_LOD || (op >= OP_DPDX && op <= OP_FWIDTH_COARSE) || op == OP_FUNCTION_CALL) last = i;
if (op == OP_FUNCTION_END) {
if (nfn == cap_fn) {
uint64_t *g = realloc(fn_deriv, 2 * cap_fn * sizeof *fn_deriv);
if (!g) { free(fn_deriv); return NULL; }
fn_deriv = g, cap_fn *= 2;
}
fn_deriv[nfn++] = last, last = 0;
}
i += l;
}
if (!kills) return NULL;
if (!kills) { free(fn_deriv); return NULL; }
uint32_t bound = w[3] < (1u << 22) ? w[3] : (1u << 22);
uint32_t *merge_of = calloc(bound ? bound : 1, sizeof *merge_of); // label -> merge block of the selection that branches to it
uint32_t *o = malloc((n + 12 + 2 * kills) * 4);
if (!merge_of || !o) { free(merge_of), free(o); return NULL; }
uint64_t on_w = 5, changed = 0;
if (!merge_of || !o) { free(merge_of), free(o), free(fn_deriv); return NULL; }
uint64_t on_w = 5, changed = 0, fn = 0;
uint32_t cur = 0, pending = 0;
int declared = 0;
memcpy(o, w, 5 * 4);
@@ -929,7 +964,7 @@ static uint32_t *spirv_demote(const uint32_t *w, uint64_t n, uint64_t *out_n) {
if (a[k] < bound && a[k] != pending) merge_of[a[k]] = merge_of[a[k]] ? ~0u : pending; // two headers: leave it
}
pending = op == OP_SELECTION_MERGE && l >= 3 ? a[0] : 0;
uint32_t m = op == OP_KILL && cur < bound ? merge_of[cur] : 0;
uint32_t m = op == OP_KILL && cur < bound && fn < nfn && fn_deriv[fn] > i ? merge_of[cur] : 0;
if (m && m != ~0u && m != cur) {
o[on_w++] = 1u << 16 | OP_DEMOTE;
o[on_w++] = 2u << 16 | OP_BRANCH, o[on_w++] = m;
@@ -937,9 +972,11 @@ static uint32_t *spirv_demote(const uint32_t *w, uint64_t n, uint64_t *out_n) {
} else {
memcpy(o + on_w, w + i, l * 4), on_w += l;
}
fn += op == OP_FUNCTION_END;
i += l;
}
free(merge_of);
free(merge_of), free(fn_deriv);
demote_note(changed != 0);
if (!changed) { free(o); return NULL; }
*out_n = on_w;
return o;
+74
View File
@@ -0,0 +1,74 @@
"""The production custom cursor must not depend on uninitialized stack colours.
python tests/cursor_art_check.py --cc path/to/clang
"""
import argparse
from pathlib import Path
import shutil
import struct
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#endif
#include "input_wsys.h"
int main(int argc, char **argv) {
assert(argc == 2);
int size = atoi(argv[1]), hot;
assert(size > 0 && size <= 128);
uint32_t *pixels = malloc((size_t)size * size * sizeof *pixels);
assert(pixels);
cursor_art(pixels, size, &hot);
#ifdef _WIN32
assert(_setmode(_fileno(stdout), _O_BINARY) != -1);
#endif
assert(fwrite(&hot, sizeof hot, 1, stdout) == 1);
assert(fwrite(pixels, sizeof *pixels, (size_t)size * size, stdout) == (size_t)size * size);
free(pixels);
return 0;
}
'''
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--cc', default=shutil.which('clang') or r'C:\msys64\ucrt64\bin\clang.exe')
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='cursor-art-') as temp:
work = Path(temp)
source = work / 'probe.c'
source.write_text(HARNESS, encoding='utf-8')
outputs = {}
for mode in ('zero', 'pattern'):
exe = work / f'{mode}.exe'
subprocess.run([args.cc, '-O2', '-std=gnu11', f'-ftrivial-auto-var-init={mode}',
'-I', str(ROOT / 'runtime'), str(source), str(ROOT / 'runtime/cursor_art.c'),
'-lm', '-o', str(exe)], check=True)
outputs[mode] = {}
for size in (16, 24, 32, 48, 64, 96, 128):
data = subprocess.run([str(exe), str(size)], check=True, capture_output=True).stdout
assert len(data) == 4 + size * size * 4
pixels = struct.unpack(f'<{size * size}I', data[4:])
assert any(p == 0 for p in pixels), 'the cursor must have transparent pixels'
assert any(p >> 24 and p & 0xffffff for p in pixels), 'the cursor must contain visible colour'
outputs[mode][size] = data
differences = []
for size in outputs['zero']:
a, b = outputs['zero'][size], outputs['pattern'][size]
different = sum(a[i:i + 4] != b[i:i + 4] for i in range(4, len(a), 4))
if different or a[:4] != b[:4]:
differences.append((size, different))
print(f'cursor {size}x{size}: {different} pixels differ between zero and pattern stack initialization')
assert not differences, f'cursor pixels depend on uninitialized automatic variables: {differences}'
if __name__ == '__main__':
main()
+130 -1
View File
@@ -9,6 +9,8 @@ Run with .venv (lz4 and numpy, as recomp/): python tests/exefs_plugins_test.py
"""
import hashlib
import json
import os
import shutil
import struct
import subprocess
import sys
@@ -450,6 +452,26 @@ class Reach(unittest.TestCase):
svcs, imports, _, _, _ = xp.reach(img, self.BASE, 0x200, [self.BASE], {self.BASE + 0x80: 'malloc'})
self.assertEqual((svcs, imports), (set(), {'malloc': 1}))
def test_own_function_through_plt_is_followed(self):
# bl plt; ret. The PLT stub at 0x80 binds to the plugin's own function at 0x100: svc 0x40; ret
img = bytearray(code([b(self.BASE, self.BASE + 0x80, True), RET_W]))
struct.pack_into('<II', img, 0x100, SVC_40, RET_W)
svcs, imports, _, _, _ = xp.reach(bytes(img), self.BASE, 0x200, [self.BASE],
{self.BASE + 0x80: self.BASE + 0x100})
self.assertEqual((svcs, imports), ({0x40}, {}))
def test_plt_slot_of_own_symbol_maps_to_its_code(self):
# Two PLT stubs (adrp x16, page 0; ldr x17, [x16, #slot]; add x16, x16, #slot; br x17) over GOT slots 0x180
# and 0x188: the first binds an import, the second a symbol the plugin defines at +0x40.
def stub(slot):
return [0x90000010, 0xF9400211 | (slot // 8) << 10, 0x91000210 | slot << 10, 0xD61F0220]
img = code(stub(0x180) + stub(0x188))
nso = mock.Mock(relocs=[(0x180, xp.R_AARCH64_JUMP_SLOT, 1, 0), (0x188, xp.R_AARCH64_JUMP_SLOT, 2, 0)],
syms=[('', 0, 0, 0, 0), ('malloc', 0x12, 0, 0, 0),
('_ZNSt6vectorIPKcSaIS1_EEC1ESt16initializer_listIS1_ERKS2_', 0x22, 7, 0x40, 8)])
self.assertEqual(xp.plt_imports(nso, img, self.BASE, 0x200),
{self.BASE: 'malloc', self.BASE + 0x10: self.BASE + 0x40})
def test_stub_returns_at_its_trampoline_branch(self):
# stur; bl impl; ldur; b trampoline (where an svc sits): the b is the stub's return
stub = [xp.STUR_X30, b(self.BASE + 4, self.BASE + 0x40, True), xp.LDUR_X30, b(self.BASE + 12, self.BASE + 0x100)]
@@ -581,6 +603,47 @@ class Lines(unittest.TestCase):
self.assertIn(f'orig mod_x plugin0 {TRAMP_OFF:x} main {SITE_OFF:x}', out)
self.assertIn(f'seed plugin0 {THUNK_OFF:x}', out)
def test_stubs_written_back_to_back_are_each_a_start(self):
# Zonai Fieldworks writes an inline-hook stub per member hook at init, back to back; a member switched on at
# play points its gate at one (1.4.3 plugin+0x135048, the 4th). The .quad callback after each stub is data.
rec = record()
img, row = bytearray(rec['images']['plugin0']), 0x8000
for k in range(3):
at = row + 0x18 * k
struct.pack_into('<4IQ', img, at, xp.STUR_X30, b(PLUGIN + at + 4, PLUGIN + IMPL_OFF, True), xp.LDUR_X30,
b(PLUGIN + at + 12, PLUGIN + TRAMP_OFF), PLUGIN + CB_OFF)
rec['images']['plugin0'] = bytes(img)
pre = bytearray(img)
pre[row:row + 0x48] = bytes(0x48)
rec['pre_images'] = {'plugin0': bytes(pre)}
starts = xp.init_code(rec, [], 'plugin0')
self.assertEqual(starts, {PLUGIN + row, PLUGIN + row + 0x18, PLUGIN + row + 0x30, PLUGIN + CB_OFF})
def test_yield_loops_are_spin_waits(self):
# Zonai Fieldworks' hook wrapper takes a byte lock (plugin+0xe3ff4 on 1.4.3): yield; ldaxrb; stxrb; cbnz; tbnz
# back to the yield. A loop with a yield and a call in it, or a back branch with no yield, is no spin wait.
ldaxrb, stxrb = 0x085FFC40, 0x08037C41
words = [xp.NOP] * 64
words[1:6] = [xp.YIELD, ldaxrb, stxrb, 0x35FFFFC3, 0x3707FF80] # cbnz w3, -8; tbnz w0, #0, -16
words[10:14] = [xp.YIELD, 0x94000100, xp.NOP, 0x17FFFFFD] # yield; bl; nop; b -12
words[20:23] = [xp.NOP, xp.NOP, 0x17FFFFFE] # b -8
img = struct.pack('<64I', *words)
self.assertEqual(xp.yield_spins(img, len(img)), {4: [20]})
def test_hook_on_main_header_keeps_only_its_expect(self):
# Challenge Mode's Enemy Health Regeneration on an update its table lacks: a replace hook at main+0x0, whose
# word 1 is main's module header. The write is checked at start; the lift gets no site, orig or seed for it.
new = b(MAIN, PLUGIN + THUNK_OFF)
rec = record(writes=[{'module': 'main', 'offset': 0, 'old': 1, 'new': new}])
hook = {'kind': 'replace', 'site': 'main+0x0', 'original': '0x00000001', 'target': f'plugin0+{THUNK_OFF:#x}',
'trampoline': f'plugin0+{TRAMP_OFF:#x}'}
with tempfile.TemporaryDirectory() as d:
(Path(d) / 'plugin0.img').write_bytes(rec['images']['plugin0'])
rec['modules'][2]['image'] = 'plugin0.img'
out = xp.plugin_lines(rec, [hook], 'mod_x', d, 'plugin0')
self.assertIn(f'expect mod_x main 0 00000001 {new:08x}', out)
self.assertFalse(any(x.startswith(('site', 'orig', 'seed', 'entry')) for x in out), out)
def test_call(self):
new = b(MAIN + SITE_OFF, PLUGIN + THUNK_OFF, True)
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': new}]
@@ -588,6 +651,27 @@ class Lines(unittest.TestCase):
self.assertIn(f'site mod_x main {SITE_OFF:x} 94000010 {new:08x}', out)
self.assertFalse(any(x.startswith(('orig', 'stub')) for x in out))
def test_data_word_matches_by_place(self):
# Zonai Fieldworks' Self Recall takes its storage off a pool size in main's .bss (1.4.3 main+0x3ad6eb8): the
# service run recorded 84800000 -> 7f1c0000, a start whose resolution grew the texture heap has
# 87a00000 -> 823c0000 there. The word shapes no lifted code, so its expect line takes any value.
rec = record(writes=[{'module': 'main', 'offset': 0x3ad6eb8, 'old': 0x84800000, 'new': 0x7F1C0000}])
rec['modules'][0]['size'] = 0x3adf000
out = self.lines(rec)
self.assertIn('expect mod_x main 3ad6eb8 * *', out)
self.assertFalse(any('84800000' in x or '7f1c0000' in x for x in out), out)
def test_pointer_swap_keeps_its_words(self):
# a table entry that now points at a plugin function is a seed of the lift: both its words stay exact
new = PLUGIN + THUNK_OFF
w = [{'module': 'main', 'offset': 0x180010, 'old': 0x00001000, 'new': new & 0xFFFFFFFF},
{'module': 'main', 'offset': 0x180014, 'old': 0, 'new': new >> 32},
{'module': 'main', 'offset': 0x180020, 'old': 5, 'new': 6}]
out = self.lines(record(writes=w))
self.assertIn(f'expect mod_x main 180010 00001000 {new & 0xFFFFFFFF:08x}', out)
self.assertIn(f'expect mod_x main 180014 00000000 {new >> 32:08x}', out)
self.assertIn('expect mod_x main 180020 * *', out)
# ---- one service run per plugin
class PerPlugin(unittest.TestCase):
@@ -691,6 +775,10 @@ def code_nso(words_at, size_text=0x5000):
FN = 0x100 # the hooked main function: mov x19, x0; mov x0, x19; ret
MSYS_BIN = Path(r'C:\msys64\ucrt64\bin') # clang for the start-up lookup below, as tests/flags_check.py
CC = (str(MSYS_BIN / 'clang.exe') if os.name == 'nt' and (MSYS_BIN / 'clang.exe').exists() else
os.environ.get('CC') or shutil.which('clang'))
CC_ENV = dict(os.environ, PATH=str(MSYS_BIN) + os.pathsep + os.environ.get('PATH', '')) if os.name == 'nt' else None
class Generator(unittest.TestCase):
@@ -767,9 +855,22 @@ class Generator(unittest.TestCase):
self.assertIn(f'void f_{stub:x}(Cpu *c);', c)
h = patches.header_text(t, 'MARK')
self.assertIn('#define RT_PLUGIN_COUNT 1', h)
self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u)', h)
self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u, 0)', h)
self.assertIn('X("plugin0", 0x4100) X("plugin0", 0x4200)', h)
def test_any_value_expect_line(self):
# `*` for both words: runtime/plugin_init.c check_writes matches the word by place only
t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3',
['stub plugin0 4000', 'expect mod_x main 3ad6eb8 * *'])
self.assertIn(('main', 0x3ad6eb8, None, None), t.plugins['plugin0']['expect'])
h = patches.header_text(t, 'MARK')
self.assertIn('X(0, "main", 0x3ad6eb8, 0x00000000u, 0x00000000u, 1)', h)
self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u, 0)', h)
for half in ('* 7f1c0000', '84800000 *'):
with self.subTest(half=half), self.assertRaises(patches.PatchError):
self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3',
['stub plugin0 4000', f'expect mod_x main 3ad6eb8 {half}'])
# exlaunch's hook impl saves no NZCV: flags pass from the site to the callback and back (recomp/flags.py)
def code(self, main_words, plugin_words=None):
"""Main's hooked function and the plugin image's words replaced; the plugin hash follows."""
@@ -882,6 +983,34 @@ class Generator(unittest.TestCase):
capture_output=True, text=True, timeout=30)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
@unittest.skipUnless(CC, 'no clang')
def test_start_matches_the_record(self):
# runtime/plugin_writes.h plugin_write_find on this table's patches.h, as runtime/plugin_init.c check_writes
# looks up each word an init changed: Self Recall's pool size at main+0x3ad6eb8, recorded by the service run as
# 84800000 -> 7f1c0000 and written at a start with a grown texture heap as 87a00000 -> 823c0000
site = f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3'
cases = [(FN, 0xAA0003F3, 0x14000000, 0), (FN, 0xAA0003F3, 0x14000001, -1),
(0x3AD6EB8, 0x84800000, 0x7F1C0000, 1), (0x3AD6EB8, 0x87A00000, 0x823C0000, 1),
(0x3AD6EBC, 0x87A00000, 0x823C0000, -1)]
main = ['#include "patches.h"', '#include "plugin_writes.h"',
'static const PluginWrite tab[] = {RT_PLUGIN_WRITES(PLUGIN_WRITE)};',
'int main(void) {', ' int n = sizeof tab / sizeof *tab, bad = 0;']
for i, (off, old, new, want) in enumerate(cases):
main.append(f' bad |= (plugin_write_find(tab, n, 0, "main", {off:#x}, {old:#x}u, {new:#x}u) != {want}) '
f'<< {i};')
main += [' return bad;', '}']
(self.d / 'start.c').write_text('\n'.join(main) + '\n')
exe = self.d / 'start.exe'
for record, failed in (('expect mod_x main 3ad6eb8 84800000 7f1c0000', 1 << 3),
('expect mod_x main 3ad6eb8 * *', 0)):
with self.subTest(record=record):
(self.d / 'patches.h').write_text(patches.header_text(self.table(site, ['stub plugin0 4000', record]),
'MARK'))
subprocess.run([CC, '-std=gnu11', '-Wall', '-Werror', '-I', str(self.d), '-I', str(ROOT / 'runtime'),
str(self.d / 'start.c'), '-o', str(exe)], check=True, env=CC_ENV, timeout=60)
# the exact record misses only the play-time write
self.assertEqual(subprocess.run([str(exe)], env=CC_ENV, timeout=60).returncode, failed)
def test_image_must_match_its_hash(self):
t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000'])
t.plugins['plugin0']['sha256'] = '0' * 64
+9
View File
@@ -156,6 +156,15 @@ class RealArchiveTest(unittest.TestCase):
ui.apply(full, members, width, height)
expected = bytearray(original)
baseline['apply'](expected, members, width, height)
# The map (its layout and the minimap animation's width keys), the Purah Pad's frame and the loading screen
# changed on purpose after it (the maps fill the screen, the frame keeps its width, the camera's album window
# has the screen's shape, the inn's clock follows the choices to the bottom edge); the rest is byte for byte.
for member in ('blyt/AppMap_00.bflyt', 'blyt/AppMenuOverlay_00.bflyt', 'blyt/LoadingFade_00.bflyt',
'blyt/CameraSystemWindow_00.bflyt', 'blyt/Time_00.bflyt',
'anim/AppMap_00_MiniMap.bflan', 'anim/LoadingFade_00_BarIn.bflan',
'anim/LoadingFade_00_BarOut.bflan'):
lo, hi = members[member]
expected[lo:hi] = full[lo:hi]
self.assertEqual(full, expected)
for cap, extension in ((16 / 9, 0), (21 / 9, 300)):
data = bytearray(original)
+101 -2
View File
@@ -370,6 +370,45 @@ class LiftKeyTest(unittest.TestCase):
self.assertEqual(self.key(), before)
class PluginsStaleTest(unittest.TestCase):
"""A plugin the game found stale (build-cache/plugins.stale, runtime/mods.c mods_plugin_off) plans the lift and the
compile of the game's rebuild: the plugin's service run is in the lift, and only Lift.run clears the file."""
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
base = Path(tmp.name)
dest, temp = base / 'install', base / 'temp'
(temp / 'gen').mkdir(parents=True)
(temp / 'gen' / 'layout.json').write_text('[]')
(temp / 'gen' / steps.STAMP).write_text('L\n')
(dest / 'build-cache').mkdir(parents=True)
(dest / ('totk' + steps.EXE)).write_bytes(b'MZ')
(dest / 'romfs-index.bin').write_bytes(b'')
layout = SimpleNamespace(release='1.0', dlls=[])
records = {'lift': {'key': 'L'}, 'compile': {'key': 'C', 'exe_sha256': steps.file_sha256(dest / ('totk' + steps.EXE))}}
self.ctx = runner.Context(layout, dest, temp, Reporter(out=io.StringIO()), SimpleNamespace(),
state={'release': '1.0', 'steps': records})
self.addCleanup(self.ctx.reporter.close)
self.ctx.steps = [steps.Lift(), steps.Compile()]
self.ctx.keys = {'lift': 'L', 'compile': 'C'}
self.stale = dest / 'build-cache' / 'plugins.stale'
def planned(self):
self.ctx.plan()
return [s.id for s in self.ctx.steps if self.ctx.will_run(s.id)]
def test_stale_plugin_runs_the_lift_and_the_compile(self):
self.assertEqual(self.planned(), [])
self.stale.write_text('A89F6A7C\t74492AD5\tits init wrote 1 words the build did not record '
'(first main+0x3ad6eb8 87a00000 -> 823c0000)\n')
self.assertEqual(self.planned(), ['lift', 'compile'])
def test_empty_stale_file_keeps_the_build(self):
self.stale.write_text('')
self.assertEqual(self.planned(), [])
class LiftRunTest(unittest.TestCase):
"""Lift.run with fake tools: the ExeFS patch stage writes the status and data files, the lift lists the bytes it
read, and the data writes are checked against that list after it; a failed lift or check drops both files."""
@@ -998,6 +1037,59 @@ class FreeSpaceTest(unittest.TestCase):
usage.assert_called_once_with(root)
class MissingLibraryTest(unittest.TestCase):
"""#1428, #1315, #1419: a system library the release's libSDL3.so.0 links is missing; the setup names it (and the
package that provides it) before the lift, and after a game start the loader stopped, instead of exit code 127."""
LDD = ('\tlinux-vdso.so.1 (0x00007ffd)\n\tlibXss.so.1 => not found\n'
'\tlibX11.so.6 => /usr/lib64/libX11.so.6 (0x00007f00)\n\tlibdecor-0.so.0 => not found\n')
def test_packages_of_known_libraries(self):
self.assertEqual(steps.library_packages(['libXss.so.1']),
' (Fedora: libXScrnSaver, Debian/Ubuntu: libxss1, Arch: libxss)')
self.assertEqual(steps.library_packages(['libXss.so.1', 'libfoo.so.9', 'libdecor-0.so.0']),
' (Fedora: libXScrnSaver libdecor, Debian/Ubuntu: libxss1 libdecor-0-0, '
'Arch: libxss libdecor)')
self.assertEqual(steps.library_packages(['libfoo.so.9']), '')
def test_ldd_not_found_lines(self):
runs = []
def ldd(cmd, **kw):
runs.append(cmd)
return SimpleNamespace(returncode=1, stdout=self.LDD, stderr='')
with mock.patch.object(steps.sys, 'platform', 'linux'), mock.patch.object(steps.subprocess, 'run', ldd):
self.assertEqual(steps.missing_libraries([Path('a/libSDL3.so.0'), Path('b/libother.so')]),
['libXss.so.1', 'libdecor-0.so.0'])
self.assertEqual([c[0] for c in runs], ['ldd', 'ldd'])
def test_no_ldd_or_not_linux(self):
def missing(cmd, **kw):
raise FileNotFoundError('ldd')
with mock.patch.object(steps.sys, 'platform', 'linux'), mock.patch.object(steps.subprocess, 'run', missing):
self.assertEqual(steps.missing_libraries([Path('libSDL3.so.0')]), [])
with mock.patch.object(steps.sys, 'platform', 'win32'):
self.assertEqual(steps.missing_libraries([Path('SDL3.dll')]), [])
def test_loader_error_in_the_prepare_log(self):
with tempfile.TemporaryDirectory() as d:
log = Path(d) / 'prepare-prepare_shaders.log'
log.write_text('/home/p/TotK/totk: error while loading shared libraries: libXss.so.1: cannot open shared '
'object file: No such file or directory\ntotk.exe --prepare-shaders: rc=127\n'
'/home/p/TotK/totk: error while loading shared libraries: libXss.so.1: cannot open shared '
'object file: No such file or directory\n', encoding='utf-8')
self.assertEqual(steps.loader_missing(log), ['libXss.so.1'])
self.assertEqual(steps.loader_missing(Path(d) / 'none.log'), [])
def test_messages_take_the_parameters(self):
for path in (ROOT / 'installer' / 'text').glob('*.json'):
catalog = json.loads(path.read_text(encoding='utf-8'))
for id in ('check.libraries_missing', 'prepare.libraries_missing'):
text = catalog[id].format(libraries='libXss.so.1', packages=' (Fedora: libXScrnSaver)', log='x.log')
self.assertIn('libXss.so.1', text, (path.name, id))
self.assertIn('libXScrnSaver', text, (path.name, id))
class BaseGameCheckTest(unittest.TestCase):
"""Issue #261: an update NSP chosen as the base game was reported as "not Tears of the Kingdom"."""
BASE, UPDATE = '0100F2C0115B6000', '0100F2C0115B6800'
@@ -1051,8 +1143,11 @@ class ShapesTest(unittest.TestCase):
def test_shape_rule(self):
self.assertEqual([screens.shape_size(*s) for s in ((5120, 2160), (3440, 1440), (1920, 800), (2560, 1600),
(1920, 1080), (1024, 768))],
['2560x1080', '3440x1440', '3840x1600', '1280x800', None, None])
(1920, 1080), (1024, 768), (3120, 1440), (2560, 1200),
(1280, 1024), (1080, 1920), (7680, 1440), (7680, 2160))],
['2560x1080', '3440x1440', '3840x1600', '1280x800', None, '1440x1080', '2340x1080',
'2560x1200', None, None, None, '3840x1080'])
self.assertIsNone(screens.shape_size(2560, 1200, listed=True)) # a display of an unlisted shape
self.assertEqual(screens.default_size(3440, 1440), '2560x1080') # runtime/cfg.c screen_default
self.assertEqual(screens.default_size(1280, 800), '1280x800')
@@ -1086,6 +1181,10 @@ class ShapesTest(unittest.TestCase):
(['2560x1080', '3440x1440', '1280x800', '1920x1280'], 'pc'))
self.assertEqual(screens.wanted(self.dest / 'none', [(2560, 1440)]), ([], None))
def test_wanted_unlisted_output_res_gets_its_own_size(self):
(self.dest / 'totk.ini').write_text('output_res = 2560x1200\n')
self.assertEqual(screens.wanted(self.dest, [(2560, 1200), (1600, 1200)]), (['1440x1080', '2560x1200'], None))
def test_layout_settings_keep_the_last_nonempty_value(self):
for empty in ('', ' ', '""'):
with self.subTest(empty=empty):
+102
View File
@@ -0,0 +1,102 @@
"""The IPC probe must not use stale or indeterminate replies after a kernel error.
python tests/ipc_probe_check.py --cc path/to/clang
"""
import argparse
from pathlib import Path
import shutil
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "ipc.h"
// The probe's expected failure diagnostics are kept off the test's stdout.
static int probe_printf(const char *format, ...) { (void)format; return 0; }
static int probe_putchar(int c) { return c; }
#define printf probe_printf
#define putchar probe_putchar
PRODUCTION
#undef printf
#undef putchar
static uint32_t kernel_result, service_result;
void rt_svc(Cpu *c, uint32_t imm, uint64_t pc) {
(void)pc;
assert(imm == 0x21);
c->x[0] = kernel_result;
if (kernel_result) return;
uint32_t *m = (uint32_t *)(uintptr_t)c->tpidrro;
int tipc = (m[0] & 0xffff) >= T_TIPC_BASE;
memset(m, 0, IPC_MSG_BYTES);
m[1] = 1u << 31;
m[2] = service_result ? 0 : 1u << 5;
uint32_t *p = m + 3;
if (!service_result) *p++ = 0x1234;
if (tipc) *p = service_result;
else {
p = m + (((p - m) + 3) & ~3);
p[0] = CMIF_OUT_MAGIC;
p[2] = service_result;
}
}
int main(void) {
Cpu c = {0};
uint32_t tlr[IPC_MSG_BYTES / 4] = {0};
c.tpidrro = (uintptr_t)tlr;
for (int tipc = 0; tipc <= 1; tipc++) {
failures = 0;
kernel_result = service_result = 0;
assert(get_service(&c, 1, "test:u", tipc) == 0x1234 && failures == 0);
kernel_result = IPC_R_BAD_HANDLE;
uint32_t h = get_service(&c, 1, "test:u", tipc);
if (h) fprintf(stderr, "%s kernel error returned stale service handle %#x\n", tipc ? "TIPC" : "CMIF", h);
assert(h == 0 && failures == 1);
}
Reply r;
kernel_result = service_result = 0;
assert(cmd(&c, 1, 0, NULL, 0, &r) == 0 && r.nmove == 1 && r.move[0] == 0x1234);
memset(&r, 0xa5, sizeof r);
kernel_result = IPC_R_BAD_HANDLE;
assert(cmd(&c, 1, 0, NULL, 0, &r) == IPC_R_BAD_HANDLE);
assert(r.result == 0 && r.ncopy == 0 && r.nmove == 0 && r.data == NULL);
for (unsigned i = 0; i < 8; i++) assert(r.copy[i] == 0 && r.move[i] == 0);
kernel_result = 0;
service_result = IPC_R_UNKNOWN_COMMAND;
assert(cmd(&c, 1, 0, NULL, 0, &r) == IPC_R_UNKNOWN_COMMAND && r.result == service_result);
assert(r.nmove == 0 && r.data != NULL);
puts("IPC probe: CMIF/TIPC success and kernel-error replies, reply reuse and service errors passed");
return 0;
}
'''
def production():
text = (ROOT / 'runtime/ipc.c').read_text(encoding='utf-8')
magic = '\n'.join(line for line in text.splitlines() if line.startswith(('#define CMIF_IN_MAGIC', '#define CMIF_OUT_MAGIC')))
start = text.index('enum { T_CLOSE')
types = text[start:text.index('};', start) + 2]
helpers = text[text.index('#define PROBE_FRAMES'):text.index('// A TotK-like renderer:')]
return magic + '\n' + types + '\n' + helpers
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('--cc', default=shutil.which('clang') or r'C:\msys64\ucrt64\bin\clang.exe')
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='ipc-probe-') as temp:
work = Path(temp)
source = work / 'probe.c'
source.write_text(HARNESS.replace('PRODUCTION', production()), encoding='utf-8')
exe = work / 'probe.exe'
subprocess.run([args.cc, '-O2', '-std=gnu11', '-ftrivial-auto-var-init=pattern',
'-I', str(ROOT / 'runtime'), str(source), '-o', str(exe)], check=True)
subprocess.run([str(exe)], check=True)
if __name__ == '__main__':
main()
+2
View File
@@ -72,8 +72,10 @@ TESTS = {
'settings_doc_check': ('.venv', None, [], ''),
'mouse_direct_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles its checks with clang'),
'cheats_vm_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles runtime/cheats.c into a harness with clang'),
'cursor_art_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the cursor with zero and pattern stack initialization'),
'romfs_shapes_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production overlay selection helpers'),
'frame_world_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production world-clock player walk'),
'ipc_probe_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the IPC probe helpers with forced kernel failures'),
'sync_ahead_check': ('.venv', 'cc', ['--cc', '<cc>'], 'compiles the production sync-ahead wait selection'),
'patches_v110_check': ('.venv', 'cc', [], 'compiles synthetic patch contracts for comparison with Unicorn'),
'patches_v110_highfps_check': ('.venv', 'cc', [], 'compiles synthetic high-fps contracts for comparison with Unicorn'),
+90 -8
View File
@@ -132,6 +132,14 @@ def u(v):
return int(v, 16) if isinstance(v, str) else v
def header_site(h):
"""The hook sits on main's module header, not on code. exlaunch adds a table offset to main's base, and a game
update the plugin's table lacks gives offset 0 (Challenge Mode's Enemy Health Regeneration names 1.0.0 to 1.4.1).
Nothing runs there, on the Switch either: the write is kept and checked, and the lift gets no site for it (its
first word, 1, decodes as a trap the generator refuses to patch)."""
return h['site'] == 'main+0x0'
def ran_view(rec):
"""The record as seen from the plugins whose inits ran: a plugin that only stayed loaded (TOTK_PLUGIN_ONLY) counts
as a module that is no plugin, so its exports and code are not checked as this record's. A record without "ran"
@@ -198,6 +206,8 @@ def relocated(orig, site, word, at):
# hook's site calls the stub and runs main's own original after it, recomp/patches.py @call; a replace hook's Orig
# reaches an unpatched copy of the function, `orig`), so these forms only tell an exlaunch hook from other code.
NOP = 0xD503201F
YIELD = 0xD503203F
SPIN_WIN = 512 # bytes from a spin wait's back-edge back to its head (tools/spin_waits.py SPIN_WIN)
LDR_X17_8 = 0x58000051 # ldr x17, #8
LDR_X17_12 = 0x58000071 # ldr x17, #12
ADR_X30_16 = 0x1000009E # adr x30, #16
@@ -377,7 +387,8 @@ def check_record(rec, impls, game=frozenset()):
# words as it left them here (runtime/plugin_init.c check_writes keeps data pages, compared word by word
# with the expect lines). .rodata holds what the lift read as constants (the jump tables), so no write
# goes there. A word that makes a pointer into a plugin's .text (a table entry swapped for a plugin
# function: Zonai Fieldworks, Material Columns) names a function start of that plugin's lift.
# function: Zonai Fieldworks, Material Columns) names a function start of that plugin's lift; any other
# word is compared by place only (plugin_lines).
if w['offset'] < main['data_off']:
reasons.append(f"a write into main's .rodata: {where} {w['old']:#010x} -> {w['new']:#010x}")
continue
@@ -456,8 +467,15 @@ def check_record(rec, impls, game=frozenset()):
# ---- the code the hooks reach
def plt_imports(nso, img, base, text_end):
"""{absolute address of a PLT stub: the import its GOT slot binds} (adrp x16; ldr x17, [x16, #slot]; add x16, x16,
#slot; br x17), from the JUMP_SLOT relocations."""
slots = {off: nso.syms[sym][0] for off, typ, sym, _ in nso.relocs if typ == R_AARCH64_JUMP_SLOT}
#slot; br x17), from the JUMP_SLOT relocations. A slot whose symbol the plugin defines itself binds to that
definition (runtime/loader.c resolve), so its stub maps to the absolute address of the plugin's own code instead of
a name: a plugin built with default visibility calls its own exported functions through its PLT (the
std::vector<const char*> constructor of Challenge Mode's Enemy Health Regeneration)."""
slots = {}
for off, typ, sym, _ in nso.relocs:
if typ == R_AARCH64_JUMP_SLOT:
name, _, shndx, value, _ = nso.syms[sym]
slots[off] = base + value if shndx else name
out = {}
for o in range(0, text_end - 16, 4):
w0, w1, _, w3 = struct.unpack_from('<4I', img, o)
@@ -498,6 +516,10 @@ def reach(img, base, text_end, roots, plt, stubs=()):
if a in seen:
break
if a in plt:
if isinstance(plt[a], int): # the plugin's own function behind its PLT: the path goes on there
seen.add(a)
a = plt[a]
continue
imports[plt[a]] = imports.get(plt[a], 0) + 1
break
if not base <= a < base + text_end:
@@ -582,7 +604,12 @@ def init_code(rec, hooks, module):
trampolines of its far hooks (the moved original words and a branch back). The plugin may point a veneer at any of
them at play (Zonai Fieldworks turns its features' hooks on and off), so each is a root of the reach check and a
seed of the lift. The trampolines of inline hooks (never run) and the Orig trampolines of replace hooks (the lift
serves them with the function's unpatched copy) are left out: their way back would split main's functions."""
serves them with the function's unpatched copy) are left out: their way back would split main's functions.
An exlaunch inline-hook stub the init writes (stur x30; bl impl; ldur x30; b trampoline; .quad callback) may be the
target of a hook the plugin turns on at play: Zonai Fieldworks writes one per member hook at init, back to back,
and a member switched on points its gate's pointer at it (the 4th of a row is plugin+0x135048 on 1.4.3). Each stub
and its callback are starts; the .quad is data, not code running on into the next stub."""
p = {m['name']: m for m in rec['modules']}[module]
img, pre = rec['images'].get(module), rec.get('pre_images', {}).get(module)
if img is None or pre is None:
@@ -591,16 +618,53 @@ def init_code(rec, hooks, module):
now, old = struct.unpack_from(f'<{n}I', img), struct.unpack_from(f'<{n}I', pre)
known = {p['base'] + int(h['trampoline'].split('+')[1], 16) for h in hooks
if (h.get('trampoline') or '').startswith(module + '+')}
out, inside = set(), False # inside: the word before is a written word that goes on to this one
for i in range(n):
text = range(p['base'], p['base'] + p['text_end'])
out, inside, i = set(), False, 0 # inside: the word before is a written word that goes on to this one
while i < n:
new = old[i] == 0 and now[i] != 0
if (new and i + 5 < n and now[i] == STUR_X30 and now[i + 1] & 0xFC000000 == 0x94000000
and now[i + 2] == LDUR_X30 and now[i + 3] & 0xFC000000 == 0x14000000):
stub = p['base'] + 4 * i
callback = now[i + 4] | now[i + 5] << 32
out.add(stub)
if callback in text:
out.add(callback)
inside, i = False, i + 6
continue
if new and not inside:
out.add(p['base'] + 4 * i)
# b, br, ret end a trampoline; one may follow right after
inside = new and now[i] & 0xFC000000 != 0x14000000 and now[i] & 0xFFFFFC1F not in (0xD61F0000, 0xD65F0000)
i += 1
return out - known
def yield_spins(img, text_end):
"""{loop head offset: [back-edge offsets]} of the plugin's spin waits: a direct branch back at most SPIN_WIN bytes
to a head whose loop body holds a `yield` and no call or SVC; the yield is the hint code puts in a loop that waits
for another thread (an exclusive
byte lock in Zonai Fieldworks' hook wrappers, plugin+0xe3ff4 on 1.4.3). On the Switch the lock holder runs on its own
core; here both hold one of the three virtual cores (runtime/kernel.c), and a holder preempted for the spinner
waits for that core while the spinner, which makes no SVC, keeps it: the game froze when Zonai Fieldworks turned a
member off. A `spin` line sends each back-edge through rt_spin_gate, which hands the core to a waiting thread
(tools/spin_waits.py finds the game's own waits; the installer has no disassembler, so this test is by word)."""
n = text_end // 4
words = struct.unpack_from(f'<{n}I', img)
out = {}
for j, w in enumerate(words):
pr = pc_relative(w, 4 * j)
if pr is None or pr[0][0] not in ('b', 'b.cond', 'cbz', 'tbz') or w & 0xFC000000 == 0x94000000:
continue
head = pr[1]
if not 4 * j - SPIN_WIN <= head <= 4 * j or head % 4:
continue
body = words[head // 4:j]
if YIELD in body and not any(x & 0x7C000000 == 0x14000000 and x >> 31 or x & 0xFFFFFC1F == 0xD63F0000
or x & 0xFFE0001F == 0xD4000001 for x in body): # bl, blr, svc: a call
out.setdefault(head, []).append(4 * j)
return out
def entries(rec, hooks, module):
"""(main offsets, plugin offsets): where module's hook code comes back into main's .text, which the lift makes
function starts (recomp/patches.py `entry`), and the code its veneers lead to, seeds of its lift. The site + 4 of a
@@ -609,6 +673,7 @@ def entries(rec, hooks, module):
back there too."""
mods = {m['name']: m for m in rec['modules']}
main, p = mods['main'], mods[module]
hooks = [h for h in hooks if not header_site(h)] # never run: no way back into main, no code to seed
out = {int(h['site'].split('+')[1], 16) + 4 for h in hooks
if h['kind'] == 'branch' or h['kind'] == 'replace' and not h.get('trampoline')}
base, img = p['base'], rec['images'][module]
@@ -633,10 +698,20 @@ def plugin_lines(rec, hooks, name, record_dir, module):
text_sha = hashlib.sha256(img[:p['text_end']]).hexdigest()
image = json.dumps((Path(record_dir) / p['image']).resolve().as_posix(), ensure_ascii=False)
lines.append(f'plugin {name} {p["name"]} {text_sha} {image}')
own = {int(h['site'].split('+')[1], 16) for h in hooks}
own = {int(h['site'].split('+')[1], 16): h for h in hooks}
# A word of main's .data or .bss that is no pointer into a plugin's .text (a data hook without a target, and not
# the upper half of one with a target) shapes no lifted code, and the game may hold another value there at play
# than in the service run: Self Recall of Zonai Fieldworks takes its storage off a pool size that grows with the
# resolution's texture heap. Its expect line says `* *`: the start matches it by place only
# (runtime/plugin_init.c check_writes), and the word keeps what the init wrote at play.
pointers = {o for o, h in own.items() if h['kind'] == 'data' and h.get('target')}
for w in rec['writes']:
if w['module'] == 'main' and w['offset'] in own:
lines.append(f'expect {name} {w["module"]} {w["offset"]:x} {w["old"]:08x} {w["new"]:08x}')
h, o = own[w['offset']], w['offset']
if h['kind'] == 'data' and o not in pointers and o - 4 not in pointers:
lines.append(f'expect {name} {w["module"]} {o:x} * *')
else:
lines.append(f'expect {name} {w["module"]} {o:x} {w["old"]:08x} {w["new"]:08x}')
seeds, stubs = {}, {}
def at(ref):
@@ -645,6 +720,8 @@ def plugin_lines(rec, hooks, name, record_dir, module):
for h in hooks:
site = int(h['site'].split('+')[1], 16)
if header_site(h):
continue
if h['kind'] == 'inline':
sm, so = at(h['stub'])
stubs.setdefault(sm, set()).add(so)
@@ -675,6 +752,8 @@ def plugin_lines(rec, hooks, name, record_dir, module):
lines.append(f'seed {m} ' + ' '.join(f'{o:x}' for o in sorted(seeds[m])))
if back:
lines.append('entry main ' + ' '.join(f'{o:x}' for o in back))
for head, edges in sorted(yield_spins(img, p['text_end']).items()):
lines.append(f'spin {module} {head:x} ' + ' '.join(f'{b:x}' for b in edges) + ' # a loop with a yield')
return lines
@@ -831,6 +910,9 @@ def report(rec, label, game=frozenset()):
else:
print(f' {h["kind"]} {h["site"]} (was {h["original"]}) -> {"bl" if h["kind"] == "call" else "b"} '
f'{h["target"]}' + (f', Orig trampoline {h["trampoline"]}' if h.get('trampoline') else ''))
if header_site(h):
print(f' note: {h["site"]} is main\'s module header, not code: the plugin has no address for this game '
f'update there, and this hook does nothing, as on the Switch')
for r in reasons:
print(f' REFUSED: {r}')
if not reasons:
+113 -10
View File
@@ -15,9 +15,10 @@ and every pane field and animation key holds the value the edit expects before i
import math
import struct
# BFLYT pane sections (pan1, pic1, txt1, ...): name at +12 (24 bytes), translate x / y at +44 / +48, scale x / y at +68 / +72.
# BFLYT pane sections (pan1, pic1, txt1, ...): name at +12 (24 bytes), translate x / y at +44 / +48, scale x / y at +68 / +72,
# size (width) at +76.
PANE_MAGICS = (b'pan1', b'pic1', b'txt1', b'wnd1', b'bnd1', b'prt1', b'ali1', b'scr1')
FIELD = {'x': 44, 'y': 48, 'scale_x': 68, 'scale_y': 72}
FIELD = {'x': 44, 'y': 48, 'scale_x': 68, 'scale_y': 72, 'w': 76, 'h': 80}
# Full-screen layouts whose root pane stays as wide as the canvas.
KEEP_ROOT = {'AppMenuBG_00', 'PauseMenuBG_00', 'ShopMenuParasailBG_00', 'ShortCutBG_00', 'TitleMenuBG_00', 'EventFade_00',
@@ -60,6 +61,22 @@ def hud_extent(k, hud_aspect):
inner = 1 / ((16 / 9) / hud_aspect) - 1 # 1 / kc - 1
return 960 * inner, 960 * k * inner
# The loading screen's map is a capture of the world map that the game draws as the 3 x 3 tiles of 840 units around the
# player's tile (measured with TOTK_DUMP at 3840x1080: nine 840x840 tile draws into the capture), so only 840 units
# either side of the player are certain to hold map; wider, the capture shows black beside the tiles where the player
# stands near a tile's edge. At 16:9 it is 1470 wide (the screen's 1920 less 450), its left edge 23 units past the
# screen's, and the side panel (a window, so its frame keeps its proportions at any width) covers its right 237 units.
LOADING_MAP_MAX = 1660
def loading_map(k):
"""(width, shift, panel width) of the loading screen's map capture and side panel for k = 16:9 over the aspect: the
map as wide as the screen allows up to LOADING_MAP_MAX, its left edge where 16:9 has it relative to the screen's
edge (shift: how far its centre moves from x -248), and the panel from the map's right part to the screen's edge."""
width = min(1920 / k - 450, max(1470, LOADING_MAP_MAX))
centre = -960 / k - 23 + width / 2
panel = 960 / k - (centre + width / 2 - 237)
return width, centre + 248, panel
def edits(k, hud_aspect):
"""(layout, pane, field, value) for the aspect: k = 16/9 over the aspect (the root's scale), w = how far a 1920-wide
layout's edge moves out in its own units (960 * (1 / k - 1)). OFF moves a pane out of sight. hud_aspect: the
@@ -71,7 +88,15 @@ def edits(k, hud_aspect):
out = [
('AppAlbum_00', 'N_FadeInOut_00', 'scale_x', k), ('AppAlbum_00', 'N_Open_01', 'scale_x', wide),
*[('AppMap_00', f'N_BlurInOut_0{i}', 'scale_x', wide) for i in range(4)],
('AppMap_00', 'N_MiniMap_00', 'x', -270 * (1 - k)),
# With the map as wide as the screen, the layer tabs go to its left edge and the time, temperature and
# position to its right edge, as at 16:9 (neither position is animated; AppMap_00_MiniMap keys their visibility).
('AppMap_00', 'N_MiniMap_00', 'x', -w), ('AppMap_00', 'N_AllMapTime_00', 'x', w),
# The map: the panes that cut it out and its black backing are 2250 wide, so under the 16:9 root the world map
# ended short of the screen's sides and black bars showed there. They take the screen's width in the root's
# units instead (a size, not a scale: the map inside keeps its proportions and more of it shows), and so do the
# icon area and the shadow frame over it.
*[('AppMap_00', pane, 'w', 2250 / k) for pane in ('N_Cut_00', 'N_Capture_00', 'Black8_01', 'N_Cut_01',
'P_MapCapture_00', 'N_Cut_02', 'N_IconArea_00', 'W_Shadow_00')],
('AppMenuOverlay_00', 'N_FadeInOut_00', 'scale_x', k), ('AppMenuOverlay_00', 'N_FadeInOut_01', 'scale_x', k),
('AppMenuOverlay_00', 'N_Icon_00', 'scale_x', k), ('AppMenuOverlay_00', 'N_TitleOne_01', 'scale_x', k),
('AppOpenDemoWindow_00', 'P_BG_00', 'scale_x', wide), ('AutoBuilder_00', 'N_BG_00', 'scale_x', wide),
@@ -83,12 +108,17 @@ def edits(k, hud_aspect):
('CameraSystemWindow_00', 'T_Text_00', 'scale_x', k),
('ChallengeLog_00', 'C_CaptureUp_00', 'x', OFF), ('ChallengeLog_00', 'C_CaptureUp_01', 'x', OFF),
('GameOver_00', 'P_BG_00', 'scale_x', wide),
('LoadingFade_00', 'N_Base_00', 'scale_x', wide), ('LoadingFade_00', 'N_Logo_00', 'x', w),
# The loading screen: the map starts at the screen's left edge and the side panel ends at its right edge, each
# unstretched. See loading_map for the widths.
('LoadingFade_00', 'N_Logo_00', 'x', w),
('LoadingFade_00', 'N_Status_00', 'x', w), ('LoadingFade_00', 'N_Tips_00', 'x', -w),
('LoadingFade_00', 'P_BG_00', 'scale_x', wide), ('LoadingFade_00', 'P_SideBGDeco_00', 'scale_x', k),
('LoadingFade_00', 'Pa_IconPlayer_00', 'scale_x', k), ('LoadingFade_00', 'Pa_LargeDungeonMap_00', 'scale_x', k),
('LoadingFade_00', 'Pa_LargeDungeonMap_01', 'scale_x', k), ('LoadingFade_00', 'Pa_Map_00', 'scale_x', k),
('LoadingFade_00', 'Pa_Map_01', 'scale_x', k),
('LoadingFade_00', 'P_BG_00', 'scale_x', wide), ('LoadingFade_00', 'P_BG_01', 'scale_x', wide),
('LoadingFade_00', 'P_Grid_00', 'scale_x', wide), ('LoadingFade_00', 'P_Bar_00', 'scale_x', wide),
*[('LoadingFade_00', pane, 'w', loading_map(k)[0]) for pane in ('C_CaptureMap_00', 'C_CaptureMap_01',
'P_CaptureMap_00', 'P_CaptureMap_01')],
('LoadingFade_00', 'N_Map_00', 'x', -248 + loading_map(k)[1]),
('LoadingFade_00', 'W_SideBGDeco_00', 'x', 960 / k), ('LoadingFade_00', 'W_SideBGDeco_00', 'w', loading_map(k)[2]),
('LoadingFade_00', 'P_SideBGDeco_00', 'x', 960 / k),
('MessageLog_01', 'P_Capture_00', 'scale_x', wide), ('OwnedHorseList_00', 'N_BG_00', 'scale_x', wide),
('PaCommonBtnTitle_00', 'B_Hit_00', 'x', OFF), ('PaCommonBtnTitle_00', 'N_Cursor_00', 'x', OFF),
('PaLargeDungeonMap_00', 'P_BG_00', 'scale_x', wide), ('PaMessageBtn_00', 'B_Hit_00', 'x', OFF),
@@ -99,6 +129,13 @@ def edits(k, hud_aspect):
*[e for pane, x, _ in BALLOON_PART for e in (('PaBalloonMessage_00', pane, 'scale_x', k),
('PaBalloonMessage_00', pane, 'x', x * k))],
]
# The Purah Pad's frame (map, album, ...): AppMenuOverlay_00 keeps a root as wide as the screen, so the stone and
# light pieces at its left and right edges (x = -960 / 960, anchored at their outer side) were stretched with it.
# They keep their own width at the edges.
out += [('AppMenuOverlay_00', f'P_Frame{side}{part}', 'scale_x', k) for side in 'LR'
for part in ('Core_00', 'AlbNrm_00', 'Light_00', 'EdgeFast_00', 'EdgeSlow_00', 'EdgeFastGlow_00',
'EdgeSlowGlow_00')]
out += [('AppMenuOverlay_00', f'P_Frame{side}Dent_0{i}', 'scale_x', k) for side in 'LR' for i in (0, 1)]
# Menus framed by two side decorations, a header and a background: the frame stays at the screen's edges.
for layout, deco in (('PauseMenuOverlay_00', 'P_Deco{}_00'), ('SystemLoadList_00', 'P_Deco{}_00'),
('SystemOption_00', 'P_Deco{}_00'), ('SystemSaveLoad_00', 'P_Deco{}_00')):
@@ -135,10 +172,21 @@ def tall_edits(k):
out = [('AppAlbum_00', 'N_FadeInOut_00', 'scale_y', k), ('AppAlbum_00', 'N_Open_01', 'scale_y', tall),
*[('AppMenuOverlay_00', p, 'scale_y', k) for p in ('N_FadeInOut_00', 'N_FadeInOut_01', 'N_Icon_00',
'N_TitleOne_01')],
('CameraPointer_00', 'N_Type_01', 'scale_y', k), ('CameraSystemWindow_00', 'N_FirstOut_00', 'scale_y', k),
('CameraPointer_00', 'N_Type_01', 'scale_y', k),
# The camera's "save to the album?" window: N_InOut_00 takes the screen's height (below), so the photo's
# frame (N_AlbumPic_00) has the screen's shape, as the photo has. The compendium's square photos
# (N_PictureBook_00) and the album's question and buttons (N_AlbumCon_00) keep their proportions, and the
# question and the buttons move out by the frame's extra half height (319.5 of its 639).
*[('CameraSystemWindow_00', p, 'scale_y', k) for p in ('N_PictureBook_00', 'N_AlbumCon_00')],
('CameraSystemWindow_00', 'T_TextAlbum_00', 'y', 380 + 319.5 * (tall - 1)),
*[('CameraSystemWindow_00', p, 'y', -396 - 319.5 * (tall - 1)) for p in ('Pa_BtnL_01', 'Pa_BtnR_01')],
*[('LoadingFade_00', p, 'scale_y', k) for p in ('Pa_IconPlayer_00', 'Pa_LargeDungeonMap_00',
'Pa_LargeDungeonMap_01', 'Pa_Map_00', 'Pa_Map_01')],
*[('AppMap_00', f'N_BlurInOut_0{i}', 'scale_y', tall) for i in range(4)],
# The map's capture, its cut, backing and shadow are 1080 high, the height of a 16:9 layout: they take the
# screen's height, 1080 / k, so the map fills it instead of leaving black above and below (tall_anim
# does the same for the keys of AppMap_00_MiniMap that hold 1080)
*[('AppMap_00', pane, 'h', 1080 * tall) for pane in MAP_TALL + ('W_Shadow_00',)],
*[(layout, 'P_BG_00', 'scale_y', tall) for layout in ('AppOpenDemoWindow_00', 'GameOver_00', 'LoadingFade_00',
'PaLargeDungeonMap_00', 'PaRecipeCardList_00')],
('LoadingFade_00', 'N_Base_00', 'scale_y', tall),
@@ -157,7 +205,10 @@ def tall_edits(k):
'ShopMenu_00', 'SystemActionGuide_00') + SYSTEM_MENUS]
out += [(name, 'RootPane', 'y', -540 * (1 - k)) for name in (
'CtrlGuide_00', 'DoCommand_00', 'EnvironmentInfo_00', 'HorseGauge_00', 'MessageDialog_00', 'MessageLog_01',
'PauseMenuOverlay_00', 'SaveLoadIcon_00', 'TreasureFullShortCut_00')]
'PauseMenuOverlay_00', 'SaveLoadIcon_00', 'TreasureFullShortCut_00',
# the clock an inn's choices show (05:00) under MessageDialog_00's list: it stayed in the middle 16:9 and was
# drawn over the list's last rows
'Time_00')]
out += [('AppAlbum_00', 'N_PicLoad_01', 'y', -540 * (1 - k)), ('AppMap_00', 'N_AllMapTime_00', 'y', -h),
('AppMenuOverlay_00', 'A_Align_00', 'y', -(505 + h)), ('AppMenuOverlay_00', 'Pa_GuideLeft_00', 'y', -(505 + h)),
('AppMenuOverlay_00', 'N_TitleTab_00', 'y', 491 + h),
@@ -200,6 +251,49 @@ def anim_keys(blarc, lo, pane, tag, target):
pos += size
return out
FLPA_SIZE_X = 8 # BFLAN FLPA target: the pane's width
# The map's panes that AppMap_00_MiniMap sizes: in the full map they hold the width 2250 in its keys (the minimap
# shrinks them), and the animation's keys win over the layout's size, so a wider screen still cut the map at 2250.
MAP_SIZED = ('N_IconArea_00', 'N_Cut_00', 'N_Capture_00', 'P_MapCapture_00', 'Black8_01', 'N_Cut_01', 'N_Cut_02')
# The map's panes that hold the 16:9 layout's height, 1080, in the layout and in the full map's keys of AppMap_00_MiniMap
MAP_TALL = ('N_Cut_00', 'N_Capture_00', 'P_MapCapture_00', 'Black8_01')
FLPA_SIZE_Y = 9 # BFLAN FLPA target: the pane's height
def wide_anim(blarc, members, k, changed):
"""The animation keys that hold the full map's width, for a canvas wider than 16:9: 2250 becomes 2250 / k, the
screen's width in the 16:9 root's units plus the same margin, as edits() does for the layout's sizes."""
member = 'anim/AppMap_00_MiniMap.bflan'
if member not in members: raise SystemExit(f'AppMap_00_MiniMap: no animation {member} in the archive')
lo = members[member][0]
if blarc[lo:lo + 4] != b'FLAN': return # tests/hud_layout_test.py's synthetic archive: fixed-offset keys only
found = 0
for pane in MAP_SIZED:
for keys in anim_keys(blarc, lo, pane, b'FLPA', FLPA_SIZE_X):
for key in keys:
if abs(struct.unpack_from('<f', blarc, key + 4)[0] - 2250) < 1e-3:
struct.pack_into('<f', blarc, key + 4, 2250 / k); found += 1
if found < len(MAP_SIZED): raise SystemExit(f'AppMap_00_MiniMap: {found} width keys of 2250, expected at least {len(MAP_SIZED)}')
changed.add(member)
def loading_anim(blarc, members, k, changed):
"""The loading screen's map slides by 24 units when the bar comes in and goes out (LoadingFade_00_BarIn: x -278 to
-302, BarOut: -302 to -326); the keys move with the map's centre (loading_map)."""
shift = loading_map(k)[1]
for name, shipped in (('LoadingFade_00_BarIn', (-278, -302)), ('LoadingFade_00_BarOut', (-302, -326))):
member = f'anim/{name}.bflan'
mini = members.get('anim/AppMap_00_MiniMap.bflan')
if mini and blarc[mini[0]:mini[0] + 4] != b'FLAN': return # tests/hud_layout_test.py's synthetic archive
if member not in members: raise SystemExit(f'{name}: no animation {member} in the archive')
lo = members[member][0]
curves = anim_keys(blarc, lo, 'N_Map_00', b'FLPA', 0)
keys = [key for curve in curves for key in curve]
values = tuple(round(struct.unpack_from('<f', blarc, key + 4)[0], 3) for key in keys)
if values != shipped: raise SystemExit(f'{name} N_Map_00 x: keys {values}, expected {shipped}')
for key in keys: struct.pack_into('<f', blarc, key + 4, struct.unpack_from('<f', blarc, key + 4)[0] + shift)
changed.add(member)
def tall_anim(blarc, members, k, changed):
"""The animation keys that hold positions or zooms on the screen's height, for a canvas narrower than 16:9."""
h = 540 * (1 / k - 1)
@@ -221,6 +315,13 @@ def tall_anim(blarc, members, k, changed):
abs(get(k1 + 4) + 360) < 1e-3 and get(k1 + 8) == 0):
raise SystemExit(f'AppMap_00_MiniMap {pane}: not a line from 0 to y -360')
put(k0 + 8, -(360 + h)), put(k1 + 4, -(360 + h))
# The full map's height keys hold 1080 (the minimap shrinks the panes), and they win over the layout's sizes
found = 0
for pane in MAP_TALL:
for keys in anim_keys(blarc, lo, pane, b'FLPA', FLPA_SIZE_Y):
for key in keys:
if abs(get(key + 4) - 1080) < 1e-3: put(key + 4, 1080 / k); found += 1
if found < len(MAP_TALL): raise SystemExit(f'AppMap_00_MiniMap: {found} height keys of 1080, expected at least {len(MAP_TALL)}')
# The large place name of a discovery holds its height (285, then 260) in flat keys; they move to the top edge.
curves = anim_keys(blarc, anim('Location_00_IsDiscovery'), 'N_Large_00', b'FLPA', FLPA_Y)
values = [get(key + 4) for keys in curves for key in keys]
@@ -317,4 +418,6 @@ def apply(blarc, members, width, height, hud_aspect=None):
have = struct.unpack_from('<f', blarc, lo + offset)[0]
if abs(have - shipped) >= 1e-4: raise SystemExit(f'{anim} +{offset}: {have}, expected {shipped}')
struct.pack_into('<f', blarc, lo + offset, value); changed.add(member)
wide_anim(blarc, members, k, changed)
loading_anim(blarc, members, k, changed)
return sorted(changed)
+50 -24
View File
@@ -53,6 +53,11 @@
# A thread waiting for a virtual core interrupts the owner when it runs game code: 1 = on, 2 = priority inheritance
# without the interrupt, 0 = off (the old scheduling).
# async_preempt = 1
# With async_preempt on, a thread asked to give its virtual core to a better one gives it up as soon as it returns
# from a port function (graphics, memory, files) to game code, instead of at its next system call or interrupt; an
# interrupt that lands inside a port function is refused. 0 or 1. Default: on. On a Ryzen 9 7900X with 4 cores the
# frame on the sky islands was about 5% shorter.
# host_checkpoint = 1
# Replay NVN submissions on their own thread, at most one frame behind the game, 0 or 1. Default: off. Helps where the
# game waits for the GPU; adds up to a frame of latency.
# replay_async = 0
@@ -69,7 +74,7 @@
# timer_1ms = 1
# One frame ahead of the GPU.
# Let the game build the next frame while the GPU still draws the previous one, 0 or 1. Default: off. Each frame the
# Let the game build the next frame while the GPU still draws the previous one, 0 or 1. Default: on. Each frame the
# game waits once for the GPU to finish the frame it presented last; with 1 that wait covers the frame before it
# instead. On Great Sky Island (Linux, RX 9070 XT) with shadow_defer = 1 this took about 73 to 100 fps. Costs one more
# frame of input delay, and frame times vary more from frame to frame than with 0. GPU results the game reads back every frame after that wait, for example its depth queries, can be a frame old; a result it reads only once is waited for.
@@ -78,7 +83,7 @@
# game's memory in place and guards copy or wait for what the game rewrites while the GPU still reads it (no shadow
# copies, about 1 ms a frame less on a weak CPU). With memory = import and no shadow storage the setting is ignored
# and the log says so.
# sync_ahead = 0
# sync_ahead = 1
# Shadow storage, 0 or 1: each CPU-visible memory pool of the game gets a host-visible copy that the GPU reads, in
# place of importing the game's memory. Default: on under Linux and Wine, off on native Windows.
# Costs about 0.2 ms a frame and doubles the memory of those pools (about 1.1 GB; docs/building.md). Read at start.
@@ -98,14 +103,16 @@
# the CPU threads).
# lib_prebuild = 1
# lib_prebuild_threads = 4
# Experimental: 1 keeps a render pass open through the game's own Barrier calls (ORDER_FRAGMENTS | INVALIDATE_TEXTURE) when
# none of the pass's draws can write a storage buffer or image, making the writes visible to the next draw with a by-region
# barrier instead of ending the pass. Scenes where the game issues about a thousand such barriers a frame (the water in
# the Nachoyah Shrine, terrain decals) go from about 1200 passes and 10000 layout changes to about 130 passes and 150;
# the GPU time there fell from 24.5 to 7.8 ms a frame. The game's barrier orders every pixel, the one inside the pass only
# the pixel a draw writes: a driver that runs it per screen tile can show flicker or squares at the edges of water, decals
# or particles (report any). Needs the feedback layout (the default). Read at start. Default: 0.
# barrier_merge = 0
# 1 keeps a render pass open through the game's own Barrier calls (ORDER_FRAGMENTS | INVALIDATE_TEXTURE) when none of the
# pass's draws can write a storage buffer or image, making the writes visible to the next draw with a by-region barrier
# instead of ending the pass. A draw that samples a target written in the pass without writing it itself still ends the
# pass. Scenes where the game issues about a thousand such barriers a frame (the water in the Nachoyah Shrine, terrain
# decals) go from about 1200 passes and 10000 layout changes to about 130 passes and 150; the GPU time there fell from
# 24.5 to 7.8 ms a frame on Linux (RADV). The game's barrier orders every pixel, the one inside the pass only the pixel a
# draw writes: a driver that runs it per screen tile could show flicker or squares at the edges of water, decals or
# particles; 0 brings back a full barrier each time (report it). Needs the feedback layout (the default). Read at start.
# Default: 1.
# barrier_merge = 1
# Build known pipelines ahead of time.
# pipe_prebuild = 1
# Threads that translate known shaders at start (1 to 64; default: half the CPU threads, at most 16).
@@ -150,6 +157,11 @@
# fix_c0 = 1
# New GPU memory pools start zero-filled, as Switch memory does.
# fix_zero = 1
# Shaders that discard a pixel and then read how fast a value changes across neighbouring pixels (a texture's
# level of detail, a derivative) keep the discarded pixel running without output, as the Switch does: stops the light
# fringe round objects against clouds and fog on AMD. Default: 1 on AMD's own Windows driver, 0 elsewhere. 0 keeps
# the plain discard everywhere, 1 also uses it on other drivers. Read at start.
# demote = 1
# Optimisations, 0 turns each off: skip bindings that did not change, remember shader lookups, reuse the previous
# draw's pipeline when its state repeats, remember texture descriptors between draws, update descriptors in bulk,
# skip push constants that did not change, bind only the vertex buffers a draw reads, compare and copy each draw's
@@ -212,16 +224,19 @@
# gpu_index = 0
# gpu_name = NVIDIA
# Game resolution: the size the game draws its picture and interface in (1280x720 to 7680x4320). Above 1920x1080 the
# game's texture heap and memory pool grow with it. Another shape than 16:9, such as 3440x1440 on a 21:9 monitor or
# the Steam Deck's 1280x800 (16:10), gives the camera's view that shape and lays the HUD out for it. The installer
# prepares the UI layout for fifteen sizes: 2560x1080, 3440x1440, 3840x1600, 5120x2160 (21:9), 3840x1080, 5120x1440
# (32:9), 1280x800, 1680x1050, 1920x1200, 2560x1600 (16:10), 1920x1280, 2160x1440, 2256x1504, 2880x1920 and 3000x2000
# (3:2). For any other size, or a source build that has not made the layout, the game draws the largest 16:9 size that
# fits inside it (3440x1080 gives 1920x1080) and the present adds bars; build the layout with
# tools/make_romfs_patches.py --aspect WxH to use the full shape. Read at start. Default: 1920x1080, or on a primary
# display of one of those shapes the smallest of its sizes at least 1080 high that fits the display (1920x1280 on a 3:2
# laptop, 2560x1080 on a 21:9 monitor), so the picture fills the screen without black bars, with prompts = xbox or pc
# too (on an install by an older setup, which built the Xbox prompts for 16:9 only, prompts = xbox keeps 1920x1080).
# game's texture heap and memory pool grow with it. Another shape than 16:9, such as 3440x1440 on a 21:9 monitor or the
# Steam Deck's 1280x800 (16:10), gives the camera's view that shape and lays the HUD out for it. Any shape from 4:3 to
# 32:9 works: 21:9 monitors (2560x1080, 3440x1440, 3840x1600, 5120x2160), 32:9 ones (3840x1080, 5120x1440, 7680x2160;
# hud_width below keeps the HUD in the middle), 16:10 and 3:2 screens, 4:3 (1440x1080, 2048x1536 on an iPad) and phone
# screens streamed to (2340x1080 or 3120x1440 at 19.5:9, 2400x1080 at 20:9). The installer makes the UI layout for the
# shapes of the connected displays and of this setting; at a shape it has none for, the game draws the largest 16:9 size
# that fits inside it with bars and makes the layout in the background for the next start (a source build: make it with
# tools/make_romfs_patches.py --aspect WxH). With vert_plus = 1 a shape narrower than 16:9 keeps the width of the 16:9
# view and shows more above and below. Portrait shapes and shapes outside 4:3..32:9 draw 16:9 with bars. Read at start.
# Default: 1920x1080, or on a primary display of 21:9, 32:9, 16:10, 3:2 or 4:3 the smallest size of that shape at least
# 1080 high that fits the display (1920x1280 on a 3:2 laptop, 2560x1080 on a 21:9 monitor), so the picture fills the
# screen without black bars, with prompts = xbox or pc too (on an install by an older setup, which built the Xbox
# prompts for 16:9 only, prompts = xbox keeps 1920x1080).
# output_res = 1920x1080
# HUD width on a game resolution wider than 16:9: full, the default, puts the HUD at the screen's left and right edges;
# 21:9 keeps it within the middle 21:9 of the screen and 16:9 within the middle 16:9 (the game's own HUD), so the
@@ -256,6 +271,11 @@
# Field of view, in percent of the game's own: 70 to 140, 100 (the default) leaves the camera as it is. Higher shows
# more of the world around Link. Game versions 1.1.0, 1.2.1 and 1.4.3. Changes while the game runs take effect at once.
# fov = 100
# Vert+ at a game resolution narrower than 16:9 (16:10, 3:2, 4:3): 1 widens the camera's vertical view so the picture
# shows as much of the world at the sides as 16:9 does, and more above and below. 0, the default: the game's own
# vertical view at every shape, so a narrower shape shows less at the sides. No effect at 16:9 or wider. Multiplies
# with fov. Changes while the game runs take effect at once.
# vert_plus = 0
# Anisotropic filtering of surface textures: game (the level the game asks for, as on the Switch) or 2, 4, 8, 16. Keeps
# ground, roads and walls seen at a shallow angle sharp into the distance. Only filtered, mipmapped textures that tile
# are raised; shadow maps, data maps and screen-sized buffers keep the game's setting. Read at start.
@@ -344,10 +364,12 @@
# for a frame. 0, the default: DLSS estimates the exposure itself, as before. Every DLSS mode. Changes while the game
# runs take effect at once.
# dlss_fixed_exposure = 0
# With DLAA (dlaa = 1, dlss = dlaa), fog, dust and other particles are drawn over the picture DLSS has already smoothed,
# as the game draws them without DLSS, so small particles in fog (shrines) no longer vanish or leave trails. 0: DLSS
# processes these effects too, as before (the default until the inventory preview, the scope and water edges are
# checked on NVIDIA). The upscaling DLSS modes always process them. Changes while the game runs take effect at once.
# With DLAA (dlaa = 1, dlss = dlaa), dust and other particles are drawn over the picture DLSS has already smoothed, as
# the game draws them without DLSS, so small particles in fog (shrines) no longer vanish or leave trails. The fog layer
# and the clouds still go through DLSS: drawn over its picture they left a flickering bright outline on distant ridges
# at night and at dawn. 0: DLSS processes all these effects too, as before (the default until the inventory preview,
# the scope and water edges are checked on NVIDIA). The upscaling DLSS modes always process them. Changes while the
# game runs take effect at once.
# dlaa_effects_after = 0
# Low latency: off, auto, on or boost. Reduces system input latency. on and boost enable NVIDIA Reflex
# (VK_NV_low_latency2); boost also keeps NVIDIA GPU clocks high in CPU-bound scenes. auto enables Reflex, or AMD
@@ -447,6 +469,10 @@
# 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 gamepad while the game window has no focus (Linux; on Windows it always plays): 1 keeps it playing behind other
# windows, 0 pauses it, auto pauses it only when Steam started the game, so the Steam overlay and Steam's menus
# (the Quick Access menu in SteamOS's Game Mode) get the gamepad while they are open. Read at start.
# pad_background = auto
# 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), playstation
# (○ × △ □, L1 R1 L2 R2, Options and Share, on the button pad_layout presses: with nintendo, A shows as ○), or pc