207 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
Valiantsin DzerakhandClaude Opus 5.5 3c5ae12830 Merge pull request #1393: build_game.py quotes command arguments with shlex on non-Windows hosts and passes the linker map path through cmd_arg and -Xlinker on both platforms (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 19:18:38 +03:00
Valiantsin DzerakhandClaude Opus 5.5 da27398c5f Merge pull request #1405: ab_summary.py prints n/a for the replay change when side A averages 0.00 ms instead of dividing by zero (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 19:18:18 +03:00
Valiantsin DzerakhandClaude Opus 5.5 4cfb2e82c4 Merge pull request #1403: perf_summary.py reports FPS as total frames over total window time instead of the mean of per-window FPS (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 19:18:12 +03:00
Valiantsin DzerakhandClaude Opus 5.5 480ccec4b1 Merge pull request #1398: run_game.py rejects a profile copy that overlaps the original and a --tag with path separators, and stops a still-running child before deleting its profile (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 19:17:37 +03:00
Valiantsin DzerakhandClaude Opus 5.5 1fcb7b967f Merge pull request #1412: null_attach = 1 gives empty colour slots below a pass's last target a shared dummy attachment, for the Intel legacy driver crash in vkCmdBeginRendering; off by default (ShannoonRuaaa) (#1343)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 19:07:36 +03:00
Valiantsin DzerakhandClaude Opus 5.5 b5b9cc2be8 null_attach reads its switch once at device creation and gives a pass one dummy that covers it, freed with the device (#1343)
With the switch off, the draw path now pays one load of vk_caps.null_attach per gkey_fill and per empty slot in
target_wmask instead of a call into vk_exec.c, and vk_exec_pass_begin one flag test per pass. The switch is read in
vk_caps_init, before the pipeline prewarm makes the first key.

With it on, only empty slots below the pass's last target get a dummy, which is where the pipelines'
colorAttachmentCount ends (vk_pipeline.c target_count); a pass without colour targets keeps none, so a depth-only or
attachment-free pass never gets a 16384-wide image. All empty slots of a pass share one view, and an image serves
every pass it covers with its sample count: 1.4.3 at 1600x896 makes one image of 1.75 MiB instead of three. The
images are destroyed in destroy_all before the allocator goes, and the log line gives each one's size.

The settings row no longer states that empty slots caused #1343: the dumps do not show it. totk.ini.example gets
the player entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 19:02:38 +03:00
Valiantsin Dzerakh 83e4037f9c Merge commit 'f278e91a' into task/pr1412
# Conflicts:
#	runtime/cfg.c
2026-11-23 19:02:11 +03:00
Valiantsin DzerakhandClaude Opus 5.5 1dad1ef60b Merge pull request #1385: restbl_cache = 1 serves the mods' merged resource size table from the last start when totk.exe, the RomFS image and every mod file are the same (about 0.9 s off a start with The Second Quest); off by default (itaskaev2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:51:57 +03:00
Valiantsin DzerakhandClaude Opus 5.5 0deeb914cf mods_romfs_check tests the kept resource size table across starts
With restbl_cache = 1 on the restbl mods: built on the first start, served on the second with the same bytes, built
again after a rewritten mod file, an added or removed mod, another order and a new totk.exe, and after a torn or
random key file and a damaged or missing table. With the default 0 the key is neither read nor written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:51:02 +03:00
Valiantsin DzerakhandClaude Opus 5.5 3b97936ed3 The kept resource size table is off by default, and its key covers the running totk.exe, the RomFS image and every overlay
restbl_cache now defaults to 0. Its key adds the path and identity of the running exe (a dev or source build that
changes the merge code keeps the VERSION string, so the port version alone served the old table), the RomFS image's
identity, the number of shipped tables and the overlays of the port's own folders, which the old filter left out.
The table's SHA-256 is taken from the bytes the build wrote instead of a read back from disk. A miss logs why the
table is built again. totk.ini.example and docs/settings.md describe the setting, its default and what the key does
not see (a rewrite that keeps size and write time).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:51:01 +03:00
Valiantsin DzerakhandClaude Opus 5.5 d810c7d271 Up version 0.5.1-rc1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:47:24 +03:00
Valiantsin DzerakhandClaude Opus 5.5 96b5e96c80 Merge pull request #1384: the in-game menu in German, French, Spanish, Italian, Dutch, Japanese, Korean and Vietnamese, and the setup in Vietnamese (itaskaev2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:40:16 +03:00
Valiantsin DzerakhandClaude Opus 5.5 8db7f2889f The new menu languages get the Low Latency Auto choice and the description of the Anti-Lag 2 merge
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:39:22 +03:00
Valiantsin Dzerakh 2149915fa6 Merge branch 'dev' into task/pr1384 2026-11-23 18:38:32 +03:00
Valiantsin DzerakhandClaude Opus 5.5 c465183dcc The new menu languages follow the FSR 4 and FSR sharpness catalog ids, and the Vietnamese setup text has the FSR download entries
The eight new menu tables still used UI_MENU_FSR3_SHARPNESS and lacked the four FSR 4 upscaler strings, which dev renamed or added, so the PR did not compile on dev. installer/text/vi.json lacked the six fsr step, phase, warning and checkbox ids. CONTRIBUTING.md lists all twelve menu languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:38:32 +03:00
Valiantsin DzerakhandClaude Opus 5.5 05d46f3538 Merge pull request #1385 head: serve the mods' merged resource size table from the last start (itaskaev2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:37:21 +03:00
Valiantsin DzerakhandClaude Opus 5.5 25832fd459 Merge pull request #1416: reflex = auto picks NVIDIA Reflex or AMD Anti-Lag 2 for the GPU; off stays the default, on and boost stay NVIDIA Reflex only (ripps818)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:35:55 +03:00
Valiantsin DzerakhandClaude Opus 5.5 e15aae0606 Anti-Lag 2 runs only with reflex = auto, so on and boost keep their old Reflex-only meaning
A player who had reflex = on on an AMD GPU got nothing from it before #1416 and would have got Anti-Lag after an
update without asking for it. on and boost now enable NVIDIA Reflex alone and log the same line as before when it is
missing; auto picks Reflex or Anti-Lag. The Anti-Lag entry point loads with atomics, since the game thread and the
present thread both make the first call, and the TOTK_TRACE=perf latency line keeps its old text unless Anti-Lag is
on. The menu description, docs/settings.md and totk.ini.example say which value turns on what.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:34:39 +03:00
Valiantsin Dzerakh 719cff3a4c Merge commit 'refs/pull/1384/head' of https://github.com/valentderah/totk-pc-recomp into task/pr1384 2026-11-23 18:25:26 +03:00
Valiantsin DzerakhandClaude Opus 5.5 1b303282a3 Merge pull request #1372: the shader-cache packer reads the loose files on up to 8 threads (half the logical CPUs, 1 below 512 MiB free memory, 32 MiB read ahead, serial reads on any failure), with a byte-identical pack (ShannoonRuaaa)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:24:38 +03:00
Valiantsin Dzerakh 8619d1bb3f Merge pull request #1416 head: AMD Anti-Lag 2 in the low latency setting (ripps818)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	runtime/vk_device.c
2026-11-23 18:24:19 +03:00
Valiantsin DzerakhandClaude Opus 5.5 fe8573916e Merge pull request #1368: FSR 3.1 and frame generation skip protected and AMD device-coherent memory types, which gave full-screen noise on RADV; the pick on Windows AMD is unchanged (gurrgur)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:43:36 +03:00
Valiantsin DzerakhandClaude Opus 5.5 96f9f868ba THIRD_PARTY_NOTICES.md counts the FidelityFX backend's memory type choice among our own changes to the SDK
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:43:07 +03:00
Valiantsin DzerakhandClaude Opus 5.5 f1ec56b592 Merge pull request #1245: AMD FSR 4 upscales the 3D scene on Windows through AMD's signed FSR SDK 2.4 libraries (scene_upscaler = fsr4, off by default), and the setup can download them (codexx-dev) (#1409)
FSR 4 is a fourth engine of the scene upscaler beside DLSS and FSR 3.1 and takes their frame point, jitter, per-object
motion vectors, mip bias, fsr_sharpness, FXAA skip and dynamic resolution hold. The PR's dlaa_backend setting, its
FSR 3 through the DLL and its separate Upscalers row are left out: dev builds FSR 3.1 from the SDK 1.1.4 sources.
Checked on an RX 9070: FSR 4.1.2 at quality, 1280x720 -> 1920x1080, picture clean; without the DLLs the upscaler stays
off with a log line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:39:08 +03:00
Valiantsin DzerakhandClaude Opus 5.5 e3befaebcc Merge pull request #1368: FSR 3.1 and frame generation skip protected and AMD device-coherent memory types (gurrgur)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:29:21 +03:00
Valiantsin DzerakhandClaude Opus 5.5 9978eb2948 Merge pull request #1371: GPUs without VK_EXT_external_memory_host run on shadow storage instead of being skipped; GPUs with it see no change (ShannoonRuaaa)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:27:33 +03:00
Valiantsin DzerakhandClaude Opus 5.5 c581b779fa Size the shader cache readers for the machine and fall back to serial reads on any failure
pack_shader_cache.py picked 8 readers on every machine. It now takes half the logical CPUs, 1 to 8, so a 1- or
2-CPU PC reads one file at a time, and reads serially with less than 512 MiB free RAM (tools/hostmem.py, as the
compile and lift workers use). --read-workers still overrides; the log names the choice.

The read-ahead is also capped at 32 MiB of file data by the listed sizes, beside the two files per reader; a file
larger than the cap is read alone.

Any failure of the parallel path (a thread that does not start, a MemoryError in a reader, an executor error) prints
a line and reads the remaining files serially, so the pack still completes with the same bytes.

Tests cover the worker choice, the byte cap and the three fallbacks, each giving the same pack as a serial run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:27:09 +03:00
Valiantsin DzerakhandClaude Opus 5.5 d9ecad571d The architecture notes and the vk_pool_init comment say that CPU-visible pools get shadow storage where VK_EXT_external_memory_host is missing, and RenderDoc no longer stops device creation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:27:06 +03:00
Valiantsin DzerakhandClaude Opus 5.5 9469ad0675 Merge pull request #1371: a GPU without VK_EXT_external_memory_host runs on shadow storage (ShannoonRuaaa)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:21:21 +03:00
Valiantsin Dzerakh a80cb1e35d Merge PR #1372 head into task/pr1372 2026-11-23 14:20:17 +03:00
Valiantsin DzerakhandClaude Opus 5.5 c6794dfe97 Merge pull request #1418: extract.py --skip-base-romfs leaves out the 17 GB base RomFS image that no build of 1.1.0, 1.2.1 or 1.4.3 reads (kaiyao7)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:19:33 +03:00
Valiantsin DzerakhandClaude Opus 5.5 802cb39fe0 Document extract.py --skip-base-romfs in the build guide
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:19:05 +03:00
Valiantsin Dzerakh 768dc30b36 Merge PR #1418: extract.py --skip-base-romfs leaves out the base RomFS nothing reads 2026-11-23 14:18:55 +03:00
Valiantsin DzerakhandClaude Opus 5.5 f9585d984b Merge pull request #1382: on Intel with Mesa ANV a by-region barrier before draws whose vertex shader reads a storage buffer stops the white and dark smoke and sky flashes; off by default, anv_vs_barrier = 1 turns it on (mattheuspaivadini) (#927)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:17:49 +03:00
Valiantsin DzerakhandClaude Opus 5.5 d98996b6e2 Turn the ANV vertex-shader storage barrier off by default on every GPU; players opt in with anv_vs_barrier = 1 (#927)
The barrier costs about 5% of the frame rate on an Iris Xe and was only tested there. TOTK_ANV_VS_BARRIER and anv_vs_barrier still force it on with 1 and off with 0. docs/settings.md says what it fixes, what it costs and that only Intel GPUs with Mesa ANV on Linux are affected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:17:26 +03:00
Valiantsin DzerakhandClaude Opus 5.5 3026d91e31 Merge PR #1382: ANV vertex-shader storage buffer barrier (#927)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:16:31 +03:00
Valiantsin DzerakhandClaude Opus 5.5 be98dbc336 Merge pull request #1245: AMD FSR 4 as a fourth scene upscaler, scene_upscaler = fsr4 (codexx-dev)
The PR's FSR 4 path (runtime/vk_ffx.c over AMD's FSR SDK 2.4 signed libraries, ffx_api_min.h, the cooperative
matrix and float8 device extensions in vk_device.c), its setup step that downloads amd_fidelityfx_loader_vk.dll and
amd_fidelityfx_upscaler_vk.dll, its notices and the FXAA copy shader hash 0x9d065204aac9766b now serve dev's own
scene upscaler as UPSCALER_FSR4. FSR 4 goes through vk_dlaa.c fsr_evaluate beside FSR 3.1: the same frame point,
jitter, motion vectors with the per-object pass, camera from vk_fg_camera, mip bias, fsr_sharpness, FXAA skip and
dynamic resolution hold.

Dropped from the PR: the dlaa_backend setting, FSR 3 through the DLL and the separate Upscalers row. vk_ffx.c pins
FSR 4 only; a device the libraries offer no FSR 4 for runs with the upscaler off and the menu says so. It keeps one
context per output size with dynamic resolution, like vk_fsr3.cpp, waits on the SDK's ring depth and is released
before the device goes. The menu's scene upscaler row gets "AMD FSR 4" (Windows; marked when the libraries or the
GPU are missing). The setup's FSR box and its strings are in all eleven installer catalogs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 14:13:20 +03:00
kaiyao7 7e54200454 extract.py: --skip-base-romfs leaves out the 17 GB base RomFS that nothing reads
The extraction writes build/extracted/v0/romfs/romfs.bin (17 GB) and no other
tool in the repository reads it: build_game.py, gen.py, prepare_shaders.py and
package_build.py all take the version's own directory, and merge_update_romfs
takes the base Program NCA from the base game file itself and verifies all six
IVFC levels of what it merges.

The base game's ExeFS still decides the file is TotK 1.0.0, so damage is still
found, only later, with a message that names the damaged file.

The flag is off by default: a run without it extracts and checks as before.
2026-11-23 16:23:55 +08:00
Valiantsin DzerakhandClaude Opus 5.5 5e5f34cd40 Merge task/plugfix: mod plugins with branch hooks, pointer swaps, SD card files and hooks switched during play build in, and may call what the game calls; Zonai Fieldworks starts (#1388)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:36:07 +03:00
Valiantsin DzerakhandClaude Opus 5.5 3fe8d7a1d9 Mod plugins that hook the middle of game functions, swap pointers in the game's data, use the SD card or switch their hooks during play build in, and may call what the game itself calls; Zonai Fieldworks starts (#1388)
Zonai Fieldworks was refused at several steps; each is now handled:
1. The start-up asked GetInfo 6, 7, 16 and 17 and SetHeapSize; runtime/plugin_init.c serves them.
2. Its start-up calls main where the lift has no function start. The tool names those addresses (--entries-out) and
   the installer lifts again with them as `entry` lines, up to four rounds (installer/steps.py PLUGIN_ENTRY_ROUNDS).
3. Branch hooks into the middle of game functions (far-jump veneers) and pointer swaps in main's data are accepted
   hook kinds; the veneer targets seed the plugin's lift, and an Orig trampoline counts as a seed.
4. Code the start-up writes into the plugin's own .text (hook pads it switches to during play) is found by comparing
   the image before and after the init, and seeds the lift (init_code). Without it the game stopped with "no function
   at guest pc" when a feature switched on.
5. recomp/gen.py: a branch-out alternative on a flag-writing site leaves with the flags from before the site; an inline
   hook may sit on a blr.
6. nn::fs::MountSdCard mounts <profile>/sdcard (runtime/fs_host.c), and nn::settings language codes are answered
   (runtime/ov_system.c).

The import check now also allows what the game's main imports (--exefs, game_imports): the game runs on those paths,
so the runtime serves them. Left out: nn::ro, the C runtime start, the thread-local allocator hook and the shader
compiler. Break in code the hooks reach is allowed (an abort ends the game with the reason, as on the Switch), and
RenameFile, DeleteDirectoryRecursively, Commit and Unmount join the SD card calls. Checked: Zonai Fieldworks, The Second
Quest, Challenge Mode and Material Columns on 1.4.3, Full Inventory Expansion, Quick Weapon Durability and Magic of the
Kingdom on 1.2.1 accepted; UltraCam's init still crashes its service run. Plain lift unchanged; probes 4/4 on both
versions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:35:59 +03:00
Valiantsin DzerakhandClaude Opus 5.5 942b6b7b2b Merge task/plugfix: mod plugins whose hooks use exlaunch's exl_inline_hook_with_fp_impl build; Magic of the Kingdom starts (#1388)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:41:34 +03:00
Valiantsin DzerakhandClaude Opus 5.5 c603112fca The plugin check accepts exlaunch's exl_inline_hook_with_fp_impl, the inline-hook entry that saves d0..d15 next to x0..x29. Magic of the Kingdom's hook stub calls it and was refused for it (#1388)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:40:59 +03:00
ripps818andClaude Sonnet 5.5 84e44f3aed Add AMD Anti-Lag 2 to the low latency setting, with an auto value that picks Reflex or Anti-Lag for the GPU
The reflex setting gains an auto value. With auto, on or boost the device uses NVIDIA Reflex when the driver has VK_NV_low_latency2, otherwise AMD Anti-Lag 2 when it has VK_AMD_anti_lag (Mesa RADV, AMD's Windows driver); with neither it does nothing. Anti-Lag marks the INPUT stage where the window texture is acquired and the PRESENT stage just before vkQueuePresentKHR, with the pacer's frame limit as maxFPS. The default stays off. The menu row is renamed Low Latency in all four languages.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 23:24:48 -06:00
Ruan Shannon f278e91a7c null_attach = 1 gives empty colour slots a dummy attachment instead of a null view (Intel legacy driver crash, #1343)
On an HD 520 with Intel's legacy Windows driver (101.2125, Vulkan 1.3.215) the game faults inside vkCmdBeginRendering
(igvk64.dll+0x5cfab2/+0x5cfab9, frames +0x5c42dd and +0x548235) right after the logo, with the recorder on or off and
with import or mirror memory. The driver reads an attachment entry of the pass that is null. vk_exec_pass_begin leaves
imageView VK_NULL_HANDLE in every colour slot without a target, which Vulkan allows, and the first pass of a boot that
has one is the 1600x896 scene G-buffer pass (slots 2 and 4 empty), the render area of the reported crash.

With TOTK_NULL_ATTACH=1 such a slot gets a view of a dummy R8_UNORM image of the pass's size, layer and sample count
(one per shape, made once, GENERAL, DONT_CARE load and store), and the pipelines name that format for it with the writes
masked off (vk_pipeline.c gkey_fill, target_wmask), so views and pipelines agree. Off by default: nothing changes, and
pipeline keys stay as they were. Untested on the affected driver; Iris Xe (101.7092) plays the same with it on.
2026-11-22 16:49:02 -08:00
mattheuspaivadiniandClaude Sonnet 5.5 5b15fc0df6 Keep fb_dirty across the ANV vertex-storage barrier, so feedback_prepare still learns the feedback targets (#927)
feedback_barrier clears fb_dirty, and feedback_prepare learns which targets go into the feedback layout from m & fb_dirty. A barrier recorded only for a vertex shader's storage read could hide a later attachment read from it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 21:05:13 -03: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
ICUMADETHIS 1b573e00bf Handle zero replay baselines in A/B reports 2026-11-22 20:58:26 +00:00
ICUMADETHIS 7d740a0083 Quote the literal linker map path on both platforms 2026-11-22 20:50:31 +00:00
ICUMADETHIS a37f7d8f15 Compute benchmark FPS from the combined window duration 2026-11-22 20:46:59 +00:00
ICUMADETHIS d7c408c4d7 Stop interrupted runs before removing their profile copy 2026-11-22 19:43:19 +00:00
ICUMADETHIS 767f2f6663 Protect the original profile during scripted runs 2026-11-22 19:37:46 +00:00
ICUMADETHIS 2acefbe473 Place command tests beside the other build checks 2026-11-22 19:25:14 +00:00
ICUMADETHIS 9e732f0096 Quote Unix build arguments before Ninja escaping 2026-11-22 19:17:05 +00:00
PC ab9dcc9bcb The in-game menu comes in Vietnamese: a full text_vi row (every menu id, checked against the English printf specifiers), a Tiếng Việt choice on the Menu tab, vi among the values of menu_lang, and the Latin Extended and Vietnamese ranges in the menu font atlas, which Roboto already covers. The text inside the performance overlay and the DLSS model row keep their English names, and the graphics terms follow common Vietnamese usage (họa tiết, bộ đổ bóng, đường ống, lệnh vẽ, tệp)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 408c1badfcdad3d85bf06ab09505a6d2669a2427)
2026-11-22 18:41:36 +01:00
mattheuspaivadiniandClaude Opus 5.5 4c95df372a On Mesa's ANV, put a by-region barrier before a draw in a pass whose vertex shader reads a storage buffer (#927)
On an Iris Xe with ANV the half-resolution particle pass drew campfire smoke and clouds as white or dark blobs and
turned the sky white for single frames. Such draws read stale data inside the pass unless the sampler cache is
invalidated first; a stall alone or the attachment flush alone does not help. The barrier is feedback_barrier, which
the feedback loops already record inside passes. TOTK_ANV_VS_BARRIER (anv_vs_barrier) turns it off or on elsewhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 13:45:13 -03:00
itaskaev2andClaude Opus 5.5 23ac5f18d1 The setup speaks Vietnamese, picked from a Vietnamese Windows or locale, launcher message included
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 17:11:26 +01:00
itaskaev2andClaude Opus 5.5 37d49d80d2 The in-game menu and the overlay speak German, French, Spanish, Italian, Dutch, Japanese and Korean, every one of the 670 menu texts, picked from the Windows display language or the Menu tab, with every Chinese Windows on the Simplified Chinese menu (the menu part of pull request #497, completed for today's menu)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 17:11:26 +01:00
itaskaev2andClaude Opus 5.5 f11987e9a7 Serve the mods' merged resource size table from the last start when the mod files are the same
Building the table opens every mod file and unpacks the mods' packs: about 7 s with an HD texture pack and The Second Quest. restbl_cache = 0 builds it at every start. Split from #1331.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 17:02:47 +01:00
Valiantsin DzerakhandClaude Opus 5.5 7f17cad783 Merge task/tramp: mod plugins with exlaunch's long trampolines build, and hooked game code reads the flags the plugin's callback left; Challenge Mode starts (#578, #1360)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:43:07 +03:00
Valiantsin Dzerakh 0e810f429a Merge branch 'dev' into task/tramp 2026-11-22 16:42:36 +03:00
Valiantsin DzerakhandClaude Opus 5.5 3c62640d80 Flags pass between a mod plugin's code and the game as on the Switch: exlaunch's inline hook saves no NZCV, so a hooked site goes on with the flags its callback left. Challenge Mode's hooked b.eq sites follow its version check (#578, #1360)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:42:31 +03:00
Valiantsin Dzerakh 89c8997bfb Merge pull request #1357: run_all skips the compiler suites when no clang is found, registers eight existing suites and finds the native executable on Linux (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	tests/run_all.py
2026-11-22 16:22:40 +03:00
Valiantsin DzerakhandClaude Opus 5.5 8c204500ed Merge pull request #1363: build_game sizes the compile jobs by free memory as well as RAM, so a PC with little free memory does not page during the setup's compile (ShannoonRuaaa)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:22:25 +03:00
Valiantsin DzerakhandClaude Opus 5.5 6af609e1b1 Merge pull request #1362: check_isa scans the instructions of a linked .exe or .dll too, not only objects (ShannoonRuaaa)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:22:08 +03:00
Valiantsin Dzerakh 18ce808d03 Merge task/pr1363 into task/pr1357 2026-11-22 16:21:08 +03:00
Valiantsin Dzerakh d6b484a5c9 Merge task/pr1362 into task/pr1357 2026-11-22 16:21:03 +03:00
Valiantsin Dzerakh 3fd3eb7be9 Merge PR 1357 2026-11-22 16:17:39 +03:00
Valiantsin Dzerakh 2bfde7ac0c Merge PR 1363 2026-11-22 16:17:00 +03:00
Valiantsin Dzerakh cfbfa70c63 Merge PR 1362 2026-11-22 16:14:22 +03:00
Valiantsin DzerakhandClaude Opus 5.5 57137cb108 Merge pull request #1355: the setup reads output_res, prompts, pad_layout and hud_width with the game's INI rules (quotes, last non-empty value), so it prepares the layouts the game will use (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:13:17 +03:00
Valiantsin DzerakhandClaude Opus 5.5 85c0de3aa3 Merge pull request #1352: the installer reads and rewrites the last non-empty lang setting in totk.ini, as the game does (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:13:16 +03:00
Valiantsin DzerakhandClaude Opus 5.5 9812378665 Merge pull request #1350: the installer rejects a state file with malformed fields as unreadable before prefill and resume, instead of a traceback (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:13:15 +03:00
Valiantsin DzerakhandClaude Opus 5.5 af60f6a062 Merge pull request #1349: the shader-cache packer checks a pack's entry count and index size against the runtime's limits before it reads the index, and rebuilds a broken pack from the loose files (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:13:14 +03:00
Valiantsin DzerakhandClaude Opus 5.5 9db523827d Merge pull request #1366: the recent-install module's docstring is a raw string, so Python 3.14 compiles it without an invalid escape warning (ShannoonRuaaa)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:13:14 +03:00
Valiantsin DzerakhandClaude Opus 5.5 6322727b67 Merge pull request #1351: the NSZ block reader skips stored padding after a raw block and bounds each compressed block by its declared size, as nsz's reader does; a block of the wrong size is still a damaged file (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:12:24 +03:00
Valiantsin DzerakhandClaude Opus 5.5 589bd9e08f A block that decompresses to the wrong size is a damaged file again, so the installer asks for a fresh copy
The size check added in this pull request raised a plain ValueError, which the installer maps to
check.unpack_failed. Before it, such a block ended in a hash or length mismatch and the player saw
check.input_damaged. ncz.unpack_ncz now turns the new BlockSizeError into DamagedFile, like ZstdError and EOFError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:11:48 +03:00
Ruan Shannon b4dcc3431f tools/pack_shader_cache.py reads the loose files with 8 bounded readers
pack() read every loose file one after the other. On Windows each open costs milliseconds (the antivirus scans it), so
folding a fresh cache was dominated by waiting: 12000 loose files took 79-90 s. The files are now read ahead by a pool
of 8 threads (--read-workers, 1..16; 1 reads serially), at most twice that many in flight, and written in the same
sorted order, so the pack is byte-identical. 12000 files: 18-20 s. The CLI prints read and cleanup progress every 5 s.
tests/pack_shader_cache_test.py checks parallel against serial packs, fresh and incremental, and the bounded read-ahead.
2026-11-22 05:10:48 -08:00
Valiantsin Dzerakh 936b0e264c Merge pull request #1355 head 2026-11-22 16:05:01 +03:00
Valiantsin Dzerakh 516b1d2ab5 Merge branch 'pr1351-head' into task/pr1351 2026-11-22 16:04:59 +03:00
Valiantsin Dzerakh 0894366f29 Merge pull request #1352 head 2026-11-22 16:04:58 +03:00
Valiantsin Dzerakh ea3c78de37 Merge pull request #1350 head 2026-11-22 16:04:46 +03:00
Valiantsin Dzerakh 7949484a40 Merge pull request #1349 head 2026-11-22 16:04:43 +03:00
Valiantsin Dzerakh 274d811d2d Merge pull request #1366 head 2026-11-22 16:04:41 +03:00
Valiantsin DzerakhandClaude Opus 5.5 b61b2b0922 The plugin check accepts the .quad exlaunch writes for a backward b.cond, cbz or tbz: its relocation drops the offset's sign. Challenge Mode's two backward b.eq hooks were refused for it (#578)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:03:48 +03:00
Valiantsin DzerakhandClaude Opus 5.5 c902d85db0 Merge pull request #1356: the plugin patch table quotes a plugin's image path, so an install folder with a space or # in its path no longer drops an accepted plugin (ICUMADETHIS)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:03:15 +03:00
Valiantsin DzerakhandClaude Opus 5.5 4c4d1310a5 A quoted plugin image path that is empty is a patch table error with its line, not a read of the folder
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:02:34 +03:00
Ruan Shannon f877aae10e A GPU without VK_EXT_external_memory_host runs the game on shadow storage instead of being skipped
The extension was in vk_device.c k_required_ext, so pick_device skipped every GPU without it ("gpu 0 skipped: missing
extension VK_EXT_external_memory_host") and the game exited: Qualcomm Adreno's Windows driver (issue #161), some older
or mobile drivers, and RenderDoc, which hides it. It is now enabled when present (VkCtx.has_external_memory_host); without
it vk_memory.c mirror_mode turns shadow storage on, the path Wine already takes, so import_pool gives every CPU-visible
pool a host-visible copy instead of an import. vk_mem_class_log runs once the device's extensions are known.
TOTK_VK_NO_HOST_IMPORT=1 takes that path on any GPU, for testing it. Docs no longer list the extension as required.

Iris Xe with a test layer that hides the extension: dev skips the GPU and exits (70); this change plays the sky-island
save (40 s, 39.9 fps, shadow storage logged). With the extension present nothing changes.
2026-11-22 05:01:27 -08:00
Valiantsin Dzerakh 2593618a65 Merge branch 'pr1356-head' into task/pr1356 2026-11-22 15:59:02 +03:00
Valiantsin DzerakhandClaude Opus 5.5 6e38d6d8b7 Merge pull request #1367: the setup's screens scroll when the window would be taller than the display, with Start, Cancel and Close kept in view (ICUMADETHIS) (#744)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:53:56 +03:00
Valiantsin Dzerakh f8eabdad46 Merge pull request #1367 head 2026-11-22 15:50:35 +03: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
Valiantsin DzerakhandClaude Opus 5.5 313e12715d Merge pull request #1361: the setup's computer check survives a crashing Vulkan layer and names it with how to turn it off, and names an App Control or antivirus block instead of a traceback (ShannoonRuaaa) (#1345, #875)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:49:54 +03:00
Valiantsin DzerakhandClaude Opus 5.5 d181714398 The installer stops with the crashing Vulkan layer named instead of going on with a warning (#1345)
A layer that crashes hostcheck at vkCreateInstance also breaks totk.exe --prepare-shaders in the prepare step and the
game (runtime/vk_device.c create_instance loads the same implicit layers): with the PR's warning the install failed
again after lift and compile. Check.probe_host now turns each listed implicit layer off alone, names the one whose
absence lets the probe pass with its manifest path in check.vulkan_layer_crash, and says how to turn it off
(VK_LOADER_LAYERS_DISABLE=<name> for the user account); when no single layer explains it, check.vulkan_layers_crash
lists the installed ones and offers ~implicit~. The list covers the loader's places: VK_(ADD_)IMPLICIT_LAYER_PATH, the
registry in the 64-bit view or the Linux implicit_layer.d folders, with names read from the manifests. A failed host
check is kept on the context, so key() and run() no longer build and crash it twice, and the App Control reputation
codes 4557-4559 and 4581-4583 count as a block too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:49:04 +03:00
Valiantsin DzerakhandClaude Opus 5.5 5634a14f6b Merge pull request #1333: above 30 fps a thunderstorm draws its distant bolts and lightning flashes with chances scaled by the frame, so it has the lightning of 30 fps; lightning_fix = 0 runs the game's chances (shinodanpen) (#1287)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:47:42 +03:00
Valiantsin Dzerakh 08e44f43ad Merge pull request #1361: Installer host check survives a crashing Vulkan layer and explains an App Control block (ShannoonRuaaa) (#1345, #875) 2026-11-22 15:37:53 +03:00
Valiantsin Dzerakh 1ee4c57cba Merge dev into task/pr1333 2026-11-22 15:37:52 +03:00
Valiantsin Dzerakh e721b582d8 Merge pull request #1333 into task/pr1333 2026-11-22 15:37:46 +03:00
gurrgurandClaude Opus 5.5 ba81204847 FSR 3.1 and frame generation no longer allocate their images in protected or AMD device-coherent memory, which turned the whole picture into noise on RADV
The SDK's findMemoryTypeIndex keeps the last matching memory type, and RADV lists protected (TMZ) and DEVICE_COHERENT_AMD / DEVICE_UNCACHED_AMD device-local types after the plain ones. The runtime enables neither feature, so on a Radeon 780M (Mesa 26.3) every FSR pass read garbage. Those types are now skipped. On unified-memory GPUs (Adreno under Turnip), where every device-local type is host-visible, it falls back to a host-visible device-local type instead of failing every texture allocation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 13:37:42 +01:00
Valiantsin DzerakhandClaude Opus 5.5 3b656f91ff Merge pull request #1348: the installer accepts a verified merge when hactool reports a failed NPDM ACID signature, as it already did for the fixed-key and NPDM signatures (ICUMADETHIS) (#1326)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:36:47 +03:00
Valiantsin Dzerakh 35553d80d5 Merge pull request #1348 2026-11-22 15:35:16 +03:00
Valiantsin DzerakhandClaude Opus 5.5 1c2a0e5a33 The plugin check accepts exlaunch's long trampolines: a hooked tbz, cbz, b.cond, adr, adrp, load literal or far b/bl whose relocation takes several words, and the jump back by ldr x17/br x17. Challenge Mode's plugin was refused at its tbnz site (#578)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:31:30 +03:00
ICUMADETHIS 5bbd461d35 Keep installer actions visible on small screens (#744) 2026-11-22 12:26:32 +00:00
Ruan ShannonandClaude Opus 5.5 df953b5062 installer/recent.py: raw docstring, so its Windows path no longer holds an invalid escape
The docstring names %LOCALAPPDATA%\TotK Recomp\setup.json; "\T" is an invalid escape sequence, which Python 3.14 (the
setup's bundled Python) reports as a SyntaxWarning every time the module is compiled, and which a later Python turns into
a SyntaxError that would stop the setup from starting. A raw docstring keeps the text as written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 03:21:11 -08:00
Ruan ShannonandClaude Opus 5.5 78f8362a9e tools/build_game.py sizes the compile jobs by the free memory too
The budget was the smaller of 50 GiB and 80% of the RAM, so RAM that other programs held counted as available: on a
16 GiB laptop with 2 GiB free it allowed 16 jobs of JOB_MEM (12 GiB), and the compile paged or a job ran out of
memory. compile_budget also takes 80% of hostmem.available_ram (free physical memory, capped by a job memory limit),
as recomp/gen.py already does for the lift workers; off Windows, where that is unknown, the budget is as before. The
build prints the budget and the free memory it saw. tests/compile_budget_test.py covers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 02:19:44 -08:00
Ruan ShannonandClaude Opus 5.5 e18eb68b6d tools/check_isa.py scans the instructions of linked images too
An instruction line of llvm-objdump starts with its address: short and indented in an object, 9+ hex digits at the
start of the line in a linked .exe or .dll. The scan kept only lines with leading whitespace, so it skipped every
instruction of a linked image and reported it clean, although the usage line names executables. It now keeps lines
that start with an address. tests/check_isa_test.py covers both forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 02:17:23 -08:00
Ruan ShannonandClaude Opus 5.5 d240181005 The installer's host check survives a crashing Vulkan layer and names an App Control block
hostcheck flushes what it found before each Vulkan call, so a probe killed inside Vulkan still shows how far it got.
Check.probe_host logs the exit code as Windows reports crashes (0xC0000005), runs a probe that died inside Vulkan once
more with the implicit layers off (VK_LOADER_LAYERS_DISABLE=~implicit~) and, when that passes, goes on with a warning
that lists the installed implicit layers; when it crashes again it stops with check.vulkan_crash. A probe Windows
refuses to start (Smart App Control and other App Control policies, group policy, an antivirus) now stops with
check.host_blocked instead of an uncaught OSError. Issues #1345 and #875.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 02:10:51 -08:00
ICUMADETHIS 7b53833a04 Run standalone regression suites with their prerequisites 2026-11-22 08:59:49 +00:00
ICUMADETHIS d4497da8c7 Preserve plugin image paths in generated patch tables 2026-11-22 08:50:14 +00:00
ICUMADETHIS 8bbc6c7ade Bound compressed NCZ blocks by their declared output size 2026-11-22 08:37:42 +00:00
ICUMADETHIS 84ca8a96b6 Read installer layout settings with the game's INI rules 2026-11-22 08:33:41 +00:00
ICUMADETHIS c97fc1b3be Honor the last language override in installer settings 2026-11-22 08:14:57 +00:00
ICUMADETHIS 4ef0e2bd4a Skip stored padding in raw NCZBLOCK blocks 2026-11-22 08:10:07 +00:00
ICUMADETHIS 83831e8ebd Validate installation state before prefill and resume 2026-11-22 08:05:04 +00:00
ICUMADETHIS daddc3e3fb Check shader-cache index bounds before allocating 2026-11-22 07:56:27 +00:00
ICUMADETHIS 6e66c8b81d Keep verified merges after an NPDM ACID signature warning (#1326) 2026-11-22 07:30:39 +00:00
codexx-devandClaude Opus 5.5 6d077a9a16 FSR skips the game's copy of the scene onto itself with the current translator too
Translator patch 0017 (#1299) adds two support buffer fields every translated shader declares, so the copy shader's
hash changed with it, as FXAA_FS's did. FXAA_COPY_FS now also holds 0x9d065204aac9766b, read from a 1.4.3 run with
FSR on. With the old hash only, the copy stayed and the picture was softer: still view on the Great Sky Island,
1920x1080, render_scale 100, mean absolute Laplacian of luma over 101 shots, 8.09 -> 9.61 (14.93 with the upscaler
off).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 17:47:56 -03:00
codexx-devandClaude Opus 5.5 c71222fecb Merge upstream dev 25a53e5 into fsr4
Conflicts: runtime/cfg.c keeps dev's FREECAM_* names next to the FSR_* ones; runtime/vk_dlaa.c keeps dev's two
FXAA_FS hashes for translator patch 0017 (#1299) and this branch's FXAA_COPY_FS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 17:41:04 -03:00
shinodanpenandClaude fb252ebf6b Scale the thunderstorm's lightning chances by the frame so a storm above 30 fps has the lightning it has at 30 fps (#1287)
In a thunderstorm the world manager's lightning update (1.4.3 main+0x62aac4, 1.2.1 main+0xab849c) runs once per frame
and draws, each update, a random number in [0, 1) for each of three fixed chances: 0.013333 for a distant bolt (the
effect Far_Lightning), 0.01 to pick a near strike and 0.01 for the environment's lightning flag. Its timers follow the
frame step, the draws do not: above 30 fps a storm has more distant bolts and lightning flags the higher the frame
rate. The new set lightning (TOTK_LIGHTNING_FIX, lightning_fix, on by default) multiplies each chance by the time
object's frame ratio (+0x38), at most 1, on 1.2.1 and 1.4.3: above 30 fps the rates per second of 30 fps, and at 30 fps
and below the game's own chances.

Counted on 1.4.3 in the reporter's storm (205 s with the storm on, Link standing still) with a local build that logs
each draw that succeeds, which this change does not contain: distant bolts 22, 52 and 94 to 96 a minute at 30, 60 and
120 fps with lightning_fix = 0, and 26, 27 and 20 to 24 with lightning_fix = 1, each one a Far_Lightning effect; the
lightning flag 19, 34 and 64 to 80 times a minute of the storm's lightning phase with 0, and 12 to 17 with 1. Near
strikes stayed at 14 to 18 per run at every rate with either value: each lightning phase lets its last pick strike in
the phase after it, where nothing is drawn, and that phase ends with a strike of its own.

On 1.2.1, which the logging build does not cover, the distant bolts were counted in screenshots of a storm in Hyrule
Field (one every 0.2 s of game time, a detector of thin bright lines, each counted screenshot checked by eye at 30 fps
and at 120 fps with lightning_fix = 1, a sample of 48 with 0): 19 screenshots with a distant bolt a minute at 30 fps,
about 61 at 120 fps (105 to 107 fps in the storm) with lightning_fix = 0, and 15 with lightning_fix = 1. The same count
on the 1.4.3 runs gives 25 to 26, 65 to 68 and 16 to 20 a minute: at high rates it misses bolts that share a
screenshot.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-21 15:24:43 +00:00
codexx-devandClaude Opus 5.5 4787140783 Rewrite the Upscalers description on the pattern of the original DLSS one
What it is and what it gives first, then each upscaler's GPUs and files in one short sentence each (the FSR DLLs by
name, as the DLSS one), then what FSR turns off, the mode below and the restart. All four menu languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:24:03 -03:00
codexx-devandClaude Opus 5.5 da9c006039 Show the upscaler's rows by the upscaler chosen, and give FSR a sharpness of its own
The Screen tab shows the upscaler mode, the character trails and the effects-after point for any upscaler, the DLSS
model and fixed exposure with DLSS only, and the new fsr_sharpness (default 80) with FSR only; FSR 1's window scaling
keeps sharpness, next to its own row. Rows that serve both upscalers lose DLSS from their names (Upscaler mode with
Native, Fog and particles after the upscaler), and Reflex moves ahead of the upscaler's rows. Texts in all four menu
languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:13:40 -03:00
codexx-devandClaude Opus 5.5 06ab655e04 Offer AMD FSR 4 and AMD FSR 3 as separate choices of the menu's Upscalers row
dlaa_backend gains fsr3, which pins the newest FSR 3 the upscaler DLL offers (3.1.6 with the SDK 2.4 libraries) on any
GPU it supports; fsr keeps taking the newest FSR 4, so existing totk.ini files keep their upscaler. The row now reads
Off, NVIDIA DLSS, AMD FSR 4, AMD FSR 3 on Windows, with the texts in all four menu languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:24:22 -03:00
codexx-devandClaude Opus 5.5 94e66ebfde Leave the setup's AMD FSR box unticked when no display adapter could be listed
A player whose adapter query fails no longer downloads AMD's FSR libraries (about 36 MB) by default; the box starts
ticked only where an AMD adapter is listed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:59:05 -03:00
codexx-devandClaude Opus 5.5 35d7411bab Merge upstream dev into fsr4
The installer runs dev's new kit step and keeps the FSR step after DLSS: check, kit, fonts, extract, lift, compile,
prepare, pc_prompts, shapes, dlss, fsr, cleanup; docs/installer.md numbers FSR 10 and the clean-up 11. cfg.c keeps
dev's DLSS settings (dlss_fixed_exposure, dlaa_effects_after, dlaa_cam_jitter) beside dlaa_backend. The Screen tab
keeps FSR sharpness with the upscaler's rows, before dev's two new DLSS rows. totk.ini.example takes dev's game
versions for dynamic_res and keeps the note that FSR holds the scene at 100 %.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:37:07 -03:00
codexx-devandClaude Opus 5.5 48cb8a198a Tick the setup's AMD FSR box by default only with an AMD display adapter
The FSR step downloads on any GPU since #1, but the box was ticked for every player. The window now lists the display
adapters Windows reports (screens.windows_adapter_names) and ticks it when one is AMD, or when none could be listed.
The README's install list gets its fourth step back, and the menu's Upscalers text no longer says FSR runs on AMD
GPUs alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:11:09 -03:00
codexx-dev dab62eaf49 Merge pull request #1 from CatDogFishFrog/fsr4
Download FSR libraries without an AMD GPU check
2026-11-16 22:08:33 -03:00
Vadim Goncharov e067faaa48 Download FSR libraries without an AMD GPU check 2026-11-17 02:13:10 +02:00
codexx-devandClaude Fable 5.2 b513393385 Put DLSS and FSR behind one Upscalers row in the menu, and hold the dynamic resolution at 100 % while FSR is on
The row (Off, NVIDIA DLSS, AMD FSR) replaces the DLAA toggle and the backend row and still writes dlaa and
dlaa_backend. "DLSS character trails" becomes "Character trails", since FSR takes the same mask, and "FSR sharpness"
moves next to the upscaler's rows. Texts in English, Russian, Brazilian Portuguese and Simplified Chinese.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 06:52:36 -03:00
codexx-devandClaude Fable 5.2 60346700f4 Keep FSR's picture equally sharp on every frame: FSR sharpens its own output and skips the game's FXAA
With FSR running in place the game ran its FXAA pass, which also sharpens, on 17 frames in every 96 and drew the copy
shader from the scene target onto itself on the others, so a still view went soft and sharp in turns. Both draws are
now skipped on those frames and FSR's own sharpening pass is on, at the strength of the sharpness setting.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 21:20:08 -03:00
codexx-devandClaude Fable 5.2 cf19811d01 Merge pull request #876 (AMD FSR 4 as a second DLAA backend) into fsr4, onto the current dev
The installer keeps dev's pc_prompts and shapes steps and gains the FSR step after DLSS. vk_dlaa.c keeps dev's rules
for where the upscaler arms and ends the scene (the scene's shape, more than half its size, the bloom pass without
depth) and takes the pull request's FSR call, its camera read and its quarter-of-the-output width test.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 19:51:47 -03:00
VictorSCostaandClaude Opus 5.5 189e64cbd3 Keep FSR to Windows and say so on Linux.
AMD's FSR SDK ships its Vulkan libraries for Windows only. On Linux a
dlaa_backend = fsr setting left DLAA off without a word; now it is ignored
with a log line and DLAA stays with DLSS, the menu has no backend row, and
resolution.c checks the DLSS library. The README says FSR is Windows only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 22:41:47 -03:00
VictorSCostaandClaude Opus 5.5 f18b051040 Show the temporal upscaler in the performance overlay.
The overlay's picture lines named the scene size and the present's scaling but not DLSS or FSR. An Upscaler line after the 3D scene now shows the backend that ran (vk_dlaa_name: FSR with its version, or DLSS) and the DLSS mode, or none while DLAA is off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 20:00:13 -03:00
VictorSCosta ba711b7f5a Add AMD FSR 4 upscaling as a second DLAA backend.
dlaa_backend = fsr hands the DLAA frame (scene light, depth, motion vectors, jitter and the characters' mask) to AMD's FSR through the FSR SDK 2.4 Vulkan loader, which picks FSR 4 where the GPU has it and FSR 3.1 elsewhere. The device enables cooperative matrix and 8-bit float support for it, the camera's near and far planes and field of view come from the scene camera block, and the setup gains an fsr step that downloads AMD's signed DLLs. DLAA also no longer arms on scenes narrower than a quarter of the output, which small loading renders did at ultrawide sizes.
2026-11-06 18:35:09 -03:00
126 changed files with 13581 additions and 753 deletions

No files matched your search

+1 -1
View File
@@ -46,7 +46,7 @@ Open pull requests against `dev`. Branch from the current `dev` and rebase on it
- **The fix, not a disabled feature.** A crash that goes away with a feature off points at the bug in that feature. Turning the feature off for a vendor is not a fix.
- **The frame time on weak hardware.** Game threads and the render thread do no file I/O, no GPU allocations, no per-draw state copies and no global atomic counters. Memory kept per frame or per object is freed. The full list with measured costs: [docs/pr-review-kit/02-performance.md](docs/pr-review-kit/02-performance.md), "What the hot path must not do".
- **Other GPUs.** New Vulkan code queries each feature, extension, format and limit it uses and keeps a working path without it. Nothing is hardcoded from what one GPU reports.
- **Text in the catalogs.** Text a player sees gets an id in `runtime/ui_text.h` and an entry in `runtime/ui_text.c` for every menu language (English, Russian, Brazilian Portuguese, Simplified Chinese); installer text goes into `installer/text/*.json`.
- **Text in the catalogs.** Text a player sees gets an id in `runtime/ui_text.h` and an entry in `runtime/ui_text.c` for every menu language (English, Russian, Brazilian Portuguese, Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese, Korean, Vietnamese); installer text goes into `installer/text/*.json`.
- **The generator owns generated C.** Change `recomp/`, never `generated/`.
### Checks by what you changed
+22 -12
View File
@@ -22,13 +22,21 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
- Custom resolutions (1080p, 2k...), supersampling and AMD FSR 1 upscaling
- NVIDIA DLSS / DLAA on RTX GPUs: the setup downloads `nvngx_dlss.dll` from NVIDIA's DLSS SDK repository
(github.com/NVIDIA/DLSS, NVIDIA RTX SDK license) when it finds an RTX GPU; untick it in the setup to skip it
- AMD FSR 3.1 on any GPU, and AMD FSR 4 on Windows on the Radeon GPUs AMD's FSR SDK libraries support, in the same
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
- Discord Rich Presence ("Playing TotK Recomp" with the play time), off by default, own application id supported
- Setup in 11 languages, in-game menu in 4 ([Languages](#languages))
- Setup in 12 languages, in-game menu in 12 ([Languages](#languages))
- Keyboard, mouse and gamepad with remapping, rumble and gyro
- Stereo or 5.1 surround sound output
- Xbox and PlayStation button prompts: Xbox's LB, RB, LT, RT, Menu, View and A, B, X, Y, or PlayStation's ○ × △ □, L1, R1, L2, R2, Options and Share, as labelled on the button to press, with either button layout
@@ -43,7 +51,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
The game keeps the text and voices of every language it shipped with. The port's own setup and in-game menu (F1) come
in these; both follow the Windows display language, and the menu has its own choice on its Menu tab. A Traditional
Chinese Windows gets the Simplified Chinese setup.
Chinese Windows gets the Simplified Chinese setup and menu.
| Language | Setup | In-game menu |
|---|:---:|:---:|
@@ -51,13 +59,14 @@ Chinese Windows gets the Simplified Chinese setup.
| Русский | ✅ | ✅ |
| Português (Brasil) | ✅ | ✅ |
| 简体中文 | ✅ | ✅ |
| Deutsch | ✅ | English |
| Français | ✅ | English |
| Español | ✅ | English |
| Italiano | ✅ | English |
| Nederlands | ✅ | English |
| 日本語 | ✅ | English |
| 한국어 | ✅ | English |
| Deutsch | ✅ | ✅ |
| Français | ✅ | ✅ |
| Español | ✅ | ✅ |
| Italiano | ✅ | ✅ |
| Nederlands | ✅ | ✅ |
| 日本語 | ✅ | ✅ |
| 한국어 | ✅ | ✅ |
| Tiếng Việt | ✅ | ✅ |
Spotted a clumsy phrase, or want your language added? The setup texts are in `installer/text/<language>.json`, the
menu texts in `runtime/ui_text.c`; open an issue or a pull request ([CONTRIBUTING.md](CONTRIBUTING.md)). Fixes from
@@ -71,13 +80,14 @@ native speakers are welcome.
### Windows
Requirements: Windows 10 or later, an x86-64 CPU with SSE4.2 (AVX2/FMA machines get a faster build), a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`, about 36 GiB free during setup (20 GiB after).
Requirements: Windows 10 or later, an x86-64 CPU with SSE4.2 (AVX2/FMA machines get a faster build), a GPU with Vulkan 1.3 (`VK_EXT_external_memory_host` recommended: without it the game copies its memory pools and runs slower), about 36 GiB free during setup (20 GiB after).
1. Download `TotK-Setup-<version>-windows.zip` from [Releases](../../releases/latest) and unpack it.
2. Start `TotK-Setup.exe`. If SmartScreen warns about an unsigned app, choose *More info*, then *Run anyway*.
3. Pick your game files, the language and an install folder, and press *Start*. The setup builds the game once. With
an NVIDIA RTX GPU it also downloads NVIDIA DLSS, unless you untick *Download NVIDIA DLSS*; turn DLSS on in the
menu (F1).
menu (F1). With *Download AMD FSR 4* ticked (the default with an AMD GPU) it downloads AMD's FSR SDK libraries;
in the menu, pick *AMD FSR 4* as the *3D scene upscaler*.
4. Play `totk.exe` from the install folder.
### Linux
+3 -1
View File
@@ -30,7 +30,7 @@ Code copied or adapted from another project is listed here with its source, the
| SDL 3.4.20, dynamic link, `SDL3.dll` copied next to `totk.exe`. Developer builds use the MSYS2 build (`mingw-w64-ucrt-x86_64-sdl3`, which imports `libiconv-2.dll`, LGPL-2.1, unmodified, copied beside it); the installer release ships the upstream release `SDL3-3.4.20-win32-x64.zip`, which imports no libiconv | https://libsdl.org, Copyright (c) 1997-2026 Sam Lantinga | zlib | `runtime/input_win.c` (gamepad input, rumble, gyro and accelerometer) |
| libopus (MSYS2 `mingw-w64-ucrt-x86_64-opus`), dynamic link, `libopus-0.dll` copied next to `totk.exe` | https://opus-codec.org, Copyright (c) 2001-2023 Xiph.Org, Skype Limited, Octasic, Jean-Marc Valin, Timothy B. Terriberry, CSIRO, Gregory Maxwell, Mark Borgerding, Erik de Castro Lopo, Mozilla, Amazon | BSD-3-Clause | `runtime/ov_media.c` (nn::codec hardware Opus decoder) |
| Dear ImGui 1.91.9 (core and Vulkan back end, unmodified), as vendored by LAS Recomp | https://github.com/ocornut/imgui, via https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f` (`third_party/imgui/`), Copyright (c) 2014-2025 Omar Cornut | MIT | `runtime/third_party/imgui/` (compiled into `totk.exe` for the in-game menu, `runtime/ui/`) |
| AMD FidelityFX SDK 1.1.4 subset (public host and shader headers, frame interpolation, optical flow and FSR 3 upscaler components, the Vulkan backend `ffx_vk.cpp` and its GLSL shaders, shared helpers), with four marked Savage Wind patches (64-byte aligned backend scratch arrays, doubled context size where `wchar_t` is 4 bytes, all six descriptor pool sizes, the upscaler's Catmull-Rom history reprojection) and one of ours (the upscaler's luma history declared `rgba16f`) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/tree/v1.1.4, Copyright (C) 2024 Advanced Micro Devices, Inc., via https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`third_party/FidelityFX/`) | MIT | `runtime/third_party/FidelityFX/` (compiled into `totk.exe`; licence text in `runtime/third_party/FidelityFX/LICENSE.txt`, shipped as `licenses/FidelityFX-SDK-LICENSE.txt`) |
| AMD FidelityFX SDK 1.1.4 subset (public host and shader headers, frame interpolation, optical flow and FSR 3 upscaler components, the Vulkan backend `ffx_vk.cpp` and its GLSL shaders, shared helpers), with four marked Savage Wind patches (64-byte aligned backend scratch arrays, doubled context size where `wchar_t` is 4 bytes, all six descriptor pool sizes, the upscaler's Catmull-Rom history reprojection) and two of ours (the upscaler's luma history declared `rgba16f`, the backend's memory type choice skipping protected and AMD device-coherent types) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/tree/v1.1.4, Copyright (C) 2024 Advanced Micro Devices, Inc., via https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`third_party/FidelityFX/`) | MIT | `runtime/third_party/FidelityFX/` (compiled into `totk.exe`; licence text in `runtime/third_party/FidelityFX/LICENSE.txt`, shipped as `licenses/FidelityFX-SDK-LICENSE.txt`) |
| SavageWindRecomp FidelityFX build support, frame generation and FSR 3 upscaler set-up: the SDK-to-clang compat header, the glslang SPIR-V shader generator with its resource reflection and its FSR 3 upscaler permutations, the blob lookup and the backend and context creation of `runtime/nvn/vulkan/framegen.cpp`, the upscaler context with its shared images and the dispatch parameters of `runtime/nvn/vulkan/fsr3.cpp`, the pair's present spacing of `runtime/nvn/vulkan/device.c` `present_wait_turn` | https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`third_party/FidelityFX/ffx_compat.h`, `tools/ffx_shaders.py`, `runtime/nvn/vulkan/framegen.cpp`, `runtime/nvn/vulkan/fsr3.cpp`, `runtime/nvn/vulkan/device.c`) | MIT | `runtime/third_party/FidelityFX/ffx_compat.h`, `runtime/third_party/FidelityFX/spirv/ffx_shaders_vk.h` and `ffx_fsr3upscaler_vk.h` (output of `tools/ffx_shaders.py`), `tools/ffx_shaders.py`, `runtime/vk_fg.cpp`, `runtime/vk_fsr3.cpp`, `runtime/vk_backend.c` (`present_pair`) |
| SavageWindRecomp settings menu: two-pane option rows (row look, left / right stepping, hold speed-up, description pane), the menu style and tab bar | https://github.com/Revivedx/SavageWindRecomp @ `575ad88e02f9a89a9a885d90039d48af33c982f4` (`runtime/ui/option_rows.mm`, `runtime/ui/menu.mm`), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/ui/option_rows.cpp`, `runtime/ui/option_rows.h`, `runtime/ui/menu.cpp` |
| SavageWindRecomp GPU overlap one-off readback rule: a target not read back within the last 16 frames (64-entry table) makes the frame wait wait up to the value that rendered it | https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`runtime/nvn/vulkan/exec.c` readback_schedule, renderer_wait_seq), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/vk_texture.c` (oneoff_streaming, vk_texture_oneshot) |
@@ -41,6 +41,8 @@ Code copied or adapted from another project is listed here with its source, the
| MacNativeGames host movie decoder (`movie::Decoder` for VP9 over libvpx: entry list, buffer and event semantics, NV12 output format, PTS pacing) | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/runtime/movie_host.c`, `movie_host.h`), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/ov_movie.c`, `runtime/movie.h` |
| libvpx 1.17.0 (MSYS2 `mingw-w64-ucrt-x86_64-libvpx`), static link (`libvpx.a`), no DLL shipped; the release notices must carry its BSD licence text and the WebM Project's `PATENTS` grant | https://chromium.googlesource.com/webm/libvpx, Copyright (c) 2010, The WebM Project authors | BSD-3-Clause | `runtime/ov_movie.c` (VP9 decoding of the `Event/Movie` WebM files) |
| MacNativeGames TotK resolution patches: output, swapchain and scene size sites and instruction words for 1.2.1 and 1.4.3, the data-page layout, the HeapDef heap names and sizes | https://github.com/ly05010419/MacNativeGames @ `aaf6ba1f494fabaa209d049e528d6f923dfe822a` (`games/totk/runtime/game_patches.c`, `game_patches_v143.c`, `game_version.h`, `games/totk/scripts/make_output_res_overlay.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v121.txt`, `recomp/patches-v143.txt`, `runtime/resolution.c` |
| AMD FSR SDK ffx-api declarations (`ffx_api.h`, `ffx_api_types.h`, `vk/ffx_api_vk.h`, `upscalers/include/ffx_upscale.h`, trimmed to the declarations used, layouts unchanged) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK @ tag `v2.4.0`, Copyright (C) 2026 Advanced Micro Devices, Inc. | MIT | `runtime/ffx_api_min.h` |
| AMD FSR SDK signed binaries `amd_fidelityfx_loader_vk.dll` and `amd_fidelityfx_upscaler_vk.dll` (not in this repository or the release: the setup's `--fsr` step downloads AMD's copies into the install folder) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK @ tag `v2.4.0` (`Kits/FidelityFX/signedbin/`), Copyright (C) 2026 Advanced Micro Devices, Inc. | AMD FSR SDK license (`docs/license.md` of that tag): redistribution in binary form with its notice, no reverse engineering | loaded at run time by `runtime/vk_ffx.c` |
| AMD FidelityFX Super Resolution 1.0 (`ffx_a.h`, `ffx_fsr1.h`, unmodified; licence text in `runtime/shaders/ffx/LICENSE.txt`) | https://github.com/GPUOpen-Effects/FidelityFX-FSR @ `a21ffb8f6c13233ba336352bdff293894c706575`, Copyright (c) 2021 Advanced Micro Devices, Inc. | MIT | `runtime/shaders/ffx/`, `runtime/shaders/fsr_easu.comp`, `runtime/shaders/fsr_rcas.comp` (compiled into `runtime/fsr_easu_spv.h`, `runtime/fsr_rcas_spv.h`) |
| AMD Display Library (ADL) declarations: `AdapterInfo`, `ADLSingleSensorData`, `ADLPMLogDataOutput`, the `ADL_PMLOG_*` sensor numbers and the `ADL2_*` function signatures | https://github.com/GPUOpen-LibrariesAndSDKs/display-library @ `84c881cb2136f04287eb3af12de00a9e2867aa9e` (`include/adl_structures.h`, `include/adl_defines.h`, `include/adl_sdk.h`), Copyright (c) 2016 - 2022 Advanced Micro Devices, Inc. | MIT | `runtime/perfmon.c` |
| Zstandard 1.5.7 (MSYS2 `mingw-w64-ucrt-x86_64-zstd`), static link | https://github.com/facebook/zstd, Copyright (c) Meta Platforms, Inc. and affiliates | BSD-3-Clause | `runtime/resolution.c` (the HeapDef table), `runtime/ov_zstd.c` (the game's zstd frames decoded on the host) |
+1 -1
View File
@@ -1 +1 @@
0.5.0
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` |
+18 -5
View File
@@ -59,8 +59,9 @@ MacNativeGames cannot run on x86-64 as is: its CPU path executes ARM64 code nati
- Settings and menu: every key with its default is in one table (`cfg.c`), read from `totk.ini` and `TOTK_*`
variables and written back when the in-game menu changes it. The menu and the performance overlay are Dear ImGui,
drawn into the swapchain image (`runtime/ui/`); their text is in `ui_text.c` (English, Russian, Brazilian Portuguese,
Simplified Chinese). The Chinese glyphs come from a system font (Microsoft YaHei, `plat_font_path`) merged into the
font atlas.
Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese, Korean,
Vietnamese). The Chinese, Japanese and Korean glyphs
come from a system font (`plat_font_path`) merged into the font atlas.
- OS calls the host makes go through `runtime/platform/` (`platform.h`, `win32.c`), so a Linux or macOS host adds one file instead of touching the rest. The split is not finished: `tools/check_platform.py` lists the Win32 uses left in the other files.
#### Threads and cores
@@ -87,10 +88,10 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app
- NVN front end from MacNativeGames (`nvn_api_*.c`, `nvn_obj.h`, texture layout and deswizzle). The game records command buffers through it; nothing reaches the GPU until the game submits.
- Vulkan 1.3 back end in place of MacNativeGames' Metal one. At `QueueSubmitCommands` the recorded NVN commands are replayed into Vulkan command buffers (`vk_exec*.c`).
- 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`). 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`).
- 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).
@@ -139,10 +140,22 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app
that computes last frame's position from last frame's blocks (the game writes them into two copies that take turns;
the uniform snapshot keeps both) and writes the difference into the motion image. `TOTK_MV_CHECK` measures the
vectors against the picture, `TOTK_DLAA_TIMES` times the passes on the GPU. `fxaa` switches the game's own FXAA pass.
- AMD FSR (`scene_upscaler = fsr3` or `fsr4`). The same frame, jitter and motion vectors (with the per-object pass)
go to AMD's FSR instead of DLSS: `vk_dlaa.c` `evaluate` calls `fsr_evaluate` where it would call NGX, and everything
around it is shared, including the texture bias (AMD's log2(scene / output) - 1), `fsr_sharpness` (FSR's own RCAS in
place of the FXAA's sharpening), the skip of the game's FXAA and of its copy of the scene onto itself, and the dynamic
resolution held at 100 %. The camera's planes and field of view come from the scene camera block (`vk_fg.cpp`
`vk_fg_camera`). FSR 3.1 (`vk_fsr3.cpp`) is compiled from the FidelityFX SDK 1.1.4 sources and runs on any GPU. FSR 4
(`vk_ffx.c`, Windows) is AMD's FSR SDK 2.4 signed libraries: `amd_fidelityfx_loader_vk.dll` is loaded at run time from
the executable's folder and finds `amd_fidelityfx_upscaler_vk.dll` next to it; only the descriptor layouts of
`ffx_api_min.h` are compiled in. At start the upscaler versions the libraries offer for the device are listed and the
newest FSR 4 is pinned; without one the scene upscaler stays off (no FSR 3 from the libraries). `vk_device.c` enables
`VK_KHR_cooperative_matrix` and `VK_EXT_shader_float8` with their features when FSR 4 is picked and the device has
them. Both hold one context per output size, made again when it changes.
- Occlusion queries never block the CPU; a result that is not ready counts as visible.
- ASTC textures are uploaded as they are where the device reports `textureCompressionASTC_LDR`, and decoded by a compute shader everywhere else (`vk_astc.c`, `TOTK_ASTC`). The CPU decoder (`tex_astc*.c`) is the fallback and the test oracle.
- Draw state. A draw whose program, bound state and textures repeat reuses the previous draw's shaders and skips rebuilding its descriptor sets; descriptor sets are written through update templates (`vk_exec_draw.c`, `vk_pipeline.c`).
- Allocation: Vulkan Memory Allocator. Debugging: Vulkan validation layers, per-pass frame dumps (`TOTK_DUMP`, `vk_dump.c`) and a flight recorder (`TOTK_FLIGHT`). RenderDoc cannot capture, because it hides `VK_EXT_external_memory_host` from the application.
- Allocation: Vulkan Memory Allocator. Debugging: Vulkan validation layers, per-pass frame dumps (`TOTK_DUMP`, `vk_dump.c`) and a flight recorder (`TOTK_FLIGHT`). RenderDoc hides `VK_EXT_external_memory_host` from the application, so under it CPU-visible pools get shadow storage, as on any GPU without the extension; captures on that path are untested.
Maxwell behaviour the back end has to match, and the TotK bugs other ports fixed: [maxwell.md](maxwell.md).
+6 -2
View File
@@ -1,6 +1,7 @@
# Building from source
Windows 10 or later, an x86-64 CPU with SSE4.2, and a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`. The
Windows 10 or later, an x86-64 CPU with SSE4.2, and a GPU with Vulkan 1.3; `VK_EXT_external_memory_host` is recommended (without it CPU-visible pools get shadow storage,
slower and larger, see `vk_no_host_import` in [settings.md](settings.md)). The
default build targets x86-64-v3 (AVX2/FMA); a CPU without them builds with `--cpu v2` instead and runs slower (see
"Build"). Allow about 60 GB for the work folder. Extraction wants about 55 GB free while it runs and keeps about 35 GB
afterwards.
@@ -78,6 +79,9 @@ of them.
.venv-py314\Scripts\python tools\extract.py
```
`--skip-base-romfs` leaves out the base game's 17 GB RomFS image (`extracted 0␍omfs`): no build step reads it, and
the update merge verifies what it takes from the base game file. Only a build of 1.0.0 itself needs it.
4. Shader translator (no game files; again after a change to its sources, and `tools\make_release.py` stops on an older
one). This publishes `build\xlate\totk_xlate.exe`:
@@ -193,7 +197,7 @@ Vega 7 of a Ryzen 5 4600G at about 34 fps). Long play sessions and the Steam Dec
Requirements:
- Linux 6.7 or later: the write watch uses userfaultfd write protection with `PAGEMAP_SCAN`. SteamOS 3.8 qualifies.
- A Vulkan 1.3 driver with `VK_EXT_external_memory_host` (RADV, NVIDIA).
- A Vulkan 1.3 driver (RADV, NVIDIA). Linux uses shadow storage by default, so `VK_EXT_external_memory_host` is not needed.
- Packages on Arch:
```sh
+9 -2
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:
@@ -356,4 +363,4 @@ each line (`mouse_camera` in `runtime/input.c`); spread a turn over lines a fram
## RenderDoc capture (blocked)
`TOTK_RDOC=<frame>[,...]` (`runtime/rdoc_win.c`; `TOTK_RDOC_DIR`, `TOTK_RDOC_DLL`) loads RenderDoc before `vkCreateInstance`. RenderDoc hides `VK_EXT_external_memory_host`, which the back end requires for guest pool imports (`runtime/vk_memory.c`), so device creation fails under it. A capture needs a copy-based pool fallback first.
`TOTK_RDOC=<frame>[,...]` (`runtime/rdoc_win.c`; `TOTK_RDOC_DIR`, `TOTK_RDOC_DLL`) loads RenderDoc before `vkCreateInstance`. RenderDoc hides `VK_EXT_external_memory_host`, which guest pool imports need (`runtime/vk_memory.c`); without it the back end gives CPU-visible pools shadow storage, as on any GPU without the extension (`vk_no_host_import`). Captures on that path are untested.
+15 -4
View File
@@ -26,6 +26,7 @@ The install folder (`main.c` `portable_paths()` reads this layout; it stays port
<install folder>/
totk.exe, SDL3.dll, libopus-0.dll, totk_xlate.exe
nvngx_dlss.dll NVIDIA DLSS, downloaded by the setup's DLSS step when the player keeps it ticked
amd_fidelityfx_*_vk.dll AMD FSR 4 (loader and upscaler), downloaded by the setup's FSR step likewise
totk.ini language; the other keys as commented defaults (totk.ini.example)
exefs/, romfs/ extracted from the player's files
shared-fonts/ the Switch system fonts, with Chinese, Korean or Traditional Chinese text
@@ -108,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
@@ -123,7 +126,15 @@ loads the saves 1.4.3 wrote.
the library; NGX loads it from the folder of totk.exe for `dlaa` and the DLSS modes. A DLSS library already in the
folder (a newer one the player put there) is kept. Without an RTX GPU the step only logs and does nothing; a failed
download warns, the game runs without DLSS, and the next run of the setup tries again.
10. **Clean up** the temp folder, except the generated C and the objects (about 1.3 GB), and write
10. **FSR** (the window's tick box, on by default when Windows lists an AMD display adapter, `screens.py`
`windows_adapter_names`; or `--fsr`; Windows): download
`amd_fidelityfx_loader_vk.dll` and `amd_fidelityfx_upscaler_vk.dll` from AMD's FSR SDK repository
(github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK, tag `v2.4.0`, `Kits/FidelityFX/signedbin/`, AMD FSR SDK
license) into the install folder and check their sizes and SHA-256 (`steps.py`, `Fsr`). Both go in only when both
downloaded and matched. `scene_upscaler = fsr4` loads them from the folder of totk.exe and runs FSR 4 where they
offer it for the GPU. Libraries already in the folder are kept; a failed download warns, the game runs without FSR
4, and the next run tries again.
11. **Clean up** the temp folder, except the generated C and the objects (about 1.3 GB), and write
`build-cache/rebuild.txt` in the install folder.
A cancelled or failed setup resumes from the last finished step (`totk-install.json`).
@@ -181,8 +192,8 @@ python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR
install sections, the explanations under More details, the share notice next to Start) in the Sun Valley ttk theme
(`installer/vendor/sv_ttk/`, the platform theme when it does not load), step list with progress, space line,
collapsible log, Cancel (Ctrl+Break to the CLI's process group, then it waits for the exit), finish screen with Open
folder. English, Russian, Brazilian Portuguese, Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese
or Korean (`guilogic.UI_LANGUAGES`), chosen from the Windows display language (every Chinese, zh-TW and zh-HK
folder. English, Russian, Brazilian Portuguese, Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese,
Korean or Vietnamese (`guilogic.UI_LANGUAGES`), chosen from the Windows display language (every Chinese, zh-TW and zh-HK
included, gives Simplified Chinese; pt-PT and languages without a catalog give English), switchable in the window;
every sentence is an id in `installer/text/<lang>.json`. The game language starts as the window's when the game has
it; a Chinese or Korean window still starts with English, because that game text needs the Switch shared fonts,
+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`). | — |
+20 -8
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
@@ -123,14 +125,24 @@ The Mods tab order decides between a plugin and another mod's patch on the same
plugin site over one of the port's own patches turns that built-in patch off while the mod is on.
The rebuild refuses a plugin when its start-up or the code its redirects reach needs what the port does not give it:
system calls other than the few its start-up needs (memory queries and maps, the clock, debug output), library calls
outside a reviewed list (memory and string functions, the heap, text formatting), threads, services or input; a
redirect that is not one of exlaunch's hook shapes (inline hook, replace hook, call-site rewrite); or two runs of its
start-up that differ in code; or a start-up that crashes the service run or does not return within two minutes. The
row then says **Its plugin ... cannot run in the port** with the reason, and the mod stays off; **Use <mod> without its
code** uses the rest of it, including its other plugins that were built in. UltraCam stays refused: it hooks the graphics API,
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 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
its start-up that differ in code; or a start-up that crashes the service run or does not return within two minutes.
The row then says **Its plugin ... cannot run in the port** with the reason, and the mod stays off; **Use <mod> without
its code** uses the rest of it, including its other plugins that were built in. UltraCam stays refused: it hooks the graphics API,
reads input and opens sockets.
When a start-up calls into the middle of a game function, the rebuild lifts the game again with that address as a
function start and reruns the start-up, up to four times. A plugin that reads or writes files on the SD card gets
the folder `sdcard` in the game's profile folder in its place.
`plugin_trace = 1` in `totk.ini` logs the first call into each of a plugin's hooks (`plugins: hook entry ... reached`).
## Cheats
+12 -4
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
@@ -115,6 +116,7 @@ Many rows below are developer tools that only act together with another setting
| `mods_without_code` (default `0`) | `1` uses every mod without its code part, as if `mods_no_code` named them all. | See `mods_no_code`. | Caution |
| `pipeline_cache` | Path of the Vulkan pipeline cache file (default `pipeline-cache.bin` beside `totk.exe`). | Moves the cache; a new path starts empty and pipelines are built again. | Caution |
| `profile_dir` | Folder of the game profile, which holds the user account id that save data is named after; the default is a `profile` folder beside `totk.exe`, else the build-time path. | Another folder means a different set of saves. | Save risk |
| `restbl_cache` (default `0`) | `1`: with player mods, the resource size table merged at the last start is served again when nothing it was built from changed: every mod file and shipped table (path, size, write time, file id), the mod list and its order, the RomFS image and `totk.exe` itself. `<profile>/mods/` keeps the table and its `.key`. `0` builds it at every start. | Saves the merge at start: the pass over every mod file and the mods' packs (about 0.9 s with The Second Quest, 3,300 files; more with a texture pack). A changed, added or removed mod file, another order, a new build or game version builds the table again; a damaged kept table or key is built again too. A tool that rewrites a mod file with the same size and write time is not seen. | Caution |
| `romfs` | Folder of the game's RomFS (with `romfs.bin`); a relative path is relative to `totk.exe`'s folder. | Without it, a `romfs` folder next to `totk.exe` is used, else the build-time path; a missing image stops the start with a message. | Save risk |
| `romfs_index` | Path of `romfs-index.bin`, which `tools/romfs_index.py` wrote; the default is beside `totk.exe`. | The index is checked against the image by SHA-256 and size; a mismatch stops the start. | Caution |
| `romfs_mmap` | `1` maps the RomFS image into memory instead of reading it with positional reads. | Changes how the image is read; the log reports when the mapped path is on. | Caution |
@@ -138,13 +140,14 @@ Many rows below are developer tools that only act together with another setting
| Setting | What it does | Effect of changing it | Safety |
| --- | --- | --- | --- |
| `anv_vs_barrier` | A by-region barrier before each draw in a pass whose vertex shader reads a storage buffer. Off by default (`0`). Only Intel GPUs with Mesa's ANV driver on Linux need it: there such reads see stale data and campfire smoke and clouds are drawn as white or dark blobs, or the sky flashes white for single frames (#927). Set `1` to turn it on. | `1` costs about 5% of the frame rate on an Iris Xe and does nothing useful on other GPUs or on Windows; `0` leaves the one-frame glitches on ANV. | Safe |
| `bind_inc` (default `0`) | `1` (or `on`) prepares a draw from what changed since the draw before (the bind ops mark the slots whose bytes they changed) instead of from the whole bound state; `check` prepares every draw as before, takes every decision of `on` beside it, logs each kind of difference once and counts them in a `bind_inc:` line every 300 frames; `0` or `off`: as before. `check` also counts what changed between draws in that line. | Less work per draw on the render thread; a change the marks missed would leave a stale descriptor, a wrong picture or a lost device, which `check` would show first. Off by default: with it on, a GTX 1050 Ti lost the device at one place, after the validation layer reported a descriptor pool reset while a command buffer still used its sets; the cause is not found yet. | Caution |
| `block_views_3d` (default `0`) | `1` gives 3D block-compressed images block views too. | On some AMD cards a GPU write past the end of the image's memory loses the Vulkan device, and the game stops. | Risky |
| `deswizzle` (default `auto`) | Where block-linear textures are deswizzled: `auto` or `gpu` uses a compute pass where the texture's storage is an imported pool and the CPU elsewhere, `cpu` always uses the CPU, `check` uses the GPU and also deswizzles every upload on the CPU and compares the two. | `cpu` brings back the long frames on entering new areas (the replay thread deswizzles every texture); `check` waits for the GPU at every upload and is for testing only. The log names the mode in use. | Caution |
| `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 |
@@ -170,7 +173,9 @@ Many rows below are developer tools that only act together with another setting
| `ub_overlay` (default `1`) | `0` copies each uniform update inside a pass into its buffer at once, ending the pass with a full barrier; `ab` alternates with the `ab` blocks. | With `0` scenes with many updated blocks (the terrain, the sky islands) take longer on the GPU; `TOTK_TRACE=perf` prints how many updates stayed in their pass. | Caution |
| `ub_overlay_out` (default `1`) | `0` copies each uniform update between passes into its buffer at once, behind a full barrier of its own; `ab` alternates with the `ab` blocks. Needs `ub_overlay`. | With `0` a run of updates before a pass costs a full GPU barrier each; `TOTK_TRACE=perf` prints how many updates between passes were overlaid. | Caution |
| `ubo_snapshot` (default `1`) | `0` binds live memory for uniform blocks; `ab` alternates with the `ab` blocks. | Without snapshots late draws read another object's matrix, so objects can be drawn in the wrong place. | Risky |
| `null_attach` (default `0`) | `1` gives the colour slots of a render pass that hold no target, below its last target, a dummy attachment (an `R8_UNORM` image covering the pass, writes masked off, loads and stores `DONT_CARE`) instead of a null image view; the pipelines name that format for those slots. A workaround to try on Intel's legacy Windows driver for 6th-10th generation graphics (HD 520, UHD 620, driver 101.21xx), which crashes inside `vkCmdBeginRendering` after the logo (#1343); untested there, and the crash dumps do not show that the empty slots are the cause. Also in `totk.ini.example`. | One or two dummy images per scene resolution (1.4 MiB at 1600x896, at most 24, freed when the device goes); pipelines with empty slots are built again once. | Caution |
| `vk_no_float64` (default `0`) | `1` clears the 64-bit float feature, so the translator lowers FP64 to FP32. | Shaders change, so the shader cache entries for it are made again; precision of FP64 shaders drops. | Caution |
| `vk_no_host_import` (default `0`) | `1` leaves `VK_EXT_external_memory_host` off even when the GPU has it, so the game takes the path of a GPU without it: every CPU-visible pool gets shadow storage, as under Wine. For testing that path. | Shadow storage costs CPU copies before each submission and more memory than imports. | Caution |
| `vk_ssbo_align` (default unset) | Power of two that storage buffer offsets are treated as needing, to test the unaligned path. | The translator and the draw code round storage offsets down to it; shaders are translated again. | Caution |
| `vk_subgroup` (default `32`) | Subgroup size to pin where the driver allows it. | A value other than 32 changes what the translator is told about the GPU, and shaders are translated again. | Caution |
| `volume_mask_bias` (default `1`) | `0` leaves the game's water volume mask draws (a volume's front faces tested LEQUAL without depth writes, blended ONE/ONE with reverse subtract) without the depth bias toward the viewer that `vk_pipeline.c` gives them; `ab` alternates with `TOTK_AB`. | Puddles and still water then flicker again where the volume's top face lies on the water surface; a test setting. | Caution |
@@ -194,6 +199,7 @@ Many rows below are developer tools that only act together with another setting
| `dlss_reactive` (default `0`) | `1` builds a reactive mask for DLSS where it ran. | Changes how DLSS blends moving areas; a test setting. | Caution |
| `fsr3_debug` (default `0`) | With `scene_upscaler = fsr3`: `1` creates the FSR 3.1 context with the SDK's input checks, whose warnings go to the log (the first 32). | Adds checks to every FSR 3.1 dispatch and log lines. | Caution |
| `fsr3_view` (default `0`) | With `scene_upscaler = fsr3`: `1` shows FSR 3.1's own debug view of its inputs and state in place of the picture. | The frame shows a debug image while it is set. | Caution |
| `fsr4_debug` (default `0`) | With `scene_upscaler = fsr4`: `1` creates the FSR 4 context with the AMD libraries' input checks, whose findings go to the log. | Adds checks to every FSR 4 dispatch and log lines. | Caution |
| `mv_check` | Frame interval; every that many DLSS frames copies the light target and motion images to host memory and logs how well the vectors explain the picture. | Costs a GPU-to-host copy and a comparison on the completion thread at each interval. | Caution |
| `mv_survey` (default `0`) | `1` notes the uniform blocks of each scene draw and compares them with those of earlier frames. | Adds per-draw work and log output. | Caution |
| `mvobj_all` (default `0`) | `1` also lists draws for object motion that read no object blocks (terrain and grass). | More draws are checked and listed, which costs time. | Caution |
@@ -208,7 +214,7 @@ Many rows below are developer tools that only act together with another setting
| `mvprev_grow` (default `1`) | `0` keeps only three banks in the previous-frame tables. | Object motion that depends on the other banks is no longer tracked. | Caution |
| `mvprev_skip` | Hex bank mask of banks left out of the previous-frame copy, replacing the default. | Different banks are tracked, which changes object motion. | Caution |
| `mvprev_trust` | Hex bank mask of banks whose found previous-frame copy is taken without the check. | A copy that does not match is used anyway, which can give wrong motion. | Caution |
| `reflex` (default `off`) | `off`, `on`, or `boost`; enables NVIDIA Reflex Low Latency (`VK_NV_low_latency2`) to reduce system input latency. Read at start. | On NVIDIA GPUs supporting the extension, coordinates simulation and presentation cadence to lower latency, holding frames to the frame limit the pacer uses (`fps_limit`, the monitor's rate for `display`); `boost` keeps GPU clocks high in CPU-bound scenes. Has no effect on non-NVIDIA GPUs. | Safe |
| `reflex` (default `off`) | `off`, `auto`, `on`, or `boost`; reduces system input latency. `on` and `boost` enable NVIDIA Reflex Low Latency (`VK_NV_low_latency2`); `auto` enables Reflex, or AMD Anti-Lag 2 (`VK_AMD_anti_lag`, Mesa RADV and AMD's Windows driver) on a GPU without Reflex. Read at start. | Only one of the two runs; on a GPU with neither extension the setting does nothing. Both coordinate simulation and presentation so input reaches the screen sooner when the GPU is the limit, holding frames to the frame limit the pacer uses (`fps_limit`, the monitor's rate for `display`). `boost` also keeps NVIDIA GPU clocks high in CPU-bound scenes. | Safe |
## Scheduling and host
@@ -216,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 |
@@ -243,7 +250,8 @@ 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 |
| `patch_output` (default `0`) | Patch set that makes the game use the configured output size for its swapchain and display configuration. | The resolution code switches this set whenever the output differs from the base size; a manual value is replaced. | Unknown |
+2 -1
View File
@@ -8,7 +8,8 @@ from it may be shared.
- Windows 10 or later, an x86-64 CPU with SSE4.2 (AVX2/FMA recommended: they build the default, faster version), about
60 GB free.
- A GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`, with a current driver.
- A GPU with Vulkan 1.3, with a current driver. `VK_EXT_external_memory_host` is recommended: without it the game
runs on shadow storage, which costs memory and frame rate.
- *Tears of the Kingdom* base game (1.0.0) and the 1.1.0, 1.2.1 or 1.4.3 update, dumped from your own Switch as NSP or XCI.
- `prod.keys` dumped from your own Switch. Never send it to anyone, and never paste it into a log or an issue.
+6 -2
View File
@@ -1,5 +1,5 @@
"""Command line: python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--firmware DIR]
[--root DIR] [--temp DIR] [--verify] [--dlss]
[--root DIR] [--temp DIR] [--verify] [--dlss] [--fsr]
A first install needs every option. --firmware names the Switch firmware folder (an unpacked firmware or an emulator's
Contents/registered); the setup extracts the system shared fonts from it when the language is Chinese, Korean or
@@ -9,7 +9,9 @@ extraction has to run again. Prints JSON events on stdout (events.py). Exit code
line, 3 cancelled (Ctrl+C or Ctrl+Break).
--dlss downloads NVIDIA's DLSS library (nvngx_dlss.dll) from NVIDIA's DLSS SDK repository into the install folder on
Windows with an NVIDIA RTX GPU (steps.py, Dlss).
Windows with an NVIDIA RTX GPU (steps.py, Dlss). --fsr downloads AMD's FSR loader and upscaler
(amd_fidelityfx_loader_vk.dll, amd_fidelityfx_upscaler_vk.dll) from AMD's FSR SDK repository into the install folder on
Windows, for scene_upscaler = fsr4; the libraries decide which GPUs get FSR 4 (steps.py, Fsr).
"""
import argparse
import signal
@@ -51,6 +53,8 @@ def main(argv=None):
ap.add_argument('--verify', action='store_true', help='hash every kept file, also those this release made')
ap.add_argument('--dlss', action='store_true', help="download NVIDIA's nvngx_dlss.dll (NVIDIA RTX SDK license) next "
'to the game, for dlaa and the DLSS modes')
ap.add_argument('--fsr', action='store_true', help="download AMD's FSR loader and upscaler DLLs (AMD FSR SDK "
'license) next to the game, for scene_upscaler = fsr4')
args = ap.parse_args(argv)
# The window cancels with Ctrl+Break to the installer's process group (CREATE_NEW_PROCESS_GROUP), which also reaches
+122 -21
View File
@@ -38,8 +38,10 @@ except ImportError:
from . import ini
from . import layout as layouts
from . import recent
from . import screens
from .guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGE_LABELS, UI_LANGUAGES, Catalog, Form, Model,
Process, amount, default_game_language, describe_event, parse_line, windows_ui_language)
Process, amount, default_game_language, describe_event, fsr_default, parse_line,
windows_ui_language)
POLL_MS = 100
GLYPH = {PENDING: '\u25cb', RUNNING: '\u25b6', DONE: '\u2714', SKIPPED: '\u2013', FAILED: '\u2716'}
@@ -114,6 +116,73 @@ def use_sun_valley(root, ui_font):
return True
class ScrollArea(ttk.Frame):
"""A screen's content scrolls while its action bar stays outside the viewport."""
def __init__(self, parent):
super().__init__(parent)
background = ttk.Style(parent).lookup('TFrame', 'background') or parent.winfo_toplevel().cget('background')
self.canvas = tk.Canvas(self, width=1, height=1, borderwidth=0, highlightthickness=0, background=background)
self.scrollbar = ttk.Scrollbar(self, orient='vertical', command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.scrollbar.set)
self.canvas.pack(side='left', fill='both', expand=True)
self.content = ttk.Frame(self.canvas)
self.window = self.canvas.create_window((0, 0), window=self.content, anchor='nw')
self.content.bind('<Configure>', lambda _e: self.canvas.configure(scrollregion=self.canvas.bbox('all')))
self.canvas.bind('<Configure>', lambda e: self.canvas.itemconfigure(self.window, width=e.width))
root = self.winfo_toplevel()
root.bind('<FocusIn>', self.reveal_focus, add='+')
for sequence in ('<MouseWheel>',) + (('<Button-4>', '<Button-5>') if sys.platform.startswith('linux') else ()):
root.bind(sequence, self.wheel, add='+')
def contains(self, widget):
return widget is self.canvas or str(widget).startswith(str(self.content) + '.') or widget is self.content
def natural(self):
width = self.content.winfo_reqwidth()
if int(self.canvas.cget('width')) == width:
return False
self.canvas.configure(width=width)
return True
def limit_height(self, height):
height = max(1, height)
scroll = height < self.content.winfo_reqheight()
changed = bool(self.scrollbar.winfo_manager()) != scroll
if changed:
if scroll:
self.scrollbar.pack(side='right', fill='y', before=self.canvas)
else:
self.scrollbar.pack_forget()
if int(self.canvas.cget('height')) != height:
self.canvas.configure(height=height)
changed = True
return changed
def reveal_focus(self, event):
if not self.contains(event.widget) or event.widget is self.canvas:
return
top = event.widget.winfo_rooty() - self.content.winfo_rooty()
bottom = top + event.widget.winfo_height()
visible = self.canvas.canvasy(0)
height = self.canvas.winfo_height()
if top < visible:
self.canvas.yview_moveto(top / max(1, self.content.winfo_height()))
elif bottom > visible + height:
self.canvas.yview_moveto((bottom - height) / max(1, self.content.winfo_height()))
def wheel(self, event):
if not self.contains(event.widget) or event.widget.winfo_class() in ('Text', 'Listbox', 'TCombobox'):
return
if self.canvas.yview() == (0.0, 1.0):
return
units = -1 if event.num == 4 else 1 if event.num == 5 else -int(event.delta / 120)
if not units and event.delta:
units = -1 if event.delta > 0 else 1
self.canvas.yview_scroll(units, 'units')
return 'break'
class App:
def __init__(self, root, ui_lang, layout, run_args=None, rebuild=None):
self.root, self.layout = root, layout
@@ -180,6 +249,7 @@ class App:
self.ui_box.pack(side='left')
self.body = ttk.Frame(root, padding=PAD)
self.body.pack(fill='both', expand=True)
self.scroll_areas = {}
self.frames = {'form': self.build_form(), 'run': self.build_run(), 'finish': self.build_finish()}
self.vars['lang'].set(self.lang_label(self.lang_code))
self.vars['dest'].trace_add('write', lambda *_: self.refresh_form())
@@ -267,13 +337,28 @@ class App:
for), so a screen or language switch does not move the buttons sideways, and the height of the shown screen,
so no screen carries the empty band of a taller one. Every text change that can add lines calls it again, or
pack takes the missing height from the button bars. Without `shrink` the window only grows and a size the user
dragged it to stays; a screen or language switch and closing the details or the log shrink it to fit."""
dragged it to stays; a screen or language switch and closing the details or the log shrink it to fit. A screen
taller than the display scrolls its content while its action bar remains outside the viewport."""
self.root.update_idletasks()
widths_changed = [area.natural() for area in self.scroll_areas.values()]
if any(widths_changed):
self.root.update_idletasks()
widths = [f.winfo_reqwidth() for f in self.frames.values()]
shown = self.frames[self.screen] if self.screen else max(self.frames.values(), key=lambda f: f.winfo_reqheight())
chrome = self.root.winfo_reqheight() - self.body.winfo_reqheight() # the title row above the body
w = max(self.root.winfo_reqwidth(), max(widths) + 2 * PAD)
h = chrome + shown.winfo_reqheight() + 2 * PAD
area = self.scroll_areas.get(self.screen)
if area:
h += area.content.winfo_reqheight() - area.canvas.winfo_reqheight()
# Leave room for window decorations and the desktop's panels. Content scrolls; the footer stays visible.
limit = max(1, self.root.winfo_screenheight() - dpi.px(80))
if area:
changed = area.limit_height(area.content.winfo_reqheight() - max(0, h - limit))
h = min(h, limit)
if changed:
self.root.update_idletasks()
w = max(w, shown.winfo_reqwidth() + 2 * PAD)
# refresh_run calls it on every poll: leave the window alone while nothing grew
if (w, h) == self.fitted and (not shrink or self.root.winfo_height() == h):
return
@@ -281,6 +366,12 @@ class App:
self.root.minsize(w, h)
self.root.geometry(f'{max(w, self.root.winfo_width())}x{h if shrink else max(h, self.root.winfo_height())}')
def scroll_content(self, parent, name):
area = ScrollArea(parent)
area.pack(fill='both', expand=True)
self.scroll_areas[name] = area
return area.content
def notice(self, parent):
w = ttk.Label(parent, style='Notice.TLabel', wraplength=WRAP, justify='left')
self.bind_text(w, 'text', 'ui.notice')
@@ -310,9 +401,10 @@ class App:
self.form_error.pack(side='bottom', anchor='w', pady=(dpi.px(4), 0))
self.update_hint = ttk.Label(f, style='Status.TLabel', wraplength=WRAP, justify='left')
self.update_hint.pack(side='bottom', anchor='w', pady=(dpi.px(8), 0))
self.form_intro = self.label(f, 'ui.intro', wraplength=WRAP, justify='left')
content = self.scroll_content(f, 'form')
self.form_intro = self.label(content, 'ui.intro', wraplength=WRAP, justify='left')
self.form_intro.pack(anchor='w', pady=(0, dpi.px(4)))
grid = ttk.Frame(f)
grid = ttk.Frame(content)
grid.pack(fill='x')
grid.columnconfigure(1, weight=1)
self.section(grid, 0, 'ui.section_files', dpi.px(6))
@@ -344,18 +436,25 @@ class App:
# On by default and named with its source and licence: the player sees what is downloaded and can untick it.
# The source and licence line is the first one under More details.
self.dlss_var = tk.BooleanVar(value=True)
dlss = ttk.Checkbutton(f, variable=self.dlss_var)
dlss = ttk.Checkbutton(content, variable=self.dlss_var)
self.bind_text(dlss, 'text', 'ui.dlss')
dlss.pack(anchor='w', pady=(dpi.px(12), 0))
# Ticked by default with an AMD display adapter only (guilogic.fsr_default); the player can tick it on any GPU.
# Its source and licence line follows DLSS's under More details.
self.fsr_var = tk.BooleanVar(value=fsr_default(screens.windows_adapter_names()))
fsr = ttk.Checkbutton(content, variable=self.fsr_var)
self.bind_text(fsr, 'text', 'ui.fsr')
fsr.pack(anchor='w', pady=(dpi.px(4), 0))
# The explanations stay out of the way until asked for: a link opens them under it
self.details_toggle = ttk.Label(f, style='Link.TLabel', cursor='hand2', takefocus=True)
self.details_toggle = ttk.Label(content, style='Link.TLabel', cursor='hand2', takefocus=True)
self.bind_text(self.details_toggle, 'text', 'ui.more_details')
for seq in ('<Button-1>', '<Return>', '<space>'):
self.details_toggle.bind(seq, lambda _e: self.toggle_details())
self.details_toggle.pack(anchor='w', pady=(dpi.px(8), 0))
self.details = ttk.Frame(f) # packed after the link when open; no holder frame, as an emptied Tk frame keeps
self.details = ttk.Frame(content) # packed after the link when open; no holder frame, as an emptied Tk frame keeps
# the height its last child gave it
for id in ('ui.dlss_help', 'ui.formats_help', 'ui.compressed_help', 'ui.firmware_help', 'ui.keys_private'):
for id in ('ui.dlss_help', 'ui.fsr_help', 'ui.formats_help', 'ui.compressed_help', 'ui.firmware_help',
'ui.keys_private'):
self.label(self.details, id, style='Muted.TLabel', wraplength=WRAP - dpi.px(16),
justify='left').pack(anchor='w', pady=(dpi.px(6), 0))
self.details_open = False
@@ -379,14 +478,15 @@ class App:
self.cancel_button.pack(side='right')
self.log_toggle = self.button(bar, 'ui.show_log', self.toggle_log)
self.log_toggle.pack(side='left')
self.run_header = ttk.Label(f, font=(self.ui_font, 11, 'bold'))
content = self.scroll_content(f, 'run')
self.run_header = ttk.Label(content, font=(self.ui_font, 11, 'bold'))
self.run_header.pack(anchor='w')
self.step_rows = {}
self.steps_box = ttk.Frame(f)
self.steps_box = ttk.Frame(content)
self.steps_box.pack(fill='x', pady=dpi.px(8))
self.phase_label = ttk.Label(f, wraplength=WRAP, justify='left')
self.phase_label = ttk.Label(content, wraplength=WRAP, justify='left')
self.phase_label.pack(anchor='w')
bar_holder = ttk.Frame(f)
bar_holder = ttk.Frame(content)
bar_holder.pack(fill='x', pady=(dpi.px(4), dpi.px(6)))
self.bar = ttk.Progressbar(bar_holder, mode='determinate', maximum=1000)
self.bar.pack(fill='both', expand=True)
@@ -396,11 +496,11 @@ class App:
# holder follows it.
bar_holder.pack_propagate(False)
bar_holder.configure(height=dpi.px(22))
self.space_label = ttk.Label(f, wraplength=WRAP, justify='left')
self.space_label = ttk.Label(content, wraplength=WRAP, justify='left')
self.space_label.pack(anchor='w')
self.warn_label = ttk.Label(f, wraplength=WRAP, justify='left', foreground='#9a6700')
self.warn_label = ttk.Label(content, wraplength=WRAP, justify='left', foreground='#9a6700')
self.warn_label.pack(anchor='w')
self.log_frame = ttk.Frame(f)
self.log_frame = ttk.Frame(content)
self.log = tk.Text(self.log_frame, height=10, wrap='word', state='disabled', font=(self.mono_font, 9))
scroll = ttk.Scrollbar(self.log_frame, command=self.log.yview)
self.log.configure(yscrollcommand=scroll.set)
@@ -420,13 +520,14 @@ class App:
self.back_button.pack(side='left')
if self.rebuild: # a failed or cancelled rebuild: the game starts with the code it has
self.button(bar, 'ui.start_game', self.start_game).pack(side='right', padx=(0, dpi.px(8)))
self.finish_title = ttk.Label(f, style='Title.TLabel', wraplength=WRAP, justify='left')
content = self.scroll_content(f, 'finish')
self.finish_title = ttk.Label(content, style='Title.TLabel', wraplength=WRAP, justify='left')
self.finish_title.pack(anchor='w')
self.finish_text = ttk.Label(f, wraplength=WRAP, justify='left')
self.finish_text = ttk.Label(content, wraplength=WRAP, justify='left')
self.finish_text.pack(anchor='w', pady=dpi.px(8))
self.finish_steps = ttk.Frame(f)
self.finish_steps = ttk.Frame(content)
self.finish_steps.pack(fill='x', pady=(0, dpi.px(8)))
self.finish_notice = self.notice(f)
self.finish_notice = self.notice(content)
self.finish_notice.pack(fill='x', pady=(dpi.px(8), 0))
return f
@@ -435,7 +536,7 @@ class App:
def form(self):
return Form(base=self.vars['base'].get(), update=self.vars['update'].get(), keys=self.vars['keys'].get(),
firmware=self.vars['firmware'].get(), lang=self.selected_lang(), dest=self.vars['dest'].get(),
dlss=self.dlss_var.get())
dlss=self.dlss_var.get(), fsr=self.fsr_var.get())
def set_prefill(self, name, value):
self.programmatic = True
@@ -711,7 +812,7 @@ class App:
# ---- self test ---------------------------------------------------------------------------------------------------
SAMPLE_START = {'type': 'start', 'release': 'selftest', 'mode': 'install', 'dest': 'Z:/selftest/TotK', 'log': 'D:\\log.txt',
'steps': ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss', 'cleanup']}
'steps': ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss', 'fsr', 'cleanup']}
SAMPLE_RUN = [
SAMPLE_START,
{'type': 'plan', 'run': ['check', 'fonts', 'extract'], 'skip': {}},
+15 -4
View File
@@ -24,20 +24,20 @@ from . import state as statefile
from .events import render
TEXT = Path(__file__).resolve().parent / 'text'
UI_LANGUAGES = ('en', 'ru', 'pt-BR', 'zh-Hans', 'de', 'fr', 'es', 'it', 'nl', 'ja', 'ko')
UI_LANGUAGES = ('en', 'ru', 'pt-BR', 'zh-Hans', 'de', 'fr', 'es', 'it', 'nl', 'ja', 'ko', 'vi')
# what the language switch in the window's corner shows for each
UI_LANGUAGE_LABELS = {'en': 'English', 'ru': 'Русский', 'pt-BR': 'Português (Brasil)', 'zh-Hans': '简体中文',
'de': 'Deutsch', 'fr': 'Français', 'es': 'Español', 'it': 'Italiano', 'nl': 'Nederlands',
'ja': '日本語', 'ko': '한국어'}
'ja': '日本語', 'ko': '한국어', 'vi': 'Tiếng Việt'}
STEP_ORDER = ('check', 'kit', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss',
'cleanup')
'fsr', 'cleanup')
# message parameter -> catalog id prefix of the names that replace its raw values
PARAM_NAMES = {'lang': 'lang.', 'known': 'lang.', 'step': 'step.', 'input': 'param.input.'}
LANG_PT_BR = 0x0416 # Portuguese (Brazil), the whole LANGID: Portugal's Portuguese stays English
# primary language id in a Windows LANGID -> window language, for the languages whose every region gets the same text.
# Every Chinese gets Simplified Chinese: the setup has no Traditional Chinese text, as the in-game menu has none.
PRIMARY_LANGS = {0x04: 'zh-Hans', 0x19: 'ru', 0x07: 'de', 0x0c: 'fr', 0x0a: 'es', 0x10: 'it', 0x13: 'nl', 0x11: 'ja',
0x12: 'ko'}
0x12: 'ko', 0x2a: 'vi'}
# window language -> the game language the form starts with (default_game_language)
GAME_LANGUAGE_FOR_UI = {'ru': 'ru', 'de': 'de', 'fr': 'fr', 'es': 'es', 'it': 'it', 'nl': 'nl', 'ja': 'ja'}
@@ -142,6 +142,14 @@ def amount(cat, done, total, unit):
# ---- the form ----------------------------------------------------------------------------------------------------
def fsr_default(adapters):
"""Whether the window ticks Download AMD FSR at start: only with an AMD display adapter among adapters (their
names, screens.windows_adapter_names). The step downloads on any GPU when ticked (steps.Fsr); on other GPUs, and
when no adapter could be listed, the box starts unticked, so a player without an AMD GPU never downloads AMD's
libraries (about 36 MB) without choosing to."""
return any('AMD' in a.upper() or 'RADEON' in a.upper() for a in adapters)
@dataclass
class Form:
base: str = ''
@@ -151,6 +159,7 @@ class Form:
lang: str = ''
dest: str = ''
dlss: bool = False
fsr: bool = False
def installed_state(self):
"""The recorded state of the install folder (totk-install.json), or None. Never raises."""
@@ -203,6 +212,8 @@ class Form:
cmd.append('--verify')
if self.dlss:
cmd.append('--dlss')
if self.fsr:
cmd.append('--fsr')
return cmd
+4
View File
@@ -57,9 +57,12 @@ static int x86_64_v3(void) {
return (c & (1u << 5)) != 0; // LZCNT (ABM)
}
// stdout is a pipe, so it is fully buffered: each part is flushed before the next call that can crash, and a probe
// that a Vulkan layer or driver kills still hands the installer what it found (installer/steps.py Check.probe_host).
int main(void) {
printf("{\"x86_64_v2\": %s, \"x86_64_v3\": %s, ", x86_64_v2() ? "true" : "false",
x86_64_v3() ? "true" : "false");
fflush(stdout);
void *lib = open_lib();
PFN_vkGetInstanceProcAddr gipa = lib ? (PFN_vkGetInstanceProcAddr)lib_sym(lib, "vkGetInstanceProcAddr") : NULL;
if (!gipa) {
@@ -67,6 +70,7 @@ int main(void) {
return 0;
}
printf("\"loader\": true, ");
fflush(stdout);
PFN_vkCreateInstance create = (PFN_vkCreateInstance)gipa(NULL, "vkCreateInstance");
VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "totk-install",
.apiVersion = VK_API_VERSION_1_3};
+10 -5
View File
@@ -1,7 +1,7 @@
"""totk.ini: set the game language and keep everything else (keys and syntax as runtime/cfg.c reads them).
A new file starts from totk.ini.example, whose lines are all commented defaults. The language goes into `lang`
(a Switch language code, runtime/ov_system.c): an active `lang = ...` line is rewritten in place, else the commented
(a Switch language code, runtime/ov_system.c): the last active `lang = ...` line is rewritten in place, else the commented
`# lang = ...` line of the example is activated, else the line is added to [language] (created at the end if
missing). Other lines, comments and line order stay as they are.
"""
@@ -32,8 +32,9 @@ def set_language(text, lang):
"""text with `lang = <lang>` (an alias written as its canonical code); see the module docstring."""
lang = canonical_language(lang)
lines = text.splitlines()
for i, line in enumerate(lines):
m = ACTIVE.match(line)
# runtime/cfg.c add gives the last non-empty value priority, regardless of section or the totk_ prefix.
for i in range(len(lines) - 1, -1, -1):
m = ACTIVE.match(lines[i])
if m:
lines[i] = f'{m.group(1)}lang{m.group(2)}{lang}'
return '\n'.join(lines) + '\n'
@@ -53,10 +54,14 @@ def set_language(text, lang):
def get_language(text):
for line in text.splitlines():
for line in reversed(text.splitlines()):
m = ACTIVE.match(line)
if m:
return m.group(3)
value = m.group(3)
if len(value) >= 2 and value[0] == value[-1] == '"':
value = value[1:-1]
if value: # cfg.c add ignores empty values, including an empty quoted string
return value
return None
+1
View File
@@ -28,6 +28,7 @@ static void fail(void)
{ LANG_DUTCH, LAUNCHER_TITLE_NL, LAUNCHER_PYTHON_MISSING_NL },
{ LANG_JAPANESE, LAUNCHER_TITLE_JA, LAUNCHER_PYTHON_MISSING_JA },
{ LANG_KOREAN, LAUNCHER_TITLE_KO, LAUNCHER_PYTHON_MISSING_KO },
{ LANG_VIETNAMESE, LAUNCHER_TITLE_VI, LAUNCHER_PYTHON_MISSING_VI },
{ LANG_CHINESE, LAUNCHER_TITLE_ZH_HANS, LAUNCHER_PYTHON_MISSING_ZH_HANS },
};
LANGID ui = GetUserDefaultUILanguage();
+1 -1
View File
@@ -1,4 +1,4 @@
"""The last install folder and source paths, in a per-user file, so an update, a reinstall or a switch to another game
r"""The last install folder and source paths, in a per-user file, so an update, a reinstall or a switch to another game
version starts with the form filled in.
{"format": 1, "dest": ..., "base": ..., "update": ..., "keys": ..., "firmware": ...}
+54 -11
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):
@@ -94,6 +108,28 @@ def windows_displays():
return out
def windows_adapter_names():
"""The names of the display adapters Windows lists (EnumDisplayDevicesW, "AMD Radeon RX 9060 XT"), without
starting Vulkan; [] elsewhere or when the call fails. The setup window decides its defaults by them before the host
check has run."""
if os.name != 'nt':
return []
try:
user32 = ctypes.WinDLL('user32')
out, i = [], 0
while i < 64:
dev = DISPLAY_DEVICEW()
dev.cb = ctypes.sizeof(dev)
if not user32.EnumDisplayDevicesW(None, i, ctypes.byref(dev), 0):
break
i += 1
if dev.DeviceString and dev.DeviceString not in out:
out.append(dev.DeviceString)
return out
except (OSError, AttributeError, ValueError):
return []
XRANDR = re.compile(r'\sconnected\s+(?:primary\s+)?(\d+)x(\d+)\+')
@@ -132,11 +168,16 @@ def displays():
# ---- totk.ini (runtime/cfg.c reads the same keys, in any section, with or without the totk_ prefix)
def ini_value(text, name):
"""The last nonempty value, with matching quotes removed, as runtime/cfg.c cfg_load and add read it."""
value = None
for line in text.splitlines():
m = re.match(rf'^\s*(?:totk_)?{name}\s*=\s*([^\s#;]*)', line, re.IGNORECASE)
m = re.match(rf'^\s*(?:totk_)?{re.escape(name)}\s*=(.*)$', line, re.IGNORECASE)
if m:
value = m.group(1)
candidate = m.group(1).strip()
if len(candidate) >= 2 and candidate[0] == candidate[-1] == '"':
candidate = candidate[1:-1]
if candidate:
value = candidate
return value
@@ -172,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'))))
@@ -181,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)
+15 -2
View File
@@ -36,10 +36,23 @@ def load(dest):
data = json.loads(path.read_text(encoding='utf-8'))
except (OSError, ValueError):
raise StateError('state.unreadable', path) from None
if not isinstance(data, dict) or not isinstance(data.get('steps'), dict):
if not isinstance(data, dict):
raise StateError('state.unreadable', path)
if data.get('format', 0) > FORMAT:
version = data.get('format', 0)
if type(version) is not int or version < 0:
raise StateError('state.unreadable', path)
if version > FORMAT:
raise StateError('state.newer_format', path)
# The GUI and resume planner read these fields before running a step. A JSON value of the wrong type must take
# the same error path as unreadable JSON, rather than raising from their comparisons or dict lookups.
for name in ('release', 'lang', 'version'):
if name in data and not isinstance(data[name], str):
raise StateError('state.unreadable', path)
for name in ('steps', 'inputs'):
records = data.get(name, {} if name == 'inputs' else None)
if not isinstance(records, dict) or any(not isinstance(record, dict) for record in records.values()):
raise StateError('state.unreadable', path)
data.setdefault('inputs', {}) # older records may omit it; the extraction step expects a dictionary
return data
+345 -26
View File
@@ -1,5 +1,5 @@
"""The eleven setup steps of docs/installer.md: check, kit, fonts, extract, lift, compile, prepare, pc_prompts, shapes,
dlss, cleanup.
"""The twelve setup steps of docs/installer.md: check, kit, fonts, extract, lift, compile, prepare, pc_prompts,
shapes, dlss, fsr, cleanup.
Extraction runs in this process through tools/extract.py (the package's sibling tools/, which ships with it); fonts
runs the vendored extract_shared_fonts.py on the firmware folder; lift, compile and prepare run the bundled Python on
@@ -8,7 +8,8 @@ recomp/gen.py, tools/build_game.py, tools/make_romfs_patches.py and tools/prepar
with the bundled clang (hostcheck.c).
Install folder: exefs/, romfs/ (romfs.bin, index.json), profile/, shared-fonts/ (Chinese and Korean text), totk.exe
and its DLLs, nvngx_dlss.dll (with --dlss), romfs-index.bin, romfs-patches/, romfs-patches-xbox/,
and its DLLs, nvngx_dlss.dll (with --dlss), amd_fidelityfx_loader_vk.dll and amd_fidelityfx_upscaler_vk.dll (with
--fsr), romfs-index.bin, romfs-patches/, romfs-patches-xbox/,
romfs-patches-xbox-label/, romfs-patches-pc/, romfs-patches-<w>x<h>/ and romfs-patches-<style>-<w>x<h>/ (for the
screen shapes and the prompts style this player needs, installer/screens.py), totk_xlate.exe, the
shader state of totk.exe --prepare-shaders, totk.ini, totk-install.json, and on Windows build-kit/ (Kit): the release
@@ -41,6 +42,11 @@ import time
import urllib.request
from pathlib import Path
if os.name == 'nt':
import winreg
else:
winreg = None
from . import ini, screens
from . import layout as layouts
from .layout import EXE, SUPPORTED, version_tag
@@ -59,6 +65,7 @@ TEMP_NEED = 3 * GiB # generated C (about 0.9 GB) and objects
KIT_NEED = 1 * GiB # the build kit (Kit), about 0.65 GB
HOSTCHECK = Path(__file__).resolve().parent / 'hostcheck.c'
STAMP = '.install-key'
PLUGIN_ENTRY_ROUNDS = 4 # plugin lifts at most: each finds where an init called into main past a function start
# ---- helpers
@@ -124,6 +131,79 @@ def kill_tree(proc):
proc.kill()
def parse_host(text):
"""The host check's JSON object, or None when it did not finish (a crash leaves the parts it flushed)."""
try:
host = json.loads(text)
except ValueError:
return None
return host if isinstance(host, dict) and 'devices' in host else None
def exit_code(code):
"""A process exit code as Windows reports crashes (0xC0000005 for an access violation), else as a number."""
if os.name == 'nt' and code is not None and (code < 0 or code >= 0xC0000000):
return f'0x{code & 0xFFFFFFFF:08X}'
return str(code)
def layer_manifests():
"""Implicit Vulkan layer manifests where the Khronos loader looks for them (its docs, LoaderLayerInterface.md,
"Layer Discovery"): the folders in VK_IMPLICIT_LAYER_PATH or VK_ADD_IMPLICIT_LAYER_PATH, then on Windows the
manifests HKLM and HKCU\\SOFTWARE\\Khronos\\Vulkan\\ImplicitLayers enable with a DWORD 0, read in the 64-bit view
the 64-bit probe and game use; elsewhere the implicit_layer.d folders. Layers a driver registers under its display
adapter's key are not listed."""
found = []
for var in ('VK_IMPLICIT_LAYER_PATH', 'VK_ADD_IMPLICIT_LAYER_PATH'):
for part in filter(None, os.environ.get(var, '').split(os.pathsep)):
p = Path(part)
found += sorted(p.glob('*.json')) if p.is_dir() else [p]
if winreg:
for root in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):
try:
key = winreg.OpenKey(root, r'SOFTWARE\Khronos\Vulkan\ImplicitLayers', 0,
winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
except OSError:
continue
with key:
i = 0
while True:
try:
path, enabled, _ = winreg.EnumValue(key, i)
except OSError:
break
i += 1
if enabled == 0: # a DWORD 0 enables the manifest, anything else skips it
found.append(Path(path))
else:
home = Path.home()
config = [os.environ.get('XDG_CONFIG_HOME') or home / '.config',
*(os.environ.get('XDG_CONFIG_DIRS') or '/etc/xdg').split(':'), '/usr/local/etc', '/etc']
data = [os.environ.get('XDG_DATA_HOME') or home / '.local' / 'share',
*(os.environ.get('XDG_DATA_DIRS') or '/usr/local/share:/usr/share').split(':')]
for base in filter(None, config + data):
found += sorted((Path(base) / 'vulkan' / 'implicit_layer.d').glob('*.json'))
return found
def implicit_vulkan_layers():
"""(layer name, manifest path) of each readable implicit Vulkan layer manifest of layer_manifests(), for the
search for the layer that crashes the host check. A manifest the loader cannot read loads no layer and is left
out; a manifest listed twice counts once."""
layers = []
for path in dict.fromkeys(layer_manifests()):
try:
manifest = json.loads(path.read_text(encoding='utf-8-sig'))
except (OSError, ValueError):
continue
entries = (manifest.get('layers') or [manifest.get('layer')]) if isinstance(manifest, dict) else []
for entry in entries:
name = entry.get('name') if isinstance(entry, dict) else None
if isinstance(name, str) and (name, path) not in layers:
layers.append((name, path))
return layers
def linux_glibc():
"""(major, minor) of the C library this Linux process runs on, None elsewhere or when it is not glibc."""
try:
@@ -138,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."""
@@ -423,8 +557,19 @@ class Check(Step):
return {}
def host(self, ctx):
"""Builds and runs the host check once per run: key() asks first and run() reports, so a failure is kept on
ctx and raised again rather than a crashing probe and its retries running twice."""
if getattr(ctx, 'host', None) is not None:
return
if getattr(ctx, 'host_error', None) is not None:
raise ctx.host_error
try:
self.check_host(ctx)
except InstallError as e:
ctx.host_error = e
raise
def check_host(self, ctx):
layout, work = ctx.layout, ctx.temp / 'check'
glibc = linux_glibc()
if glibc and glibc < GLIBC_NEEDED and not layout.dev:
@@ -443,14 +588,15 @@ class Check(Step):
if r.returncode:
ctx.reporter.log(r.stdout + r.stderr)
raise InstallError('check.toolchain_broken', detail=(r.stderr or r.stdout).strip()[-400:])
r = subprocess.run([str(exe)], capture_output=True, text=True, errors='replace')
try:
host = json.loads(r.stdout)
except ValueError:
raise InstallError('check.host_probe_failed', code=r.returncode) from None
ctx.reporter.log(f'host: {r.stdout.strip()}')
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']:
@@ -468,6 +614,60 @@ class Check(Step):
ctx.reporter.warning('warn.kernel_old', version='.'.join(map(str, kernel)))
ctx.host = host
# Windows refuses to start a program a policy does not trust (issue #875): Smart App Control and other App Control
# policies (4551 "An Application Control policy has blocked this file"; 4556-4559 and 4580-4583 the same with the
# reputation verdict, among them 4559 "Unable to contact reputation service for unknown file"), group policy (1260
# "This program is blocked by group policy") and an antivirus that flags or removes the file (225, 226). hostcheck
# is the first program the setup builds on this PC; totk.exe is built the same way and unsigned too, so the install
# cannot go on.
BLOCKED_WINERRORS = {225, 226, 1260, 4551, 4556, 4557, 4558, 4559, 4580, 4581, 4582, 4583}
LAYER_TRIES = 16 # implicit layers tried one by one in the search for the one that crashes the probe
def probe_host(self, ctx, exe):
"""Runs the host check check_host() built and returns its JSON. A probe that crashes inside Vulkan is run again
with the implicit Vulkan layers off (VK_LOADER_LAYERS_DISABLE=~implicit~, Vulkan loader 1.3.234 or later):
overlays, recorders and tuning tools install such layers, and a broken one kills every Vulkan program at
vkCreateInstance (issue #1345, exit code 0xC0000005 after "Checking the processor and the graphics card").
When that run passes, each listed layer is turned off alone to name the one that crashes. The install stops
either way: totk.exe --prepare-shaders in the prepare step and the game itself load the same layers
(runtime/vk_device.c create_instance), so going on would fail after lift and compile."""
rep = ctx.reporter
r = self.run_probe(exe)
host = parse_host(r.stdout)
if host is not None:
rep.log(f'host: {r.stdout.strip()}')
return host
code = exit_code(r.returncode)
rep.log(f'host: the check stopped with exit code {code}; it printed {r.stdout.strip()!r}')
if '"loader": true' not in r.stdout:
raise InstallError('check.host_probe_failed', code=code)
retry = self.run_probe(exe, dict(os.environ, VK_LOADER_LAYERS_DISABLE='~implicit~'))
if parse_host(retry.stdout) is None:
rep.log(f'host: without implicit Vulkan layers too: exit code {exit_code(retry.returncode)}, '
f'{retry.stdout.strip()!r}')
raise InstallError('check.vulkan_crash', code=code)
layers = implicit_vulkan_layers()
rep.log(f'host: passes with the implicit Vulkan layers off; installed: '
f'{", ".join(f"{n} ({p})" for n, p in layers) or "none listed"}')
culprits = [(name, path) for name, path in layers[:self.LAYER_TRIES]
if parse_host(self.run_probe(exe, dict(os.environ, VK_LOADER_LAYERS_DISABLE=name)).stdout)]
if culprits:
rep.log(f'host: passes without {", ".join(n for n, _ in culprits)}')
raise InstallError('check.vulkan_layer_crash', code=code,
layers=', '.join(f'{n} ({p})' for n, p in culprits),
disable=','.join(n for n, _ in culprits))
raise InstallError('check.vulkan_layers_crash', code=code,
layers=', '.join(f'{n} ({p})' for n, p in layers) or '?')
def run_probe(self, exe, env=None):
try:
return subprocess.run([str(exe)], capture_output=True, text=True, errors='replace', env=env)
except OSError as e:
if getattr(e, 'winerror', None) in self.BLOCKED_WINERRORS:
raise InstallError('check.host_blocked', path=str(exe), detail=e.strerror or str(e)) from None
raise InstallError('check.host_probe_failed',
code=f'{getattr(e, "winerror", None) or e.errno}: {e.strerror or e}') from None
def inputs(self, ctx):
"""Open both files with the keys as the extraction will. Returns the bytes of both Program NCAs."""
o = ctx.options
@@ -1001,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."""
@@ -1054,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
@@ -1108,20 +1320,39 @@ class Lift(Step):
lift_plugins = []
if plugins:
listed = ['--plugins', ','.join(str(f) for f in plugins)]
code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', args + ['--patches', patches] + listed, parse)
if not code:
code, log = run_tool(ctx, 'lift', layout.tools / 'build_game.py', build_args(ctx, gen))
if not code:
# the service run's totk.exe loads its DLLs from its own folder, as the installed one does
for dll in layout.dlls:
replace_file(dll, ctx.temp / 'build' / dll.name)
code, log = run_tool(ctx, 'lift', layout.tools / 'exefs_plugins.py', [
'--exe', ctx.temp / 'build' / ('totk' + EXE), '--out', ctx.temp / 'plugins', '--mods',
ctx.dest / 'mods', '--patches', patches, '--patches-out', ctx.temp / 'patches-plugins.txt',
'--status', plugins_status(ctx)])
# exit 1 with a status file: refused plugins, their reasons in it; the rest goes on
if plugins_status(ctx).is_file() and (ctx.temp / 'patches-plugins.txt').is_file():
code = 0
# An init that calls into main where the lift has no function start crashes its service run; the tool
# names those addresses (--entries-out), and one more lift with them as `entry` lines lets the init go on
# (Zonai Fieldworks calls the second word of a 1.4.3 function). Each round adds what the last one found.
lift_patches, found = patches, []
for _ in range(PLUGIN_ENTRY_ROUNDS):
code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', args + ['--patches', lift_patches] + listed,
parse)
if not code:
code, log = run_tool(ctx, 'lift', layout.tools / 'build_game.py', build_args(ctx, gen))
if not code:
# the service run's totk.exe loads its DLLs from its own folder, as the installed one does
for dll in layout.dlls:
replace_file(dll, ctx.temp / 'build' / dll.name)
entries_file = ctx.temp / 'plugin-entries.txt'
entries_file.unlink(missing_ok=True)
code, log = run_tool(ctx, 'lift', layout.tools / 'exefs_plugins.py', [
'--exe', ctx.temp / 'build' / ('totk' + EXE), '--out', ctx.temp / 'plugins', '--mods',
ctx.dest / 'mods', '--exefs', ctx.dest / 'exefs', '--patches', lift_patches,
'--patches-out', ctx.temp / 'patches-plugins.txt', '--status', plugins_status(ctx),
'--entries-out', entries_file])
# exit 1 with a status file: refused plugins, their reasons in it; the rest goes on
if plugins_status(ctx).is_file() and (ctx.temp / 'patches-plugins.txt').is_file():
code = 0
if code:
break
new = [line for line in (entries_file.read_text(encoding='utf-8').splitlines()
if entries_file.is_file() else []) if line and line not in found]
if not new:
break
found += new
lift_patches = ctx.temp / 'patches-entries.txt'
lift_patches.write_text(Path(patches).read_text(encoding='utf-8') + '\n' + '\n'.join(found) + '\n',
encoding='utf-8')
if code:
drop([plugins_status(ctx)])
skipped['warn.plugins_skipped'] = log
@@ -1210,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')
@@ -1346,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))
@@ -1603,7 +1841,87 @@ class Dlss(Step):
return {'installed': DLSS_VERSION}
# ---- 8. clean up
# ---- 8. AMD FSR
# AMD's FSR 4 for scene_upscaler = fsr4 (runtime/vk_ffx.c): the ffx-api loader and the upscaler effect, which the
# loader finds next to itself. AMD's FSR SDK license lets them be redistributed in binary form with its notice
# (THIRD_PARTY_NOTICES.md); the setup still does not ship them: with --fsr it downloads AMD's signed copies from the SDK
# repository at a pinned tag and checks their hashes. The game runs without them; scene_upscaler = fsr4 then does
# nothing.
FSR_VERSION = '2.4.0' # the FSR SDK release; the upscaler DLL is FSR 4.1.2 (FSR 3.1.6 inside goes unused)
FSR_BASE = (f'https://raw.githubusercontent.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/v{FSR_VERSION}/'
'Kits/FidelityFX/signedbin/')
FSR_FILES = ( # name, size, SHA-256
('amd_fidelityfx_loader_vk.dll', 39184, '38a56a01fb3565c0757d9f5c1e4e69de4b65e5f2e5769b323b200dc1f142bab9'),
('amd_fidelityfx_upscaler_vk.dll', 36135696, '4a7e895af6e0b615d40a84d59eb8c2b1054ad91cdd0c739567940270d51bdab7'),
)
FSR_LICENSE = f'https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/blob/v{FSR_VERSION}/docs/license.md'
class Fsr(Step):
"""With --fsr on Windows: AMD's FSR loader and upscaler next to totk.exe; the game pins FSR 4 where they offer it
for the GPU. Libraries the player put there (other versions) are kept. A failed download warns and is tried again
on the next run; the game runs without them."""
id = 'fsr'
def key(self, ctx):
if not getattr(ctx.options, 'fsr', False):
return fingerprint('fsr-2', 'off')
return fingerprint('fsr-2', FSR_VERSION, *(sha for _, _, sha in FSR_FILES))
def current(self, ctx, record):
if record.get('failed'):
return False
return not record.get('installed') or all((ctx.dest / name).is_file() for name, _, _ in FSR_FILES)
def run(self, ctx):
if not getattr(ctx.options, 'fsr', False):
return {}
if os.name != 'nt':
return {'skipped': 'not_windows'}
rep = ctx.reporter
present = [ctx.dest / name for name, _, _ in FSR_FILES if (ctx.dest / name).is_file()]
if present:
if all((ctx.dest / name).is_file() and file_sha256(ctx.dest / name) == sha for name, _, sha in FSR_FILES):
return {'installed': FSR_VERSION}
# A set the player put there (or half of one): kept as it is, the loader and its effect belong together
rep.warning('warn.fsr_kept', path=str(present[0]))
return {'kept': True}
total, done = sum(size for _, size, _ in FSR_FILES), 0
rep.progress('fsr', 'download', 0, total, 'bytes', force=True)
rep.log(f'fsr: {FSR_BASE} (license {FSR_LICENSE})')
parts = []
try:
for name, size, sha in FSR_FILES:
url, part = FSR_BASE + name, ctx.temp / (name + '.part')
parts.append(part)
part.parent.mkdir(parents=True, exist_ok=True)
h, got = hashlib.sha256(), 0
with urllib.request.urlopen(url, timeout=60) as r, open(part, 'wb') as f:
while block := r.read(1 << 20):
f.write(block)
h.update(block)
got += len(block)
rep.progress('fsr', 'download', min(done + got, total), total, 'bytes')
if got != size or h.hexdigest() != sha:
raise OSError(f'{name}: {got} bytes, SHA-256 {h.hexdigest()[:16]}, not the expected file')
done += size
# both downloaded and checked: only then into the install folder, so it never holds half a set
for (name, _, _), part in zip(FSR_FILES, parts):
replace_file(part, ctx.dest / name)
remove(part)
# urllib's errors, timeouts and a bad file; a connection cut mid-file raises http.client.IncompleteRead,
# which is not an OSError
except (OSError, http.client.HTTPException) as e:
for part in parts:
remove(part)
rep.warning('warn.fsr_download_failed', url=FSR_BASE, detail=str(e)[:300])
return {'failed': True}
return {'installed': FSR_VERSION}
# ---- 9. clean up
class Cleanup(Step):
id = 'cleanup'
@@ -1685,4 +2003,5 @@ def romfs_problem(romfs, expected):
def all_steps():
return [Check(), Kit(), Fonts(), Extract(), Lift(), Compile(), Prepare(), PcPrompts(), Shapes(), Dlss(), Cleanup()]
return [Check(), Kit(), Fonts(), Extract(), Lift(), Compile(), Prepare(), PcPrompts(), Shapes(), Dlss(), Fsr(),
Cleanup()]
+12
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Tastatur- und Maussymbole zeichnen",
"step.shapes": "Spielbildschirme für deine Monitore anordnen",
"step.dlss": "NVIDIA DLSS herunterladen",
"step.fsr": "AMD FSR 4 herunterladen",
"step.cleanup": "Aufräumen",
"phase.check.host": "Prozessor und Grafikkarte prüfen",
"phase.check.verify": "Bereits installierte Dateien prüfen",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "Shader-Cache in eine Datei packen",
"phase.shapes.layouts": "Bildschirmlayouts und Tastensymbole für jedes Bildschirmformat schreiben",
"phase.dlss.download": "nvngx_dlss.dll aus NVIDIAs DLSS SDK herunterladen",
"phase.fsr.download": "Die FSR-4-Bibliotheken aus AMDs FSR SDK herunterladen",
"phase.cleanup.ini": "totk.ini schreiben",
"phase.cleanup.temp": "Temporäre Dateien entfernen",
"cli.usage": "Ungültige Befehlszeile: {detail}",
@@ -54,10 +56,15 @@
"check.toolchain_broken": "Der mitgelieferte Compiler funktioniert nicht: {detail}",
"check.glibc_old": "Die C-Bibliothek dieses Systems ist glibc {version}; der Compiler des Setups braucht {need} oder neuer (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 und neuer haben sie). Ein Systemupdate behebt das.",
"check.host_probe_failed": "Die Computerprüfung ist nicht gelaufen (Exit-Code {code}).",
"check.host_blocked": "Windows hat ein Programm blockiert, das das Setup auf diesem PC erstellt hat ({path}): {detail}. Smart App Control, eine App-Control-Richtlinie oder ein Virenscanner blockiert unsignierte Programme; das Spiel selbst wird genauso auf diesem PC erstellt und würde ebenfalls blockiert. Erlaube den Setup-Ordner in deinem Virenscanner oder schalte Smart App Control in der Windows-Sicherheit (App- und Browsersteuerung) aus und starte das Setup erneut.",
"check.vulkan_crash": "Der Grafiktreiber ist abgestürzt, als das Setup nach den Grafikkarten gefragt hat (Exit-Code {code}), auch mit ausgeschalteten Vulkan-Layern anderer Programme. Installiere den neuesten Treiber für deine Grafikkarte.",
"check.vulkan_layer_crash": "Ein Vulkan-Layer, den ein anderes Programm installiert hat, lässt Vulkan-Programme auf diesem PC abstürzen (Exit-Code {code}), und das Spiel würde beim Start genauso abstürzen. Der Layer: {layers}. Aktualisiere oder deinstalliere das Programm, zu dem er gehört (der Pfad zeigt seinen Ordner), oder schalte den Layer aus: Setze für dein Benutzerkonto die Umgebungsvariable VK_LOADER_LAYERS_DISABLE auf {disable}. Starte danach das Setup erneut.",
"check.vulkan_layers_crash": "Ein Vulkan-Layer, den ein anderes Programm installiert hat, lässt Vulkan-Programme auf diesem PC abstürzen (Exit-Code {code}): Mit allen solchen Layern ausgeschaltet läuft die Prüfung durch, und mit ihnen würde das Spiel beim Start genauso abstürzen. Die installierten Layer einzeln auszuschalten hat ihn nicht eingegrenzt. Installierte Layer: {layers}. Aktualisiere oder deinstalliere die Overlay-, Aufnahme- oder Tuning-Programme darunter, oder schalte alle solchen Layer aus: Setze für dein Benutzerkonto die Umgebungsvariable VK_LOADER_LAYERS_DISABLE auf ~implicit~ (das schaltet auch Overlays wie das von Steam in jedem Vulkan-Spiel aus). Starte danach das Setup erneut.",
"check.cpu_too_old": "Diesem Prozessor fehlt x86-64-v2 (SSE4.2, POPCNT und CMPXCHG16B), die älteste Stufe, für die das Spiel gebaut wird. Intel Nehalem (2008) oder AMD Bulldozer (2011) und neuer haben sie.",
"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}",
@@ -100,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}",
@@ -113,6 +121,8 @@
"warn.kernel_old": "Linux {version} fehlt das Schreib-Tracking, auf das das Spiel angewiesen ist (6.7 oder neuer); das Spiel kann sehr langsam laufen. Ein Systemupdate behebt das.",
"warn.dlss_kept": "Im Installationsordner liegt bereits eine DLSS-Bibliothek ({path}); das Setup behält sie.",
"warn.dlss_download_failed": "NVIDIA DLSS konnte nicht von {url} heruntergeladen werden: {detail}. Das Spiel läuft ohne; der nächste Setup-Lauf versucht es erneut.",
"warn.fsr_kept": "Im Installationsordner liegt bereits eine FSR-Bibliothek ({path}); das Setup behält die Bibliotheken dort.",
"warn.fsr_download_failed": "AMD FSR 4 konnte nicht von {url} heruntergeladen werden: {detail}. Das Spiel läuft ohne; der nächste Setup-Lauf versucht es erneut.",
"ui.title": "TotK-Setup",
"ui.rebuild_title": "Spiel für deine Mods neu bauen",
"ui.start_game": "Spiel starten",
@@ -135,6 +145,8 @@
"ui.firmware_help": "Für chinesischen, koreanischen und traditionell chinesischen Text: der Ordner Contents/registered der Firmware, zum Beispiel aus Ryujinx oder Yuzu. Das Setup kopiert daraus die Systemschriften der Switch in den Installationsordner.",
"ui.dlss": "NVIDIA DLSS (nvngx_dlss.dll) für NVIDIA-RTX-Grafikkarten herunterladen",
"ui.dlss_help": "Aus NVIDIAs DLSS SDK auf GitHub, unter NVIDIAs RTX-SDK-Lizenz (github.com/NVIDIA/DLSS). Damit funktionieren die Einstellungen dlaa und DLSS; ohne die Datei bewirken sie nichts.",
"ui.fsr": "AMD FSR 4 (AMDs FSR-SDK-Bibliotheken) für AMD-Radeon-Grafikkarten herunterladen",
"ui.fsr_help": "Aus AMDs FSR SDK auf GitHub, unter AMDs FSR-SDK-Lizenz (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Damit funktioniert die Wahl AMD FSR 4 beim 3D-Szenen-Upscaler auf den Radeon-Karten, für die AMDs Bibliotheken FSR 4 anbieten; ohne sie bewirkt diese Wahl nichts. Beim Start angehakt, wenn der Computer eine AMD-Grafikkarte hat.",
"ui.compressed_help": "Komprimierte NSZ- und XCZ-Dateien funktionieren direkt: Das Setup entpackt sie selbst (bis die Spieldaten extrahiert sind, braucht das so viel freien Speicher, wie die entpackten Dateien belegen).",
"ui.section_files": "Spieldateien",
"ui.section_install": "Installation",
+12
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Drawing the keyboard and mouse prompts",
"step.shapes": "Laying out the game screens for your displays",
"step.dlss": "Downloading NVIDIA DLSS",
"step.fsr": "Downloading AMD FSR 4",
"step.cleanup": "Cleaning up",
"phase.check.host": "Checking the processor and the graphics card",
@@ -40,6 +41,7 @@
"phase.prepare.pack": "Packing the shader cache into one file",
"phase.shapes.layouts": "Writing the screen layouts and button prompts for each display shape",
"phase.dlss.download": "Downloading nvngx_dlss.dll from NVIDIA's DLSS SDK",
"phase.fsr.download": "Downloading the FSR 4 libraries from AMD's FSR SDK",
"phase.cleanup.ini": "Writing totk.ini",
"phase.cleanup.temp": "Removing temporary files",
@@ -57,10 +59,15 @@
"check.toolchain_broken": "The bundled compiler does not work: {detail}",
"check.glibc_old": "This system's C library is glibc {version}; the setup's compiler needs {need} or later (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 and newer have it). Updating the system fixes this.",
"check.host_probe_failed": "The computer check did not run (exit code {code}).",
"check.host_blocked": "Windows blocked a program the setup built on this PC ({path}): {detail}. Smart App Control, an App Control policy or an antivirus blocks unsigned programs; the game itself is built on this PC the same way, so it would be blocked too. Allow the setup folder in your antivirus, or turn off Smart App Control in Windows Security (App & browser control), then run the setup again.",
"check.vulkan_crash": "The graphics driver crashed while the setup asked it for the graphics cards (exit code {code}), also with the Vulkan layers of other programs turned off. Install the latest driver for your graphics card.",
"check.vulkan_layer_crash": "A Vulkan layer that another program installed crashes Vulkan programs on this PC (exit code {code}), and the game would crash at start the same way. The layer: {layers}. Update or uninstall the program it belongs to (the path shows its folder), or turn the layer off: set the environment variable VK_LOADER_LAYERS_DISABLE to {disable} for your user account. Then run the setup again.",
"check.vulkan_layers_crash": "A Vulkan layer that another program installed crashes Vulkan programs on this PC (exit code {code}): with all such layers off the check passes, and the game would crash at start the same way with them on. Turning the installed layers off one at a time did not single it out. Installed layers: {layers}. Update or uninstall the overlay, recorder or tuning programs among them, or turn all such layers off: set the environment variable VK_LOADER_LAYERS_DISABLE to ~implicit~ for your user account (this also turns off overlays such as Steam's in every Vulkan game). Then run the setup again.",
"check.cpu_too_old": "This processor lacks x86-64-v2 (SSE4.2, POPCNT and CMPXCHG16B), the oldest level the game is built for. Intel Nehalem (2008) or AMD Bulldozer (2011) and newer have it.",
"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}",
@@ -104,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}",
@@ -118,6 +126,8 @@
"warn.kernel_old": "Linux {version} lacks the write tracking the game relies on (6.7 or later); the game may run very slowly. Updating the system fixes this.",
"warn.dlss_kept": "A DLSS library is already in the install folder ({path}); the setup keeps it.",
"warn.dlss_download_failed": "NVIDIA DLSS could not be downloaded from {url}: {detail}. The game runs without it; the next setup run tries again.",
"warn.fsr_kept": "An FSR library is already in the install folder ({path}); the setup keeps the libraries there.",
"warn.fsr_download_failed": "AMD FSR 4 could not be downloaded from {url}: {detail}. The game runs without it; the next setup run tries again.",
"ui.title": "TotK Setup",
"ui.rebuild_title": "Rebuilding the game for your mods",
@@ -141,6 +151,8 @@
"ui.firmware_help": "For Chinese, Korean and Traditional Chinese text: the firmware's Contents/registered folder, for example from Ryujinx or Yuzu. The setup copies the Switch system fonts from it into the install folder.",
"ui.dlss": "Download NVIDIA DLSS (nvngx_dlss.dll) for NVIDIA RTX graphics cards",
"ui.dlss_help": "From NVIDIA's DLSS SDK on GitHub, under NVIDIA's RTX SDK license (github.com/NVIDIA/DLSS). It makes the dlaa and DLSS settings work; without it they do nothing.",
"ui.fsr": "Download AMD FSR 4 (AMD's FSR SDK libraries) for AMD Radeon graphics cards",
"ui.fsr_help": "From AMD's FSR SDK on GitHub, under AMD's FSR SDK license (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). It makes the AMD FSR 4 choice of the 3D scene upscaler work on the Radeon cards AMD's libraries offer FSR 4 for; without it that choice does nothing. Ticked at start when the computer has an AMD graphics card.",
"ui.compressed_help": "Compressed NSZ and XCZ files work as they are: the setup unpacks them by itself (until the game data is extracted, that needs as much free space as the unpacked files take).",
"ui.section_files": "Game files",
"ui.section_install": "Install",
+12
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Dibujando los iconos de teclado y ratón",
"step.shapes": "Ajustando las pantallas del juego a tus monitores",
"step.dlss": "Descargando NVIDIA DLSS",
"step.fsr": "Descargando AMD FSR 4",
"step.cleanup": "Limpiando",
"phase.check.host": "Comprobando el procesador y la tarjeta gráfica",
"phase.check.verify": "Comprobando los archivos ya instalados",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "Empaquetando la caché de shaders en un archivo",
"phase.shapes.layouts": "Escribiendo las disposiciones de pantalla y los iconos de botones para cada formato de pantalla",
"phase.dlss.download": "Descargando nvngx_dlss.dll del DLSS SDK de NVIDIA",
"phase.fsr.download": "Descargando las bibliotecas de FSR 4 del FSR SDK de AMD",
"phase.cleanup.ini": "Escribiendo totk.ini",
"phase.cleanup.temp": "Eliminando los archivos temporales",
"cli.usage": "Línea de comandos no válida: {detail}",
@@ -54,10 +56,15 @@
"check.toolchain_broken": "El compilador incluido no funciona: {detail}",
"check.glibc_old": "La biblioteca C de este sistema es glibc {version}; el compilador del instalador necesita {need} o posterior (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 y posteriores la tienen). Actualizar el sistema lo soluciona.",
"check.host_probe_failed": "La comprobación del equipo no se ejecutó (código de salida {code}).",
"check.host_blocked": "Windows bloqueó un programa que el instalador creó en este PC ({path}): {detail}. Smart App Control, una directiva de App Control o un antivirus bloquean los programas sin firmar; el propio juego se crea igual en este PC, así que también se bloquearía. Permite la carpeta del instalador en tu antivirus o desactiva Smart App Control en Seguridad de Windows (Control de aplicaciones y navegador) y vuelve a ejecutar el instalador.",
"check.vulkan_crash": "El controlador gráfico falló cuando el instalador le pidió las tarjetas gráficas (código de salida {code}), también con las capas Vulkan de otros programas desactivadas. Instala el controlador más reciente de tu tarjeta gráfica.",
"check.vulkan_layer_crash": "Una capa Vulkan que instaló otro programa hace fallar los programas Vulkan en este PC (código de salida {code}), y el juego fallaría igual al iniciar. La capa: {layers}. Actualiza o desinstala el programa al que pertenece (la ruta muestra su carpeta), o desactiva la capa: define para tu cuenta de usuario la variable de entorno VK_LOADER_LAYERS_DISABLE con el valor {disable}. Después vuelve a ejecutar el instalador.",
"check.vulkan_layers_crash": "Una capa Vulkan que instaló otro programa hace fallar los programas Vulkan en este PC (código de salida {code}): con todas esas capas desactivadas la comprobación pasa, y con ellas el juego fallaría igual al iniciar. Desactivar las capas instaladas una por una no permitió identificarla. Capas instaladas: {layers}. Actualiza o desinstala los programas de superposición, grabación o ajuste que haya entre ellas, o desactiva todas esas capas: define para tu cuenta de usuario la variable de entorno VK_LOADER_LAYERS_DISABLE con el valor ~implicit~ (esto también desactiva superposiciones como la de Steam en todos los juegos Vulkan). Después vuelve a ejecutar el instalador.",
"check.cpu_too_old": "Este procesador no tiene x86-64-v2 (SSE4.2, POPCNT y CMPXCHG16B), el nivel más antiguo para el que se compila el juego. Intel Nehalem (2008) o AMD Bulldozer (2011) y posteriores lo tienen.",
"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}",
@@ -100,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}",
@@ -113,6 +121,8 @@
"warn.kernel_old": "Linux {version} no tiene el seguimiento de escrituras del que depende el juego (6.7 o posterior); el juego puede ir muy lento. Actualizar el sistema lo soluciona.",
"warn.dlss_kept": "Ya hay una biblioteca DLSS en la carpeta de instalación ({path}); el instalador la conserva.",
"warn.dlss_download_failed": "No se pudo descargar NVIDIA DLSS desde {url}: {detail}. El juego funciona sin él; la próxima ejecución del instalador lo intentará de nuevo.",
"warn.fsr_kept": "Ya hay una biblioteca FSR en la carpeta de instalación ({path}); el instalador conserva las bibliotecas que hay.",
"warn.fsr_download_failed": "No se pudo descargar AMD FSR 4 desde {url}: {detail}. El juego funciona sin él; la próxima ejecución del instalador lo intentará de nuevo.",
"ui.title": "Instalador de TotK",
"ui.rebuild_title": "Reconstruyendo el juego para tus mods",
"ui.start_game": "Iniciar el juego",
@@ -135,6 +145,8 @@
"ui.firmware_help": "Para texto en chino, coreano y chino tradicional: la carpeta Contents/registered del firmware, por ejemplo de Ryujinx o Yuzu. El instalador copia de ella las fuentes del sistema de Switch a la carpeta de instalación.",
"ui.dlss": "Descargar NVIDIA DLSS (nvngx_dlss.dll) para tarjetas gráficas NVIDIA RTX",
"ui.dlss_help": "Del DLSS SDK de NVIDIA en GitHub, bajo la licencia RTX SDK de NVIDIA (github.com/NVIDIA/DLSS). Hace que funcionen los ajustes dlaa y DLSS; sin él no hacen nada.",
"ui.fsr": "Descargar AMD FSR 4 (bibliotecas del FSR SDK de AMD) para tarjetas gráficas AMD Radeon",
"ui.fsr_help": "Del FSR SDK de AMD en GitHub, bajo la licencia FSR SDK de AMD (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Hace que funcione la opción AMD FSR 4 del escalador de la escena 3D en las tarjetas Radeon para las que las bibliotecas de AMD ofrecen FSR 4; sin ellas esa opción no hace nada. Viene marcada si el equipo tiene una tarjeta gráfica AMD.",
"ui.compressed_help": "Los archivos comprimidos NSZ y XCZ funcionan tal cual: el instalador los descomprime por sí mismo (hasta que se extraen los datos del juego, necesita tanto espacio libre como ocupan los archivos descomprimidos).",
"ui.section_files": "Archivos del juego",
"ui.section_install": "Instalación",
+12
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Dessin des icônes du clavier et de la souris",
"step.shapes": "Mise en page des écrans du jeu pour vos moniteurs",
"step.dlss": "Téléchargement de NVIDIA DLSS",
"step.fsr": "Téléchargement d'AMD FSR 4",
"step.cleanup": "Nettoyage",
"phase.check.host": "Vérification du processeur et de la carte graphique",
"phase.check.verify": "Vérification des fichiers déjà installés",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "Regroupement du cache de shaders en un fichier",
"phase.shapes.layouts": "Écriture des mises en page et des icônes de boutons pour chaque format d’écran",
"phase.dlss.download": "Téléchargement de nvngx_dlss.dll depuis le DLSS SDK de NVIDIA",
"phase.fsr.download": "Téléchargement des bibliothèques FSR 4 depuis le FSR SDK d'AMD",
"phase.cleanup.ini": "Écriture de totk.ini",
"phase.cleanup.temp": "Suppression des fichiers temporaires",
"cli.usage": "Ligne de commande invalide : {detail}",
@@ -54,10 +56,15 @@
"check.toolchain_broken": "Le compilateur fourni ne fonctionne pas : {detail}",
"check.glibc_old": "La bibliothèque C de ce système est glibc {version} ; le compilateur de l'installation demande {need} ou plus récent (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 et plus récents l'ont). Mettre à jour le système corrige cela.",
"check.host_probe_failed": "La vérification de l'ordinateur ne s'est pas exécutée (code de sortie {code}).",
"check.host_blocked": "Windows a bloqué un programme que l'installateur a compilé sur ce PC ({path}) : {detail}. Smart App Control, une stratégie App Control ou un antivirus bloque les programmes non signés ; le jeu lui-même est compilé de la même façon sur ce PC et serait bloqué aussi. Autorisez le dossier de l'installateur dans votre antivirus, ou désactivez Smart App Control dans Sécurité Windows (Contrôle des applications et du navigateur), puis relancez l'installateur.",
"check.vulkan_crash": "Le pilote graphique a planté quand l'installateur lui a demandé les cartes graphiques (code de sortie {code}), même avec les couches Vulkan des autres programmes désactivées. Installez le dernier pilote de votre carte graphique.",
"check.vulkan_layer_crash": "Une couche Vulkan installée par un autre programme fait planter les programmes Vulkan sur ce PC (code de sortie {code}), et le jeu planterait de la même façon au démarrage. La couche : {layers}. Mettez à jour ou désinstallez le programme auquel elle appartient (le chemin montre son dossier), ou désactivez la couche : définissez pour votre compte utilisateur la variable d'environnement VK_LOADER_LAYERS_DISABLE avec la valeur {disable}. Relancez ensuite l'installateur.",
"check.vulkan_layers_crash": "Une couche Vulkan installée par un autre programme fait planter les programmes Vulkan sur ce PC (code de sortie {code}) : avec toutes ces couches désactivées, la vérification réussit, et avec elles le jeu planterait de la même façon au démarrage. Désactiver les couches installées une par une n'a pas permis de l'identifier. Couches installées : {layers}. Mettez à jour ou désinstallez les programmes d'overlay, d'enregistrement ou de réglage parmi elles, ou désactivez toutes ces couches : définissez pour votre compte utilisateur la variable d'environnement VK_LOADER_LAYERS_DISABLE avec la valeur ~implicit~ (cela désactive aussi les overlays comme celui de Steam dans tous les jeux Vulkan). Relancez ensuite l'installateur.",
"check.cpu_too_old": "Ce processeur ne prend pas en charge x86-64-v2 (SSE4.2, POPCNT et CMPXCHG16B), le niveau le plus ancien pour lequel le jeu est compilé. Intel Nehalem (2008) ou AMD Bulldozer (2011) et plus récents l'ont.",
"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}",
@@ -100,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}",
@@ -113,6 +121,8 @@
"warn.kernel_old": "Linux {version} ne dispose pas du suivi des écritures dont le jeu dépend (6.7 ou plus récent) ; le jeu peut être très lent. Mettre à jour le système corrige cela.",
"warn.dlss_kept": "Une bibliothèque DLSS se trouve déjà dans le dossier d'installation ({path}) ; l'installation la conserve.",
"warn.dlss_download_failed": "NVIDIA DLSS n'a pas pu être téléchargé depuis {url} : {detail}. Le jeu fonctionne sans ; la prochaine installation réessaiera.",
"warn.fsr_kept": "Une bibliothèque FSR se trouve déjà dans le dossier d'installation ({path}) ; l'installation conserve les bibliothèques présentes.",
"warn.fsr_download_failed": "AMD FSR 4 n'a pas pu être téléchargé depuis {url} : {detail}. Le jeu fonctionne sans ; la prochaine installation réessaiera.",
"ui.title": "Installation de TotK",
"ui.rebuild_title": "Reconstruction du jeu pour vos mods",
"ui.start_game": "Lancer le jeu",
@@ -135,6 +145,8 @@
"ui.firmware_help": "Pour le texte en chinois, en coréen et en chinois traditionnel : le dossier Contents/registered du firmware, par exemple celui de Ryujinx ou de Yuzu. L'installation en copie les polices système de la Switch dans le dossier d'installation.",
"ui.dlss": "Télécharger NVIDIA DLSS (nvngx_dlss.dll) pour les cartes graphiques NVIDIA RTX",
"ui.dlss_help": "Depuis le DLSS SDK de NVIDIA sur GitHub, sous la licence RTX SDK de NVIDIA (github.com/NVIDIA/DLSS). Il fait fonctionner les réglages dlaa et DLSS ; sans lui, ils n'ont aucun effet.",
"ui.fsr": "Télécharger AMD FSR 4 (bibliothèques du FSR SDK d'AMD) pour les cartes graphiques AMD Radeon",
"ui.fsr_help": "Depuis le FSR SDK d'AMD sur GitHub, sous la licence FSR SDK d'AMD (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Il fait fonctionner le choix AMD FSR 4 de l'upscaler de la scène 3D sur les cartes Radeon pour lesquelles les bibliothèques d'AMD proposent FSR 4 ; sans elles, ce choix n'a aucun effet. Coché au départ quand l'ordinateur a une carte graphique AMD.",
"ui.compressed_help": "Les fichiers compressés NSZ et XCZ fonctionnent tels quels : l'installation les décompresse elle-même (jusqu'à l'extraction des données du jeu, il faut autant d'espace libre que les fichiers décompressés).",
"ui.section_files": "Fichiers du jeu",
"ui.section_install": "Installation",
+12
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Disegno delle icone di tastiera e mouse",
"step.shapes": "Impaginazione delle schermate del gioco per i tuoi monitor",
"step.dlss": "Download di NVIDIA DLSS",
"step.fsr": "Download di AMD FSR 4",
"step.cleanup": "Pulizia",
"phase.check.host": "Controllo del processore e della scheda grafica",
"phase.check.verify": "Controllo dei file già installati",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "Raccolta della cache degli shader in un file",
"phase.shapes.layouts": "Scrittura dei layout dello schermo e delle icone dei pulsanti per ogni formato di schermo",
"phase.dlss.download": "Download di nvngx_dlss.dll dal DLSS SDK di NVIDIA",
"phase.fsr.download": "Download delle librerie FSR 4 dal FSR SDK di AMD",
"phase.cleanup.ini": "Scrittura di totk.ini",
"phase.cleanup.temp": "Rimozione dei file temporanei",
"cli.usage": "Riga di comando non valida: {detail}",
@@ -54,10 +56,15 @@
"check.toolchain_broken": "Il compilatore incluso non funziona: {detail}",
"check.glibc_old": "La libreria C di questo sistema è glibc {version}; il compilatore dell'installazione richiede {need} o successiva (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 e successivi la hanno). Aggiornare il sistema risolve il problema.",
"check.host_probe_failed": "Il controllo del computer non è stato eseguito (codice di uscita {code}).",
"check.host_blocked": "Windows ha bloccato un programma che il programma di installazione ha compilato su questo PC ({path}): {detail}. Smart App Control, un criterio App Control o un antivirus bloccano i programmi non firmati; anche il gioco viene compilato così su questo PC e verrebbe bloccato. Consenti la cartella di installazione nell'antivirus oppure disattiva Smart App Control in Sicurezza di Windows (Controllo app e browser), poi esegui di nuovo l'installazione.",
"check.vulkan_crash": "Il driver grafico si è bloccato quando l'installazione gli ha chiesto le schede grafiche (codice di uscita {code}), anche con i livelli Vulkan degli altri programmi disattivati. Installa il driver più recente della tua scheda grafica.",
"check.vulkan_layer_crash": "Un livello Vulkan installato da un altro programma fa bloccare i programmi Vulkan su questo PC (codice di uscita {code}) e il gioco si bloccherebbe allo stesso modo all'avvio. Il livello: {layers}. Aggiorna o disinstalla il programma a cui appartiene (il percorso mostra la sua cartella), oppure disattiva il livello: imposta per il tuo account utente la variabile d'ambiente VK_LOADER_LAYERS_DISABLE con il valore {disable}. Poi esegui di nuovo l'installazione.",
"check.vulkan_layers_crash": "Un livello Vulkan installato da un altro programma fa bloccare i programmi Vulkan su questo PC (codice di uscita {code}): con tutti questi livelli disattivati il controllo riesce, e con essi il gioco si bloccherebbe allo stesso modo all'avvio. Disattivare i livelli installati uno alla volta non ha permesso di individuarlo. Livelli installati: {layers}. Aggiorna o disinstalla i programmi di overlay, registrazione o tuning tra questi, oppure disattiva tutti questi livelli: imposta per il tuo account utente la variabile d'ambiente VK_LOADER_LAYERS_DISABLE con il valore ~implicit~ (questo disattiva anche overlay come quello di Steam in tutti i giochi Vulkan). Poi esegui di nuovo l'installazione.",
"check.cpu_too_old": "Questo processore non supporta x86-64-v2 (SSE4.2, POPCNT e CMPXCHG16B), il livello più vecchio per cui il gioco viene compilato. Intel Nehalem (2008) o AMD Bulldozer (2011) e successivi lo supportano.",
"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}",
@@ -100,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}",
@@ -113,6 +121,8 @@
"warn.kernel_old": "Linux {version} non ha il tracciamento delle scritture su cui si basa il gioco (6.7 o successivo); il gioco potrebbe essere molto lento. Aggiornare il sistema risolve il problema.",
"warn.dlss_kept": "Nella cartella di installazione c'è già una libreria DLSS ({path}); l'installazione la mantiene.",
"warn.dlss_download_failed": "Impossibile scaricare NVIDIA DLSS da {url}: {detail}. Il gioco funziona senza; la prossima esecuzione dell'installazione riproverà.",
"warn.fsr_kept": "Nella cartella di installazione c'è già una libreria FSR ({path}); l'installazione mantiene le librerie presenti.",
"warn.fsr_download_failed": "Impossibile scaricare AMD FSR 4 da {url}: {detail}. Il gioco funziona senza; la prossima esecuzione dell'installazione riproverà.",
"ui.title": "Installazione di TotK",
"ui.rebuild_title": "Ricostruzione del gioco per le tue mod",
"ui.start_game": "Avvia il gioco",
@@ -135,6 +145,8 @@
"ui.firmware_help": "Per il testo in cinese, coreano e cinese tradizionale: la cartella Contents/registered del firmware, ad esempio da Ryujinx o Yuzu. L'installazione ne copia i font di sistema di Switch nella cartella di installazione.",
"ui.dlss": "Scarica NVIDIA DLSS (nvngx_dlss.dll) per le schede grafiche NVIDIA RTX",
"ui.dlss_help": "Dal DLSS SDK di NVIDIA su GitHub, con la licenza RTX SDK di NVIDIA (github.com/NVIDIA/DLSS). Fa funzionare le impostazioni dlaa e DLSS; senza, non hanno effetto.",
"ui.fsr": "Scarica AMD FSR 4 (librerie del FSR SDK di AMD) per le schede grafiche AMD Radeon",
"ui.fsr_help": "Dal FSR SDK di AMD su GitHub, con la licenza FSR SDK di AMD (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Fa funzionare la scelta AMD FSR 4 dell'upscaler della scena 3D sulle schede Radeon per cui le librerie di AMD offrono FSR 4; senza, quella scelta non ha effetto. Selezionata all'avvio se il computer ha una scheda grafica AMD.",
"ui.compressed_help": "I file compressi NSZ e XCZ funzionano così come sono: l'installazione li decomprime da sé (finché i dati del gioco non sono estratti, serve tanto spazio libero quanto occupano i file decompressi).",
"ui.section_files": "File del gioco",
"ui.section_install": "Installazione",
+12
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "キーボードとマウスのボタン表示の作成",
"step.shapes": "ディスプレイに合わせたゲーム画面のレイアウト",
"step.dlss": "NVIDIA DLSS のダウンロード",
"step.fsr": "AMD FSR 4 のダウンロード",
"step.cleanup": "後片付け",
"phase.check.host": "プロセッサーとグラフィックカードを確認しています",
"phase.check.verify": "インストール済みのファイルを確認しています",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "シェーダーキャッシュを 1 つのファイルにまとめています",
"phase.shapes.layouts": "画面の形ごとに画面レイアウトとボタン表示を書き込んでいます",
"phase.dlss.download": "NVIDIA の DLSS SDK から nvngx_dlss.dll をダウンロードしています",
"phase.fsr.download": "AMD の FSR SDK から FSR 4 のライブラリをダウンロードしています",
"phase.cleanup.ini": "totk.ini を書き込んでいます",
"phase.cleanup.temp": "一時ファイルを削除しています",
"cli.usage": "コマンドラインが無効です: {detail}",
@@ -54,10 +56,15 @@
"check.toolchain_broken": "同梱のコンパイラーが動作しません: {detail}",
"check.glibc_old": "このシステムの C ライブラリは glibc {version} です。セットアップのコンパイラーには {need} 以降が必要です (Ubuntu 22.04、Debian 12、Fedora 35、SteamOS 3 以降にあります)。システムを更新すると解決します。",
"check.host_probe_failed": "コンピューターの確認を実行できませんでした (終了コード {code})。",
"check.host_blocked": "セットアップがこの PC でビルドしたプログラム ({path}) を Windows がブロックしました: {detail}。スマート アプリ コントロール、App Control ポリシー、またはウイルス対策ソフトが署名のないプログラムをブロックしています。ゲーム本体も同じ方法でこの PC でビルドされるため、同じくブロックされます。ウイルス対策ソフトでセットアップのフォルダーを許可するか、Windows セキュリティ (アプリとブラウザー コントロール) でスマート アプリ コントロールをオフにしてから、セットアップをもう一度実行してください。",
"check.vulkan_crash": "セットアップがグラフィックカードを問い合わせたときにグラフィックドライバーがクラッシュしました (終了コード {code})。他のプログラムの Vulkan レイヤーをオフにしても同じでした。グラフィックカードの最新ドライバーをインストールしてください。",
"check.vulkan_layer_crash": "他のプログラムがインストールした Vulkan レイヤーが、この PC の Vulkan プログラムをクラッシュさせています (終了コード {code})。ゲームも起動時に同じようにクラッシュします。レイヤー: {layers}。そのレイヤーが属するプログラムを更新するかアンインストールするか (パスでフォルダーがわかります)、レイヤーをオフにしてください: ユーザー アカウントの環境変数 VK_LOADER_LAYERS_DISABLE に {disable} を設定します。その後、セットアップをもう一度実行してください。",
"check.vulkan_layers_crash": "他のプログラムがインストールした Vulkan レイヤーが、この PC の Vulkan プログラムをクラッシュさせています (終了コード {code})。そのようなレイヤーをすべてオフにすると確認は成功し、オンのままではゲームも起動時に同じようにクラッシュします。インストール済みのレイヤーを 1 つずつオフにしても特定できませんでした。インストール済みのレイヤー: {layers}。この中のオーバーレイ、録画、チューニングのプログラムを更新するかアンインストールするか、そのようなレイヤーをすべてオフにしてください: ユーザー アカウントの環境変数 VK_LOADER_LAYERS_DISABLE に ~implicit~ を設定します (Steam などのオーバーレイもすべての Vulkan ゲームでオフになります)。その後、セットアップをもう一度実行してください。",
"check.cpu_too_old": "このプロセッサーは、ゲームのビルド対象となる最も古いレベルである x86-64-v2 (SSE4.2、POPCNT、CMPXCHG16B) に対応していません。Intel Nehalem (2008 年) または AMD Bulldozer (2011 年) 以降が対応しています。",
"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}",
@@ -100,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}",
@@ -113,6 +121,8 @@
"warn.kernel_old": "Linux {version} には、ゲームが必要とする書き込み追跡 (6.7 以降) がありません。ゲームが非常に遅くなることがあります。システムを更新すると解決します。",
"warn.dlss_kept": "インストール先フォルダーには既に DLSS ライブラリがあります ({path})。セットアップはそれを残します。",
"warn.dlss_download_failed": "NVIDIA DLSS を {url} からダウンロードできませんでした: {detail}。ゲームはなしで動作します。次回のセットアップ実行時に再試行します。",
"warn.fsr_kept": "インストール先フォルダーには既に FSR ライブラリがあります ({path})。セットアップはそれらを残します。",
"warn.fsr_download_failed": "AMD FSR 4 を {url} からダウンロードできませんでした: {detail}。ゲームはなしで動作します。次回のセットアップ実行時に再試行します。",
"ui.title": "TotK セットアップ",
"ui.rebuild_title": "Mod に合わせてゲームを再ビルドしています",
"ui.start_game": "ゲームを開始",
@@ -135,6 +145,8 @@
"ui.firmware_help": "中国語、韓国語、繁体字中国語のテキスト用: ファームウェアの Contents/registered フォルダー (例: Ryujinx や Yuzu のもの)。セットアップはそこから Switch のシステムフォントをインストール先フォルダーにコピーします。",
"ui.dlss": "NVIDIA RTX グラフィックカード用に NVIDIA DLSS (nvngx_dlss.dll) をダウンロードする",
"ui.dlss_help": "GitHub 上の NVIDIA の DLSS SDK から、NVIDIA の RTX SDK ライセンスのもとで取得します (github.com/NVIDIA/DLSS)。これで dlaa と DLSS の設定が機能します。ない場合、これらの設定は効果がありません。",
"ui.fsr": "AMD Radeon グラフィックカード用に AMD FSR 4 (AMD の FSR SDK ライブラリ) をダウンロードする",
"ui.fsr_help": "GitHub 上の AMD の FSR SDK から、AMD の FSR SDK ライセンスのもとで取得します (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK)。これで、AMD のライブラリが FSR 4 を提供する Radeon カードで、3D シーンのアップスケーラーの AMD FSR 4 が機能します。ない場合、この選択は効果がありません。AMD のグラフィックカードがあるときは最初からチェックされています。",
"ui.compressed_help": "圧縮された NSZ / XCZ ファイルはそのまま使えます。セットアップが自分で展開します(ゲームデータの展開が終わるまで、展開後のファイルと同じだけの空き容量が必要です)。",
"ui.section_files": "ゲームファイル",
"ui.section_install": "インストール",
+12
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "키보드 및 마우스 버튼 표시 그리기",
"step.shapes": "모니터에 맞게 게임 화면 배치",
"step.dlss": "NVIDIA DLSS 다운로드",
"step.fsr": "AMD FSR 4 다운로드",
"step.cleanup": "정리",
"phase.check.host": "프로세서와 그래픽 카드를 확인하는 중",
"phase.check.verify": "이미 설치된 파일을 확인하는 중",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "셰이더 캐시를 파일 하나로 묶는 중",
"phase.shapes.layouts": "화면 형태마다 화면 레이아웃과 버튼 표시 쓰는 중",
"phase.dlss.download": "NVIDIA DLSS SDK에서 nvngx_dlss.dll을 다운로드하는 중",
"phase.fsr.download": "AMD FSR SDK에서 FSR 4 라이브러리를 다운로드하는 중",
"phase.cleanup.ini": "totk.ini를 쓰는 중",
"phase.cleanup.temp": "임시 파일을 삭제하는 중",
"cli.usage": "잘못된 명령줄: {detail}",
@@ -54,10 +56,15 @@
"check.toolchain_broken": "포함된 컴파일러가 작동하지 않습니다: {detail}",
"check.glibc_old": "이 시스템의 C 라이브러리는 glibc {version}입니다. 설치 프로그램의 컴파일러에는 {need} 이상이 필요합니다(Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 이상에 있음). 시스템을 업데이트하면 해결됩니다.",
"check.host_probe_failed": "컴퓨터 확인이 실행되지 않았습니다(종료 코드 {code}).",
"check.host_blocked": "설치 프로그램이 이 PC에서 빌드한 프로그램({path})을 Windows가 차단했습니다: {detail}. 스마트 앱 컨트롤, App Control 정책 또는 백신이 서명되지 않은 프로그램을 차단합니다. 게임 자체도 이 PC에서 같은 방식으로 빌드되므로 마찬가지로 차단됩니다. 백신에서 설치 프로그램 폴더를 허용하거나 Windows 보안(앱 및 브라우저 컨트롤)에서 스마트 앱 컨트롤을 끈 다음 설치 프로그램을 다시 실행하세요.",
"check.vulkan_crash": "설치 프로그램이 그래픽 카드를 조회하는 중에 그래픽 드라이버가 충돌했습니다(종료 코드 {code}). 다른 프로그램의 Vulkan 레이어를 끈 상태에서도 마찬가지였습니다. 그래픽 카드의 최신 드라이버를 설치하세요.",
"check.vulkan_layer_crash": "다른 프로그램이 설치한 Vulkan 레이어 때문에 이 PC의 Vulkan 프로그램이 충돌합니다(종료 코드 {code}). 게임도 시작할 때 같은 방식으로 충돌합니다. 레이어: {layers}. 그 레이어가 속한 프로그램을 업데이트하거나 제거하거나(경로에 폴더가 나옵니다), 레이어를 끄세요: 사용자 계정의 환경 변수 VK_LOADER_LAYERS_DISABLE을 {disable}(으)로 설정합니다. 그런 다음 설치 프로그램을 다시 실행하세요.",
"check.vulkan_layers_crash": "다른 프로그램이 설치한 Vulkan 레이어 때문에 이 PC의 Vulkan 프로그램이 충돌합니다(종료 코드 {code}). 그런 레이어를 모두 끄면 확인을 통과하고, 켜 두면 게임도 시작할 때 같은 방식으로 충돌합니다. 설치된 레이어를 하나씩 꺼 봐도 어느 것인지 찾지 못했습니다. 설치된 레이어: {layers}. 이 중 오버레이, 녹화 또는 튜닝 프로그램을 업데이트하거나 제거하거나, 그런 레이어를 모두 끄세요: 사용자 계정의 환경 변수 VK_LOADER_LAYERS_DISABLE을 ~implicit~(으)로 설정합니다(Steam 같은 오버레이도 모든 Vulkan 게임에서 꺼집니다). 그런 다음 설치 프로그램을 다시 실행하세요.",
"check.cpu_too_old": "이 프로세서에는 게임이 빌드되는 가장 오래된 수준인 x86-64-v2(SSE4.2, POPCNT, CMPXCHG16B)가 없습니다. Intel Nehalem(2008) 또는 AMD Bulldozer(2011) 이후 프로세서에 있습니다.",
"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}",
@@ -100,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}",
@@ -113,6 +121,8 @@
"warn.kernel_old": "Linux {version}에는 게임이 사용하는 쓰기 추적(6.7 이상)이 없습니다. 게임이 매우 느릴 수 있습니다. 시스템을 업데이트하면 해결됩니다.",
"warn.dlss_kept": "설치 폴더에 이미 DLSS 라이브러리가 있습니다({path}). 설치 프로그램은 그대로 둡니다.",
"warn.dlss_download_failed": "{url}에서 NVIDIA DLSS를 다운로드할 수 없습니다: {detail}. 게임은 없이도 실행되며, 다음 설치 실행 때 다시 시도합니다.",
"warn.fsr_kept": "설치 폴더에 이미 FSR 라이브러리가 있습니다({path}). 설치 프로그램은 그대로 둡니다.",
"warn.fsr_download_failed": "{url}에서 AMD FSR 4를 다운로드할 수 없습니다: {detail}. 게임은 없이도 실행되며, 다음 설치 실행 때 다시 시도합니다.",
"ui.title": "TotK 설치",
"ui.rebuild_title": "모드에 맞게 게임을 다시 빌드하는 중",
"ui.start_game": "게임 시작",
@@ -135,6 +145,8 @@
"ui.firmware_help": "중국어, 한국어, 번체 중국어 텍스트용: 펌웨어의 Contents/registered 폴더(예: Ryujinx 또는 Yuzu의 폴더). 설치 프로그램이 여기에서 Switch 시스템 글꼴을 설치 폴더로 복사합니다.",
"ui.dlss": "NVIDIA RTX 그래픽 카드용 NVIDIA DLSS (nvngx_dlss.dll) 다운로드",
"ui.dlss_help": "GitHub의 NVIDIA DLSS SDK에서, NVIDIA RTX SDK 라이선스에 따라 받습니다(github.com/NVIDIA/DLSS). 이 파일이 있어야 dlaa 및 DLSS 설정이 작동하며, 없으면 아무 효과가 없습니다.",
"ui.fsr": "AMD Radeon 그래픽 카드용 AMD FSR 4 (AMD FSR SDK 라이브러리) 다운로드",
"ui.fsr_help": "GitHub의 AMD FSR SDK에서, AMD FSR SDK 라이선스에 따라 받습니다(github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). 이 라이브러리가 있어야 AMD 라이브러리가 FSR 4를 제공하는 Radeon 카드에서 3D 장면 업스케일러의 AMD FSR 4 선택이 작동하며, 없으면 아무 효과가 없습니다. AMD 그래픽 카드가 있는 컴퓨터에서는 처음부터 체크되어 있습니다.",
"ui.compressed_help": "압축된 NSZ 및 XCZ 파일은 그대로 사용할 수 있습니다. 설치 프로그램이 직접 압축을 풉니다(게임 데이터를 추출할 때까지 압축을 푼 파일만큼의 여유 공간이 필요합니다).",
"ui.section_files": "게임 파일",
"ui.section_install": "설치",
+12
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Toetsenbord- en muispictogrammen tekenen",
"step.shapes": "De spelschermen voor je beeldschermen indelen",
"step.dlss": "NVIDIA DLSS downloaden",
"step.fsr": "AMD FSR 4 downloaden",
"step.cleanup": "Opruimen",
"phase.check.host": "Processor en videokaart controleren",
"phase.check.verify": "Al geïnstalleerde bestanden controleren",
@@ -39,6 +40,7 @@
"phase.prepare.pack": "Shadercache in één bestand verpakken",
"phase.shapes.layouts": "Schermindelingen en knoppictogrammen voor elke schermvorm schrijven",
"phase.dlss.download": "nvngx_dlss.dll downloaden uit NVIDIA's DLSS SDK",
"phase.fsr.download": "De FSR 4-bibliotheken downloaden uit AMD's FSR SDK",
"phase.cleanup.ini": "totk.ini schrijven",
"phase.cleanup.temp": "Tijdelijke bestanden verwijderen",
"cli.usage": "Ongeldige opdrachtregel: {detail}",
@@ -54,10 +56,15 @@
"check.toolchain_broken": "De meegeleverde compiler werkt niet: {detail}",
"check.glibc_old": "De C-bibliotheek van dit systeem is glibc {version}; de compiler van de installatie heeft {need} of nieuwer nodig (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 en nieuwer hebben die). Het systeem bijwerken lost dit op.",
"check.host_probe_failed": "De computercontrole is niet uitgevoerd (afsluitcode {code}).",
"check.host_blocked": "Windows heeft een programma geblokkeerd dat de installatie op deze pc heeft gebouwd ({path}): {detail}. Slim app-beheer, een App Control-beleid of een virusscanner blokkeert niet-ondertekende programma's; het spel zelf wordt op dezelfde manier op deze pc gebouwd en zou ook worden geblokkeerd. Sta de installatiemap toe in je virusscanner, of zet Slim app-beheer uit in Windows-beveiliging (App- en browserbeheer), en start de installatie opnieuw.",
"check.vulkan_crash": "Het grafische stuurprogramma is gecrasht toen de installatie het om de videokaarten vroeg (afsluitcode {code}), ook met de Vulkan-lagen van andere programma's uitgeschakeld. Installeer het nieuwste stuurprogramma voor je videokaart.",
"check.vulkan_layer_crash": "Een Vulkan-laag die een ander programma heeft geïnstalleerd laat Vulkan-programma's op deze pc crashen (afsluitcode {code}), en het spel zou bij het starten op dezelfde manier crashen. De laag: {layers}. Werk het programma waar hij bij hoort bij of verwijder het (het pad toont de map), of zet de laag uit: stel voor je gebruikersaccount de omgevingsvariabele VK_LOADER_LAYERS_DISABLE in op {disable}. Start daarna de installatie opnieuw.",
"check.vulkan_layers_crash": "Een Vulkan-laag die een ander programma heeft geïnstalleerd laat Vulkan-programma's op deze pc crashen (afsluitcode {code}): met al zulke lagen uit slaagt de controle, en met die lagen aan zou het spel bij het starten op dezelfde manier crashen. De geïnstalleerde lagen één voor één uitzetten wees hem niet aan. Geïnstalleerde lagen: {layers}. Werk de overlay-, opname- of tuningprogramma's daartussen bij of verwijder ze, of zet al zulke lagen uit: stel voor je gebruikersaccount de omgevingsvariabele VK_LOADER_LAYERS_DISABLE in op ~implicit~ (dit zet ook overlays zoals die van Steam uit in elk Vulkan-spel). Start daarna de installatie opnieuw.",
"check.cpu_too_old": "Deze processor mist x86-64-v2 (SSE4.2, POPCNT en CMPXCHG16B), het oudste niveau waarvoor het spel wordt gebouwd. Intel Nehalem (2008) of AMD Bulldozer (2011) en nieuwer hebben het.",
"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}",
@@ -100,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}",
@@ -113,6 +121,8 @@
"warn.kernel_old": "Linux {version} mist de schrijftracering waar het spel op rekent (6.7 of nieuwer); het spel kan erg traag zijn. Het systeem bijwerken lost dit op.",
"warn.dlss_kept": "Er staat al een DLSS-bibliotheek in de installatiemap ({path}); de installatie laat die staan.",
"warn.dlss_download_failed": "NVIDIA DLSS kon niet worden gedownload van {url}: {detail}. Het spel werkt zonder; de volgende installatieronde probeert het opnieuw.",
"warn.fsr_kept": "Er staat al een FSR-bibliotheek in de installatiemap ({path}); de installatie laat de bibliotheken daar staan.",
"warn.fsr_download_failed": "AMD FSR 4 kon niet worden gedownload van {url}: {detail}. Het spel werkt zonder; de volgende installatieronde probeert het opnieuw.",
"ui.title": "TotK-installatie",
"ui.rebuild_title": "Spel opnieuw bouwen voor je mods",
"ui.start_game": "Spel starten",
@@ -135,6 +145,8 @@
"ui.firmware_help": "Voor Chinese, Koreaanse en traditioneel Chinese tekst: de map Contents/registered van de firmware, bijvoorbeeld uit Ryujinx of Yuzu. De installatie kopieert daaruit de systeemlettertypen van de Switch naar de installatiemap.",
"ui.dlss": "NVIDIA DLSS (nvngx_dlss.dll) downloaden voor NVIDIA RTX-videokaarten",
"ui.dlss_help": "Uit NVIDIA's DLSS SDK op GitHub, onder NVIDIA's RTX SDK-licentie (github.com/NVIDIA/DLSS). Hiermee werken de instellingen dlaa en DLSS; zonder doen ze niets.",
"ui.fsr": "AMD FSR 4 (AMD's FSR SDK-bibliotheken) downloaden voor AMD Radeon-videokaarten",
"ui.fsr_help": "Uit AMD's FSR SDK op GitHub, onder AMD's FSR SDK-licentie (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Hiermee werkt de keuze AMD FSR 4 van de 3D-scène-upscaler op de Radeon-kaarten waarvoor AMD's bibliotheken FSR 4 bieden; zonder doet die keuze niets. Aangevinkt bij de start als de computer een AMD-videokaart heeft.",
"ui.compressed_help": "Gecomprimeerde NSZ- en XCZ-bestanden werken zoals ze zijn: de installatie pakt ze zelf uit (tot de spelgegevens zijn uitgepakt, is daarvoor evenveel vrije ruimte nodig als de uitgepakte bestanden innemen).",
"ui.section_files": "Spelbestanden",
"ui.section_install": "Installatie",
+12
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Desenhando os ícones de teclado e mouse",
"step.shapes": "Ajustando as telas do jogo aos seus monitores",
"step.dlss": "Baixando o NVIDIA DLSS",
"step.fsr": "Baixando o AMD FSR 4",
"step.cleanup": "Finalizando",
"phase.check.host": "Verificando o processador e a placa de vídeo",
@@ -40,6 +41,7 @@
"phase.prepare.pack": "Juntando o cache de shaders num único arquivo",
"phase.shapes.layouts": "Gravando os layouts de tela e os botões para cada formato de monitor",
"phase.dlss.download": "Baixando o nvngx_dlss.dll do DLSS SDK da NVIDIA",
"phase.fsr.download": "Baixando as bibliotecas do FSR 4 do FSR SDK da AMD",
"phase.cleanup.ini": "Gravando o totk.ini",
"phase.cleanup.temp": "Removendo os arquivos temporários",
@@ -57,10 +59,15 @@
"check.toolchain_broken": "O compilador incluído não funciona: {detail}",
"check.glibc_old": "A biblioteca C deste sistema é a glibc {version}; o compilador da instalação precisa da {need} ou mais nova (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 e mais novos têm). Atualizar o sistema resolve.",
"check.host_probe_failed": "A verificação do computador não rodou (código de saída {code}).",
"check.host_blocked": "O Windows bloqueou um programa que o instalador compilou neste PC ({path}): {detail}. O Controle Inteligente de Aplicativos, uma política de App Control ou um antivírus bloqueia programas sem assinatura; o próprio jogo é compilado do mesmo jeito neste PC e também seria bloqueado. Libere a pasta do instalador no seu antivírus ou desative o Controle Inteligente de Aplicativos na Segurança do Windows (Controle de aplicativos e do navegador) e rode o instalador de novo.",
"check.vulkan_crash": "O driver de vídeo travou quando o instalador pediu a lista de placas de vídeo (código de saída {code}), mesmo com as camadas Vulkan de outros programas desativadas. Instale o driver mais recente da sua placa de vídeo.",
"check.vulkan_layer_crash": "Uma camada Vulkan instalada por outro programa faz os programas Vulkan travarem neste PC (código de saída {code}), e o jogo travaria do mesmo jeito ao iniciar. A camada: {layers}. Atualize ou desinstale o programa ao qual ela pertence (o caminho mostra a pasta dele), ou desative a camada: defina para a sua conta de usuário a variável de ambiente VK_LOADER_LAYERS_DISABLE com o valor {disable}. Depois rode o instalador de novo.",
"check.vulkan_layers_crash": "Uma camada Vulkan instalada por outro programa faz os programas Vulkan travarem neste PC (código de saída {code}): com todas essas camadas desativadas a verificação passa, e com elas o jogo travaria do mesmo jeito ao iniciar. Desativar as camadas instaladas uma de cada vez não apontou qual é. Camadas instaladas: {layers}. Atualize ou desinstale os programas de overlay, gravação ou ajuste entre elas, ou desative todas essas camadas: defina para a sua conta de usuário a variável de ambiente VK_LOADER_LAYERS_DISABLE com o valor ~implicit~ (isso também desativa overlays como o da Steam em todos os jogos Vulkan). Depois rode o instalador de novo.",
"check.cpu_too_old": "Este processador não tem x86-64-v2 (SSE4.2, POPCNT e CMPXCHG16B), o nível mais antigo para o qual o jogo é compilado. Intel Nehalem (2008) ou AMD Bulldozer (2011) e mais novos têm.",
"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}",
@@ -104,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}",
@@ -118,6 +126,8 @@
"warn.kernel_old": "O Linux {version} não tem o rastreamento de escrita de que o jogo depende (6.7 ou mais novo); o jogo pode rodar muito devagar. Atualizar o sistema resolve.",
"warn.dlss_kept": "Já existe uma biblioteca DLSS na pasta de instalação ({path}); a instalação a mantém.",
"warn.dlss_download_failed": "Não foi possível baixar o NVIDIA DLSS de {url}: {detail}. O jogo funciona sem ele; a próxima execução da instalação tenta de novo.",
"warn.fsr_kept": "Já existe uma biblioteca FSR na pasta de instalação ({path}); a instalação mantém as bibliotecas que estão lá.",
"warn.fsr_download_failed": "Não foi possível baixar o AMD FSR 4 de {url}: {detail}. O jogo funciona sem ele; a próxima execução da instalação tenta de novo.",
"ui.title": "Instalação do TotK",
"ui.rebuild_title": "Recompilando o jogo para os seus mods",
@@ -141,6 +151,8 @@
"ui.firmware_help": "Para textos em chinês, coreano e chinês tradicional: a pasta Contents/registered do firmware, por exemplo do Ryujinx ou do Yuzu. A instalação copia dela as fontes do sistema do Switch para a pasta de instalação.",
"ui.dlss": "Baixar o NVIDIA DLSS (nvngx_dlss.dll) para placas de vídeo NVIDIA RTX",
"ui.dlss_help": "Do DLSS SDK da NVIDIA no GitHub, sob a licença NVIDIA RTX SDK (github.com/NVIDIA/DLSS). Sem ele as opções dlaa e DLSS não fazem nada.",
"ui.fsr": "Baixar o AMD FSR 4 (bibliotecas do FSR SDK da AMD) para placas de vídeo AMD Radeon",
"ui.fsr_help": "Do FSR SDK da AMD no GitHub, sob a licença do AMD FSR SDK (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Elas fazem a opção AMD FSR 4 do upscaler da cena 3D funcionar nas placas Radeon para as quais as bibliotecas da AMD oferecem o FSR 4; sem elas essa opção não faz nada. Vem marcada quando o computador tem uma placa de vídeo AMD.",
"ui.compressed_help": "Arquivos compactados NSZ e XCZ funcionam do jeito que estão: a instalação os descompacta sozinha (para isso, até os dados do jogo serem extraídos, ela precisa de tanto espaço livre quanto ocupam os arquivos descompactados).",
"ui.section_files": "Arquivos do jogo",
"ui.section_install": "Instalação",
+12
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "Рисование подсказок клавиатуры и мыши",
"step.shapes": "Раскладка экранов игры под ваши мониторы",
"step.dlss": "Загрузка NVIDIA DLSS",
"step.fsr": "Загрузка AMD FSR 4",
"step.cleanup": "Уборка",
"phase.check.host": "Проверка процессора и видеокарты",
@@ -40,6 +41,7 @@
"phase.prepare.pack": "Упаковка кэша шейдеров в один файл",
"phase.shapes.layouts": "Запись раскладок экрана и кнопок для каждой формы монитора",
"phase.dlss.download": "Загрузка nvngx_dlss.dll из DLSS SDK от NVIDIA",
"phase.fsr.download": "Загрузка библиотек FSR 4 из FSR SDK от AMD",
"phase.cleanup.ini": "Запись totk.ini",
"phase.cleanup.temp": "Удаление временных файлов",
@@ -57,10 +59,15 @@
"check.toolchain_broken": "Встроенный компилятор не работает: {detail}",
"check.glibc_old": "Библиотека C этой системы — glibc {version}; компилятору установщика нужна {need} или новее (она есть в Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 и новее). Обновление системы это исправит.",
"check.host_probe_failed": "Проверка компьютера не выполнилась (код выхода {code}).",
"check.host_blocked": "Windows заблокировала программу, которую установщик собрал на этом компьютере ({path}): {detail}. Интеллектуальное управление приложениями (Smart App Control), политика App Control или антивирус блокируют неподписанные программы; сама игра собирается на этом компьютере так же и тоже будет заблокирована. Разрешите папку установщика в антивирусе или отключите интеллектуальное управление приложениями в «Безопасности Windows» («Управление приложениями/браузером») и запустите установщик снова.",
"check.vulkan_crash": "Видеодрайвер аварийно завершился, когда установщик запросил список видеокарт (код выхода {code}), в том числе с отключёнными слоями Vulkan других программ. Установите свежий драйвер видеокарты.",
"check.vulkan_layer_crash": "Слой Vulkan, установленный другой программой, обрушивает Vulkan-программы на этом компьютере (код выхода {code}), и игра так же упадёт при запуске. Слой: {layers}. Обновите или удалите программу, которой он принадлежит (путь показывает её папку), или отключите слой: задайте для своей учётной записи переменную среды VK_LOADER_LAYERS_DISABLE со значением {disable}. Затем запустите установщик снова.",
"check.vulkan_layers_crash": "Слой Vulkan, установленный другой программой, обрушивает Vulkan-программы на этом компьютере (код выхода {code}): со всеми такими слоями отключёнными проверка проходит, а с ними игра так же упадёт при запуске. Отключение установленных слоёв по одному не выявило виновника. Установленные слои: {layers}. Обновите или удалите программы оверлея, записи или настройки среди них, или отключите все такие слои: задайте для своей учётной записи переменную среды VK_LOADER_LAYERS_DISABLE со значением ~implicit~ (это также отключит оверлеи вроде оверлея Steam во всех играх на Vulkan). Затем запустите установщик снова.",
"check.cpu_too_old": "Этому процессору не хватает x86-64-v2 (SSE4.2, POPCNT и CMPXCHG16B) — минимального уровня, под который собрана игра. Он есть у Intel Nehalem (2008) и AMD Bulldozer (2011) и новее.",
"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}",
@@ -104,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}",
@@ -118,6 +126,8 @@
"warn.kernel_old": "В Linux {version} нет отслеживания записи, на которое опирается игра (нужна версия 6.7 или новее); игра может работать очень медленно. Обновление системы это исправит.",
"warn.dlss_kept": "В папке установки уже есть библиотека DLSS ({path}); установка её оставляет.",
"warn.dlss_download_failed": "Не удалось загрузить NVIDIA DLSS с {url}: {detail}. Игра работает и без него; при следующем запуске установка попробует снова.",
"warn.fsr_kept": "В папке установки уже есть библиотека FSR ({path}); установка оставляет имеющиеся библиотеки.",
"warn.fsr_download_failed": "Не удалось загрузить AMD FSR 4 с {url}: {detail}. Игра работает и без него; при следующем запуске установка попробует снова.",
"ui.title": "Установка TotK",
"ui.rebuild_title": "Пересборка игры под ваши моды",
@@ -141,6 +151,8 @@
"ui.firmware_help": "Для текста на китайском и корейском: папка Contents/registered прошивки, например из Ryujinx или Yuzu. Установка скопирует из неё системные шрифты Switch в папку установки.",
"ui.dlss": "Загрузить NVIDIA DLSS (nvngx_dlss.dll) для видеокарт NVIDIA RTX",
"ui.dlss_help": "Из DLSS SDK от NVIDIA на GitHub, по лицензии NVIDIA RTX SDK (github.com/NVIDIA/DLSS). Без него настройки dlaa и DLSS ничего не делают.",
"ui.fsr": "Загрузить AMD FSR 4 (библиотеки FSR SDK от AMD) для видеокарт AMD Radeon",
"ui.fsr_help": "Из FSR SDK от AMD на GitHub, по лицензии AMD FSR SDK (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). С ними работает вариант AMD FSR 4 в апскейлере 3D-сцены на тех видеокартах Radeon, для которых библиотеки AMD предлагают FSR 4; без них этот выбор ничего не делает. Отмечено по умолчанию, если в компьютере есть видеокарта AMD.",
"ui.compressed_help": "Сжатые файлы NSZ и XCZ подходят как есть: установка сама их распакует (для этого, пока извлекаются данные игры, нужно столько свободного места, сколько занимают распакованные файлы).",
"ui.section_files": "Файлы игры",
"ui.section_install": "Установка",
+227
View File
@@ -0,0 +1,227 @@
{
"step.check": "Kiểm tra máy tính và các tệp trò chơi",
"step.kit": "Sao chép bộ công cụ biên dịch vào thư mục trò chơi",
"step.fonts": "Trích xuất phông chữ hệ thống",
"step.extract": "Trích xuất trò chơi",
"step.lift": "Chuyển mã trò chơi sang C",
"step.compile": "Biên dịch {game_exe}",
"step.prepare": "Chuẩn bị shader",
"step.pc_prompts": "Vẽ biểu tượng nút bàn phím và chuột",
"step.shapes": "Bố trí giao diện trò chơi theo màn hình của bạn",
"step.dlss": "Tải xuống NVIDIA DLSS",
"step.fsr": "Tải xuống AMD FSR 4",
"step.cleanup": "Dọn dẹp",
"phase.check.host": "Kiểm tra bộ xử lý và card đồ họa",
"phase.check.verify": "Kiểm tra các tệp đã cài đặt",
"phase.check.verify_romfs": "Kiểm tra dữ liệu trò chơi đã cài đặt",
"phase.check.inputs": "Mở các tệp trò chơi bằng khóa",
"phase.check.unpack_base": "Giải nén trò chơi gốc đã nén",
"phase.check.unpack_update": "Giải nén bản cập nhật đã nén",
"phase.check.versions": "Kiểm tra phiên bản trò chơi",
"phase.kit.copy": "Sao chép các công cụ mà trò chơi dùng để tự biên dịch lại cho mod mã",
"phase.fonts.extract": "Trích xuất phông chữ dùng chung từ firmware",
"phase.fonts.copy": "Sao chép phông chữ dùng chung vào thư mục cài đặt",
"phase.extract.hash_base": "Tính tổng kiểm tra của trò chơi gốc",
"phase.extract.hash_update": "Tính tổng kiểm tra của bản cập nhật",
"phase.extract.exefs": "Trích xuất mã trò chơi",
"phase.extract.copy": "Sao chép dữ liệu trò chơi",
"phase.extract.merge": "Áp dụng bản cập nhật vào dữ liệu trò chơi",
"phase.extract.diagnose": "Tìm tệp trò chơi bị hỏng",
"phase.extract.index": "Xác minh dữ liệu trò chơi",
"phase.lift.discover": "Tìm các hàm",
"phase.lift.emit": "Ghi mã C",
"phase.compile.compile": "Biên dịch",
"phase.compile.link": "Liên kết {game_exe}",
"phase.prepare.romfs_patches": "Ghi các bản vá dữ liệu trò chơi cho 60 fps",
"phase.pc_prompts.draw": "Vẽ biểu tượng phím và nút chuột theo các phím gán trong totk.ini",
"phase.prepare.seed": "Đọc shader từ dữ liệu trò chơi",
"phase.prepare.translate": "Chuyển đổi shader",
"phase.prepare.libraries": "Biên dịch shader cho trình điều khiển đồ họa",
"phase.prepare.pack": "Đóng gói bộ nhớ đệm shader thành một tệp",
"phase.shapes.layouts": "Ghi bố cục màn hình và biểu tượng nút cho từng tỷ lệ màn hình",
"phase.dlss.download": "Tải xuống nvngx_dlss.dll từ DLSS SDK của NVIDIA",
"phase.fsr.download": "Tải xuống các thư viện FSR 4 từ FSR SDK của AMD",
"phase.cleanup.ini": "Ghi totk.ini",
"phase.cleanup.temp": "Xóa các tệp tạm",
"cli.usage": "Dòng lệnh không hợp lệ: {detail}",
"internal": "Lỗi không mong muốn ({exception}): {detail}",
"state.unreadable": "Không thể đọc {path}. Hãy chọn thư mục khác hoặc xóa tệp đó.",
"state.newer_format": "{path} được ghi bởi một trình cài đặt mới hơn. Hãy dùng trình cài đặt đó hoặc chọn thư mục khác.",
"state.output_changed": "Các tệp đã cài đặt của bước '{step}' đã thay đổi kể từ khi được tạo; bước đó sẽ chạy lại.",
"check.release_incomplete": "Thư mục trình cài đặt không đầy đủ; còn thiếu: {paths}. Hãy giải nén lại bản phát hành.",
"check.dest_not_folder": "Vị trí cài đặt {path} là một tệp, không phải thư mục.",
"check.dest_not_empty": "Thư mục cài đặt {path} không trống và không chứa bản cài đặt nào trước đó. Hãy chọn một thư mục trống.",
"check.lang_missing": "Hãy chọn ngôn ngữ trò chơi.",
"check.lang_unknown": "Ngôn ngữ không xác định '{lang}'. Các ngôn ngữ đã biết: {known}.",
"check.toolchain_broken": "Trình biên dịch đi kèm không hoạt động: {detail}",
"check.glibc_old": "Thư viện C của hệ thống này là glibc {version}; trình biên dịch của trình cài đặt cần {need} trở lên (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 và mới hơn đều có). Cập nhật hệ thống sẽ khắc phục lỗi này.",
"check.host_probe_failed": "Không chạy được bước kiểm tra máy tính (mã thoát {code}).",
"check.host_blocked": "Windows đã chặn một chương trình mà trình cài đặt biên dịch trên máy tính này ({path}): {detail}. Smart App Control (Kiểm soát ứng dụng thông minh), một chính sách App Control hoặc phần mềm diệt virus chặn các chương trình không có chữ ký; bản thân trò chơi cũng được biên dịch trên máy tính này theo cách tương tự nên cũng sẽ bị chặn. Hãy cho phép thư mục trình cài đặt trong phần mềm diệt virus, hoặc tắt Smart App Control trong Bảo mật Windows (Kiểm soát ứng dụng và trình duyệt), rồi chạy lại trình cài đặt.",
"check.vulkan_crash": "Trình điều khiển đồ họa bị lỗi khi trình cài đặt yêu cầu danh sách card đồ họa (mã thoát {code}), kể cả khi đã tắt các lớp Vulkan của chương trình khác. 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_layer_crash": "Một lớp Vulkan do chương trình khác cài đặt làm các chương trình Vulkan trên máy tính này bị lỗi (mã thoát {code}), và trò chơi cũng sẽ bị lỗi khi khởi động theo cách tương tự. Lớp đó: {layers}. Hãy cập nhật hoặc gỡ cài đặt chương trình sở hữu lớp này (đường dẫn cho biết thư mục của chương trình), hoặc tắt lớp đó: đặt biến môi trường VK_LOADER_LAYERS_DISABLE thành {disable} cho tài khoản người dùng của bạn. Sau đó chạy lại trình cài đặt.",
"check.vulkan_layers_crash": "Một lớp Vulkan do chương trình khác cài đặt làm các chương trình Vulkan trên máy tính này bị lỗi (mã thoát {code}): khi tắt tất cả các lớp như vậy thì bước kiểm tra thành công, còn khi bật chúng thì trò chơi cũng sẽ bị lỗi khi khởi động theo cách tương tự. Tắt lần lượt từng lớp đã cài đặt không xác định được lớp gây lỗi. Các lớp đã cài đặt: {layers}. Hãy cập nhật hoặc gỡ cài đặt các chương trình lớp phủ (overlay), quay màn hình hoặc tinh chỉnh trong số đó, hoặc tắt tất cả các lớp như vậy: đặt biến môi trường VK_LOADER_LAYERS_DISABLE thành ~implicit~ cho tài khoản người dùng của bạn (thao tác này cũng tắt các lớp phủ như của Steam trong mọi trò chơi Vulkan). Sau đó chạy lại trình cài đặt.",
"check.cpu_too_old": "Bộ xử lý này không hỗ trợ x86-64-v2 (SSE4.2, POPCNT và CMPXCHG16B), mức thấp nhất mà trò chơi được biên dịch cho. Intel Nehalem (2008) hoặc AMD Bulldozer (2011) trở lên đều hỗ trợ.",
"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}",
"check.keys_unreadable": "Không thể đọc tệp khóa. Hãy chọn một tệp prod.keys.",
"check.keys_no_header_key": "Tệp khóa không có header_key. Hãy trích xuất lại prod.keys từ máy console của bạn.",
"check.keys_wrong": "Các khóa này không mở được tệp {input}. Hãy dùng prod.keys của chính máy console của bạn.",
"check.keys_too_old": "Tệp khóa quá cũ đối với tệp {input} (cần thế hệ khóa {generation}). Hãy trích xuất prod.keys từ máy console có firmware mới hơn.",
"check.not_game_file": "Tệp {input} không phải là tệp trò chơi XCI, NSP, XCZ hoặc NSZ.",
"check.file_unreadable": "Không thể đọc tệp {input}: {detail}",
"check.unpack_failed": "Không thể giải nén tệp nén {input}: {detail}",
"check.ticket_personalized": "Tệp {input} chứa ticket cá nhân hóa (personalized); cần có ticket chung (common).",
"check.ticket_missing": "Tệp {input} thiếu ticket mà nội dung của nó cần.",
"check.base_not_totk": "Tệp trò chơi gốc không phải là The Legend of Zelda: Tears of the Kingdom ({detail}).",
"check.base_is_update": "Tệp trò chơi gốc là một bản cập nhật. Hãy chọn NSP hoặc XCI của trò chơi gốc (phiên bản 1.0.0) ở đây và chọn tệp này làm bản cập nhật.",
"check.base_combined": "Tệp trò chơi gốc chứa nhiều gói (trò chơi gốc, bản cập nhật hoặc DLC trong cùng một tệp). Hãy chọn bản dump trò chơi gốc chỉ chứa trò chơi.",
"check.update_not_nsp": "Bản cập nhật phải là tệp NSP hoặc NSZ.",
"check.update_is_base": "Tệp cập nhật chứa trò chơi gốc. Hãy chọn tệp NSP của bản cập nhật 1.1.0 hoặc 1.2.1 hoặc 1.4.3.",
"check.update_not_totk": "Tệp cập nhật không phải là bản cập nhật của Tears of the Kingdom ({detail}).",
"check.exefs_failed": "Mã trò chơi trong tệp {input} không vượt qua bước kiểm tra; xem {log}.",
"check.input_damaged": "Tệp {input} bị hỏng hoặc không đầy đủ: {path} ({detail}). Hãy sao chép lại tệp đó từ nguồn của nó hoặc dump lại, rồi chạy lại trình cài đặt.",
"check.base_wrong_version": "Trò chơi gốc không phải phiên bản 1.0.0 ({modules} khác biệt).",
"check.update_wrong_version": "Bản cập nhật là phiên bản {found}; bản phát hành này yêu cầu {wanted}.",
"check.disk_space": "Không đủ dung lượng trống cho {path}: cần {need_gb} GB, còn trống {free_gb} GB.",
"check.firmware_missing": "Thư mục firmware {path} không tồn tại. Hãy chọn thư mục Contents/registered của firmware.",
"check.firmware_empty": "Thư mục firmware {path} không chứa tệp NCA nào. Hãy chọn thư mục Contents/registered của firmware.",
"check.fonts_keys_needed": "Phông chữ dùng chung cho ngôn ngữ này chưa được cài đặt; hãy chọn prod.keys để trình cài đặt trích xuất chúng từ firmware.",
"extract.exefs_mismatch": "Mã trò chơi đã trích xuất không khớp với phiên bản {version} ({modules}).",
"extract.romfs_merge_failed": "Áp dụng bản cập nhật vào dữ liệu trò chơi không thành công: {detail}. Chi tiết: {log}",
"extract.romfs_mismatch": "Dữ liệu trò chơi đã trích xuất không khớp với phiên bản {version} (kích thước {size}, tổng kiểm tra {sha256}...).",
"fonts.failed": "Trích xuất phông chữ dùng chung không thành công (mã thoát {code}): {detail}. Chi tiết: {log}",
"fonts.incomplete": "Quá trình trích xuất phông chữ dùng chung không ghi đủ mọi tệp ({files}).",
"fonts.copy_failed": "Không thể sao chép phông chữ dùng chung vào {path}: {detail}",
"lift.failed": "Chuyển mã trò chơi không thành công (mã thoát {code}). Chi tiết: {log}",
"compile.failed": "Biên dịch {game_exe} không thành công (mã thoát {code}). Chi tiết: {log}",
"compile.exe_in_use": "{path} đang được sử dụng. Hãy đóng trò chơi rồi chạy lại trình cài đặt.",
"kit.in_use": "{path} đang được sử dụng. Hãy đóng trò chơi và mọi cửa sổ cài đặt hoặc biên dịch lại đang mở, rồi chạy lại trình cài đặt.",
"kit.copy_failed": "Không thể sao chép bộ công cụ biên dịch vào {path}: {detail}",
"compile.exe_locked": "Không thể ghi {path}: một chương trình khác đang giữ tệp này, có thể là trò chơi được khởi động từ thư mục đó hoặc phần mềm diệt virus đã gắn cờ tệp. Hãy đóng trò chơi, thêm thư mục trình cài đặt và thư mục cài đặt vào danh sách loại trừ của phần mềm diệt virus, khởi động lại Windows, rồi chạy lại trình cài đặt. Chi tiết: {log}",
"prepare.xlate_in_use": "{path} đang được sử dụng. Hãy đóng trò chơi, kết thúc mọi tiến trình totk_xlate còn sót lại từ lần chạy trước, rồi chạy lại trình cài đặt.",
"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}",
"warn.lang_needs_fonts": "Văn bản bằng {lang} cần phông chữ hệ thống của Switch, nhưng chưa có phông chữ nào được cung cấp. Trò chơi sẽ không khởi động bằng ngôn ngữ này cho đến khi chúng được thêm vào. Hãy chọn thư mục firmware (Contents/registered), hoặc xem mục \"Switch system fonts\" trong docs/installer.md.",
"warn.npdm_differs": "main.npdm khác với bản dump tham chiếu {version}; chỉ các mô-đun mã được sử dụng.",
"warn.cheats_skipped": "Không thể biên dịch các cheat trong thư mục mods có thay đổi mã của trò chơi; trò chơi sẽ được cài đặt mà không có chúng. Chi tiết: {log}",
"warn.exefs_skipped": "Không thể biên dịch các bản vá ExeFS của mod (.ips, .pchtxt); trò chơi sẽ được cài đặt mà không có chúng. Chi tiết: {log}",
"warn.plugins_skipped": "Không thể biên dịch các plugin mã của mod (exefs subsdk); trò chơi sẽ được cài đặt mà không có chúng. Chi tiết: {log}",
"warn.xbox_prompts_failed": "Không thể chuẩn bị biểu tượng nút Xbox, PlayStation hoặc PC (mã thoát {code}); trò chơi giữ biểu tượng nút của Switch. Chi tiết: {log}",
"warn.shaders_skipped": "Trình điều khiển đồ họa bị lỗi khi biên dịch một số shader, nên {count} shader đã bị bỏ qua khi chuẩn bị. Trò chơi sẽ biên dịch chúng khi cần đến lần đầu, và trình điều khiển cũng có thể bị lỗi ở đó; cập nhật trình điều khiển có thể khắc phục điều này. Chi tiết: {log}",
"warn.kernel_old": "Linux {version} thiếu tính năng theo dõi ghi (write tracking) mà trò chơi cần (6.7 trở lên); trò chơi có thể chạy rất chậm. Cập nhật hệ thống sẽ khắc phục điều này.",
"warn.dlss_kept": "Thư mục cài đặt đã có một thư viện DLSS ({path}); trình cài đặt giữ nguyên thư viện đó.",
"warn.dlss_download_failed": "Không thể tải xuống NVIDIA DLSS từ {url}: {detail}. Trò chơi vẫn chạy mà không có DLSS; lần chạy trình cài đặt tiếp theo sẽ thử lại.",
"warn.fsr_kept": "Thư mục cài đặt đã có một thư viện FSR ({path}); trình cài đặt giữ nguyên các thư viện đó.",
"warn.fsr_download_failed": "Không thể tải xuống AMD FSR 4 từ {url}: {detail}. Trò chơi vẫn chạy mà không có nó; lần chạy trình cài đặt sau sẽ thử lại.",
"ui.title": "Cài đặt TotK",
"ui.rebuild_title": "Biên dịch lại trò chơi cho các mod của bạn",
"ui.start_game": "Khởi động trò chơi",
"ui.version": "phiên bản {version}",
"ui.intro": "Tạo một thư mục Tears of the Kingdom có thể chơi được từ chính các tệp trò chơi của bạn. Quá trình này mất khá nhiều thời gian và chỉ chạy một lần.",
"ui.notice": "Thư mục do trình cài đặt này tạo ra có chứa trò chơi. Thư mục này chỉ dành cho mục đích sử dụng cá nhân; không chia sẻ hoặc tải lên.",
"ui.keys_private": "Tệp khóa được đọc tại chỗ. Nội dung của tệp không bao giờ được hiển thị, sao chép hoặc lưu trữ.",
"ui.base": "Trò chơi gốc",
"ui.update": "Bản cập nhật",
"ui.keys": "prod.keys",
"ui.firmware": "Firmware (tùy chọn)",
"ui.game_language": "Ngôn ngữ trò chơi",
"ui.dest": "Thư mục cài đặt",
"ui.browse": "Duyệt...",
"ui.pick_game": "Chọn tệp trò chơi gốc",
"ui.pick_update": "Chọn tệp cập nhật 1.1.0 hoặc 1.2.1 hoặc 1.4.3",
"ui.pick_keys": "Chọn prod.keys",
"ui.pick_firmware": "Chọn thư mục firmware của Switch (Contents/registered)",
"ui.pick_dest": "Chọn thư mục cài đặt",
"ui.firmware_help": "Dành cho văn bản tiếng Trung Giản thể, tiếng Hàn và tiếng Trung Phồn thể: thư mục Contents/registered của firmware, ví dụ từ Ryujinx hoặc Yuzu. Trình cài đặt sẽ sao chép phông chữ hệ thống của Switch từ đó vào thư mục cài đặt.",
"ui.dlss": "Tải xuống NVIDIA DLSS (nvngx_dlss.dll) cho card đồ họa NVIDIA RTX",
"ui.dlss_help": "Từ DLSS SDK của NVIDIA trên GitHub, theo giấy phép RTX SDK của NVIDIA (github.com/NVIDIA/DLSS). Thư viện này giúp các tùy chọn dlaa và DLSS hoạt động; nếu không có, các tùy chọn đó không có tác dụng.",
"ui.fsr": "Tải xuống AMD FSR 4 (thư viện FSR SDK của AMD) cho card đồ họa AMD Radeon",
"ui.fsr_help": "Từ FSR SDK của AMD trên GitHub, theo giấy phép FSR SDK của AMD (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Thư viện này giúp lựa chọn AMD FSR 4 cho bộ nâng độ phân giải cảnh 3D hoạt động trên các card Radeon mà thư viện của AMD hỗ trợ FSR 4; nếu không có, lựa chọn đó không có tác dụng. Được chọn sẵn khi máy có card đồ họa AMD.",
"ui.compressed_help": "Các tệp nén NSZ và XCZ dùng được ngay: trình cài đặt tự giải nén chúng (cho đến khi dữ liệu trò chơi được trích xuất xong, cần dung lượng trống bằng dung lượng của các tệp sau khi giải nén).",
"ui.section_files": "Tệp trò chơi",
"ui.section_install": "Cài đặt",
"ui.more_details": "▸ Xem thêm chi tiết",
"ui.fewer_details": "▾ Ẩn chi tiết",
"ui.formats_help": "Trò chơi gốc: NSP, XCI, NSZ hoặc XCZ. Bản cập nhật: 1.1.0, 1.2.1 hoặc 1.4.3, dạng NSP hoặc NSZ.",
"ui.type_game": "Tệp trò chơi (NSP, XCI, NSZ, XCZ)",
"ui.type_keys": "Tệp khóa (*.keys)",
"ui.type_all": "Tất cả các tệp",
"ui.start": "Bắt đầu",
"ui.cancel": "Hủy",
"ui.cancelling": "Đang hủy...",
"ui.show_log": "Hiện nhật ký",
"ui.hide_log": "Ẩn nhật ký",
"ui.close": "Đóng",
"ui.back": "Quay lại",
"ui.open_folder": "Mở thư mục",
"ui.update_mode": "Thư mục này có một bản cài đặt trước đó. Trình cài đặt sẽ tiếp tục hoặc cập nhật bản cài đặt đó; các tệp trò chơi chỉ được yêu cầu nếu cần dùng lại.",
"ui.need_dest": "Hãy chọn thư mục cài đặt.",
"ui.need_base": "Hãy chọn tệp trò chơi gốc.",
"ui.need_update": "Hãy chọn tệp cập nhật 1.1.0 hoặc 1.2.1 hoặc 1.4.3.",
"ui.need_keys": "Hãy chọn tệp prod.keys.",
"ui.need_lang": "Hãy chọn ngôn ngữ trò chơi.",
"ui.missing_base": "Tệp trò chơi gốc không tồn tại.",
"ui.missing_update": "Tệp cập nhật không tồn tại.",
"ui.missing_keys": "Tệp khóa không tồn tại.",
"ui.missing_firmware": "Thư mục firmware không tồn tại.",
"ui.running_install": "Đang cài đặt",
"ui.running_resume": "Đang tiếp tục lần cài đặt trước",
"ui.running_update": "Đang cập nhật bản cài đặt",
"ui.state_started": "đã bắt đầu",
"ui.state_done": "xong",
"ui.state_skipped": "đã bỏ qua",
"ui.state_pending": "đang chờ",
"ui.state_running": "đang chạy",
"ui.state_failed": "thất bại",
"ui.log_warning": "Cảnh báo",
"ui.log_error": "Lỗi",
"ui.log_space": "Dung lượng cần: {need} GB, còn trống: {free} GB",
"ui.log_end": "Đã hoàn tất",
"ui.result_ok": "Trò chơi đã sẵn sàng",
"ui.result_failed": "Cài đặt không thành công",
"ui.result_cancelled": "Đã hủy cài đặt",
"ui.done_text": "Hãy khởi động {game_exe} từ {dest}. Chương trình cài đặt và các tệp trò chơi bạn đã chọn không còn cần thiết nữa.",
"ui.cancelled_text": "Các bước đã hoàn tất được giữ lại. Hãy chạy lại trình cài đặt với cùng thư mục để tiếp tục.",
"ui.log_file": "Tệp nhật ký: {path}",
"ui.process_died": "Trình cài đặt đã dừng đột ngột (mã thoát {code}).",
"ui.confirm_cancel": "Trình cài đặt đang chạy. Hủy cài đặt và đóng cửa sổ?",
"ui.space_one": "Dung lượng trống cần có trên {path}: {need} GB (còn trống: {free} GB).",
"ui.space_two": "Dung lượng trống cần có trên {path}: {need} GB (còn trống: {free} GB); trên {temp}: {temp_need} GB (còn trống: {temp_free} GB).",
"ui.amount_bytes": "{done} / {total} GB",
"ui.amount_chunks": "{done} / {total} phần",
"ui.amount_objects": "{done} / {total} tệp",
"ui.amount_shaders": "{done} / {total} shader",
"ui.amount_other": "{done} / {total} {unit}",
"ui.seconds": "{n} giây",
"param.input.base": "trò chơi gốc",
"param.input.update": "cập nhật",
"param.input.keys": "khóa",
"launcher.title": "Cài đặt TotK",
"launcher.python_missing": "Các tệp cài đặt không đầy đủ: thiếu thư mục python bên cạnh TotK-Setup.exe. Hãy giải nén lại toàn bộ tệp lưu trữ và khởi động TotK-Setup.exe từ thư mục đã giải nén.",
"lang.ja": "Tiếng Nhật",
"lang.en-US": "Tiếng Anh (Mỹ)",
"lang.en-GB": "Tiếng Anh (Anh)",
"lang.fr": "Tiếng Pháp",
"lang.fr-CA": "Tiếng Pháp (Canada)",
"lang.de": "Tiếng Đức",
"lang.it": "Tiếng Ý",
"lang.es": "Tiếng Tây Ban Nha",
"lang.es-419": "Tiếng Tây Ban Nha (Mỹ Latinh)",
"lang.nl": "Tiếng Hà Lan",
"lang.pt": "Tiếng Bồ Đào Nha",
"lang.pt-BR": "Tiếng Bồ Đào Nha (Brazil)",
"lang.ru": "Tiếng Nga",
"lang.ko": "Tiếng Hàn",
"lang.zh-Hans": "Tiếng Trung (Giản thể)",
"lang.zh-Hant": "Tiếng Trung (Phồn thể)"
}
+12
View File
@@ -9,6 +9,7 @@
"step.pc_prompts": "绘制键盘和鼠标按键提示",
"step.shapes": "为你的显示器调整游戏画面布局",
"step.dlss": "下载 NVIDIA DLSS",
"step.fsr": "下载 AMD FSR 4",
"step.cleanup": "清理",
"phase.check.host": "检查处理器和显卡",
@@ -40,6 +41,7 @@
"phase.prepare.pack": "将着色器缓存打包成一个文件",
"phase.shapes.layouts": "为每种显示器比例写入画面布局和按键提示",
"phase.dlss.download": "从 NVIDIA 的 DLSS SDK 下载 nvngx_dlss.dll",
"phase.fsr.download": "从 AMD 的 FSR SDK 下载 FSR 4 库",
"phase.cleanup.ini": "写入 totk.ini",
"phase.cleanup.temp": "删除临时文件",
@@ -57,10 +59,15 @@
"check.toolchain_broken": "自带的编译器无法工作:{detail}",
"check.glibc_old": "此系统的 C 库为 glibc {version};安装程序的编译器需要 {need} 或更新版本(Ubuntu 22.04、Debian 12、Fedora 35、SteamOS 3 及更新版本都满足)。更新系统即可解决。",
"check.host_probe_failed": "电脑检查未能运行(退出代码 {code})。",
"check.host_blocked": "Windows 阻止了安装程序在这台电脑上编译的程序({path}):{detail}。智能应用控制、App Control 策略或杀毒软件会阻止未签名的程序;游戏本身也以同样方式在这台电脑上编译,同样会被阻止。请在杀毒软件中允许安装程序所在的文件夹,或在 Windows 安全中心(应用和浏览器控制)中关闭智能应用控制,然后重新运行安装程序。",
"check.vulkan_crash": "安装程序向显卡驱动查询显卡时,驱动崩溃了(退出代码 {code}),关闭其他程序的 Vulkan 层后依然如此。请为你的显卡安装最新的驱动程序。",
"check.vulkan_layer_crash": "另一个程序安装的 Vulkan 层会让这台电脑上的 Vulkan 程序崩溃(退出代码 {code}),游戏启动时也会同样崩溃。该层:{layers}。请更新或卸载它所属的程序(路径显示了它的文件夹),或者关闭该层:为你的用户帐户设置环境变量 VK_LOADER_LAYERS_DISABLE,值为 {disable}。然后重新运行安装程序。",
"check.vulkan_layers_crash": "另一个程序安装的 Vulkan 层会让这台电脑上的 Vulkan 程序崩溃(退出代码 {code}):关闭所有此类层后检查通过,开着它们时游戏启动也会同样崩溃。逐个关闭已安装的层未能找出是哪一个。已安装的层:{layers}。请更新或卸载其中的叠加层、录制或调校程序,或者关闭所有此类层:为你的用户帐户设置环境变量 VK_LOADER_LAYERS_DISABLE,值为 ~implicit~(这也会在所有 Vulkan 游戏中关闭 Steam 等叠加层)。然后重新运行安装程序。",
"check.cpu_too_old": "此处理器不支持 x86-64-v2(SSE4.2、POPCNT 和 CMPXCHG16B),这是游戏所需的最低指令集。Intel Nehalem(2008 年)或 AMD Bulldozer(2011 年)及更新的处理器都支持。",
"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}",
@@ -104,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}",
@@ -118,6 +126,8 @@
"warn.kernel_old": "Linux {version} 缺少游戏依赖的写入跟踪功能(需要 6.7 或更新版本);游戏可能运行得很慢。更新系统即可解决。",
"warn.dlss_kept": "安装文件夹中已有 DLSS 库({path});安装程序将保留它。",
"warn.dlss_download_failed": "无法从 {url} 下载 NVIDIA DLSS:{detail}。游戏无需它也能运行;下次运行安装程序时会重试。",
"warn.fsr_kept": "安装文件夹中已有 FSR 库({path});安装程序将保留其中的库。",
"warn.fsr_download_failed": "无法从 {url} 下载 AMD FSR 4:{detail}。游戏无需它也能运行;下次运行安装程序时会重试。",
"ui.title": "TotK 安装程序",
"ui.rebuild_title": "正在为你的模组重新构建游戏",
@@ -141,6 +151,8 @@
"ui.firmware_help": "用于中文、韩文和繁体中文文本:固件的 Contents/registered 文件夹,例如来自 Ryujinx 或 Yuzu。安装程序会从中把 Switch 系统字体复制到安装文件夹。",
"ui.dlss": "为 NVIDIA RTX 显卡下载 NVIDIA DLSS(nvngx_dlss.dll)",
"ui.dlss_help": "来自 GitHub 上 NVIDIA 的 DLSS SDK,遵循 NVIDIA RTX SDK 许可(github.com/NVIDIA/DLSS)。没有它,dlaa 和 DLSS 设置不起作用。",
"ui.fsr": "为 AMD Radeon 显卡下载 AMD FSR 4(AMD 的 FSR SDK 库)",
"ui.fsr_help": "来自 GitHub 上 AMD 的 FSR SDK,遵循 AMD FSR SDK 许可(github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK)。有了这些库,3D 场景超分中的 AMD FSR 4 选项才能在 AMD 库提供 FSR 4 的 Radeon 显卡上工作;没有它们,该选项不起作用。电脑装有 AMD 显卡时默认勾选。",
"ui.compressed_help": "压缩的 NSZ 和 XCZ 文件可以直接使用:安装程序会自行解压(在游戏数据提取完成之前,需要与解压后文件大小相同的可用空间)。",
"ui.section_files": "游戏文件",
"ui.section_install": "安装",
+50 -8
View File
@@ -15,6 +15,11 @@ definitions then also write it.
A read that can see flags a callee left reads the caller's flags from before the call instead. AAPCS64 code never
reads a callee's flags, so such a read only sits on a path that does not run: in TotK it follows calls to noreturn
functions (asserts) that the compiler placed before another branch's target. Plan.after_call counts them.
A mod plugin's inline hook breaks that rule. exlaunch's exl_inline_hook_impl saves and restores x0..x29 around the
callback but not NZCV, so the hooked game code goes on with the flags the callback left (Challenge Mode's callbacks end
in a cmp, and the b.eq at their sites follows it). So in a plugin module flags pass through calls and returns (plan's
`through`), and a hook site takes the flags the stub's call left (plan's `hooks`).
"""
import re
@@ -26,7 +31,7 @@ NZ_DEF = 'c->nzcv = '
NZ_USE = '(c->nzcv)'
KIND_NAME = {'subs': 'sub', 'adds': 'add', 'logic': 'logic'}
ENTRY, CALL = 'entry', 'call'
ENTRY, CALL, HOOK = 'entry', 'call', 'hook' # HOOK: (HOOK, i), the callback's flags at hook site i
class FlagError(Exception):
@@ -55,6 +60,8 @@ class Plan:
self.reader = [None] * n
self.pack = [False] * n
self.exit = [None] * n # kind of the flags to publish in c->nzcv at a tail exit, or None
self.pre = [None] * n # kind of the flags to publish before a call whose callee sees them, or None
self.takes = [False] * n # the call leaves its callee's flags (F.nz from c->nzcv after it)
self.entry = False # F.nz starts as c->nzcv: flags from the entry reach a read or an exit
self.entry_read = False # they reach a read, not only an exit
self.after_call = 0 # reads that can see flags a callee left (see the module docstring)
@@ -69,6 +76,16 @@ class Plan:
k = self.exit[i]
return f'c->nzcv = fnz_{k}(&F); ' if k else ''
def give(self, i):
"""Statement writing the flags to c->nzcv before instruction i's call, whose callee sees them (plan's through
and hooks; '' when it need not)."""
k = self.pre[i]
return f'c->nzcv = fnz_{k}(&F); ' if k else ''
def take(self, i):
"""Statement taking the flags the callee of instruction i's call left (plan's through and hooks)."""
return ' F.nz = c->nzcv;' if self.used and self.takes[i] else ''
def rewrite(self, i, code):
"""code of instruction i with its flag reads and writes on F."""
rk = self.reader[i]
@@ -91,7 +108,7 @@ class Plan:
return code
def plan(effects, succ, calls, exits):
def plan(effects, succ, calls, exits, through=(), hooks=()):
"""effects[i]: (reads, kind or None); succ[i]: successor indices inside the function; calls: indices of calls,
whose callee may leave any flags; exits: indices that can leave for another function other than by a call or a
return (a tail branch, falling into the next function, a br through rt_dispatch).
@@ -99,25 +116,41 @@ def plan(effects, succ, calls, exits):
Discovery can start a function inside another one (a branch target, a materialised address), and the code
before it then falls or branches into it with live flags. So a tail exit publishes the flags in c->nzcv, and a
function whose reads can see its entry flags starts F.nz from c->nzcv. Calls and returns publish nothing: AAPCS64
code neither passes flags to a callee nor reads a callee's, so a call's flags count as no definition."""
code neither passes flags to a callee nor reads a callee's, so a call's flags count as no definition.
through: calls whose flags pass both ways (a plugin module, see the module docstring; its returns are in exits):
each publishes the flags before the call (Plan.give) and defines F.nz from c->nzcv after it (Plan.take).
hooks: patched sites with a plugin inline hook before the site's own word, when the hook's set is on: the hook
publishes the flags before its call and leaves the callback's after it, which the site's own word reads unless it
writes flags itself. With the set off the flags are the ones before the site, so what follows can see both."""
n = len(effects)
p = Plan(n)
if not any(r or k for r, k in effects):
return p
p.used = True
hooks = set(hooks) - set(calls) # a hook before a bl: the bl's callee leaves the flags
reach = [set() for _ in range(n)]
reach[0].add(ENTRY)
work = [0]
while work:
i = work.pop()
out = {i} if effects[i][1] else ({CALL} if i in calls else reach[i])
if effects[i][1] or i in through:
out = {i}
elif i in calls:
out = {CALL}
elif i in hooks:
out = reach[i] | {(HOOK, i)}
else:
out = reach[i]
for s in succ[i]:
if not out <= reach[s]:
reach[s] |= out
work.append(s)
def kind(d):
return 'nz' if d == ENTRY else effects[d][1]
if d == ENTRY or isinstance(d, tuple):
return 'nz'
return effects[d][1] or 'nz' # a through call leaves its callee's flags packed
def use(r):
"""Kind a use of the definitions r reads; several kinds read the packed form, which they then all write."""
@@ -127,18 +160,27 @@ def plan(effects, succ, calls, exits):
if len(kinds) == 1:
return kinds.pop()
for d in r:
if d != ENTRY:
if isinstance(d, int) and effects[d][1]:
p.pack[d] = True
return 'nz' # several kinds, or none (unreachable)
def seen(i):
"""What a read or an exit at instruction i sees: at a hook site also the callback's flags."""
return reach[i] | {(HOOK, i)} if i in hooks else reach[i]
for i, (reads, _) in enumerate(effects):
if reads:
p.after_call += CALL in reach[i]
p.reader[i] = use(reach[i] - {CALL})
p.reader[i] = use(seen(i) - {CALL})
p.entry_read |= ENTRY in reach[i]
for i in exits:
# Entry flags alone are still in c->nzcv.
r = reach[i] - {CALL}
r = seen(i) - {CALL}
if r and r != {ENTRY}:
p.exit[i] = use(r)
for i in set(through) | hooks:
p.takes[i] = True
r = reach[i] - {CALL}
if r and r != {ENTRY}:
p.pre[i] = use(r)
return p
+96 -35
View File
@@ -96,10 +96,13 @@ def orig_name(a):
def open_module(name, path, base, table, plugin=False):
"""Module name for lifting: a plugin with a `plugin` line of the patch table (recomp/patches.py) is lifted from its
image after the init, its inline-hook stubs returning where they would branch to their trampolines."""
image after the init, its inline-hook stubs returning where they would branch to their trampolines. A game module's
`entry` lines are function starts of its lift."""
p = table.plugins.get(name)
if not p:
return Module(name, path, base, 'c', plugin=plugin)
mod = Module(name, path, base, 'c', plugin=plugin)
mod.entries = sorted(base + o for o in table.entries.get(name, ()))
return mod
image = Path(p['image']).read_bytes()
mod = Module(name, path, base, 'c', plugin=True, image=image, rets=[o + 12 for o in p['stubs']],
seeds=sorted(p['stubs'] | p['seeds']))
@@ -195,24 +198,58 @@ def discover(mod):
stats = {'seeds': int(len(seeds)), 'bl_targets': int(len(np.unique(bl_tgt))),
'materialised_targets': int(len(np.unique(mat))), 'initial_starts': int(len(starts))}
rounds = 0
while True:
rounds += 1
f = np.searchsorted(starts, br_src, side='right') - 1
live = f >= 0
f = np.where(live, f, 0)
lo = starts[f]
hi = np.where(f + 1 < len(starts), starts[np.minimum(f + 1, len(starts) - 1)], n)
out = live & ((br_tgt < lo) | (br_tgt >= hi))
new = np.setdiff1d(br_tgt[out], starts, assume_unique=False)
if not len(new):
break
starts = np.union1d(starts, new)
stats['rounds'] = rounds
def close(starts):
rounds = 0
while True:
rounds += 1
f = np.searchsorted(starts, br_src, side='right') - 1
live = f >= 0
f = np.where(live, f, 0)
lo = starts[f]
hi = np.where(f + 1 < len(starts), starts[np.minimum(f + 1, len(starts) - 1)], n)
out = live & ((br_tgt < lo) | (br_tgt >= hi))
new = np.setdiff1d(br_tgt[out], starts, assume_unique=False)
if not len(new):
return starts, rounds
starts = np.union1d(starts, new)
starts, stats['rounds'] = close(starts)
entries = getattr(mod, 'entries', ())
if entries:
extra = entry_starts(mod, starts, entries, br)
stats['entries'] = len(entries)
starts, more = close(np.union1d(starts, (np.asarray(sorted(extra), dtype=np.int64) - pc0) >> 2))
stats['rounds'] += more
stats['functions'] = int(len(starts))
return starts, stats
def entry_starts(mod, starts, entries, br):
"""The function starts mod's `entry` addresses add (recomp/patches.py): each entry, and every target of the jump
tables of the function that held it. A table whose cases fell on both sides of the new boundary would reach the
cases outside its function through rt_dispatch, which only enters function starts; with every case a start, the
table's br dispatches to them (the all-label fallback). An unresolved computed br there gets a warning: its targets
are not known, so a case past the entry would stop the game with a named fatal."""
out, pc0 = set(), mod.lo
for e in entries:
if not mod.in_text(e):
raise SystemExit(f'{mod.name}: the entry {e:#x} is outside its .text')
k = int(np.searchsorted(starts, (e - pc0) >> 2, side='right')) - 1
lo = pc0 + int(starts[k]) * 4
hi = pc0 + int(starts[k + 1]) * 4 if k + 1 < len(starts) else mod.hi
out.add(e)
if e == lo:
continue
for i in br[(br >= (lo - pc0) >> 2) & (br < (hi - pc0) >> 2)].tolist():
jt = jumptables.resolve(mod, pc0 + 4 * i, lo, hi)
if jt:
out.update(jt)
elif jumptables.is_computed(mod, pc0 + 4 * i, lo):
print(f'{mod.name}: warning: the entry {e:#x} lies in the function {lo:#x} with an unresolved table '
f'jump at {pc0 + 4 * i:#x}', flush=True)
return out
def estimate_sizes(mod, starts):
"""Estimated bytes of C per function (for chunking only; the manifest records the real sizes)."""
w = mod.words
@@ -316,7 +353,8 @@ class Emitter:
def replacements(self, a):
"""The lifted words of each alternative of the patched site a, in set order. Only the last word of an
alternative may branch (bl, b, b.cond / cbz / tbz, ret)."""
alternative may branch (bl, blr, b, b.cond / cbz / tbz, ret); a blr is a site's own word kept after an inline
hook."""
out = []
for _, words in self.patched[a]:
# ('call', target): a plugin's inline hook (recomp/patches.py @call), before the site's own instruction
@@ -325,7 +363,7 @@ class Emitter:
last = j == len(lifted) - 1
if r.kind == 'hook' and not last:
continue
if r.kind != 'op' and not (last and r.kind in ('bl', 'b', 'bcond', 'ret')):
if r.kind != 'op' and not (last and r.kind in ('bl', 'blr', 'b', 'bcond', 'ret')):
raise patches.PatchError(f'{a:#x}: replacement word {words[j]:08x} is a {r.kind}')
out.append(lifted)
return out
@@ -363,7 +401,7 @@ class Emitter:
def flag_plan(self, insns, entry, end, tables, succ):
"""recomp/flags.py plan for the function: each instruction's flag use over the flow succ (flow())."""
n = len(insns)
calls, effects, exits = set(), [], {n}
calls, effects, exits, hooks = set(), [], {n}, set()
for i, ins in enumerate(insns):
k, a = ins.kind, entry + 4 * i
if k in ('bl', 'blr'):
@@ -372,34 +410,45 @@ class Emitter:
exits.add(i)
elif k == 'br':
exits.add(i) # through rt_dispatch, also a table's default
elif k == 'ret' and self.mod.plugin:
exits.add(i) # a plugin's caller sees the flags it leaves (recomp/flags.py)
if a in self.patched:
effects.append(self.patched_effect(ins, a))
for words in self.replacements(a):
r = words[-1]
if r.kind == 'bl':
if r.kind in ('bl', 'blr'):
calls.add(i)
elif r.kind in ('b', 'bcond') and not entry <= r.target < end:
exits.add(i)
if any(w.kind == 'hook' for w in words):
hooks.add(i)
else:
effects.append(flags.effect(ins.cond if k == 'bcond' else ins.code or ''))
effects.append((False, None))
return flags.plan(effects, succ, calls, exits)
return flags.plan(effects, succ, calls, exits, through=calls if self.mod.plugin else (), hooks=hooks)
def patched_effect(self, ins, a):
"""Flag effect of a patched site: every alternative (the original and each replacement) must write the same
flags, in at most one word each; the site reads flags when any alternative does (a b.cond reads them)."""
flags, in at most one word each; the site reads flags when any alternative does (a b.cond reads them).
An alternative that only branches out of the module (a plugin's branch hook, whose trampoline runs the
original word) counts for none: it leaves with the flags from before the site, which its tail exit publishes
(flags.plan), and nothing after the site in this function sees it."""
alts = []
for words in [[ins]] + self.replacements(a):
for k, words in enumerate([[ins]] + self.replacements(a)):
fx = [flags.effect(w.code or '') if w.kind == 'op' else flags.effect(w.cond) for w in words
if w.kind in ('op', 'bcond')]
fx = [e for e in fx if e[0] or e[1]]
if len(fx) > 1:
raise patches.PatchError(f'{a:#x}: several flag-using words in one alternative')
last = words[-1]
if k and not fx and last.kind == 'b' and not self.mod.lo <= last.target < self.mod.hi:
continue
alts.append(fx[0] if fx else (False, None))
if any(e[1] != alts[0][1] for e in alts):
raise patches.PatchError(f'{a:#x}: the alternatives write different flags ({[e[1] for e in alts]})')
reads = any(e[0] for e in alts)
if (alts[0][1] or reads) and (ins.kind == 'bl' or any(w[-1].kind == 'bl' for w in self.replacements(a))):
if (alts[0][1] or reads) and (ins.kind in ('bl', 'blr') or
any(w[-1].kind in ('bl', 'blr') for w in self.replacements(a))):
raise patches.PatchError(f'{a:#x}: a patched call that uses flags')
return reads, alts[0][1]
@@ -450,6 +499,12 @@ class Emitter:
def publish(i):
return fp.publish(i) if fp and fp.used else ''
def give(i): # flags a plugin's callee or a hook's callback sees (recomp/flags.py plan's through, hooks)
return fp.give(i) if fp and fp.used else ''
def take(i): # flags that callee or callback left
return fp.take(i) if fp and fp.used else ''
def jump(t, i):
if entry <= t < end:
return f'goto L_{t:x};'
@@ -478,12 +533,12 @@ class Emitter:
if fp.used:
out.append(' ' + fp.decl())
def call(t, a):
def call(t, a, i):
if t in starts:
refs.add(t)
return f'c->x[30] = {hx(a + 4)}; {spill}{fname(t)}(c);{reload_call}'
return f'{give(i)}c->x[30] = {hx(a + 4)}; {spill}{fname(t)}(c);{reload_call}{take(i)}'
self.stats['external_calls'] += 1
return f'c->x[30] = {hx(a + 4)}; {spill}c->pc = {hx(t)}; rt_dispatch(c);{reload_call}'
return f'{give(i)}c->x[30] = {hx(a + 4)}; {spill}c->pc = {hx(t)}; rt_dispatch(c);{reload_call}{take(i)}'
def op(i, code):
code = fx(i, code)
@@ -494,25 +549,29 @@ class Emitter:
if r.kind == 'op':
return op(i, r.code)
if r.kind == 'bl':
return call(r.target, a)
return call(r.target, a, i)
if r.kind == 'b':
return jump(r.target, i)
if r.kind == 'bcond':
return f'if ({fx(i, r.cond)}) {{ {jump(r.target, i)} }}'
if r.kind == 'ret':
return f'{spill}return;'
if r.kind == 'blr': # an original call through a register (a plugin hooks Zonai Fieldworks' blr x8 sites)
return (f'{give(i)}c->pc = {r.target}; c->x[30] = {hx(a + 4)}; {spill}rt_dispatch(c);{reload_call}'
f'{take(i)}')
if r.kind == 'hook':
# a call that writes no x30, the whole Cpu current before it and read back after it: the stub saves and
# restores x30 itself, and the callback may change any register through exlaunch's hook context
# exlaunch's hook impl saves no NZCV: the callback sees the flags and the site goes on with its own
refs.add(r.target)
self.stats['plugin_hook_calls'] += 1
return f'{spill}{fname(r.target)}(c);{reload}'
return f'{give(i)}{spill}{fname(r.target)}(c);{reload}{take(i)}'
raise patches.PatchError(f'{a:#x}: patched instruction is a {r.kind}')
def patch(i, ins, a):
"""if (switch) { replacement } else if ... else { original } for a patched site (recomp/patches.py); an
ordered set of a contested site tests the site's pick byte instead of its switch."""
if ins.kind not in ('op', 'bl', 'b', 'bcond'):
if ins.kind not in ('op', 'bl', 'blr', 'b', 'bcond'):
raise patches.PatchError(f'{a:#x}: patched instruction is a {ins.kind}')
line = ' '
n, values = self.picks.get(a, (None, {}))
@@ -548,9 +607,10 @@ class Emitter:
self.stats['spin_gates'] += 1
emit(i, ' ' + j if k == 'b' else f' if ({fx(i, ins.cond)}) {{ {j} }}')
elif k == 'bl':
emit(i, ' ' + call(ins.target, a))
emit(i, ' ' + call(ins.target, a, i))
elif k == 'blr':
emit(i, f' c->pc = {ins.target}; c->x[30] = {hx(a + 4)}; {spill}rt_dispatch(c);{reload_call}')
emit(i, f' {give(i)}c->pc = {ins.target}; c->x[30] = {hx(a + 4)}; {spill}rt_dispatch(c);{reload_call}'
f'{take(i)}')
elif k == 'br':
jt = tables.get(a)
if jt == 'all':
@@ -562,7 +622,7 @@ class Emitter:
else:
emit(i, f' {publish(i)}{spill}c->pc = {ins.target}; {MUSTTAIL} rt_dispatch(c);')
elif k == 'ret':
emit(i, f' {spill}return;')
emit(i, f' {publish(i)}{spill}return;')
else:
raise ValueError(f'{a:#x}: unknown instruction kind {k!r}')
n = len(insns)
@@ -992,8 +1052,9 @@ def main():
n = len(starts) if not args.limit else min(args.limit, len(starts))
ends = np.append(abs_starts[1:], mod.hi)
chunks = partition(est[:n], args.chunk_fns, args.chunk_bytes, args.big_fn)
missing = sorted(base + o for o in (table.plugins.get(name) or {}).get('seeds', ())
if base + o not in set(abs_starts.tolist()))
# a seed that is an `orig` trampoline counts as found: dispatch takes its address to the function's copy
missing = sorted(base + o for o in set((table.plugins.get(name) or {}).get('seeds', ())) |
table.entries.get(name, set()) if base + o not in set(abs_starts.tolist()) | set(extra))
if missing:
raise SystemExit(f'{name}: the seeds {", ".join(hex(a) for a in missing)} are no function starts')
mkey = module_key(gen_key, name, path, base, abs_starts)
+12
View File
@@ -1209,3 +1209,15 @@ site ability main 1622bf4 b4000155 aa0903f5 b4000155 # cbz x21 -> mov x21, x9;
# the game with the set off in two runs of two, a pause of 1 s in none of one.
set audiodrain TOTK_AUDIO_DRAIN_FIX 1
site audiodrain main 883780 17fffee6 17fffeda # b 0x883318 -> b 0x8832e8
# Thunderstorm lightning (issue #1287): as in patches-v143.txt, the same update (main+0xab849c, called from
# main+0xab7cf4) with the same chances and timers. The sites are the loads of 0.013333 (distant bolt) and of 0.01 (state
# 1, both draws through s9, which the prologue saves; state 5). The time object is loaded as the game's own trampoline
# check does (main+0xbda4bc): its global through the GOT slot main+0x462e038, then +0xc8. After each site x10, s2 and s3
# are written, or a call comes, before any read.
set lightning TOTK_LIGHTNING_FIX 1
site lightning main ab8d50 bd43fd01 bd43fd01 d001dbaa f9401d4a f940014a f940654a bd403942 1e2e1003 1e237842 1e220821 # ldr s1, [x8, #0x3fc] (0.013333)
site lightning main ab9014 bd46f109 bd46f109 b001dbaa f9401d4a f940014a f940654a bd403942 1e2e1003 1e237842 1e220929 # ldr s9, [x8, #0x6f0] (0.01)
site lightning main ab8f90 bd46f101 bd46f101 d001dbaa f9401d4a f940014a f940654a bd403942 1e2e1003 1e237842 1e220821 # ldr s1, [x8, #0x6f0] (0.01)
# each: the game's load; adrp x10, main+0x462e000; ldr x10, [x10, #0x38]; ldr x10, [x10]; ldr x10, [x10, #0xc8];
# ldr s2, [x10, #0x38] (ratio); fmov s3, #1.0; fminnm s2, s2, s3; fmul (chance * ratio)
+28
View File
@@ -1251,3 +1251,31 @@ site shutter main 25e55d0 bc605900 bc605900 f9402ea9 927ef529 39400129 1e230123
# keep their numbers.
set freecam TOTK_FREECAM_PATCH 0
site freecam main 6286d4 f9400e68 94d2de1f # ldr x8, [x19, #0x18]
# Thunderstorm lightning (issue #1287). While the current weather type has IsThunder (main+0x62a40c), the world
# manager's lightning update (main+0x62aac4, called once per frame from main+0x62a310) runs a state machine whose times
# advance by the world's frame step: near strikes for 150 to 450 units (state 1), a phase main+0x21c34d0 ends (2), 30
# and 240 units without (3, 4), then 1 again; 5 takes over from 1 when main+0x21d2930 returns false and leads back to 0.
# On top of it the update draws, each update, a random number in [0, 1) for each of three fixed chances: 0.013333 in
# every state but 0 for a distant bolt (bit 0 of its +8 flags, which main+0x58b4d8 hands to the environment, where
# main+0x69fb98 starts the effect Far_Lightning 2000 m from the camera along its view, picked by main+0x21c3940), 0.01
# in state 1 to pick a near strike (a point 90 m ahead of the camera, main+0x21c4c74, struck by main+0x21c3a6c once 90
# units of frame step pass without another pick) and 0.01 in states 1 and 5 for bit 3, which sets the environment
# input's flag +0x2e4 as a near strike does (main+0x58b4fc). Counted in one storm with a local build that logs each
# draw that succeeds: with the set off 22 distant bolts a minute at 30 fps, 52 at 60 and 94 to 96 at 120, each one a
# Far_Lightning effect, and bit 3 19, 34 and 64 to 80 times a minute of state 1. Near strikes stayed at 14 to 18 in
# 205 s at every rate: state 1 lets its last pick strike in state 2, where nothing is drawn, and state 2 ends with a
# strike of its own, so the picks that start the countdown again at high frame rates change little. Each site
# multiplies the chance it loads by the frame ratio, time object +0x38 ([[main+0x3ad27c8] + 0xc8], as the sets bounce
# and shutter read it), at most 1: above 30 fps the rates per second of 30 fps (counted: 26, 27 and 20 to 24 distant
# bolts a minute at 30, 60 and 120 fps, bit 3 12 to 17 times a minute of state 1), and at 30 fps and below the game's
# own chances. After each site x10 and the two scratch registers (s3 and s4 at the first,
# where s2 is the chance; s2 and s3 at the others) are written, or a call comes, before any read; at the second the
# chance is s9, which the prologue saves and both draws of state 1 compare with. Its own switch, lightning_fix
# (TOTK_LIGHTNING_FIX); 0 runs the game's loads.
set lightning TOTK_LIGHTNING_FIX 1
site lightning main 62b1fc bd472d02 bd472d02 f001a52a f943e54a f940654a bd403943 1e2e1004 1e247863 1e230842 # ldr s2, [x8, #0x72c] (0.013333)
site lightning main 62b3d8 bd4ccd09 bd4ccd09 f001a52a f943e54a f940654a bd403942 1e2e1003 1e237842 1e220929 # ldr s9, [x8, #0xccc] (0.01)
site lightning main 62b51c bd4ccd01 bd4ccd01 f001a52a f943e54a f940654a bd403942 1e2e1003 1e237842 1e220821 # ldr s1, [x8, #0xccc] (0.01)
# each: the game's load; adrp x10, main+0x3ad2000; ldr x10, [x10, #0x7c8]; ldr x10, [x10, #0xc8];
# ldr s3 (s2), [x10, #0x38] (ratio); fmov s4 (s3), #1.0; fminnm (ratio, 1.0); fmul (chance * ratio)
+50 -15
View File
@@ -1,7 +1,8 @@
"""Code patch table for the generator: guest instructions replaced in the lifted C, switchable at run time.
Lifted code cannot be byte-patched when the game runs, so a patch is applied when the C is generated. A patch file
(gen.py --patches) has these kinds of lines; `#` starts a comment, fields are separated by whitespace:
(gen.py --patches) has these kinds of lines; `#` starts a comment, fields are separated by whitespace. A plugin image
path may be a JSON double-quoted string to preserve spaces, `#` and escaped characters:
set <name> <env> <default> [ordered] a patch set: a run-time switch <env>=0/1, <default> when it is unset
site <set> <module> <address> <original> <replacement> [<replacement> ...]
@@ -15,6 +16,7 @@ Lifted code cannot be byte-patched when the game runs, so a patch is applied whe
stub <module> <offset>
seed <module> <offset> [<offset> ...]
orig <set> <module> <offset> <function module> <function offset>
entry <module> <offset> [<offset> ...]
<address> is a module offset (hex), <original> the instruction word the module has there (checked; a mismatch stops
the generator), each <replacement> an instruction word (hex) or `@page:x<n>`, which is `adrp x<n>, <patch page>`
@@ -40,7 +42,7 @@ wins, a tie goes to the set later in the file). The other alternatives of a cont
their rt_patch_on test, so a cheat before the mods' sets still wins while it is on. A site with at most one ordered
set, and a table without contested sites, is emitted exactly as without the keyword.
The original may be any instruction but br, blr and ret; a replacement's last word may be
The original may be any instruction but br and ret; a replacement's last word may be
a bl (lifted with the site's return address), a b or b.cond / cbz / tbz (its target joins the function's labels when
inside it) or a ret; earlier words must not branch. Every alternative of a site writes the same flags. The generator
writes patches.h (set names, switches, the page address, the contested sites) next to layout.h for the runtime.
@@ -58,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.
@@ -67,16 +70,24 @@ run's record; the design follows #845 by itaskaev2):
lifts the function at <function module>+<function offset> a second time without its patched sites
(fo_<address>) and lists that copy at the trampoline's address in <module>'s function table, so the call reaches
the original code and not the hook again.
An `entry` line names addresses of a game module that a plugin calls by pointer although they are no function start
of the game's code (Zonai Fieldworks calls main+0x481918 of 1.4.3, the second word of a function, skipping its first
test). gen.py makes each one a function start of the module's lift: the function that held it ends there and runs on
into it by a tail jump, as at any function boundary, so the game's own path through the code does not change.
tools/exefs_plugins.py writes them when a service run calls such an address (installer/steps.py lifts again).
A replacement word `@call:<module>+<offset>` is a call of the function there that writes no x30: every register in
the Cpu at the call and all read back after it (the callback may change any of them, as exlaunch's hook context
allows); the flags stay as they were. It may stand before the site's last word, which is then the original
instruction.
allows); the flags are published before it and taken back after it, since exlaunch's hook impl saves no NZCV and the
game code goes on with the flags the callback left (recomp/flags.py plan's hooks). It may stand before the site's last
word, which is then the original instruction.
A `hook` line names guest functions (module offsets of function starts; gen.py stops on any other address) whose
entry the runtime watches: their lifted C starts with FN_ENTER (runtime/cpu.h), a load of g_fnprof and a predicted
branch to fnprof_hit while the runtime sets it. A table with hook lines puts FN_ENTER into these functions only; a table
without any keeps it in every function, as does gen.py --fn-enter-all (a whole-game function-entry profile).
"""
import json
from pathlib import Path
PAGE = 0x1000
@@ -101,14 +112,16 @@ class Table:
from here (for_module, picks_for, spins_for, hooks_for) is in the lift cache's key (recomp/gen.py chunk_key); a new
kind of line the Emitter reads must go there too."""
def __init__(self, sets=(), sites=None, page=0, spins=None, hooks=None, ordered=(), plugins=None):
def __init__(self, sets=(), sites=None, page=0, spins=None, hooks=None, ordered=(), plugins=None, entries=None):
self.sets = list(sets)
self.entries = entries or {} # {module: {offset}}: `entry` lines
self.sites = sites or {}
self.page = page
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 {}
@@ -184,13 +197,26 @@ class Table:
def load(path, mods):
"""Table from a patch file; mods is layout() output [(name, base, size)]."""
sets, index, sites, spins, hooks, ordered, plugins = [], {}, {}, {}, {}, set(), {}
sets, index, sites, spins, hooks, ordered, plugins, entries = [], {}, {}, {}, {}, set(), {}, {}
bases = {n: (b, s) for n, b, s in mods}
for no, raw in enumerate(Path(path).read_text(encoding='utf-8').splitlines(), 1):
f = raw.split('#', 1)[0].split()
where = f'{path}:{no}'
prefix = raw.split(None, 4)
if len(prefix) == 5 and prefix[0] == 'plugin' and prefix[4].startswith('"'):
try:
image, end = json.JSONDecoder().raw_decode(prefix[4])
except json.JSONDecodeError as e:
raise PatchError(f'{where}: invalid quoted plugin image: {e.msg}') from None
if not image:
raise PatchError(f'{where}: empty quoted plugin image')
tail = prefix[4][end:].strip()
if tail and not tail.startswith('#'):
raise PatchError(f'{where}: unexpected text after quoted plugin image')
f = prefix[:4] + [image]
else:
f = raw.split('#', 1)[0].split()
if not f:
continue
where = f'{path}:{no}'
if f[0] == 'set' and (len(f) == 4 or len(f) == 5 and f[4] == 'ordered'):
if f[1] in index:
raise PatchError(f'{where}: set {f[1]} defined twice')
@@ -239,6 +265,10 @@ def load(path, mods):
'seeds': set(), 'origs': {}}
elif f[0] in ('expect', 'stub', 'seed', 'orig'):
plugin_line(f, where, index, bases, plugins)
elif f[0] == 'entry' and len(f) >= 3:
if f[1] not in bases:
raise PatchError(f'{where}: module {f[1]} not in the layout')
entries.setdefault(f[1], set()).update(int(o, 16) for o in f[2:])
elif f[0] == 'hook' and len(f) >= 3:
if f[1] not in bases:
raise PatchError(f'{where}: module {f[1]} not in the layout')
@@ -250,7 +280,7 @@ def load(path, mods):
nxt = min((b for _, b, _ in mods if b > base), default=None)
if nxt is not None and page + PAGE > nxt:
raise PatchError(f'no room for the patch page after main ({page:#x})')
table = Table(sets, sites, page, spins, hooks, ordered, plugins)
table = Table(sets, sites, page, spins, hooks, ordered, plugins, entries)
table.bases = {n: b for n, (b, _) in bases.items()}
return table
@@ -268,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:
@@ -317,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
+45 -27
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", "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,10 +41,10 @@ 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", "FSR_SHARPNESS",
"FREEZE_IDLE", "FREE_CORES", "FSR3_DEBUG", "FSR3_VIEW", "FSR4_DEBUG", "FSR_SHARPNESS",
"FULLSCREEN", "FXAA",
"GAMEPLAY_DISTANCE_SENSITIVITY", "GAMEPLAY_ITEM_AD", "GAMEPLAY_ITEM_SENSITIVITY", "GAMEPLAY_ITEM_WHEEL",
"GAMEPLAY_MAP_ZOOM", "GAMEPLAY_MAP_ZOOM_SENSITIVITY", "GAMEPLAY_ROTATION_SENSITIVITY", "GAMEPLAY_TWEAKS_ENABLED",
@@ -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",
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "LOD_STEADY", "LSTICK_DEADZONE", "MAP_CLICK", "MEMORY", "MEMX", "MENU_LANG", "MENU_TEST", "MENU_FONT_FONTCONFIG",
"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",
"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",
"MV_SURVEY", "NULL_ATTACH",
"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", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
"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",
"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",
@@ -77,10 +77,11 @@ static const struct { const char *key, *section; } sections[] = {
{"FPS_LIMIT", "frame rate"}, {"FPS60", "frame rate"}, {"FRAME_QUEUE", "frame rate"}, {"FRAME_GEN", "frame rate"},
{"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"},
{"CLIMB_FIX", "frame rate"}, {"AUDIO_DRAIN_FIX", "frame rate"}, {"SHUTTER_FIX", "frame rate"},
{"LIGHTNING_FIX", "frame rate"},
{"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"},
{"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"},
{"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"},
@@ -97,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"},
@@ -106,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"},
@@ -141,13 +142,14 @@ static const CfgMeta metas[] = {
{"HUD_WIDTH", "full", "full|21:9|16:9", RESTART},
{"DYNAMIC_RES", "1", "0|1", LIVE}, // resolution.c res_dynres_live
{"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE},
{"SCENE_UPSCALER", "off", "off|dlss|fsr3", RESTART}, {"DLAA", "0", "0|1", RESTART},
{"SCENE_UPSCALER", "off", "off|dlss|fsr3|fsr4", RESTART}, {"DLAA", "0", "0|1", RESTART},
{"DLSS", "dlaa", "dlaa|quality|balanced|performance|ultra_performance", LIVE},
{"FSR_SHARPNESS", "80", "0..100", LIVE}, // vk_dlaa.c fsr_evaluate
{"DLSS_PRESET", "default", "default|k|j", LIVE}, {"DLSS_FIXED_EXPOSURE", "0", "0|1", LIVE}, {"DLAA_EFFECTS_AFTER", "0", "0|1", LIVE},
{"DLSS_CHAR_MASK", "65", "0|35|65|100", LIVE}, {"REFLEX", "off", "off|on|boost", RESTART}, {"FXAA", "1", "0|1", LIVE},
{"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},
@@ -168,7 +170,7 @@ static const CfgMeta metas[] = {
{"MODS_REBUILD", "auto", "auto|off", RESTART},
{"MODS_WITHOUT_CODE", "0", "0|1", RESTART}, // 1: a mod is used without the code module it cannot run (mods.c)
{"HIGHFPS_FIX", "1", "0|1", RESTART}, {"CLIMB_FIX", "1", "0|1", RESTART}, {"AUDIO_DRAIN_FIX", "1", "0|1", RESTART},
{"SHUTTER_FIX", "1", "0|1", RESTART},
{"SHUTTER_FIX", "1", "0|1", RESTART}, {"LIGHTNING_FIX", "1", "0|1", RESTART},
{"LANG", "", "ja|en-US|fr|de|it|es|zh-CN|ko|nl|pt|ru|zh-TW|en-GB|fr-CA|es-419|zh-Hans|zh-Hant|pt-BR", RESTART},
{"OPERATION_MODE", "docked", "docked|handheld", RESTART},
{"ASSUME_FOCUS", "1", "0|1", LIVE}, // read on every focus change (ov_system.c)
@@ -182,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},
@@ -203,7 +206,7 @@ static const CfgMeta metas[] = {
{"GAMEPLAY_MAP_ZOOM_SENSITIVITY", "1", "0.25..4", LIVE}, {"GAMEPLAY_ROTATION_SENSITIVITY", "1", "0.25..4", LIVE},
{"GAMEPLAY_DISTANCE_SENSITIVITY", "1", "0.25..4", LIVE}, {"GAMEPLAY_ITEM_SENSITIVITY", "1", "0.25..4", LIVE},
{"GAMEPLAY_WEAPON_WHEEL", "1", "0|1", LIVE}, {"GAMEPLAY_WEAPON_SENSITIVITY", "1", "0.25..4", LIVE},
{"MENU_LANG", "", "en|ru|pt-BR|zh-Hans", LIVE},
{"MENU_LANG", "", "en|ru|pt-BR|zh-Hans|de|fr|es|it|nl|ja|ko|vi", LIVE},
// plat_font_path on Linux: 1 asks fontconfig which file draws the language, 0 keeps the fixed distribution
// paths. A rebuild of the atlas reads it, so a change shows on the next window size or language switch.
{"MENU_FONT_FONTCONFIG", "1", "0|1", LIVE},
@@ -213,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},
@@ -231,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},
@@ -405,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;
@@ -423,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;
}
@@ -862,9 +880,9 @@ void cfg_init(void) {
}
// scene_upscaler, or for a totk.ini that predates it the dlaa switch it replaced: dlaa = 1 is DLSS, anything else off.
// FSR 3.1 is never the answer for a player who did not pick it. An unknown value is off.
// FSR is never the answer for a player who did not pick it. An unknown value is off.
const char *cfg_scene_upscaler(void) {
if (!cfg_is_set("TOTK_SCENE_UPSCALER")) return cfg_bool("TOTK_DLAA") ? "dlss" : "off";
const char *v = cfg_value("TOTK_SCENE_UPSCALER");
return !strcmp(v, "dlss") ? "dlss" : !strcmp(v, "fsr3") ? "fsr3" : "off";
return !strcmp(v, "dlss") ? "dlss" : !strcmp(v, "fsr3") ? "fsr3" : !strcmp(v, "fsr4") ? "fsr4" : "off";
}
+8 -5
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
@@ -69,14 +70,16 @@ const char *cfg_value(const char *name);
int cfg_int(const char *name);
double cfg_double(const char *name);
int cfg_bool(const char *name);
// The 3D scene upscaler the settings name now: "off", "dlss" or "fsr3" (scene_upscaler; without it dlaa = 1 is "dlss").
// The 3D scene upscaler the settings name now: "off", "dlss", "fsr3" or "fsr4" (scene_upscaler; without it dlaa = 1 is
// "dlss").
// The engine in use is the one named at start (vk_dlaa.c vk_upscaler_engine).
const char *cfg_scene_upscaler(void);
// vk_dlaa.c, the 3D scene upscaler (scene_upscaler): the engine picked at start (UPSCALER_*),
// 1 while the settings still name it (the menu switches it off at once), the engine that is running (it
// ran and has not failed; 0 none), and why an engine cannot run here (UPSCALER_MISSING_*, 0 it can).
enum { UPSCALER_OFF, UPSCALER_DLSS, UPSCALER_FSR3 };
enum { UPSCALER_MISSING_GPU = 1, UPSCALER_MISSING_DLL };
// UPSCALER_FSR4 is AMD's FSR 4 from its FSR SDK libraries (vk_ffx.c), Windows only (UPSCALER_MISSING_OS elsewhere).
enum { UPSCALER_OFF, UPSCALER_DLSS, UPSCALER_FSR3, UPSCALER_FSR4 };
enum { UPSCALER_MISSING_GPU = 1, UPSCALER_MISSING_DLL, UPSCALER_MISSING_OS };
int vk_upscaler_engine(void);
int vk_upscaler_on(void);
int vk_upscaler_running(void);
+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;
}
+245
View File
@@ -0,0 +1,245 @@
// The part of AMD's FSR API (ffx-api) that vk_ffx.c uses: the entry points of amd_fidelityfx_loader_vk.dll, the
// Vulkan backend descriptor and the upscaler's create and dispatch descriptors. Copied from the FidelityFX SDK v2.4.0
// (GPUOpen-LibrariesAndSDKs/FidelityFX-SDK, Kits/FidelityFX/api/include/ffx_api.h, ffx_api_types.h, vk/ffx_api_vk.h
// and Kits/FidelityFX/upscalers/include/ffx_upscale.h), trimmed to those declarations; the layouts and values are
// unchanged. The SDK's headers use a C++ attribute for deprecations, so they are not included as they are.
//
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2026 Advanced Micro Devices, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and /or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <wchar.h>
#include <vulkan/vulkan.h>
// ---- ffx_api.h
enum FfxApiReturnCodes {
FFX_API_RETURN_OK = 0,
FFX_API_RETURN_ERROR = 1,
FFX_API_RETURN_ERROR_UNKNOWN_DESCTYPE = 2,
FFX_API_RETURN_ERROR_RUNTIME_ERROR = 3,
FFX_API_RETURN_NO_PROVIDER = 4,
FFX_API_RETURN_ERROR_MEMORY = 5,
FFX_API_RETURN_ERROR_PARAMETER = 6,
FFX_API_RETURN_PROVIDER_NO_SUPPORT_NEW_DESCTYPE = 7,
};
typedef void *ffxContext;
typedef uint32_t ffxReturnCode_t;
#define FFX_API_EFFECT_MASK 0x00ff0000u
#define FFX_API_BACKEND_MASK 0xff000000u
typedef uint64_t ffxStructType_t;
typedef struct ffxApiHeader {
ffxStructType_t type;
struct ffxApiHeader *pNext;
} ffxApiHeader;
typedef ffxApiHeader ffxCreateContextDescHeader;
typedef ffxApiHeader ffxConfigureDescHeader;
typedef ffxApiHeader ffxQueryDescHeader;
typedef ffxApiHeader ffxDispatchDescHeader;
enum FfxApiMsgType { FFX_API_MESSAGE_TYPE_ERROR = 0, FFX_API_MESSAGE_TYPE_WARNING = 1 };
typedef void (*ffxApiMessage)(uint32_t type, const wchar_t *message);
#define FFX_API_QUERY_DESC_TYPE_GET_VERSIONS 4u
struct ffxQueryDescGetVersions {
ffxQueryDescHeader header;
uint64_t createDescType;
void *device; // Vulkan: a VkDeviceContext *
uint64_t *outputCount;
uint64_t *versionIds;
const char **versionNames;
};
#define FFX_API_DESC_TYPE_OVERRIDE_VERSION 5u
struct ffxOverrideVersion {
ffxApiHeader header;
uint64_t versionId;
};
#define FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION 6u
struct ffxQueryGetProviderVersion {
ffxQueryDescHeader header;
uint64_t versionId;
const char *versionName;
};
typedef struct ffxAllocationCallbacks ffxAllocationCallbacks;
typedef ffxReturnCode_t (*PfnFfxCreateContext)(ffxContext *context, ffxCreateContextDescHeader *desc,
const ffxAllocationCallbacks *memCb);
typedef ffxReturnCode_t (*PfnFfxDestroyContext)(ffxContext *context, const ffxAllocationCallbacks *memCb);
typedef ffxReturnCode_t (*PfnFfxQuery)(ffxContext *context, ffxQueryDescHeader *desc);
typedef ffxReturnCode_t (*PfnFfxDispatch)(ffxContext *context, const ffxDispatchDescHeader *desc);
#define FFX_API_EFFECT_ID_UPSCALE 0x00010000u
#define FFX_API_MAKE_EFFECT_SUB_ID(effectId, subversion) ((effectId & FFX_API_EFFECT_MASK) | (subversion & ~FFX_API_EFFECT_MASK))
#define FFX_API_BACKEND_ID_VK 0x01000000u
#define FFX_API_MAKE_BACKEND_SUB_ID(backendId, subversion) ((backendId & FFX_API_BACKEND_MASK) | (subversion & ~FFX_API_BACKEND_MASK))
// ---- ffx_api_types.h
enum FfxApiSurfaceFormat {
FFX_API_SURFACE_FORMAT_UNKNOWN,
FFX_API_SURFACE_FORMAT_R32G32B32A32_TYPELESS,
FFX_API_SURFACE_FORMAT_R32G32B32A32_UINT,
FFX_API_SURFACE_FORMAT_R32G32B32A32_FLOAT,
FFX_API_SURFACE_FORMAT_R16G16B16A16_FLOAT,
FFX_API_SURFACE_FORMAT_R32G32B32_FLOAT,
FFX_API_SURFACE_FORMAT_R32G32_FLOAT,
FFX_API_SURFACE_FORMAT_R8_UINT,
FFX_API_SURFACE_FORMAT_R32_UINT,
FFX_API_SURFACE_FORMAT_R8G8B8A8_TYPELESS,
FFX_API_SURFACE_FORMAT_R8G8B8A8_UNORM,
FFX_API_SURFACE_FORMAT_R8G8B8A8_SNORM,
FFX_API_SURFACE_FORMAT_R8G8B8A8_SRGB,
FFX_API_SURFACE_FORMAT_B8G8R8A8_TYPELESS,
FFX_API_SURFACE_FORMAT_B8G8R8A8_UNORM,
FFX_API_SURFACE_FORMAT_B8G8R8A8_SRGB,
FFX_API_SURFACE_FORMAT_R11G11B10_FLOAT,
FFX_API_SURFACE_FORMAT_R10G10B10A2_UNORM,
FFX_API_SURFACE_FORMAT_R16G16_FLOAT,
FFX_API_SURFACE_FORMAT_R16G16_UINT,
FFX_API_SURFACE_FORMAT_R16G16_SINT,
FFX_API_SURFACE_FORMAT_R16_FLOAT,
FFX_API_SURFACE_FORMAT_R16_UINT,
FFX_API_SURFACE_FORMAT_R16_UNORM,
FFX_API_SURFACE_FORMAT_R16_SNORM,
FFX_API_SURFACE_FORMAT_R8_UNORM,
FFX_API_SURFACE_FORMAT_R8G8_UNORM,
FFX_API_SURFACE_FORMAT_R8G8_UINT,
FFX_API_SURFACE_FORMAT_R32_FLOAT,
};
enum FfxApiResourceUsage {
FFX_API_RESOURCE_USAGE_READ_ONLY = 0,
FFX_API_RESOURCE_USAGE_RENDERTARGET = (1 << 0),
FFX_API_RESOURCE_USAGE_UAV = (1 << 1),
FFX_API_RESOURCE_USAGE_DEPTHTARGET = (1 << 2),
};
enum FfxApiResourceState {
FFX_API_RESOURCE_STATE_COMMON = (1 << 0),
FFX_API_RESOURCE_STATE_UNORDERED_ACCESS = (1 << 1),
FFX_API_RESOURCE_STATE_COMPUTE_READ = (1 << 2),
FFX_API_RESOURCE_STATE_PIXEL_READ = (1 << 3),
FFX_API_RESOURCE_STATE_COPY_SRC = (1 << 4),
FFX_API_RESOURCE_STATE_GENERIC_READ = (FFX_API_RESOURCE_STATE_COPY_SRC | FFX_API_RESOURCE_STATE_COMPUTE_READ),
};
enum FfxApiResourceType { FFX_API_RESOURCE_TYPE_BUFFER, FFX_API_RESOURCE_TYPE_TEXTURE1D, FFX_API_RESOURCE_TYPE_TEXTURE2D };
struct FfxApiDimensions2D {
uint32_t width, height;
};
struct FfxApiFloatCoords2D {
float x, y;
};
struct FfxApiResourceDescription {
uint32_t type;
uint32_t format;
uint32_t width; // union with size (buffers)
uint32_t height; // union with stride
uint32_t depth; // union with alignment
uint32_t mipCount;
uint32_t flags;
uint32_t usage;
};
struct FfxApiResource {
void *resource; // Vulkan: the VkImage
struct FfxApiResourceDescription description;
uint32_t state;
};
// ---- vk/ffx_api_vk.h
typedef struct VkDeviceContext {
VkDevice vkDevice;
VkPhysicalDevice vkPhysicalDevice;
PFN_vkGetDeviceProcAddr vkDeviceProcAddr;
} VkDeviceContext;
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK FFX_API_MAKE_BACKEND_SUB_ID(FFX_API_BACKEND_ID_VK, 0x03)
struct ffxCreateBackendVKDesc {
ffxCreateContextDescHeader header;
VkDeviceContext deviceContext;
};
// ---- upscalers/include/ffx_upscale.h
#define FFX_UPSCALER_MAKE_VERSION(major, minor, patch) (((major) << 22) | ((minor) << 12) | (patch))
#define FFX_UPSCALER_VERSION FFX_UPSCALER_MAKE_VERSION(4, 1, 2)
enum FfxApiCreateContextUpscaleFlags {
FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE = (1 << 0),
FFX_UPSCALE_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS = (1 << 1),
FFX_UPSCALE_ENABLE_MOTION_VECTORS_JITTER_CANCELLATION = (1 << 2),
FFX_UPSCALE_ENABLE_DEPTH_INVERTED = (1 << 3),
FFX_UPSCALE_ENABLE_DEPTH_INFINITE = (1 << 4),
FFX_UPSCALE_ENABLE_AUTO_EXPOSURE = (1 << 5),
FFX_UPSCALE_ENABLE_DYNAMIC_RESOLUTION = (1 << 6),
FFX_UPSCALE_ENABLE_DEBUG_CHECKING = (1 << 7),
};
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x00)
struct ffxCreateContextDescUpscale {
ffxCreateContextDescHeader header;
uint32_t flags;
struct FfxApiDimensions2D maxRenderSize;
struct FfxApiDimensions2D maxUpscaleSize;
ffxApiMessage fpMessage;
};
#define FFX_API_DISPATCH_DESC_TYPE_UPSCALE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x01)
struct ffxDispatchDescUpscale {
ffxDispatchDescHeader header;
void *commandList; // Vulkan: the VkCommandBuffer
struct FfxApiResource color;
struct FfxApiResource depth;
struct FfxApiResource motionVectors;
struct FfxApiResource exposure;
struct FfxApiResource reactive;
struct FfxApiResource transparencyAndComposition;
struct FfxApiResource output;
struct FfxApiFloatCoords2D jitterOffset;
struct FfxApiFloatCoords2D motionVectorScale;
struct FfxApiDimensions2D renderSize;
struct FfxApiDimensions2D upscaleSize;
bool enableSharpening;
float sharpness;
float frameTimeDelta; // milliseconds
float preExposure;
bool reset;
float cameraNear;
float cameraFar;
float cameraFovAngleVertical; // radians
float viewSpaceToMetersFactor;
uint32_t flags;
};
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE_VERSION FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x0b)
struct ffxCreateContextDescUpscaleVersion {
ffxCreateContextDescHeader header;
uint32_t version; // FFX_UPSCALER_VERSION
};
+16 -1
View File
@@ -11,6 +11,8 @@
// <profile>/save-backup/<time>/ the three committed saves before the current one
// <profile>/temp/ emptied at start
// <profile>/cache/<index>/ cache storage
// <profile>/sdcard/ the SD card a mod plugin mounts (MountSdCard, under any mount name: Zonai
// Fieldworks keeps its settings and logs there); the game never mounts it
//
// The save mount is journaled as on Horizon: changes go to a working copy and become the committed save atomically at
// Commit; a crash or an Unmount before Commit leaves the previous committed save. Commit returns at once and the copy
@@ -33,7 +35,8 @@
#define NMOUNTS 16
#define PATH_CAP 1100
enum { M_FREE, M_SAVE, M_TEMP, M_CACHE, M_SAVE_RO }; // M_SAVE: the working copy; M_SAVE_RO: the committed save
// M_SAVE: the working copy; M_SAVE_RO: the committed save; M_SDCARD: <profile>/sdcard
enum { M_FREE, M_SAVE, M_TEMP, M_CACHE, M_SAVE_RO, M_SDCARD };
typedef struct { int kind; char name[32]; char root[1024]; } Mount;
typedef struct { PlatFile *h; int mode, save; } File; // h NULL = free; save: on a save-data mount
@@ -800,6 +803,14 @@ static uint32_t mount_temp(const char *name) {
return mount_add(name, M_TEMP, p);
}
static uint32_t mount_sdcard(const char *name) {
ready();
char p[PATH_CAP];
snprintf(p, sizeof p, "%s/sdcard", profile);
make_dirs(p);
return mount_add(name, M_SDCARD, p);
}
static void cache_dir(int index, char *out, size_t cap) { snprintf(out, cap, "%s/cache/%d", profile, index); }
static uint32_t create_cache(int index, int64_t size, int64_t journal) {
@@ -1013,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);
@@ -1210,6 +1222,7 @@ static void ov_mount_save(Cpu *c) { ret_x(c, mount_save(arg_p(c, 0), arg_p(c, 1)
static void ov_mount_save_ro(Cpu *c) { ret_x(c, mount_save_ro(arg_p(c, 0), arg_x(c, 1), arg_p(c, 2))); }
static void ov_save_exists(Cpu *c) { ret_x(c, save_exists(arg_x(c, 0), arg_p(c, 1))); }
static void ov_mount_temp(Cpu *c) { ret_x(c, mount_temp(arg_p(c, 0))); }
static void ov_mount_sdcard(Cpu *c) { ret_x(c, mount_sdcard(arg_p(c, 0))); }
static void ov_unmount(Cpu *c) { unmount(arg_p(c, 0)); }
static void ov_commit(Cpu *c) { ret_x(c, commit(arg_p(c, 0))); }
static void ov_create_cache(Cpu *c) { ret_x(c, create_cache(I32(0), I64(1), I64(2))); }
@@ -1245,6 +1258,7 @@ static void ov_set_priority(Cpu *c) { (void)c; }
#define S_MOUNT_SAVE_RO "_ZN2nn2fs21MountSaveDataReadOnlyEPKcNS_13ApplicationIdERKNS_7account3UidE"
#define S_SAVE_EXISTS "_ZN2nn2fs18IsSaveDataExistingENS_13ApplicationIdERKNS_7account3UidE"
#define S_MOUNT_TEMP "_ZN2nn2fs21MountTemporaryStorageEPKc"
#define S_MOUNT_SDCARD "_ZN2nn2fs11MountSdCardEPKc"
#define S_UNMOUNT "_ZN2nn2fs7UnmountEPKc"
#define S_COMMIT "_ZN2nn2fs6CommitEPKc"
#define S_CREATE_CACHE "_ZN2nn2fs18CreateCacheStorageEill"
@@ -1281,6 +1295,7 @@ HOST_OVERRIDE(S_MOUNT_SAVE, ov_mount_save);
HOST_OVERRIDE(S_MOUNT_SAVE_RO, ov_mount_save_ro);
HOST_OVERRIDE(S_SAVE_EXISTS, ov_save_exists);
HOST_OVERRIDE(S_MOUNT_TEMP, ov_mount_temp);
HOST_OVERRIDE(S_MOUNT_SDCARD, ov_mount_sdcard);
HOST_OVERRIDE(S_UNMOUNT, ov_unmount);
HOST_OVERRIDE(S_COMMIT, ov_commit);
HOST_OVERRIDE(S_CREATE_CACHE, ov_create_cache);
+4
View File
@@ -33,6 +33,10 @@ void vk_reflex_marker(int marker, uint64_t present_id); // present_id: the fra
uint64_t vk_reflex_frame_begin(void); // SIMULATION_START: the new frame's present ID
uint64_t vk_reflex_frame(void); // the ID of the frame the game simulates now
void vk_reflex_sleep(void); // before SIMULATION_START: the driver's latency sleep
// AMD Anti-Lag 2 (gfx_present.c, VK_AMD_anti_lag): the driver paces the CPU from the INPUT call to the PRESENT call of a
// frame. Both return at once unless reflex = auto turned Anti-Lag on at device creation (vk_device.c create_device).
void vk_antilag_input(uint64_t frame); // before the frame's input and simulation; may sleep
void vk_antilag_present(uint64_t frame); // right before the frame's vkQueuePresentKHR
// ---- shader service client (gfx_shader.c)
enum { GFX_STAGE_VS, GFX_STAGE_TCS, GFX_STAGE_TES, GFX_STAGE_GS, GFX_STAGE_FS, GFX_STAGE_CS };
+33 -3
View File
@@ -390,8 +390,9 @@ static void latency_note(VkCtx *c, uint64_t pid) {
"end %.2f ms", full, gi.timingCount, full ? sum / full / 1000.0 : 0.0);
}
}
rt_log("reflex: frame start to present %.2f ms over %llu frames (reflex %s)%s", g_lat.n ? g_lat.ns / 1e6 / g_lat.n : 0.0,
(unsigned long long)g_lat.n, g_reflex_mode == 2 ? "boost" : g_reflex_mode == 1 ? "on" : "off", drv);
rt_log("reflex: frame start to present %.2f ms over %llu frames (reflex %s%s)%s", g_lat.n ? g_lat.ns / 1e6 / g_lat.n : 0.0,
(unsigned long long)g_lat.n, g_reflex_mode == 2 ? "boost" : g_reflex_mode == 1 ? "on" : "off",
c->has_amd_antilag ? ", anti-lag on" : "", drv);
g_lat.n = g_lat.ns = 0;
}
@@ -405,7 +406,8 @@ uint64_t vk_reflex_submit_id(void) { return t_reflex_submit ? t_reflex_submit :
void vk_reflex_present_frame(uint64_t id) {
// g_blit_pid feeds flip_locked's VkPresentIdKHR (Reflex) and latency_note (TOTK_TRACE=perf); with neither, the
// present skips the lock
if (!vk_has_reflex() && !(rt_trace & RT_TRACE_PERF)) return;
VkCtx *c = vk_ctx();
if (!vk_has_reflex() && !(c && c->has_amd_antilag) && !(rt_trace & RT_TRACE_PERF)) return;
plat_rmutex_lock(&g_pl);
g_blit_pid = id;
plat_rmutex_unlock(&g_pl);
@@ -452,6 +454,33 @@ void vk_reflex_sleep(void) {
}
}
// ---- AMD Anti-Lag 2 (VK_AMD_anti_lag)
static PFN_vkAntiLagUpdateAMD g_antilag_update;
// The INPUT call runs on the game thread (nvnWindowAcquireTexture), the PRESENT call on the present thread (flip_one,
// g_pl held): both carry the frame's ID, as the spec asks of a frame's two calls. The first call of either thread loads
// the entry point; the atomics keep that load race-free.
static void antilag_update(VkAntiLagStageAMD stage, uint64_t frame) {
VkCtx *c = vk_ctx();
if (!c || !c->has_amd_antilag || !frame) return;
PFN_vkAntiLagUpdateAMD fn = __atomic_load_n(&g_antilag_update, __ATOMIC_ACQUIRE);
if (!fn) {
fn = (PFN_vkAntiLagUpdateAMD)vkGetDeviceProcAddr(c->device, "vkAntiLagUpdateAMD");
if (!fn) return;
__atomic_store_n(&g_antilag_update, fn, __ATOMIC_RELEASE);
}
// the driver holds frames to the pacer's frame limit, as Reflex's minimum interval does (0: no limit known)
double hz = frame_step_limit_hz();
VkAntiLagPresentationInfoAMD pi = {
.sType = VK_STRUCTURE_TYPE_ANTI_LAG_PRESENTATION_INFO_AMD, .stage = stage, .frameIndex = frame};
VkAntiLagDataAMD d = {.sType = VK_STRUCTURE_TYPE_ANTI_LAG_DATA_AMD, .mode = VK_ANTI_LAG_MODE_ON_AMD,
.maxFPS = hz > 0 ? (uint32_t)(hz + 0.5) : 0, .pPresentationInfo = &pi};
fn(c->device, &d);
}
void vk_antilag_input(uint64_t frame) { antilag_update(VK_ANTI_LAG_STAGE_INPUT_AMD, frame); }
void vk_antilag_present(uint64_t frame) { antilag_update(VK_ANTI_LAG_STAGE_PRESENT_AMD, frame); }
// ---- swapchain
static const char *g_present_got = ""; // the TOTK_VK_PRESENT value of the mode the swapchain got; "" before one
@@ -503,6 +532,7 @@ static void flip_one(void) {
pid_info.pPresentIds = &pid;
vk_reflex_marker(4, pid); // VK_LATENCY_MARKER_PRESENT_START_NV
}
if (!generated) vk_antilag_present(frame_pid);
VkPresentInfoKHR pi = {.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
.pNext = with_id ? &pid_info : NULL,
.waitSemaphoreCount = 1,
+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) {
+11
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)
@@ -313,6 +323,7 @@ void res_init(void); // after rt_patches_i
float res_dlss_lod_bias(void); // TOTK_DLSS upscaling: texture LOD bias (<= 0)
int res_dlss_mode(const char *mode); // TOTK_DLSS changed while running: new scene size
int res_dlss_dll(void); // the DLSS library is next to the executable
int res_ffx_dlls(void); // AMD's two FSR 4 libraries are (Windows; 0 elsewhere)
void res_fn_hit(uint64_t addr, uint64_t x0); // main.c fnprof_hit: catches the renderer at start
void res_present(Cpu *c); // nvnQueuePresentTexture: applies a pending scene size
void res_sizes(unsigned out[2], unsigned scene[2]); // the output and scene sizes in effect (the game's own
+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);
+3 -1
View File
@@ -688,7 +688,9 @@ NVN_API(nvnWindowAcquireTexture) {
perf_end(PERF_PACE, p0);
}
vk_reflex_sleep();
vk_reflex_marker(0, vk_reflex_frame_begin()); // VK_LATENCY_MARKER_SIMULATION_START_NV: a new frame and its ID
uint64_t fid = vk_reflex_frame_begin();
vk_reflex_marker(0, fid); // VK_LATENCY_MARKER_SIMULATION_START_NV: a new frame and its ID
vk_antilag_input(fid);
// The sync means "the display no longer reads this image". Presents are copies queued in submit order, so it is
// already satisfied: fenced = 3 with fence 0.
if (s) {
+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));
+34 -11
View File
@@ -1012,31 +1012,45 @@ static void probe_fonts(void) {
(unsigned long long)addr, (unsigned long long)size, path);
}
// The host catalog (ui_text.c): every menu id has its own English, Russian, Brazilian Portuguese and Simplified
// Chinese text, the software keyboard keeps its game-language rows, and menu_text follows TOTK_MENU_LANG.
// The host catalog (ui_text.c): every menu id has its own English, Russian, Brazilian Portuguese, Simplified Chinese
// and Vietnamese text, every menu language's text fits the description pane and keeps the English conversions of the
// overlay formats, the software keyboard keeps its game-language rows, and menu_text follows TOTK_MENU_LANG.
static void probe_menu_text(void) {
static const char *const langs[] = {"en", "ja", "fr", "de", "it", "es", "nl", "pt", "ru", "zh-Hans", "zh-Hant", "ko",
"pt-BR"};
"pt-BR", "vi"};
static const char *const menu_langs[] = {"de", "fr", "es", "it", "nl", "ja", "ko", "vi"};
for (int id = UI_MENU_FIRST; id <= UI_MENU_LAST_ID; id++) {
CHECK(ui_text_defined("en", (UiTextId)id) && ui_text_defined("ru", (UiTextId)id) &&
ui_text_defined("pt-BR", (UiTextId)id), "menu text id %d lacks en, ru or pt-BR", id);
ui_text_defined("pt-BR", (UiTextId)id) && ui_text_defined("vi", (UiTextId)id),
"menu text id %d lacks en, ru, pt-BR or vi", id);
CHECK(*ui_text_in("en", (UiTextId)id) && *ui_text_in("ru", (UiTextId)id) && *ui_text_in("pt-BR", (UiTextId)id),
"menu text id %d is empty", id);
// the description pane keeps the whole text and a note after it (option_rows.cpp desc_set)
CHECK(strlen(ui_text_in("en", (UiTextId)id)) + 256 < UI_DESC_BYTES &&
strlen(ui_text_in("ru", (UiTextId)id)) + 256 < UI_DESC_BYTES &&
strlen(ui_text_in("pt-BR", (UiTextId)id)) + 256 < UI_DESC_BYTES &&
strlen(ui_text_in("zh-Hans", (UiTextId)id)) + 256 < UI_DESC_BYTES,
strlen(ui_text_in("zh-Hans", (UiTextId)id)) + 256 < UI_DESC_BYTES &&
strlen(ui_text_in("vi", (UiTextId)id)) + 256 < UI_DESC_BYTES,
"menu text id %d is too long for the description pane", id);
for (size_t i = 0; i < sizeof menu_langs / sizeof *menu_langs; i++)
CHECK(strlen(ui_text_in(menu_langs[i], (UiTextId)id)) + 256 < UI_DESC_BYTES,
"menu text id %d is too long for the description pane in %s", id, menu_langs[i]);
CHECK(ui_text_defined("zh-Hans", (UiTextId)id), "menu text id %d lacks Simplified Chinese", id);
}
CHECK(!ui_text_defined("en", UI_TEXT_COUNT) && !*ui_text_in("ru", UI_TEXT_COUNT), "an id past the catalog gives text");
// other languages fall back to English for the menu, and keep their own keyboard texts
CHECK(!strcmp(ui_text_in("ja", UI_MENU_CONTINUE), ui_text_in("en", UI_MENU_CONTINUE)), "ja menu text is not English");
// the other game languages have their own menu text; Traditional Chinese falls back to English in the catalog
for (size_t i = 0; i < sizeof menu_langs / sizeof *menu_langs; i++) {
CHECK(ui_text_defined(menu_langs[i], UI_MENU_TITLE) && ui_text_defined(menu_langs[i], UI_MENU_CONTINUE),
"%s has no menu text", menu_langs[i]);
CHECK(strstr(ui_text_in(menu_langs[i], UI_MENU_OV_GAME_PCT), "%.0f%%"), "%s overlay format lost its conversion",
menu_langs[i]);
}
CHECK(!strcmp(ui_text_in("zh-Hant", UI_MENU_CONTINUE), ui_text_in("en", UI_MENU_CONTINUE)),
"zh-Hant menu text is not English");
CHECK(!strcmp(ui_text_in("ru", UI_SWKBD_OK), "ОК") && !strcmp(ui_text_in("de", UI_SWKBD_CANCEL), "Abbrechen") &&
!strcmp(ui_text_in("en", UI_SWKBD_OK), "OK"), "keyboard texts changed");
// language names: the same string in every row
for (int id = UI_MENU_LANGNAME_EN; id <= UI_MENU_LANGNAME_ES_419; id++)
for (int id = UI_MENU_LANGNAME_EN; id <= UI_MENU_LANGNAME_VI; id++)
for (size_t i = 1; i < sizeof langs / sizeof *langs; i++)
CHECK(!strcmp(ui_text_in(langs[i], (UiTextId)id), ui_text_in("en", (UiTextId)id)), "language name %d differs in %s", id, langs[i]);
CHECK(!strcmp(ui_text_in("en", UI_MENU_LANGNAME_RU), "Русский"), "Russian is not shown as Russian");
@@ -1075,15 +1089,24 @@ static void probe_menu_text(void) {
CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in("en", UI_MENU_CONTINUE), "menu_text did not follow MENU_LANG=en");
cfg_set("TOTK_MENU_LANG", "zh-Hans");
CHECK(menu_text(UI_MENU_TITLE) == ui_text_in("zh-Hans", UI_MENU_TITLE), "menu_text ignores MENU_LANG=zh-Hans");
cfg_set("TOTK_MENU_LANG", "ja");
CHECK(menu_text(UI_MENU_TITLE) == ui_text_in("ja", UI_MENU_TITLE), "menu_text ignores MENU_LANG=ja");
cfg_set("TOTK_MENU_LANG", "de-DE");
CHECK(menu_text(UI_MENU_TITLE) == ui_text_in("de", UI_MENU_TITLE), "menu_text ignores MENU_LANG=de-DE");
// Traditional Chinese (zh-TW, zh-HK) reads the Simplified Chinese menu
cfg_set("TOTK_MENU_LANG", "zh-TW");
CHECK(menu_text(UI_MENU_TITLE) == ui_text_in("zh-Hans", UI_MENU_TITLE), "zh-TW does not get the zh-Hans menu");
cfg_set("TOTK_MENU_LANG", "");
// the system language as ui_text.c resolve_menu_lang takes it: the tag, else its base language (ru-RU: ru), else en
// the system language as ui_text.c resolve_menu_lang takes it: the tag, else its base language (ru-RU: ru), else
// Simplified Chinese for any Chinese, else en
const char *sys_lang = ui_text_lang(plat_ui_language());
char sys_base[16] = "";
size_t base_n = strcspn(sys_lang, "-");
if (sys_lang[base_n] && base_n < sizeof sys_base) memcpy(sys_base, sys_lang, base_n);
const char *auto_lang = ui_text_defined(sys_lang, UI_MENU_TITLE) ? sys_lang
const char *auto_lang = ui_text_defined(sys_lang, UI_MENU_TITLE) ? sys_lang
: *sys_base && ui_text_defined(sys_base, UI_MENU_TITLE) ? sys_base
: "en";
: !strncmp(sys_lang, "zh", 2) ? "zh-Hans"
: "en";
CHECK(menu_text(UI_MENU_CONTINUE) == ui_text_in(auto_lang, UI_MENU_CONTINUE), "menu_text auto ignores the system language");
}
+13
View File
@@ -119,6 +119,18 @@ static void ov_desired_language(Cpu *c) {
ret_x(c, v);
}
// nn::settings::detail::GetLanguageCode(LanguageCode *out): the system language, the one GetDesiredLanguage gives.
// The game never calls it; Material Columns picks its text by it. x0 = 0 for the callers that read a Result.
static void ov_settings_language(Cpu *c) {
const char *code = ov_language();
uint8_t *out = arg_p(c, 0);
if (out) {
memset(out, 0, 8);
memcpy(out, code, strlen(code));
}
ret_x(c, 0);
}
static void ov_oe_initialize(Cpu *c) { (void)c; rt_log("oe: application environment: a local host process"); }
// void SetPerformanceConfiguration(PerformanceMode mode, int config)
@@ -872,6 +884,7 @@ static void ov_font_size(Cpu *c) {
// ==== registration
HOST_OVERRIDE("_ZN2nn2oe10InitializeEv", ov_oe_initialize);
HOST_OVERRIDE("_ZN2nn2oe18GetDesiredLanguageEv", ov_desired_language);
HOST_OVERRIDE("_ZN2nn8settings6detail15GetLanguageCodeEPNS0_12LanguageCodeE", ov_settings_language);
HOST_OVERRIDE("_ZN2nn2oe27SetPerformanceConfigurationENS0_15PerformanceModeEi", ov_performance_config);
HOST_OVERRIDE("_ZN2nn2oe15SetCpuBoostModeENS0_12CpuBoostModeE", ov_cpu_boost);
HOST_OVERRIDE("_ZN2nn2oe16GetOperationModeEv", ov_operation_mode);
+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.
+41 -26
View File
@@ -38,9 +38,15 @@
// hook branches reach main's .text.
// - nn::oe::GetDisplayVersion is answered with this build's game version, so the plugin picks its table for the
// installed game without the applet services.
// Only svcs the init needs are allowed (QueryMemory, GetSystemTick, OutputDebugString, GetInfo 2-5, 12-15 and 65001,
// Map/UnmapProcessMemory); any other one, such as CreateSession and ReplyAndReceive of exlaunch's process-handle
// fallback, ends the run with the reason in the record.
// - GetInfo 6, 16 and 17, the total memory and the system resource size and use, are constants (memory.c
// mem_info); 7, the memory in use, is the same at the same point of the same init. Zonai Fieldworks asks them
// after its hooks are in.
// - SetHeapSize grows the process heap past the size the game's nninitStartup set before the init runs (Zonai
// Fieldworks keeps a pool in the tail). The heap base is fixed and the game asked its size the same way at every
// start, so the init gets the same answer each time.
// Only svcs the init needs are allowed (SetHeapSize, QueryMemory, GetSystemTick, OutputDebugString, GetInfo 2-7,
// 12-17 and 65001, Map/UnmapProcessMemory); any other one, such as CreateSession and ReplyAndReceive of exlaunch's
// process-handle fallback, ends the run with the reason in the record.
//
// The record, in DIR: record.json (modules, which plugins' inits ran, the writes into every game module as words, the
// alias calls, svc and import counts, the tick offset, a refusal), plugin<N>.img (the plugin's image after its init,
@@ -56,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"
@@ -69,7 +76,9 @@
#define POOL_SIZE (64 * GiB)
#define POOL_ALIGN (4 * GiB)
#define RTLD_ALIGN 0x200000ull
#define MAX_ALIASES 256
// exlaunch maps a page alias for every patch it writes and unmaps it after; Zonai Fieldworks makes over 211 in its
// init. Each slot is 48 bytes, and only the live aliases hold a copy of their pages.
#define MAX_ALIASES 2048
#define MAX_IMPORTS 64
#define CUR_PROCESS 0xFFFF8001u
// Horizon memory states and permissions of QueryMemory, and results.
@@ -94,7 +103,7 @@ static uint64_t pool_base;
static int running; // a plugin's init runs: svcs and imports are counted
static int play; // plugins_start: a refused SVC fails the plugin instead of ending the process
static char failed[256]; // play: why the running init was refused
static uint64_t svc_count[0x80], info_count[16], info_65001;
static uint64_t svc_count[0x80], info_count[18], info_65001;
static struct { const char *name; uint64_t calls; } imports[MAX_IMPORTS];
static int nimports;
static uint8_t **pre; // per loaded module: its image before the plugins' inits
@@ -198,11 +207,22 @@ static uint32_t process_memory(int unmap, uint64_t dst, uint32_t process, uint64
}
return R_INVALID_STATE;
}
if (!module_holding(src, size)) return R_INVALID_STATE; // only the modules' own memory
if (!module_holding(src, size)) { // only the modules' own memory
rt_log("plugin-init: MapProcessMemory refused: the source %#llx+%#llx is no module's memory",
(unsigned long long)src, (unsigned long long)size);
return R_INVALID_STATE;
}
RtMemoryInfo q;
mem_query(dst, &q);
if (q.state != ST_FREE || dst + size > q.base + q.size) return R_INVALID_STATE;
if (naliases == MAX_ALIASES) return R_LIMIT_REACHED;
if (q.state != ST_FREE || dst + size > q.base + q.size) {
rt_log("plugin-init: MapProcessMemory refused: the destination %#llx+%#llx is not free (state %#x)",
(unsigned long long)dst, (unsigned long long)size, q.state);
return R_INVALID_STATE;
}
if (naliases == MAX_ALIASES) {
rt_log("plugin-init: MapProcessMemory refused: all %d alias slots used", MAX_ALIASES);
return R_LIMIT_REACHED;
}
if (!plat_mem_commit(dst, size)) return R_INVALID_STATE; // not inside one of our reservations
Alias *al = &aliases[naliases];
al->snap = malloc(size);
@@ -235,10 +255,10 @@ static int plugin_svc(Cpu *c, uint32_t imm, uint64_t pc) {
svc_count[imm & 0x7F]++;
char why[256], at[128];
switch (imm) {
case 0x06: case 0x1E: case 0x27: case 0x74: case 0x75: return 0;
case 0x01: case 0x06: case 0x1E: case 0x27: case 0x74: case 0x75: return 0;
case 0x29: {
uint32_t id = (uint32_t)c->x[1];
if ((id >= 2 && id <= 5) || (id >= 12 && id <= 15)) {
if ((id >= 2 && id <= 7) || (id >= 12 && id <= 17)) {
info_count[id]++;
return 0;
}
@@ -252,8 +272,8 @@ static int plugin_svc(Cpu *c, uint32_t imm, uint64_t pc) {
return 1;
}
}
snprintf(why, sizeof why, "svc %#x at %s (only QueryMemory, GetSystemTick, OutputDebugString, GetInfo 2-5, 12-15 "
"and 65001, Map/UnmapProcessMemory are served)", imm, ldr_describe(pc, at, sizeof at));
snprintf(why, sizeof why, "svc %#x at %s (only SetHeapSize, QueryMemory, GetSystemTick, OutputDebugString, "
"GetInfo 2-7, 12-17 and 65001, Map/UnmapProcessMemory are served)", imm, ldr_describe(pc, at, sizeof at));
refuse(why);
c->x[0] = R_NOT_IMPLEMENTED;
return 1;
@@ -392,7 +412,7 @@ static void write_record(const char *refused) {
if (svc_count[i]) fprintf(f, "%s\"%#x\": %llu", first ? "" : ", ", i, (unsigned long long)svc_count[i]), first = 0;
fputs("},\n\"get_info\": {", f);
first = 1;
for (int i = 0; i < 16; i++)
for (int i = 0; i < 18; i++)
if (info_count[i]) fprintf(f, "%s\"%d\": %llu", first ? "" : ", ", i, (unsigned long long)info_count[i]), first = 0;
if (info_65001) fprintf(f, "%s\"65001\": %llu", first ? "" : ", ", (unsigned long long)info_65001);
fputs("},\n\"imports\": {", f);
@@ -504,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[] = {
@@ -571,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.
@@ -593,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);
@@ -608,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);
@@ -694,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;
}
+73 -19
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
@@ -102,11 +104,35 @@ int res_dlss_dll(void) {
return dll;
}
// The engine picked at start can run, as far as is known before the device exists: DLSS needs its DLL (dlss_dll); FSR
// 3.1 is built in (vk_fsr3.cpp). Off: nothing to run.
// AMD's FSR 4 (vk_ffx.c) loads amd_fidelityfx_loader_vk.dll from the folder of totk.exe, which finds
// amd_fidelityfx_upscaler_vk.dll next to itself; both come from the setup's FSR step. Windows only: AMD ships no Linux
// libraries.
static int ffx_dlls(void) {
#ifdef _WIN32
char exe[1024], path[1024 + 48];
if (!plat_exe_path(exe, sizeof exe)) return 1;
char *last = plat_last_sep(exe);
if (!last) return 1;
snprintf(path, sizeof path, "%.*s/amd_fidelityfx_loader_vk.dll", (int)(last - exe), exe);
if (!plat_file_exists(path)) return 0;
snprintf(path, sizeof path, "%.*s/amd_fidelityfx_upscaler_vk.dll", (int)(last - exe), exe);
return plat_file_exists(path);
#else
return 0;
#endif
}
int res_ffx_dlls(void) {
static int dlls = -1;
if (dlls < 0) dlls = ffx_dlls();
return dlls;
}
// The engine picked at start can run, as far as is known before the device exists: DLSS needs its DLL (dlss_dll), FSR
// 4 AMD's two libraries (ffx_dlls); FSR 3.1 is built in (vk_fsr3.cpp). Off: nothing to run.
static int upscaler_ready(void) {
int e = vk_upscaler_engine();
return e == UPSCALER_DLSS ? res_dlss_dll() : e == UPSCALER_FSR3;
return e == UPSCALER_DLSS ? res_dlss_dll() : e == UPSCALER_FSR4 ? res_ffx_dlls() : e == UPSCALER_FSR3;
}
static uint64_t shadow_kib(void);
@@ -143,8 +169,12 @@ static double dlss_share(const char *m) {
int ready = upscaler_ready();
if (!ready && !told++) {
#ifdef _WIN32
rt_log("resolution: DLSS %s needs nvngx_dlss.dll next to totk.exe, which is missing: the scene follows "
"render_scale", m);
if (vk_upscaler_engine() == UPSCALER_FSR4)
rt_log("resolution: FSR 4 %s needs amd_fidelityfx_loader_vk.dll and amd_fidelityfx_upscaler_vk.dll "
"next to totk.exe, which are missing: the scene follows render_scale", m);
else
rt_log("resolution: DLSS %s needs nvngx_dlss.dll next to totk.exe, which is missing: the scene "
"follows render_scale", m);
#else
rt_log("resolution: DLSS %s needs libnvidia-ngx-dlss.so.<version> next to totk, which is missing: the "
"scene follows render_scale", m);
@@ -208,7 +238,7 @@ static void decide(void) {
else rt_log("resolution: TOTK_SHADOW_RES=%s is not game or a size 256..4096 (a multiple of 8); game", sr);
}
// A DLSS mode other than dlaa sets the scene size instead. On 1.4.3 with the scene upscaler able to run (DLSS with
// its DLL there, or FSR 3.1 in the build)
// its DLL there, FSR 4 with AMD's libraries there, or FSR 3.1 in the build)
// the mode can change while the game runs (res_dlss_mode): the scene patch is then always on and the heap is sized
// for the largest scene the modes ask for. Everyone else keeps the game's own scene size and its dynamic resolution
// unless render_scale or a DLSS mode asks for another, and a heap sized for that scene alone.
@@ -615,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
@@ -645,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,
@@ -674,8 +727,8 @@ void res_fov_live(void) {
// 2867-wide scene stays at 100 %, one wider than about 2970 does not, and a 4267-wide one (5120x1440 at render_scale
// 83) fits no tier and falls back to 80 % every frame, whatever the GPU's load. 1 (the default) leaves the game's own
// stepping and the set off. Runs on a settings change (gfx_present.c window_settings_live), like res_fov_live.
// FSR 3.1 as the scene upscaler holds it at 100 % whatever dynamic_res says, as codexx-dev's pull request #1245 does
// for its FSR: each tier is a scene of another size, so every step starts FSR's history again, and below 100 % the
// FSR 3.1 or FSR 4 as the scene upscaler holds it at 100 % whatever dynamic_res says, as codexx-dev's pull request
// #1245 does for its FSR: each tier is a scene of another size, so every step starts FSR's history again, and below 100 % the
// game ends its frame another way (a frame log on 1.4.3: its copy shader scales the scene straight into the
// output-sized target instead of the scaling FXAA draw), which #1245 measured as a picture that went soft and sharp in
// turns at a 2560x1440 scene. A 1280x720 scene (1080p, quality) stayed at 100 % through a 70 s town run, so it gains
@@ -683,7 +736,8 @@ void res_fov_live(void) {
void res_dynres_live(void) {
static int set = -2, shown = -1;
if (set == -2) set = rt_patch_set("fixres");
int fsr = vk_upscaler_on() && vk_upscaler_engine() == UPSCALER_FSR3;
int e = vk_upscaler_engine();
int fsr = vk_upscaler_on() && (e == UPSCALER_FSR3 || e == UPSCALER_FSR4);
int dyn = cfg_bool("TOTK_DYNAMIC_RES") && !fsr;
int state = dyn | fsr << 1;
if (state == shown) return;
@@ -695,7 +749,7 @@ void res_dynres_live(void) {
rt_patch_switch(set, !dyn);
rt_log("resolution: dynamic resolution %s",
dyn ? "on: the game's own 100, 90 or 80 %"
: fsr ? "off while FSR 3.1 upscales the scene: the scene stays at 100 %"
: fsr ? "off while FSR upscales the scene: the scene stays at 100 %"
: "off: the scene stays at 100 %");
}
+135 -2
View File
@@ -25,7 +25,8 @@
//
// The resource size table: with a player mod enabled, the game's table is rebuilt at start with the tables the mods
// ship merged in and the entries of the mods' files raised to what they need (restbl_overlay), the members of their
// packs too (restbl_packs), and served from <profile>/mods/ in place of the game's or a mod's table.
// packs too (restbl_packs), and served from <profile>/mods/ in place of the game's or a mod's table. TOTK_RESTBL_CACHE=1
// serves the table of the last start instead when every input of the build is the same (restbl_cache_key).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -761,6 +762,127 @@ static int restbl_packs(Restbl *out, const Restbl *base, int *packs, int *lines)
return raised;
}
// ---- the merged table across starts (TOTK_RESTBL_CACHE=1, off by default). Building it opens every mod file and
// unpacks the mods' packs. A start whose inputs are the same as the last one's serves the table that start wrote.
// The key is a SHA-256 over every input restbl_overlay reads:
// - the running totk.exe's path and identity: a new build may merge differently, and it carries the port version, the
// game version and the RomFS index's SHA-256 (romfs_config.h);
// - the RomFS image's path and identity and the game table's index entry: the base table, the game's copies of the
// mods' packs and Pack/ZsDic.pack.zs come from the image;
// - every shipped table (restbl_collect, mod_walk_cb; also the ones overlay_contest drops) with its owner and identity;
// - every overlay overlay_contest kept (player mods, the TOTK_ROMFS_MODS manifest, the port's folders) with its RomFS
// path, file path, place in the order (index, prio, mod) and identity.
// Identity is the volume, file id, size, last write and creation time. A file's bytes are not hashed: identity is
// what the overlay layer already trusts (romfs_open stops the game on a file whose identity changed after the start
// check), and hashing a texture pack would cost more than the merge does. <profile>/mods/<table>.key holds the key,
// what the build gave (a table or none) and the SHA-256 of the table it wrote; it is replaced atomically after the
// table is written. A key file of another size, magic or version, another key, or a table of another SHA-256 is a
// miss: the table is built again and both files are replaced, so the cache stays two files.
#define RESTBL_CACHE_VERSION 3
typedef struct { char magic[8]; uint32_t version, outcome; uint8_t key[32], table[32]; } RestblCache;
enum { RESTBL_NONE = 1, RESTBL_TABLE = 2 };
static void restbl_cache_paths(char *key, size_t key_cap, char *table, size_t table_cap) {
const char *leaf = strrchr(restbl_rel, '/') ? strrchr(restbl_rel, '/') + 1 : restbl_rel;
need(snprintf(table, table_cap, "%s/mods/%s", rt_config()->profile, leaf) < (int)table_cap, "table path");
need(snprintf(key, key_cap, "%s.key", table) < (int)key_cap, "table key path");
}
static void hash_identity(Sha256 *h, const char *path, const Identity *id) {
sha256_update(h, path, strlen(path) + 1);
sha256_update(h, id, sizeof *id);
}
// 0 when path cannot be opened.
static int hash_file_id(Sha256 *h, const char *path) {
PlatFile *f = open_read(path);
Identity id = {0};
if (f) id = identity_of(f), plat_file_close(f);
hash_identity(h, path, &id);
return f != NULL;
}
// The key of this start's inputs into out; 0 when the running exe cannot be opened (no key: the table is built).
static int restbl_cache_key(uint64_t gi, uint8_t out[32]) {
char exe[2100];
Sha256 h;
sha256_init(&h);
static const char tag[] = "totk restbl cache";
uint32_t v = RESTBL_CACHE_VERSION;
sha256_update(&h, tag, sizeof tag);
sha256_update(&h, &v, sizeof v);
sha256_update(&h, rt_port_version, strlen(rt_port_version) + 1);
if (!plat_exe_path(exe, sizeof exe) || !hash_file_id(&h, exe)) return 0;
Identity img = identity_of(image);
hash_identity(&h, image_file, &img);
Entry ge = entry(gi);
sha256_update(&h, &ge, sizeof ge);
uint64_t n = nshipped;
sha256_update(&h, &n, sizeof n);
for (size_t s = 0; s < nshipped; s++) {
int32_t m[2] = {shipped[s].mod, shipped[s].other};
sha256_update(&h, m, sizeof m);
hash_file_id(&h, shipped[s].file);
}
n = noverlay;
sha256_update(&h, &n, sizeof n);
for (size_t k = 0; k < noverlay; k++) {
const Overlay *o = &overlays[k];
int64_t place[3] = {o->index == ADDED ? -1 : (int64_t)o->index, o->prio, o->mod};
sha256_update(&h, o->name, strlen(o->name) + 1);
sha256_update(&h, place, sizeof place);
hash_identity(&h, o->path, &o->id);
}
sha256_final(&h, out);
return 1;
}
// Records the build's result for key: RESTBL_NONE, or RESTBL_TABLE with the SHA-256 of the table it wrote.
static void restbl_cache_store(const uint8_t key[32], int outcome, const uint8_t table[32]) {
char kp[2300], tp[2300];
restbl_cache_paths(kp, sizeof kp, tp, sizeof tp);
RestblCache c = {.magic = {'T', 'O', 'T', 'K', 'R', 'S', 'Z', 'C'}, .version = RESTBL_CACHE_VERSION,
.outcome = (uint32_t)outcome};
memcpy(c.key, key, 32);
if (table) memcpy(c.table, table, 32);
if (!plat_file_write_atomic(kp, &c, sizeof c))
rt_log("RomFS: cannot write %s; the resource size table is built at every start", kp);
}
// 1 when the last start's result fits: its table is served again (or none, as then). A miss logs why.
static int restbl_cache_use(const uint8_t key[32], Overlay *served, const char *keeps, double t0) {
char kp[2300], tp[2300];
restbl_cache_paths(kp, sizeof kp, tp, sizeof tp);
uint64_t n = 0;
RestblCache *c = (RestblCache *)plat_file_read(kp, &n);
const char *miss = NULL;
if (!c || n != sizeof *c || memcmp(c->magic, "TOTKRSZC", 8) || c->version != RESTBL_CACHE_VERSION ||
(c->outcome != RESTBL_NONE && c->outcome != RESTBL_TABLE))
miss = "no usable key from an earlier start";
else if (memcmp(c->key, key, 32))
miss = "the mods, the game files or the build changed since the last start";
if (!miss && c->outcome == RESTBL_TABLE) {
uint64_t zn = 0;
uint8_t *z = plat_file_read(tp, &zn), sum[32];
if (z) sha256(z, (size_t)zn, sum);
if (!z || memcmp(sum, c->table, 32)) {
free(z);
miss = "the kept table is missing or damaged";
} else if (!serve_generated(restbl_rel, served, z, (size_t)zn, "mods", // frees z
"merged resource sizes, kept from the last start", keeps)) {
miss = "the kept table cannot be served";
}
}
if (miss)
rt_log("RomFS: resource size table: built again: %s", miss);
else
rt_log("RomFS: resource size table: the mods' files are the ones of the last start: %s (%.0f ms)",
c->outcome == RESTBL_TABLE ? "its merged table is used" : "they fit the game's entries",
(now_s() - t0) * 1000);
free(c);
return !miss;
}
// With a player mod (or the TOTK_ROMFS_MODS manifest) serving files: the game's table with every shipped table of this
// version merged in (an entry larger than the game's wins), the entries a mod's table for another version gives for
// that mod's files, and each served mod file's entry raised to what its size needs (restbl_grow for a file the game
@@ -773,6 +895,12 @@ static void restbl_overlay(void) {
static const char keeps[] = "mod files that grew may fail to load";
double t0 = now_s();
uint64_t gi = lower(restbl_rel);
uint8_t cache_key[32];
Overlay *served_now = NULL;
for (size_t k = 0; k < noverlay; k++)
if (overlays[k].index == gi) served_now = &overlays[k];
int cached = rt_knob("RESTBL_CACHE", "0") && restbl_cache_key(gi, cache_key);
if (cached && restbl_cache_use(cache_key, served_now, keeps, t0)) return;
Entry ge = entry(gi);
void *gz = ge.size < (64u << 20) ? malloc((size_t)ge.size) : NULL;
Restbl *base = NULL, *out = NULL;
@@ -838,6 +966,7 @@ static void restbl_overlay(void) {
if (!merged && !raised && !members && !served) {
restbl_free(out);
rt_log("RomFS: resource size table: the mods' files fit the game's entries (%.0f ms)", (now_s() - t0) * 1000);
if (cached) restbl_cache_store(cache_key, RESTBL_NONE, NULL);
return;
}
size_t rn = 0, zn = 0;
@@ -852,10 +981,14 @@ static void restbl_overlay(void) {
rt_log("RomFS: cannot pack the merged resource size table; %s", keeps);
return;
}
if (serve_generated(restbl_rel, served, z, zn, "mods", "merged resource sizes", keeps))
uint8_t sum[32];
if (cached) sha256(z, zn, sum); // before serve_generated frees z
if (serve_generated(restbl_rel, served, z, zn, "mods", "merged resource sizes", keeps)) {
rt_log("RomFS: resource size table: %d tables merged (%d entries), %d entries raised for mod files (%d "
"added files estimated), %d for members of %d mod packs, %.0f ms", tables, merged, raised, estimated,
members, packs, (now_s() - t0) * 1000);
if (cached) restbl_cache_store(cache_key, RESTBL_TABLE, sum);
}
}
// The HeapDef table a bigger game resolution or TOTK_TEX_HEAP_EXTRA_MB needs (resolution.c): its texture heaps and
+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;
}
+6
View File
@@ -43,3 +43,9 @@ Changes of our own (marked "TotK Recomp"):
- `sdk/include/FidelityFX/gpu/fsr3upscaler/ffx_fsr3upscaler_callbacks_glsl.h`: the luma history's storage image is
declared `rgba16f`, the format of its images (R16G16B16A16_FLOAT in `ffx_fsr3upscaler.cpp`). It was `rgba8`, which
the Vulkan validation layer reports as a format mismatch with undefined loads and stores.
- `sdk/src/backends/vk/ffx_vk.cpp` `findMemoryTypeIndex`: memory types with `PROTECTED`, `DEVICE_COHERENT_AMD` or
`DEVICE_UNCACHED_AMD` are skipped, since the runtime enables neither protected memory nor device-coherent memory. The
function keeps the last matching type, and RADV lists those types after the plain device-local ones, so on a Radeon
780M (Mesa 26.3) FSR 3.1's images were allocated in them and its whole output was noise. When no device-local type
without `HOST_VISIBLE` exists (unified-memory GPUs: Adreno under Turnip) it takes a host-visible device-local one
instead of failing every texture allocation.
@@ -402,14 +402,28 @@ uint32_t findMemoryTypeIndex(VkPhysicalDevice physicalDevice, VkMemoryRequiremen
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
uint32_t bestCandidate = UINT32_MAX;
// TotK Recomp: unified-memory GPUs (Adreno under Turnip) have no device-local type without HOST_VISIBLE: the first
// host-visible one is taken rather than failing when no invisible type exists.
uint32_t visibleCandidate = UINT32_MAX;
VkMemoryPropertyFlags visibleProperties = 0;
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
if ((memRequirements.memoryTypeBits & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & requestedProperties)) {
// if just device-local memory is requested, make sure this is the invisible heap to prevent over-subscribing the local heap
if (requestedProperties == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT && (memProperties.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT))
// TotK Recomp: types that need a device feature the application did not enable are skipped. The loop keeps
// the last match, and RADV lists protected (TMZ) and AMD device-coherent/uncached device-local types after
// the plain ones: FSR 3.1's images landed in them and every pass read noise.
if (memProperties.memoryTypes[i].propertyFlags & (VK_MEMORY_PROPERTY_PROTECTED_BIT | VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD |
VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD))
continue;
// if just device-local memory is requested, make sure this is the invisible heap to prevent over-subscribing the local heap
if (requestedProperties == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT && (memProperties.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) {
if (visibleCandidate == UINT32_MAX)
visibleCandidate = i, visibleProperties = memProperties.memoryTypes[i].propertyFlags;
continue;
}
bestCandidate = i;
outProperties = memProperties.memoryTypes[i].propertyFlags;
@@ -419,6 +433,10 @@ uint32_t findMemoryTypeIndex(VkPhysicalDevice physicalDevice, VkMemoryRequiremen
}
}
if (bestCandidate == UINT32_MAX && visibleCandidate != UINT32_MAX) {
bestCandidate = visibleCandidate;
outProperties = visibleProperties;
}
return bestCandidate;
}
+51 -30
View File
@@ -67,7 +67,7 @@ int playtime_get(uint64_t *total_s, uint64_t *session_s); // playtime.c
bool amiibo_check_font_rebuild(void); // ui/amiibo_page.cpp; check and clear font rebuild request
}
// Roboto Medium (Apache-2.0, ui/fonts/LICENSE-Roboto.txt) with Latin and Cyrillic glyphs.
// Roboto Medium (Apache-2.0, ui/fonts/LICENSE-Roboto.txt) with Latin, Vietnamese and Cyrillic glyphs.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc23-extensions" // #embed in C++
static const unsigned char roboto_ttf[] = {
@@ -276,12 +276,14 @@ static int vk_up(const MenuTarget *t) {
return 1;
}
// Roboto Medium (Latin, Cyrillic, dashes and quotes) at 26 px per 1080 lines, with the glyphs of the Japanese, Korean
// and Chinese language names merged in from a system font when there is one (each language is named in its own script).
// A catalog row also holds menu text (Simplified Chinese), so every string of the row goes into the builder: the merged
// font must cover the whole menu of that language, not only its name. Made again when the window height changes; the old
// texture goes after the queue is idle (CreateFontsTexture).
static const ImWchar kRanges[] = {0x0020, 0x00FF, 0x0400, 0x052F, 0x2010, 0x2027, 0};
// Roboto Medium (Latin with Latin Extended-A for the French oe and the Vietnamese letters Latin-1 lacks:
// 0x0100-0x01B0, the combining marks 0x0300-0x0323 and 0x1EA0-0x1EF9; Cyrillic, dashes and quotes) at 26 px per
// 1080 lines, with the glyphs of the Japanese, Korean and Chinese language names merged in from a system font when
// there is one (each language is named in its own script). A catalog row also holds menu text (Japanese, Korean,
// Simplified Chinese), so every string of the row goes into the builder: the merged font must cover the whole menu
// of that language, not only its name. Made again when the window height changes; the old texture goes after the
// queue is idle (CreateFontsTexture).
static const ImWchar kRanges[] = {0x0020, 0x01B0, 0x0300, 0x0323, 0x0400, 0x052F, 0x1EA0, 0x1EF9, 0x2010, 0x2027, 0};
static const struct { const char *lang; UiTextId name; } kCjk[] = {
{"ja", UI_MENU_LANGNAME_JA}, {"ko", UI_MENU_LANGNAME_KO}, {"zh-Hans", UI_MENU_LANGNAME_ZH_HANS},
{"zh-Hant", UI_MENU_LANGNAME_ZH_HANT},
@@ -569,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];
@@ -616,22 +621,30 @@ static void row_hud_width(void) {
opt_choice_list("TOTK_HUD_WIDTH", UI_MENU_HUD_WIDTH, vals, names, n, UI_MENU_HUD_WIDTH_DESC);
}
// The 3D scene upscaler (vk_dlaa.c): off, NVIDIA DLSS or AMD FSR 3.1. An engine that cannot run here is left out of
// the steps, and the note under the value says why; a totk.ini that names it anyway shows it, with the same note.
// Returns the value the settings name ("off", "dlss", "fsr3"; without scene_upscaler, dlaa = 1 is "dlss").
// The 3D scene upscaler (vk_dlaa.c): off, NVIDIA DLSS, AMD FSR 3.1 or AMD FSR 4. An engine that cannot run here is
// left out of the steps, and the note under the value says why; a totk.ini that names it anyway shows it, with the
// same note. FSR 4 is Windows only (AMD ships no Linux libraries): elsewhere it is left out without a note.
// Returns the value the settings name ("off", "dlss", "fsr3", "fsr4"; without scene_upscaler, dlaa = 1 is "dlss").
static const char *row_scene_upscaler(void) {
static const char *const all[] = {"off", "dlss", "fsr3"};
static const int engines[] = {UPSCALER_OFF, UPSCALER_DLSS, UPSCALER_FSR3};
static const UiTextId ids[] = {UI_MENU_SCENE_UPSCALER_OFF, UI_MENU_SCENE_UPSCALER_DLSS, UI_MENU_SCENE_UPSCALER_FSR3};
enum { N = 4 };
static const char *const all[N] = {"off", "dlss", "fsr3", "fsr4"};
static const int engines[N] = {UPSCALER_OFF, UPSCALER_DLSS, UPSCALER_FSR3, UPSCALER_FSR4};
static const UiTextId ids[N] = {UI_MENU_SCENE_UPSCALER_OFF, UI_MENU_SCENE_UPSCALER_DLSS, UI_MENU_SCENE_UPSCALER_FSR3,
UI_MENU_SCENE_UPSCALER_FSR4};
const char *now = cfg_scene_upscaler();
const char *vals[3], *names[3];
const char *vals[N], *names[N];
static char note[256];
note[0] = 0;
int n = 0, cur = -1;
for (int i = 0; i < 3; i++) {
for (int i = 0; i < N; i++) {
int why = vk_upscaler_missing(engines[i]);
if (why) {
UiTextId t = why == UPSCALER_MISSING_DLL ? UI_MENU_SCENE_UPSCALER_NO_DLSS_DLL : UI_MENU_SCENE_UPSCALER_NO_DLSS_GPU;
if (why && (why != UPSCALER_MISSING_OS || !strcmp(now, all[i]))) {
UiTextId t = engines[i] == UPSCALER_FSR4
? (why == UPSCALER_MISSING_DLL ? UI_MENU_SCENE_UPSCALER_NO_FSR4_DLL
: why == UPSCALER_MISSING_OS ? UI_MENU_SCENE_UPSCALER_NO_FSR4_OS
: UI_MENU_SCENE_UPSCALER_NO_FSR4_GPU)
: why == UPSCALER_MISSING_DLL ? UI_MENU_SCENE_UPSCALER_NO_DLSS_DLL
: UI_MENU_SCENE_UPSCALER_NO_DLSS_GPU;
size_t k = strlen(note);
snprintf(note + k, sizeof note - k, "%s%s", k ? "; " : "", menu_text(t));
}
@@ -812,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);
@@ -827,9 +841,9 @@ static void tab_screen(float scale) {
UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA};
opt_choice("TOTK_DLSS", UI_MENU_DLSS, dlss, 5, UI_MENU_DLSS_DESC);
}
if (!strcmp(engine, "fsr3")) // FSR 3.1's own sharpening (vk_dlaa.c fsr_evaluate)
opt_slider("TOTK_FSR_SHARPNESS", UI_MENU_FSR3_SHARPNESS, 0, 100, UI_MENU_FSR3_SHARPNESS_DESC, 5, "%.0f %%");
if (!strcmp(engine, "dlss")) { // DLSS's model, its characters' mask and its other switches (FSR 3.1 has none)
if (!strcmp(engine, "fsr3") || !strcmp(engine, "fsr4")) // FSR's own sharpening (vk_dlaa.c fsr_evaluate)
opt_slider("TOTK_FSR_SHARPNESS", UI_MENU_FSR_SHARPNESS, 0, 100, UI_MENU_FSR_SHARPNESS_DESC, 5, "%.0f %%");
if (!strcmp(engine, "dlss")) { // DLSS's model, its characters' mask and its other switches (FSR has none)
static const UiTextId preset[] = {UI_MENU_DLSS_PRESET_DEFAULT, UI_MENU_DLSS_PRESET_K, UI_MENU_DLSS_PRESET_J};
opt_choice("TOTK_DLSS_PRESET", UI_MENU_DLSS_PRESET, preset, 3, UI_MENU_DLSS_PRESET_DESC);
static const UiTextId chars[] = {UI_MENU_DLSS_CHARS_OFF, UI_MENU_DLSS_CHARS_LIGHT, UI_MENU_DLSS_CHARS_MEDIUM,
@@ -838,8 +852,8 @@ static void tab_screen(float scale) {
opt_toggle("TOTK_DLSS_FIXED_EXPOSURE", UI_MENU_DLSS_FIXED_EXPOSURE, UI_MENU_DLSS_FIXED_EXPOSURE_DESC);
opt_toggle("TOTK_DLAA_EFFECTS_AFTER", UI_MENU_DLAA_EFFECTS_AFTER, UI_MENU_DLAA_EFFECTS_AFTER_DESC);
}
static const UiTextId reflex[] = {UI_MENU_REFLEX_OFF, UI_MENU_REFLEX_ON, UI_MENU_REFLEX_BOOST};
opt_choice("TOTK_REFLEX", UI_MENU_REFLEX, reflex, 3, UI_MENU_REFLEX_DESC);
static const UiTextId reflex[] = {UI_MENU_REFLEX_OFF, UI_MENU_REFLEX_AUTO, UI_MENU_REFLEX_ON, UI_MENU_REFLEX_BOOST};
opt_choice("TOTK_REFLEX", UI_MENU_REFLEX, reflex, 4, UI_MENU_REFLEX_DESC);
opt_toggle("TOTK_FXAA", UI_MENU_FXAA, UI_MENU_FXAA_DESC);
rows_color();
opt_group(UI_MENU_HDR_GROUP);
@@ -1179,7 +1193,10 @@ static void tab_controls(float scale) {
static void tab_menu(float scale) {
opt_begin("##menu", scale);
static const UiTextId langs[] = {UI_MENU_MENU_LANG_AUTO, UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_RU,
UI_MENU_LANGNAME_PT_BR, UI_MENU_LANGNAME_ZH_HANS};
UI_MENU_LANGNAME_PT_BR, UI_MENU_LANGNAME_ZH_HANS, UI_MENU_LANGNAME_DE,
UI_MENU_LANGNAME_FR, UI_MENU_LANGNAME_ES, UI_MENU_LANGNAME_IT,
UI_MENU_LANGNAME_NL, UI_MENU_LANGNAME_JA, UI_MENU_LANGNAME_KO,
UI_MENU_LANGNAME_VI};
opt_choice("TOTK_MENU_LANG", UI_MENU_MENU_LANG, langs, sizeof langs / sizeof *langs, UI_MENU_MENU_LANG_DESC);
opt_toggle("TOTK_DISCORD_RPC", UI_MENU_DISCORD_RPC, UI_MENU_DISCORD_RPC_DESC);
opt_end();
@@ -1263,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);
@@ -1779,7 +1798,9 @@ static void perf_picture(const MenuTarget *t, const ImVec4 &c) {
: !strcmp(m, "ultra_performance") ? UI_MENU_DLSS_ULTRA
: UI_MENU_DLSS_DLAA;
snprintf(v[6], sizeof v[6], "%s, %s",
menu_text(up == UPSCALER_FSR3 ? UI_MENU_SCENE_UPSCALER_FSR3 : UI_MENU_SCENE_UPSCALER_DLSS),
menu_text(up == UPSCALER_FSR4 ? UI_MENU_SCENE_UPSCALER_FSR4
: up == UPSCALER_FSR3 ? UI_MENU_SCENE_UPSCALER_FSR3
: UI_MENU_SCENE_UPSCALER_DLSS),
menu_text(mt));
}
// with frame generation: the pictures shown a second, of which the FPS row above counts the ones the game drew
+6831 -58
View File
File diff suppressed because it is too large. Load diff
+15 -9
View File
@@ -10,9 +10,12 @@ 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 and
// Simplified Chinese texts.
// 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.
UI_MENU_FIRST,
UI_MENU_TITLE = UI_MENU_FIRST,
UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_MODS, UI_MENU_TAB_SOUND, UI_MENU_TAB_CONTROLS, UI_MENU_TAB_AMIIBO,
@@ -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,
@@ -63,10 +67,11 @@ typedef enum {
UI_MENU_DLSS_BALANCED, UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA, UI_MENU_DLSS_PRESET, UI_MENU_DLSS_PRESET_DESC,
UI_MENU_DLSS_PRESET_DEFAULT, UI_MENU_DLSS_PRESET_K, UI_MENU_DLSS_PRESET_J, UI_MENU_DLSS_CHARS, UI_MENU_DLSS_CHARS_DESC,
UI_MENU_DLSS_CHARS_OFF, UI_MENU_DLSS_CHARS_LIGHT, UI_MENU_DLSS_CHARS_MEDIUM, UI_MENU_DLSS_CHARS_FULL, UI_MENU_FXAA, UI_MENU_FXAA_DESC,
UI_MENU_REFLEX, UI_MENU_REFLEX_DESC, UI_MENU_REFLEX_OFF, UI_MENU_REFLEX_ON, UI_MENU_REFLEX_BOOST,
UI_MENU_REFLEX, UI_MENU_REFLEX_DESC, UI_MENU_REFLEX_AUTO, UI_MENU_REFLEX_OFF, UI_MENU_REFLEX_ON, UI_MENU_REFLEX_BOOST,
UI_MENU_SCENE_UPSCALER, UI_MENU_SCENE_UPSCALER_DESC, UI_MENU_SCENE_UPSCALER_OFF, UI_MENU_SCENE_UPSCALER_DLSS,
UI_MENU_SCENE_UPSCALER_FSR3, UI_MENU_SCENE_UPSCALER_NO_DLSS_GPU, UI_MENU_SCENE_UPSCALER_NO_DLSS_DLL, UI_MENU_FSR3_SHARPNESS,
UI_MENU_FSR3_SHARPNESS_DESC,
UI_MENU_SCENE_UPSCALER_FSR3, UI_MENU_SCENE_UPSCALER_NO_DLSS_GPU, UI_MENU_SCENE_UPSCALER_NO_DLSS_DLL, UI_MENU_FSR_SHARPNESS,
UI_MENU_FSR_SHARPNESS_DESC, UI_MENU_SCENE_UPSCALER_FSR4, UI_MENU_SCENE_UPSCALER_NO_FSR4_GPU,
UI_MENU_SCENE_UPSCALER_NO_FSR4_DLL, UI_MENU_SCENE_UPSCALER_NO_FSR4_OS,
// Game
UI_MENU_FPS_LIMIT, UI_MENU_FPS_LIMIT_DESC, UI_MENU_FPS_30, UI_MENU_FPS_40, UI_MENU_FPS_45, UI_MENU_FPS_60, UI_MENU_FPS_90,
@@ -228,7 +233,7 @@ typedef enum {
UI_MENU_LANGNAME_EN, UI_MENU_LANGNAME_JA, UI_MENU_LANGNAME_FR, UI_MENU_LANGNAME_DE, UI_MENU_LANGNAME_IT,
UI_MENU_LANGNAME_ES, UI_MENU_LANGNAME_NL, UI_MENU_LANGNAME_RU, UI_MENU_LANGNAME_ZH_HANS,
UI_MENU_LANGNAME_ZH_HANT, UI_MENU_LANGNAME_KO, UI_MENU_LANGNAME_PT_BR, UI_MENU_LANGNAME_EN_GB,
UI_MENU_LANGNAME_FR_CA, UI_MENU_LANGNAME_ES_419,
UI_MENU_LANGNAME_FR_CA, UI_MENU_LANGNAME_ES_419, UI_MENU_LANGNAME_VI,
// Advanced
UI_MENU_ADV_WARNING,
@@ -239,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,
@@ -331,7 +337,7 @@ const char *ui_text_lang(const char *switch_code);
typedef struct { const char *code; UiTextId name; } UiGameLang;
int ui_text_game_langs(int game_version, UiGameLang *out, int max);
// Menu text: ui_text_in(menu language, id). The menu language is TOTK_MENU_LANG ("en", "ru", "pt-BR", "zh-Hans");
// unset, the system UI language when the catalog has menu text for it (English, Russian, Brazilian Portuguese,
// Simplified Chinese), else English. Follows a live change of the setting.
// Menu text: ui_text_in(menu language, id). The menu language is TOTK_MENU_LANG ("en", "ru", "pt-BR", "zh-Hans", "de",
// "fr", "es", "it", "nl", "ja", "ko"); unset, the system UI language when the catalog has menu text for it, Simplified
// Chinese for Traditional Chinese, else English. Follows a live change of the setting.
const char *menu_text(UiTextId id);
+14 -4
View File
@@ -11,7 +11,7 @@
#include "vk_ahead.h" // TOTK_SYNC_AHEAD=check hooks (vk_ahead_on)
// Required (device choice fails without them): Vulkan 1.3; VK_KHR_swapchain, VK_KHR_push_descriptor,
// VK_EXT_depth_clip_control, VK_EXT_external_memory_host; features timelineSemaphore, dynamicRendering,
// VK_EXT_depth_clip_control; features timelineSemaphore, dynamicRendering,
// synchronization2, shaderStorageImageWriteWithoutFormat, depthClipControl, shaderInt64, samplerAnisotropy,
// independentBlend, geometryShader, textureCompressionBC.
// Optional (flag set in VkCtx when enabled): the has_* members.
@@ -38,13 +38,16 @@ typedef struct VkCtx {
has_astc_ldr, // textureCompressionASTC_LDR (enabled when reported)
has_calibrated, // VK_KHR/EXT_calibrated_timestamps (GPU idle split in the perf line)
has_hdr_metadata, // VK_EXT_hdr_metadata (vk_hdr.c vk_hdr_metadata)
has_nv_reflex; // VK_NV_low_latency2 (NVIDIA Reflex Low Latency)
has_nv_reflex, // VK_NV_low_latency2 (NVIDIA Reflex Low Latency)
has_amd_antilag; // VK_AMD_anti_lag (AMD Anti-Lag 2)
// Feedback loops (maxwell.md 1.9, vk_exec_draw.c feedback_prepare): a draw samples a target of its open pass that
// an earlier draw of the pass wrote. TOTK_FEEDBACK=0: VK_FEEDBACK_OFF (sampled in GENERAL without a barrier, the
// old behaviour); VK_FEEDBACK_LAYOUT with VK_EXT_attachment_feedback_loop_layout and dynamicRenderingLocalRead
// (attachable images get feedback usage, a by-region barrier inside the pass); else (or TOTK_FEEDBACK=restart)
// VK_FEEDBACK_RESTART (the pass ends and restarts behind the full barrier).
int feedback; // VK_FEEDBACK_*
int has_external_memory_host; // VK_EXT_external_memory_host; without it CPU-visible pools get shadow
// storage (vk_memory.c mirror_mode), as under Wine
uint32_t min_imported_host_alignment; // VK_EXT_external_memory_host
VkDeviceSize vma_block; // VMA's block size for heaps over 1 GiB (TOTK_VMA_BLOCK_MIB, vk_device.c)
int device_index; // index in vkEnumeratePhysicalDevices
@@ -63,6 +66,7 @@ typedef struct {
int mesa; // a Mesa driver the game runs on: RADV, ANV or NVK
int intel_igpu_win; // Intel's Windows driver on an integrated GPU (UHD, Iris Xe, Core Ultra graphics)
int demote; // shaderDemoteToHelperInvocation enabled: modules may use OpDemoteToHelperInvocation
int null_attach; // TOTK_NULL_ATTACH=1: empty colour slots get a dummy attachment (vk_exec.c null_attach_view)
} VkCaps;
extern VkCaps vk_caps;
void vk_caps_driver(VkPhysicalDevice p); // first, before vkCreateDevice: vk_caps.amd, amd_sc, mesa, intel_igpu_win
@@ -209,7 +213,8 @@ long vk_validation_errors_total(void); // validation errors since th
// Guest or host threads; every call needs vk_init(). The first nine have the GfxBackend signatures of gfx.h; vk_backend.c builds
// gfx_vulkan_backend from them.
int vk_pool_init(pool_t *p); // CPU-visible: guest storage imported (VK_EXT_external_memory_host) as one
// VkBuffer; physical: device-local memory; virtual: a 64 KiB page table
// VkBuffer, or its shadow copy (vk_memory.c mirror_mode); physical:
// device-local memory; virtual: a 64 KiB page table
void vk_pool_fini(pool_t *p); // drops images cut from the pool; waits for the GPU if it used the pool
int vk_pool_map_virtual(pool_t *v, int n, const void *requests); // nvn_mapping_t[n], checked by the front end
void vk_texture_register(int id, const tex_t *t, const view_t *v); // texture descriptor slot (copied)
@@ -343,7 +348,8 @@ int vk_mem_flush_add_probe(void); // --probe-vkexec: the flush range list
uint64_t vk_mem_mirror_uploaded(void); // --probe-vkexec: bytes copied into mirrors since the last summary line
int vk_mem_mirror_probe(uint64_t addr); // --probe-vkexec: the pool at addr gets its mirror as on a first buffer use;
// 1 when it has one
void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDeviceMemoryProperties *m); // once
void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDeviceMemoryProperties *m,
int host_import); // once; host_import: VK_EXT_external_memory_host is enabled
int vk_mem_class_of(uint64_t addr); // VK_MCLS_* of the pool at addr (NONE when unbacked)
void vk_mem_census(uint64_t frame); // at each present: pool census and traffic, logged at frame 1800 and,
// with TOTK_TRACE=perf, every 1800 frames
@@ -502,6 +508,10 @@ typedef struct {
// into it, when the last draw into it was that copy and the swapchain is HDR10.
void vk_hdr_present_source(const VkTexImage *win, VkImage *image, VkFormat *format);
void vk_hdr_image_gone(VkImage image);
// vk_caps.null_attach: empty colour slots of a pass get a dummy VK_EXEC_NULL_ATTACH_FMT attachment, and the pipelines
// name that format for them with writes masked off (vk_exec.c null_attach_view, vk_pipeline.c gkey_fill).
#define VK_EXEC_NULL_ATTACH_FMT VK_FORMAT_R8_UNORM
void vk_exec_null_attach_release(void); // vk_device.c, before the device goes: frees the dummy attachments
const VkTexImage *vk_texture_get(const tex_t *t); // created and made current; NULL for BUFFER or unmapped formats
const VkTexImage *vk_texture_revive(const tex_t *t, uint32_t pos); // the entry vk_texture_get would return if it exists, made live at op pos
// A texture slot; a slot whose texture was finalized follows the live texture at the same storage (hle_nvn.c).
+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);
}
+3
View File
@@ -123,6 +123,9 @@ void vk_caps_init(VkCtx *c) {
uint32_t zero_locals = env_u32("TOTK_ZERO_LOCALS", (uint32_t)vk_caps.mesa);
gfx_shader_set_host(vk_caps.float64, vk_caps.sbuf_align, told, gather, zero_locals != 0);
if (gather) rt_log("vk caps: gather coordinates biased for %u sub-texel bits (TOTK_GATHER_BIAS)", gather);
// Read here, before any pipeline key is made: the pipelines' colour formats depend on it (vk_pipeline.c gkey_fill)
vk_caps.null_attach = rt_knob("NULL_ATTACH", "0") == 1;
if (vk_caps.null_attach) rt_log("vk caps: empty colour slots get a dummy attachment (TOTK_NULL_ATTACH=1)");
char dv[32];
driver_version(dv, sizeof dv, c->props.vendorID, c->props.driverVersion);
+45 -7
View File
@@ -13,6 +13,7 @@
#include "platform/platform.h"
#include "vk_dlaa.h"
#include "vk_fg.h"
#include "vk_ffx.h"
#include "vk_fsr3.h"
static VkCtx g_vk;
@@ -174,8 +175,7 @@ static int create_instance(void) {
}
static const char *const k_required_ext[] = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME, VK_EXT_DEPTH_CLIP_CONTROL_EXTENSION_NAME,
VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME};
VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME, VK_EXT_DEPTH_CLIP_CONTROL_EXTENSION_NAME};
// Name of the first missing required extension, or NULL.
static const char *missing_required(VkPhysicalDevice pd) {
@@ -263,7 +263,6 @@ static int pick_device(void) {
}
free(qp);
rt_log("vk: using gpu %d: %s", best, g_vk.props.deviceName);
vk_mem_class_log(&g_vk.props, &g_vk.mem_props);
return 1;
}
@@ -289,6 +288,11 @@ typedef struct {
VkPhysicalDeviceDynamicRenderingLocalReadFeaturesKHR lr;
VkPhysicalDeviceAddressBindingReportFeaturesEXT abr;
VkPhysicalDevicePresentIdFeaturesKHR pid;
VkPhysicalDeviceCooperativeMatrixFeaturesKHR coop; // FSR 4 (vk_ffx.c)
#ifdef VK_EXT_SHADER_FLOAT8_EXTENSION_NAME
VkPhysicalDeviceShaderFloat8FeaturesEXT f8; // FSR 4 (vk_ffx.c)
#endif
VkPhysicalDeviceAntiLagFeaturesAMD al;
} FeatureChain;
static int create_device(void) {
@@ -299,6 +303,13 @@ static int create_device(void) {
const char *ext[52];
uint32_t n_ext = 0;
for (size_t i = 0; i < sizeof k_required_ext / sizeof *k_required_ext; i++) ext[n_ext++] = k_required_ext[i];
// VK_EXT_external_memory_host is optional: without it (or with TOTK_VK_NO_HOST_IMPORT=1, which tests that path on
// any GPU) CPU-visible pools get shadow storage (vk_memory.c mirror_mode).
const char *no_import = cfg_get("TOTK_VK_NO_HOST_IMPORT");
g_vk.has_external_memory_host = has_ext(ep, ne, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) &&
!(no_import && *no_import && strcmp(no_import, "0"));
if (g_vk.has_external_memory_host) ext[n_ext++] = VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME;
vk_mem_class_log(&g_vk.props, &g_vk.mem_props, g_vk.has_external_memory_host);
FeatureChain *c = calloc(1, sizeof *c);
void **tail = &c->f2.pNext;
@@ -340,7 +351,16 @@ static int create_device(void) {
CHAIN(fbl, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_LAYOUT_FEATURES_EXT);
CHAIN(lr, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_LOCAL_READ_FEATURES_KHR);
}
vk_dlaa_device_exts(ep, ne, ext, &n_ext, 40); // NGX's; the twelve slots after it stay for the nine below
vk_dlaa_device_exts(ep, ne, ext, &n_ext, 40); // NGX's or FSR 4's; the twelve slots after it stay for the nine below
// FSR 4's shader extensions (vk_ffx_device_exts) are enabled with their features, as far as the driver reports them
for (uint32_t i = 0; i < n_ext; i++) {
if (!strcmp(ext[i], VK_KHR_COOPERATIVE_MATRIX_EXTENSION_NAME))
CHAIN(coop, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR);
#ifdef VK_EXT_SHADER_FLOAT8_EXTENSION_NAME
else if (!strcmp(ext[i], VK_EXT_SHADER_FLOAT8_EXTENSION_NAME))
CHAIN(f8, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT8_FEATURES_EXT);
#endif
}
if (has_ext(ep, ne, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) { g_vk.has_memory_budget = 1; ext[n_ext++] = VK_EXT_MEMORY_BUDGET_EXTENSION_NAME; }
// GPU timestamps on the CPU clock (vk_sync.c): the perf line splits GPU idle time into waiting for a submission or not.
if (has_ext(ep, ne, VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME)) { g_vk.has_calibrated = 2; ext[n_ext++] = VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME; }
@@ -357,14 +377,24 @@ static int create_device(void) {
g_vk.has_nv_checkpoints = 1;
ext[n_ext++] = VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME;
}
// NVIDIA Reflex Low Latency (VK_NV_low_latency2 requires VK_KHR_present_id)
// Low latency (the reflex setting). on and boost: NVIDIA Reflex (VK_NV_low_latency2, which requires
// VK_KHR_present_id), as before Anti-Lag came in, so a GPU without Reflex still gets nothing new from them. auto:
// Reflex, or AMD Anti-Lag 2 (VK_AMD_anti_lag: RADV and AMD's Windows driver) on a GPU without Reflex. Only one of
// the two runs. off (the default) enables neither extension.
const char *rv = cfg_value("TOTK_REFLEX");
if (rv && strcmp(rv, "off") != 0 && strcmp(rv, "0") != 0) {
if (strcmp(rv, "off") != 0 && strcmp(rv, "0") != 0) {
int want_antilag = !strcmp(rv, "auto");
if (has_ext(ep, ne, VK_KHR_PRESENT_ID_EXTENSION_NAME) && has_ext(ep, ne, "VK_NV_low_latency2")) {
g_vk.has_nv_reflex = 1;
ext[n_ext++] = VK_KHR_PRESENT_ID_EXTENSION_NAME;
ext[n_ext++] = "VK_NV_low_latency2";
CHAIN(pid, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_ID_FEATURES_KHR);
} else if (want_antilag && has_ext(ep, ne, VK_AMD_ANTI_LAG_EXTENSION_NAME)) {
g_vk.has_amd_antilag = 1;
ext[n_ext++] = VK_AMD_ANTI_LAG_EXTENSION_NAME;
CHAIN(al, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ANTI_LAG_FEATURES_AMD);
} else if (want_antilag) {
rt_log("Low latency: neither VK_NV_low_latency2 nor VK_AMD_anti_lag is available");
} else {
rt_log("Reflex: VK_NV_low_latency2 not available");
}
@@ -418,6 +448,11 @@ static int create_device(void) {
g_vk.has_nv_reflex = 0;
rt_log("Reflex: VK_NV_low_latency2 not available (no presentId feature)");
}
if (g_vk.has_amd_antilag && !c->al.antiLag) {
g_vk.has_amd_antilag = 0;
rt_log("Anti-Lag: VK_AMD_anti_lag not available (no antiLag feature)");
}
if (g_vk.has_amd_antilag) rt_log("Anti-Lag: AMD Anti-Lag 2 on (VK_AMD_anti_lag)");
g_vk.has_astc_ldr = h->textureCompressionASTC_LDR;
{
const char *e = cfg_get("TOTK_FEEDBACK");
@@ -450,7 +485,8 @@ static int create_device(void) {
else { g_vk.xfer_queue = g_vk.gfx_queue; g_vk.xfer_shared = 1; }
VkPhysicalDeviceExternalMemoryHostPropertiesEXT emh = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT};
VkPhysicalDeviceProperties2 p2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &emh};
VkPhysicalDeviceProperties2 p2 = {.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,
.pNext = g_vk.has_external_memory_host ? &emh : NULL};
vkGetPhysicalDeviceProperties2(g_vk.phys, &p2);
g_vk.min_imported_host_alignment = (uint32_t)emh.minImportedHostPointerAlignment;
vk_caps_init(&g_vk);
@@ -486,9 +522,11 @@ static void destroy_all(void) {
if (g_vk.device) vkDeviceWaitIdle(g_vk.device);
if (g_vk.device) vk_fg_release();
if (g_vk.device) fsr3_release();
if (g_vk.device) vk_ffx_release();
if (g_vk.device) vk_astc_release();
if (g_vk.device) vk_deswz_release();
if (g_vk.device) vk_crumbs_release();
if (g_vk.device) vk_exec_null_attach_release();
if (g_vk.timeline) vkDestroySemaphore(g_vk.device, g_vk.timeline, NULL);
vk_headroom_stop();
if (g_vk.vma) vmaDestroyAllocator(g_vk.vma);
+132 -51
View File
@@ -11,6 +11,10 @@
// layout with a set-then-get round trip before anything relies on it.
//
// Where DLAA runs in the frame, the jitter and the motion vectors: see the sections below.
//
// The scene upscaler (scene_upscaler) is DLSS, AMD FSR 3.1 (vk_fsr3.cpp, built from the FidelityFX SDK 1.1.4 sources)
// or AMD FSR 4 (vk_ffx.c, AMD's FSR SDK 2.4 libraries, Windows): the arming, the jitter, the motion vectors and the
// copy of the result below are shared, and only the call that upscales differs (evaluate, fsr_evaluate).
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
@@ -25,6 +29,7 @@
#include "input.h"
#include "nvn_api.h"
#include "vk_exec.h"
#include "vk_ffx.h"
#include "vk_fg.h"
#include "vk_fsr3.h"
#include "vk_rec.h"
@@ -105,25 +110,43 @@ static int p_getp(const NgxParam *p, const char *n, void **v) { return NGX_OK(((
#endif
// The scene upscaler picked at start (scene_upscaler; without it dlaa = 1 is DLSS): a restart applies another. AMD FSR
// 3.1 (vk_fsr3.cpp) takes the same inputs at the same point of the frame as DLSS and runs on any GPU.
// 3.1 (vk_fsr3.cpp) and FSR 4 (vk_ffx.c) take the same inputs at the same point of the frame as DLSS; FSR 3.1 runs on
// any GPU, FSR 4 on Windows where AMD's libraries offer it for the GPU (vk_ffx_init). AMD ships those libraries for
// Windows only, so elsewhere fsr4 is off.
int vk_upscaler_engine(void) {
static int e = -1;
if (e < 0) {
const char *v = cfg_scene_upscaler();
e = !strcmp(v, "dlss") ? UPSCALER_DLSS : !strcmp(v, "fsr3") ? UPSCALER_FSR3 : UPSCALER_OFF;
e = !strcmp(v, "dlss") ? UPSCALER_DLSS : !strcmp(v, "fsr3") ? UPSCALER_FSR3
: !strcmp(v, "fsr4") ? UPSCALER_FSR4 : UPSCALER_OFF;
#ifndef _WIN32
if (e == UPSCALER_FSR4) {
rt_log("dlaa: scene_upscaler = fsr4 runs on Windows only (AMD's FSR SDK has no Linux libraries): off");
e = UPSCALER_OFF;
}
#endif
}
return e;
}
// The setting's name of an engine, and the name the log gives it.
static const char *engine_value(int e) {
return e == UPSCALER_DLSS ? "dlss" : e == UPSCALER_FSR3 ? "fsr3" : e == UPSCALER_FSR4 ? "fsr4" : "off";
}
static const char *engine_name(int e) {
return e == UPSCALER_DLSS ? "DLSS" : e == UPSCALER_FSR3 ? "FSR 3.1" : e == UPSCALER_FSR4 ? "FSR 4" : "none";
}
// The engine picked at start while the settings still name it (the menu turns it off at once, as dlaa did).
int vk_upscaler_on(void) {
int e = vk_upscaler_engine();
return e && !strcmp(cfg_scene_upscaler(), e == UPSCALER_DLSS ? "dlss" : "fsr3");
return e && !strcmp(cfg_scene_upscaler(), engine_value(e));
}
// NGX is brought up only when DLSS is the scene upscaler at start: its device extensions can only be asked for at
// device creation, and loading the driver's NGX core on every NVIDIA machine would cost start time and change the device
// with DLSS off. So the choice applies after a restart; with DLSS not picked (off or FSR 3.1), nothing of NGX runs.
// with DLSS off. So the choice applies after a restart; with DLSS not picked (off or FSR), nothing of NGX runs. FSR
// 4's device extensions are chosen at device creation as well (vk_ffx_device_exts).
int vk_dlaa_wanted(void) {
static int wanted = -1;
if (wanted < 0) wanted = vk_upscaler_engine() == UPSCALER_DLSS;
@@ -182,6 +205,7 @@ void vk_dlaa_device_exts(const VkExtensionProperties *have, uint32_t nhave, cons
uint32_t max) {
unsigned ni = 0, nd = 0;
const char **ie = NULL, **de = NULL;
vk_ffx_device_exts(have, nhave, ext, n, max); // FSR 4's, when it is the engine
if (!vk_dlaa_wanted() || !core_load() || !NGX_OK(N.req_ext(&ni, &ie, &nd, &de))) return;
for (unsigned i = 0; i < nd; i++) {
int ok = 0;
@@ -210,12 +234,18 @@ static int vtable_ok(void) {
}
// The upscaler's half of the per-object motion's gate (vk_objmv_wanted, below the frame state): DLSS once NGX came up
// with it (vk_dlaa_available), FSR 3.1 whenever it is the scene upscaler picked at start. Latched in vk_dlaa_init,
// before the first frame: with no upscaler, or DLSS without NGX, it stays 0 as vk_dlaa_available does.
// with it (vk_dlaa_available), FSR 3.1 whenever it is the scene upscaler picked at start, FSR 4 once AMD's libraries
// offered it for the device (vk_ffx_available). Latched in vk_dlaa_init, before the first frame: with no upscaler, or
// one that did not come up, it stays 0.
static int objmv;
void vk_dlaa_init(void) {
objmv = vk_upscaler_engine() == UPSCALER_FSR3;
if (vk_upscaler_engine() == UPSCALER_FSR4) {
vk_ffx_init();
objmv = vk_ffx_available();
return;
}
if (!vk_dlaa_wanted() || !core_load()) return;
// The executable's folder, where NGX looks for the DLSS model library and writes its logs.
wchar_t wdir[PLAT_PATH_MAX];
@@ -297,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
@@ -338,26 +369,38 @@ static struct {
VkExecTarget hud_t, win; // the output-sized target the scene is scaled into; the window texture
float cam_dr[2]; // the viewport depth range of the draw cam_addr was noted at
int fg_mv_ok; // the frame's motion is in the motion image (fg_motion)
int fsr; // the engine is AMD FSR 3.1 (scene_upscaler = fsr3 at start), else DLSS
int fsr; // the AMD FSR engine (UPSCALER_FSR3 or UPSCALER_FSR4, picked at start), 0: DLSS
} D = {.mv_ok = -1, .cfg_seen = ~0u};
#define DLSS_SIZES (sizeof D.sizes / sizeof D.sizes[0])
const VkTexImage *vk_dlaa_swap_img;
VkImageView vk_dlaa_swap_view;
// DLSS needs NGX and its model, FSR 3.1 runs on any GPU the back end runs on: on already says the engine is there.
// DLSS needs NGX and its model, FSR 4 AMD's libraries with FSR 4 for the GPU, FSR 3.1 runs on any GPU the back end
// runs on: on already says the engine is there (vk_dlaa_frame).
static int dl_active(void) { return !D.failed && D.on; }
// The scene is followed (its G-buffer, light target, end and camera): for DLSS, or with DLSS off for frame generation.
static int track(void) { return dl_active() || D.fg; }
int vk_dlaa_fg_on; // D.fg for vk_exec_draw.c's per-draw test (vk_dlaa_hud)
int vk_upscaler_running(void) {
return dl_active() && D.evals ? (D.fsr ? UPSCALER_FSR3 : UPSCALER_DLSS) : UPSCALER_OFF;
return dl_active() && D.evals ? (D.fsr ? D.fsr : UPSCALER_DLSS) : UPSCALER_OFF;
}
// For the menu. DLSS: after a start with it picked, what NGX said; before, an NVIDIA GPU and the DLL (an NVIDIA GPU
// without RTX shows only once NGX came up). FSR 3.1 is built in.
// without RTX shows only once NGX came up). FSR 4 likewise: Windows, AMD's two libraries, then after a start with it
// picked what they offered for the device (vk_ffx_init), before one an AMD GPU (the libraries decide which Radeons get
// FSR 4, so another Radeon shows only after that start). FSR 3.1 is built in.
int vk_upscaler_missing(int engine) {
if (engine == UPSCALER_FSR4) {
#ifndef _WIN32
return UPSCALER_MISSING_OS;
#else
if (!res_ffx_dlls()) return UPSCALER_MISSING_DLL;
if (vk_ffx_tried()) return vk_ffx_available() ? 0 : UPSCALER_MISSING_GPU;
return vk_ctx()->props.vendorID == 0x1002 ? 0 : UPSCALER_MISSING_GPU;
#endif
}
if (engine != UPSCALER_DLSS) return 0;
if (!res_dlss_dll()) return UPSCALER_MISSING_DLL;
if (N.tried) return N.available ? 0 : UPSCALER_MISSING_GPU;
@@ -377,7 +420,8 @@ static int fg_objects(void) {
int vk_fg_objects_on(void) { return D.fg && fg_objects(); }
// The per-object motion's gates (vk_mvprev.c's tables, vk_usnap.c's host copy, vk_exec_draw.c's motion draws and
// lock): the upscaler that reads the motion image (objmv: DLSS once NGX came up, or FSR 3.1 picked at start), or frame
// lock): the upscaler that reads the motion image (objmv: DLSS once NGX came up, FSR 3.1 picked at start, or FSR 4
// once it came up), or frame
// generation following the scene with its objects. Frame generation is off with either upscaler, so the second term is
// 0 whenever one runs.
int vk_objmv_wanted(void) { return objmv || vk_fg_objects_on(); }
@@ -1303,18 +1347,18 @@ static int scene_shaped(const VkExecTarget *c) {
return a * 20 >= b * 19 && b * 20 >= a * 19;
}
// FSR 3.1's half of evaluate (vk_fsr3.cpp), after the motion vectors and the recorder's drain: the camera, the time step
// and the history reset, then the dispatch into e->out. 0 when it failed (DLAA is then off for the run). The camera
// comes from the scene camera block's rows 0-10 (vk_fg.cpp vk_fg_camera, which frame generation reads too: FSR 3.1
// wants the near and far planes and the vertical field of view for its depth tests); a cut there (a cutscene's camera
// jump) starts a new history. The block's bytes are the snapshot's host copy, which vk_usnap.c keeps while the
// per-object motion runs (vk_objmv_wanted, so with FSR 3.1).
// FSR's half of evaluate (FSR 3.1: vk_fsr3.cpp, FSR 4: vk_ffx.c), after the motion vectors and the recorder's drain:
// the camera, the time step and the history reset, then the dispatch into e->out. Both engines get the same inputs.
// 0 when it failed (DLAA is then off for the run). The camera comes from the scene camera block's rows 0-10 (vk_fg.cpp
// vk_fg_camera, which frame generation reads too: FSR wants the near and far planes and the vertical field of view
// for its depth tests); a cut there (a cutscene's camera jump) starts a new history. The block's bytes are the
// snapshot's host copy, which vk_usnap.c keeps while the per-object motion runs (vk_objmv_wanted, so with FSR).
static int fsr_evaluate(VkExec *ex, struct Size *e, const VkExecTarget *t, const VkExecTarget *z, uint32_t ow,
uint32_t oh, float jx, float jy, int timed) {
static VkFgScene cam = {.near_m = 0.1f, .far_m = 25000.0f, .fov_y = 0.8727f}; // until the first camera read
// the SDK takes whole images: the scene's targets are level 0, layer 0 of their own images
if (t->level || t->base_layer || z->level || z->base_layer || z->format != VK_FORMAT_D32_SFLOAT)
return dl_fail("FSR 3.1 input (not level 0, layer 0 of a colour and a D32F depth image)", 0), 0;
return dl_fail("FSR input (not level 0, layer 0 of a colour and a D32F depth image)", 0), 0;
const float *rows = D.cam_addr ? (const float *)vk_usnap_bytes(D.cam_addr, 11 * 16) : NULL;
int cut = rows && vk_fg_camera(rows, nvn_depth_minus_w(), D.cam_dr, &cam);
if (D.last_color != t->image) D.reset = 1, D.why[2]++, D.last_color = t->image;
@@ -1326,19 +1370,31 @@ static int fsr_evaluate(VkExec *ex, struct Size *e, const VkExecTarget *t, const
// without (vk_dlaa_skip_draw), so without it FSR's picture is softer than the game's own
int sharp = cfg_int("TOTK_FSR_SHARPNESS");
sharp = sharp < 0 ? 0 : sharp > 100 ? 100 : sharp;
Fsr3Frame fr = {.color = t->image, .color_format = t->format, .depth = z->image, .mv = e->mv, .out = e->out,
.w = t->width, .h = t->height, .ow = ow, .oh = oh, .jx = jx, .jy = jy, .near_m = cam.near_m,
.far_m = cam.infinite || cam.far_m <= cam.near_m ? 1e5f : cam.far_m, .fov_y = cam.fov_y,
.dt_ms = dt > 0 && dt < 100 ? (float)dt : 16.67f, .reset = D.reset, .sharpness = sharp / 100.0f,
.fence = ex->fence};
float far_m = cam.infinite || cam.far_m <= cam.near_m ? 1e5f : cam.far_m;
float dt_ms = dt > 0 && dt < 100 ? (float)dt : 16.67f;
uint64_t c0 = timed ? kern_now_ns() : 0;
int ok = fsr3_dispatch(ex->cb, &fr);
int ok;
if (D.fsr == UPSCALER_FSR4) {
VkFfxDispatch fd = {.color = {t->image, t->format, t->width, t->height},
.depth = {z->image, z->format, t->width, t->height},
.mv = {e->mv, VK_FORMAT_R16G16_SFLOAT, t->width, t->height},
.out = {e->out, VK_FORMAT_R16G16B16A16_SFLOAT, ow, oh}, .jx = jx, .jy = jy,
.dt_ms = dt_ms, .cam_near = cam.near_m, .cam_far = far_m, .fov_y = cam.fov_y,
.sharpness = sharp / 100.0f, .reset = D.reset, .fence = ex->fence};
ok = vk_ffx_dispatch(ex->cb, &fd);
} else {
Fsr3Frame fr = {.color = t->image, .color_format = t->format, .depth = z->image, .mv = e->mv, .out = e->out,
.w = t->width, .h = t->height, .ow = ow, .oh = oh, .jx = jx, .jy = jy, .near_m = cam.near_m,
.far_m = far_m, .fov_y = cam.fov_y, .dt_ms = dt_ms, .reset = D.reset,
.sharpness = sharp / 100.0f, .fence = ex->fence};
ok = fsr3_dispatch(ex->cb, &fr);
}
if (timed) T.cpu_ngx += kern_now_ns() - c0;
if (!ok) {
// the SDK may have bound a pipeline or descriptor sets of its own before it failed: the next draw binds
// everything again, and the game's own scaling and FXAA run from the next frame (DLAA off for the run)
vk_exec_draw_new_cb(ex);
return dl_fail("FSR 3.1 dispatch", 0), 0;
return dl_fail(D.fsr == UPSCALER_FSR4 ? "FSR 4 dispatch" : "FSR 3.1 dispatch", 0), 0;
}
return 1;
}
@@ -1487,7 +1543,7 @@ engine_done:
rt_log("dlaa: %llu frames anti-aliased%s (scene %ux%u, output %ux%u; %llu before the effects, %llu frames without the "
"DLAA point, %llu with camera motion, %llu with the characters' mask, %llu without a camera, %llu jitter "
"holds; resets: %llu size, %llu camera, %llu target; reactive mask %llu, without its copy %llu)",
(unsigned long long)D.evals, D.fsr ? " by FSR 3.1" : "", w, h, ow, oh, (unsigned long long)D.fx_frames, (unsigned long long)D.frames_missed,
(unsigned long long)D.evals, D.fsr == UPSCALER_FSR4 ? " by FSR 4" : D.fsr ? " by FSR 3.1" : "", w, h, ow, oh, (unsigned long long)D.fx_frames, (unsigned long long)D.frames_missed,
(unsigned long long)D.mv_frames, (unsigned long long)D.masked, (unsigned long long)D.mv_none,
(unsigned long long)D.holds, (unsigned long long)D.why[0], (unsigned long long)D.why[1],
(unsigned long long)D.why[2], (unsigned long long)R.made, (unsigned long long)R.missed);
@@ -1562,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) {
@@ -1575,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;
}
@@ -1832,9 +1903,9 @@ void vk_dlaa_pass(VkExec *ex) {
}
// TOTK_DLSS, read at each present (the menu switches it live): the scene size of the mode (resolution.c) and the
// texture bias that goes with it while the upscaler runs. DLSS takes NVIDIA's log2(scene / output); FSR 3.1 takes AMD's
// log2(scene / output) - 1 (FidelityFX FSR 3 upscaler docs, "Mipmap biasing"), so -1 also in place. The bias follows
// the mode and the upscaler going on or off; the engine is fixed for the run.
// texture bias that goes with it while the upscaler runs. DLSS takes NVIDIA's log2(scene / output); FSR 3.1 and FSR 4
// take AMD's log2(scene / output) - 1 (FidelityFX FSR 3 upscaler docs, "Mipmap biasing"), so -1 also in place. The
// bias follows the mode and the upscaler going on or off; the engine is fixed for the run.
static void dlss_mode(void) {
static char mode[32];
static float bias; // what the material samplers have (vk_texture.c starts at 0)
@@ -1844,7 +1915,8 @@ static void dlss_mode(void) {
res_dlss_mode(m);
}
float b = 0.0f;
if (dl_active()) b = res_dlss_lod_bias() - (vk_upscaler_engine() == UPSCALER_FSR3 ? 1.0f : 0.0f);
int e = vk_upscaler_engine();
if (dl_active()) b = res_dlss_lod_bias() - (e == UPSCALER_FSR3 || e == UPSCALER_FSR4 ? 1.0f : 0.0f);
if (b != bias) bias = b, vk_sampler_dlss_bias(b);
}
@@ -1870,22 +1942,29 @@ void vk_dlaa_frame(void) {
vk_dlaa_swap_img = NULL, vk_dlaa_swap_view = VK_NULL_HANDLE;
dlss_mode();
preset_check();
int fsr = vk_upscaler_engine() == UPSCALER_FSR3; // fixed for the run: D.fsr never changes while on
int on = (fsr || N.available) && vk_upscaler_on();
// the engine is fixed for the run: D.fsr never changes while on. FSR 4 runs once AMD's libraries offered it for
// the device (vk_ffx_init said why not otherwise, and the upscaler stays off)
int e = vk_upscaler_engine();
int fsr = e == UPSCALER_FSR3 || e == UPSCALER_FSR4 ? e : 0;
int ready = e == UPSCALER_FSR3 || (e == UPSCALER_FSR4 ? vk_ffx_available() : N.available);
int on = ready && vk_upscaler_on();
vk_fg_frame();
// frame generation with an upscaler is not built yet: with FSR 3.1 picked it stays off (said once)
// frame generation with an upscaler is not built yet: with FSR picked it stays off (said once)
static int fg_said;
if (fsr && on && vk_fg_engine() != VK_FG_OFF && !fg_said++)
rt_log("fg: frame generation off while FSR 3.1 upscales the scene (scene_upscaler = fsr3)");
rt_log("fg: frame generation off while %s upscales the scene (scene_upscaler = %s)", engine_name(fsr),
engine_value(fsr));
int fg = fsr && on ? 0 : vk_fg_wanted(on && !D.failed);
D.bloom = D.hud = D.hud_wait = D.fin = D.gen = D.fg_mv_ok = 0;
if (on != D.on || fg != D.fg) {
if (on != D.on) rt_log("dlaa: %s", on ? (fsr ? "on with FSR 3.1" : "on") : "off");
if (on != D.on)
rt_log("dlaa: %s%s%s", on ? "on" : "off", on && fsr ? " with " : "",
on && fsr == UPSCALER_FSR4 ? vk_ffx_version() : on && fsr ? "FSR 3.1" : "");
if (fg != D.fg) rt_log("dlaa: the scene is %s for frame generation", fg ? "followed" : "no longer followed");
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;
@@ -1894,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;
@@ -1922,10 +2001,12 @@ void vk_dlaa_frame(void) {
// stretched over the whole screen.
static const uint64_t FXAA_FS[] = {0xf450003ebeb3dc52ull, 0x0a12f4bc2a9a4fbeull, 0x5c43ae18948d52cbull,
0xaad42238801d31d8ull, 0xde20aef90fea4ce6ull, 0x755964e8dce7f34dull};
// The fragment shader of the FXAA's first pass, the copy of the scene target into the scratch target (this build's
// translator, seen in 1.4.3 frame logs; another hash leaves the draw alone). See vk_dlaa_skip_draw for why FSR 3.1's
// frames skip it where it copies the scene target onto itself.
static const uint64_t FXAA_COPY_FS[] = {0xa0fd34391f2af811ull};
// The fragment shader of the FXAA's first pass, the copy of the scene target into the scratch target (another hash
// leaves the draw alone): this build's translator, seen in 1.4.3 frame logs, and the one with patch 0017, whose two
// support buffer fields change every fragment shader's hash (as with FXAA_FS above), read by codexx-dev from a 1.4.3
// run with FSR on (pull request #1245). See vk_dlaa_skip_draw for why FSR's frames skip it where it copies the scene
// target onto itself.
static const uint64_t FXAA_COPY_FS[] = {0xa0fd34391f2af811ull, 0x9d065204aac9766bull};
// Chunks of one submission look shaders up side by side: an entry's hash is stored before its shader, and entries are
// added under the lock.
@@ -1970,14 +2051,14 @@ int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs) {
"FXAA_FS): the FXAA stays on", (unsigned long long)fx_off_frames);
}
}
// FSR 3.1 in place (the scene as large as the output, so no scaling draw follows) goes without the game's FXAA
// and its copy of the scene target onto itself on every frame, as codexx-dev found for FSR (pull request #1245,
// vk_dlaa.c vk_dlaa_skip_draw there). Measured there on 1.4.3 at a 2560x1440 scene and output: with the upscaler on
// the game ran its FXAA, which also sharpens, on 17 frames in every 96 and on the others drew its copy shader from
// the scene target onto itself, so the picture went soft and sharp in turns. Here the dynamic resolution stays at
// 100 % while FSR 3.1 runs (resolution.c res_dynres_live) and FSR sharpens its own output (fsr_sharpness,
// fsr_evaluate) in place of the FXAA's sharpening. Scaled frames (D.up) need nothing more: there FSR's picture
// already replaces the scaling FXAA draw below.
// FSR 3.1 or FSR 4 in place (the scene as large as the output, so no scaling draw follows) goes without the game's
// FXAA and its copy of the scene target onto itself on every frame, as codexx-dev found for FSR (pull request
// #1245, vk_dlaa.c vk_dlaa_skip_draw there). Measured there on 1.4.3 at a 2560x1440 scene and output: with the
// upscaler on the game ran its FXAA, which also sharpens, on 17 frames in every 96 and on the others drew its copy
// shader from the scene target onto itself, so the picture went soft and sharp in turns. Here the dynamic
// resolution stays at 100 % while FSR runs (resolution.c res_dynres_live) and FSR sharpens its own output
// (fsr_sharpness, fsr_evaluate) in place of the FXAA's sharpening. Scaled frames (D.up) need nothing more: there
// FSR's picture already replaces the scaling FXAA draw below.
int fsr_in_place = D.done && !D.up && D.fsr;
if (fxaa && !D.up && !fsr_in_place) return 0; // nothing to skip: no shader lookup per draw at the defaults
if (!fs) return 0;
@@ -2003,7 +2084,7 @@ int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs) {
static int logged_fxaa, logged_copy;
if (known && ex->depth.image) {
if (!logged_fxaa)
logged_fxaa = 1, rt_log("dlaa: FSR 3.1 skips the game's FXAA (fragment shader %016llx) and sharpens its "
logged_fxaa = 1, rt_log("dlaa: FSR skips the game's FXAA (fragment shader %016llx) and sharpens its "
"own picture (fsr_sharpness)", (unsigned long long)h);
return 1;
}
@@ -2011,7 +2092,7 @@ int vk_dlaa_skip_draw(VkExec *ex, const GfxShader *fs) {
for (size_t i = 0; i < sizeof FXAA_COPY_FS / sizeof FXAA_COPY_FS[0]; i++) copy |= h == FXAA_COPY_FS[i];
if (copy && ex->color[0].image == D.color.image && vk_exec_draw_samples(ex, fs, D.color.img)) {
if (!logged_copy)
logged_copy = 1, rt_log("dlaa: FSR 3.1 skips the game's copy of the scene target onto itself (fragment "
logged_copy = 1, rt_log("dlaa: FSR skips the game's copy of the scene target onto itself (fragment "
"shader %016llx)", (unsigned long long)h);
return 1;
}
+6 -5
View File
@@ -1,5 +1,5 @@
// DLAA (vk_dlaa.c): the scene upscaler, NVIDIA DLSS or AMD FSR 3.1 (vk_fsr3.cpp), behind scene_upscaler (dlaa = 1 without
// it: DLSS).
// DLAA (vk_dlaa.c): the scene upscaler, NVIDIA DLSS, AMD FSR 3.1 (vk_fsr3.cpp) or AMD FSR 4 (vk_ffx.c, Windows), behind
// scene_upscaler (dlaa = 1 without it: DLSS).
#pragma once
#include "vk.h"
@@ -15,9 +15,10 @@ void vk_dlaa_device_exts(const VkExtensionProperties *have, uint32_t nhave, cons
void vk_dlaa_init(void);
// 1 when dlaa is on and NGX came up with DLSS (after vk_dlaa_init): a DLSS mode's smaller scene is scaled up by DLSS.
int vk_dlaa_available(void);
// 1 when the per-object motion runs (DLSS's and FSR 3.1's half after vk_dlaa_init, frame generation's live): DLSS
// with NGX up (vk_dlaa_available), FSR 3.1 picked as the scene upscaler, or frame generation following the scene with
// its objects (vk_fg_objects_on: TOTK_FG_OBJECTS, default 1).
// 1 when the per-object motion runs (the upscaler's half after vk_dlaa_init, frame generation's live): DLSS with NGX
// up (vk_dlaa_available), FSR 3.1 picked as the scene upscaler, FSR 4 picked and offered for the device
// (vk_ffx_available), or frame generation following the scene with its objects (vk_fg_objects_on: TOTK_FG_OBJECTS,
// default 1).
int vk_objmv_wanted(void);
int vk_fg_objects_on(void);
// vk_exec.c vk_exec_pass_begin, once the pass's targets are resolved and before its barrier: arms the frame on the
+107 -10
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;
@@ -674,6 +674,85 @@ static void barrier_to(VkExec *ex, const VkImage *want, const VkImageAspectFlags
void vk_exec_barrier(VkExec *ex) { barrier_to(ex, NULL, NULL, 0); }
// TOTK_NULL_ATTACH=1 (null_attach, default 0; vk_caps.null_attach): colour slots of a pass that hold no target get a
// view of a dummy image instead of VK_NULL_HANDLE. Leaving a slot's imageView null is valid Vulkan, but Intel's legacy
// Windows driver for 6th-10th generation graphics (HD 520, UHD 620; driver 101.21xx, Vulkan 1.3.215) faulted inside
// vkCmdBeginRendering reading an attachment entry of the pass, at the first scene passes after the logo (issue #1343);
// whether the empty slots are the cause is untested on that driver. The pipelines then name NULL_ATTACH_FMT for those
// slots, with their writes masked off (vk_pipeline.c gkey_fill, target_wmask), so the views match the pipelines'
// formats. Only slots below the last one with a target get a dummy: the pipelines' colorAttachmentCount ends there
// (vk_pipeline.c target_count), and a pass without colour targets keeps none. All empty slots of a pass share one
// view; an image serves every pass it covers (size, layers) with its sample count, so TotK makes one or two per scene
// resolution. Each is moved to GENERAL in the upload batch and kept until the device goes (vk_exec_null_attach_release);
// loads and stores are DONT_CARE, so the slots cost no bandwidth.
#define NULL_ATTACH_MAX 24
typedef struct { uint32_t w, h, layers, samples; VkImage img; VmaAllocation alloc; VkImageView view; } NullAttach;
static NullAttach null_att[NULL_ATTACH_MAX];
static int nnull_att;
static PlatMutex null_att_lock = PLAT_MUTEX_INIT;
void vk_exec_null_attach_release(void) {
VkCtx *c = vk_ctx();
plat_mutex_lock(&null_att_lock);
for (int i = 0; c && i < nnull_att; i++) {
vkDestroyImageView(c->device, null_att[i].view, NULL);
vmaDestroyImage(c->vma, null_att[i].img, null_att[i].alloc);
}
nnull_att = 0;
plat_mutex_unlock(&null_att_lock);
}
static VkImageView null_attach_view(uint32_t w, uint32_t h, uint32_t layers, uint32_t samples) {
plat_mutex_lock(&null_att_lock);
for (int i = 0; i < nnull_att; i++) { // a view may be larger than the render area (VkRenderingInfo needs it to cover it)
const NullAttach *a = &null_att[i];
if (a->w >= w && a->h >= h && a->layers >= layers && a->samples == samples) {
VkImageView v = a->view;
plat_mutex_unlock(&null_att_lock);
return v;
}
}
static int warned;
if (nnull_att == NULL_ATTACH_MAX) {
if (!warned++) rt_log("vk_exec: more than %d dummy attachment shapes: further empty slots stay empty", NULL_ATTACH_MAX);
plat_mutex_unlock(&null_att_lock);
return VK_NULL_HANDLE;
}
VkCtx *c = vk_ctx();
NullAttach a = {w, h, layers, samples, VK_NULL_HANDLE, NULL, VK_NULL_HANDLE};
VkImageCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D,
.format = VK_EXEC_NULL_ATTACH_FMT, .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = layers,
.samples = (VkSampleCountFlagBits)samples, .tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE};
VmaAllocationInfo info = {0};
if (vmaCreateImage(c->vma, &ci, &ai, &a.img, &a.alloc, &info) != VK_SUCCESS) {
if (!warned++) rt_log("vk_exec: a %ux%u x %u dummy attachment could not be created: the slot stays empty", w, h, layers);
plat_mutex_unlock(&null_att_lock);
return VK_NULL_HANDLE;
}
VkImageViewCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = a.img,
.viewType = layers > 1 ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D,
.format = VK_EXEC_NULL_ATTACH_FMT,
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, layers}};
if (vkCreateImageView(c->device, &vi, NULL, &a.view) != VK_SUCCESS) {
vmaDestroyImage(c->vma, a.img, a.alloc);
if (!warned++) rt_log("vk_exec: a dummy attachment view could not be created: the slot stays empty");
plat_mutex_unlock(&null_att_lock);
return VK_NULL_HANDLE;
}
// In the upload batch, which goes to the queue before the part that records this pass (as the BC stand-ins)
VkCommandBuffer cb = vk_upload_begin();
image_barrier(cb, a.img, VK_IMAGE_LAYOUT_UNDEFINED, layers);
vk_upload_end();
null_att[nnull_att++] = a;
int n = nnull_att;
plat_mutex_unlock(&null_att_lock);
rt_log("vk_exec: dummy attachment %ux%u x %u, %u samples, for empty colour slots: %.2f MiB (%d of %d)", w, h, layers,
samples, info.size / 1048576.0, n, NULL_ATTACH_MAX);
return a.view;
}
void vk_exec_pass_begin(VkExec *ex) {
if (ex->in_pass) return;
resolve_rt(ex);
@@ -696,10 +775,24 @@ void vk_exec_pass_begin(VkExec *ex) {
ex->fb_dirty = 0;
ex->pass_serial++;
VkRenderingAttachmentInfo ca[8], da = {0}, sa = {0};
uint32_t dummies = 0; // null_attach: empty slots below this get a dummy (the pipelines' colorAttachmentCount)
VkImageView dummy = VK_NULL_HANDLE;
if (vk_caps.null_attach)
for (uint32_t i = 0; i < ex->pass_ncolor; i++)
if (ex->color[i].image) dummies = i + 1;
for (uint32_t i = 0; i < ex->pass_ncolor; i++) {
const VkExecTarget *t = &ex->color[i];
ca[i] = (VkRenderingAttachmentInfo){.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO};
if (!t->image) continue;
if (!t->image) {
if (i < dummies) { // a dummy for the empty slot, which the pipelines name too (null_attach_view)
if (!dummy) dummy = null_attach_view(ex->pass_w, ex->pass_h, ex->pass_layers, ex->pass_samples);
ca[i].imageView = dummy;
ca[i].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
ca[i].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
ca[i].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
}
continue;
}
ca[i].imageView = view_of(ex, t);
ca[i].imageLayout = fbl >> i & 1 ? VK_IMAGE_LAYOUT_ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT : VK_IMAGE_LAYOUT_GENERAL;
ca[i].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
@@ -891,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
@@ -899,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");
@@ -1078,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);
@@ -1652,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
+117 -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
@@ -3328,6 +3345,22 @@ static void bi_done(VkExec *ex, const VkPipeInfo *info, const VkPipeState *s, co
D->B.bi_valid = 1;
}
// Mesa ANV (Intel iGPU, Linux): a draw whose vertex shader reads a storage buffer reads stale data inside a pass unless
// the sampler cache is invalidated first: the half-resolution particle pass drew campfire smoke and clouds as white or
// dark blobs and turned the sky white for single frames (#927). A by-region barrier before such a draw removes it
// (0 of 1460 frames broken against 57 of 779, about 2 fps of 40 on an Iris Xe); a stall alone or the attachment flush
// alone does not. The barrier costs about 5% of the frame rate on an Iris Xe and was only tested there, so it is off
// on every GPU by default; TOTK_ANV_VS_BARRIER=1 (ini: anv_vs_barrier = 1) turns it on, 0 keeps it off.
static int anv_vs_barrier(void) {
static int on = -1;
if (on < 0) {
const char *e = cfg_get("TOTK_ANV_VS_BARRIER");
on = e && *e && strcmp(e, "0") != 0;
rt_log("vk_exec: barrier before vertex-stage storage reads in a pass %s", on ? "on" : "off");
}
return on;
}
// Pass, shaders, pipeline, fixed state and resources for a draw. 0: the draw is skipped.
static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) {
VkExecDraw *D = ex->draw;
@@ -3434,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
@@ -3540,6 +3585,8 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) {
if (bim == 2) bi_census(ex, info, sp, bgt, bgb, bsg, sm_hit); // on counts nothing: it is what gets timed
bind_resources(ex, info, bim ? bgt : NULL, bgb);
if (fbl & ex->fb_dirty) feedback_barrier(ex);
else if (ex->in_pass && anv_vs_barrier() && gfx_shader_resources(vs, GFX_RES_SSBO, &(const GfxShaderRes *){0}))
{ uint32_t keep = ex->fb_dirty; feedback_barrier(ex); ex->fb_dirty = keep; } // keep fb_dirty: feedback_prepare learns from it
feedback_written(ex, sp);
bind_vertex_buffers(ex);
if (vk_dump_armed) vk_dump_draw(ex, sp, p, info);
@@ -4466,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;
@@ -4475,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");
@@ -4504,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;
}
}
+296
View File
@@ -0,0 +1,296 @@
// AMD FSR 4 for the scene upscaler (vk_ffx.h). The FSR SDK 2.4 ships its Vulkan effects as signed DLLs behind a
// loader: amd_fidelityfx_loader_vk.dll exports the ffx-api entry points and finds the effect DLL
// (amd_fidelityfx_upscaler_vk.dll) next to itself. Both are loaded from the executable's folder at run time; no SDK
// code is compiled in, only the descriptor layouts of ffx_api_min.h.
//
// The upscaler DLL offers several versions (FSR 4.x, FSR 3.1.x) and decides by itself which ones a device can run:
// vk_ffx_init lists them and pins the newest 4.x. A device the DLL offers no FSR 4 for runs without the upscaler (the
// log and the menu say so): FSR 3.1 is scene_upscaler = fsr3, built from the SDK 1.1.4 sources (vk_fsr3.cpp), not a
// fallback of this DLL. Every context is created with the pinned version (ffxOverrideVersion).
//
// What FSR 4 gets is what FSR 3.1 gets (vk_dlaa.c fsr_evaluate): the R11G11B10F light target as linear HDR colour, the
// D32F scene depth (standard direction, the far plane finite), motion vectors at the render size in render pixels
// pointing from this frame's position to last frame's without the jitter (motionVectorScale 1), the jitter the scene
// was drawn with, the camera's planes and field of view. That is FSR's own convention: its guide derives the
// projection offset as (2 jx / w, -2 jy / h), which moves the picture by (jx, jy) window pixels with y down, the way
// vk_dlaa_viewport moves the viewport. The exposure is FSR's own (AUTO_EXPOSURE), as codexx-dev's pull request #1245
// ran it on an RX 9070 XT.
#include "vk_ffx.h"
#include "cfg.h"
#include "host.h"
#ifndef _WIN32
int vk_ffx_wanted(void) { return 0; }
void vk_ffx_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max) {
(void)have, (void)nhave, (void)ext, (void)n, (void)max;
}
void vk_ffx_init(void) {}
int vk_ffx_tried(void) { return 0; }
int vk_ffx_available(void) { return 0; }
int vk_ffx_dispatch(VkCommandBuffer cb, const VkFfxDispatch *d) { return (void)cb, (void)d, 0; }
void vk_ffx_release(void) {}
const char *vk_ffx_version(void) { return ""; }
#else
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ffx_api_min.h"
#define FFX_LOADER L"amd_fidelityfx_loader_vk.dll"
#define FFX_MAX_VERSIONS 16
// The SDK's Vulkan backend writes a dispatch's descriptor sets and constants into rings this deep and frees the views
// of the dispatch that many back without knowing the GPU (FFX_MAX_QUEUED_FRAMES in the SDK's ffx_types.h, as
// vk_fsr3.cpp wait_ring reads it for SDK 1.1.4).
#define FFX_QUEUED 4
static struct {
HMODULE dll;
PfnFfxCreateContext create;
PfnFfxDestroyContext destroy;
PfnFfxQuery query;
PfnFfxDispatch dispatch;
int tried, loaded, available, failed;
VkDeviceContext dev;
uint64_t version_id;
char version[48];
ffxContext ctx; // the live context, made for ow x oh
uint32_t ow, oh;
uint64_t ring[FFX_QUEUED], n, waits; // the fences of the last dispatches (wait_ring)
} F;
int vk_ffx_wanted(void) { return vk_upscaler_engine() == UPSCALER_FSR4; }
static int loader_load(void) {
if (F.tried) return F.loaded;
F.tried = 1;
wchar_t path[MAX_PATH + 64];
DWORD len = GetModuleFileNameW(NULL, path, MAX_PATH);
while (len && path[len - 1] != L'\\') len--;
path[len] = 0;
wcscat(path, FFX_LOADER);
// LOAD_WITH_ALTERED_SEARCH_PATH: the loader's own imports and the effect DLL resolve from the executable's folder
F.dll = LoadLibraryExW(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!F.dll) {
rt_log("fsr4: cannot load amd_fidelityfx_loader_vk.dll next to totk.exe (error %lu): the scene upscaler is off",
GetLastError());
return 0;
}
F.create = (PfnFfxCreateContext)(void *)GetProcAddress(F.dll, "ffxCreateContext");
F.destroy = (PfnFfxDestroyContext)(void *)GetProcAddress(F.dll, "ffxDestroyContext");
F.query = (PfnFfxQuery)(void *)GetProcAddress(F.dll, "ffxQuery");
F.dispatch = (PfnFfxDispatch)(void *)GetProcAddress(F.dll, "ffxDispatch");
if (!F.create || !F.destroy || !F.query || !F.dispatch) {
rt_log("fsr4: amd_fidelityfx_loader_vk.dll lacks the ffx-api entry points: the scene upscaler is off");
return 0;
}
return F.loaded = 1;
}
static int has(const VkExtensionProperties *have, uint32_t nhave, const char *name) {
for (uint32_t i = 0; i < nhave; i++)
if (!strcmp(have[i].extensionName, name)) return 1;
return 0;
}
static void add(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max,
const char *name) {
for (uint32_t i = 0; i < *n; i++)
if (!strcmp(ext[i], name)) return;
if (has(have, nhave, name) && *n < max) ext[(*n)++] = name;
}
// The extensions the FSR SDK's own sample enables for its effects (Cauldron2 device_vk.cpp): cooperative matrix and
// 8-bit floats for FSR 4's network where the device has them. The rest it uses (16-bit floats and storage, integer
// dot products, subgroup size control) is core Vulkan 1.3, which vk_device.c enables as far as the driver reports it.
void vk_ffx_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max) {
if (!vk_ffx_wanted()) return;
add(have, nhave, ext, n, max, VK_KHR_COOPERATIVE_MATRIX_EXTENSION_NAME);
#ifdef VK_EXT_SHADER_FLOAT8_EXTENSION_NAME
add(have, nhave, ext, n, max, VK_EXT_SHADER_FLOAT8_EXTENSION_NAME);
#endif
}
void vk_ffx_init(void) {
if (!vk_ffx_wanted() || !loader_load()) return;
const VkCtx *c = vk_ctx();
F.dev = (VkDeviceContext){c->device, c->phys, vkGetDeviceProcAddr};
uint64_t count = FFX_MAX_VERSIONS, ids[FFX_MAX_VERSIONS] = {0};
const char *names[FFX_MAX_VERSIONS] = {0};
struct ffxQueryDescGetVersions q = {.header = {FFX_API_QUERY_DESC_TYPE_GET_VERSIONS, NULL},
.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE, .device = &F.dev,
.outputCount = &count, .versionIds = ids, .versionNames = names};
ffxReturnCode_t r = F.query(NULL, &q.header);
if (r != FFX_API_RETURN_OK || !count) {
rt_log("fsr4: no upscaler for this device (query %u, %llu versions; is amd_fidelityfx_upscaler_vk.dll next to "
"totk.exe?): the scene upscaler is off", (unsigned)r, (unsigned long long)count);
return;
}
if (count > FFX_MAX_VERSIONS) count = FFX_MAX_VERSIONS;
char list[256] = "";
// The newest 4.x the DLL offers for this device; the DLL leaves FSR 4 out for GPUs it does not run on
int best = -1, best_minor = 0, best_patch = 0;
for (uint64_t i = 0; i < count; i++) {
const char *nm = names[i] ? names[i] : "?";
size_t used = strlen(list);
snprintf(list + used, sizeof list - used, "%s%s", i ? ", " : "", nm);
int ma = 0, mi = 0, pa = 0;
if (sscanf(nm, "%d.%d.%d", &ma, &mi, &pa) < 1 || ma != 4) continue;
if (best < 0 || mi > best_minor || (mi == best_minor && pa > best_patch))
best = (int)i, best_minor = mi, best_patch = pa;
}
if (best < 0) {
rt_log("fsr4: the FSR libraries offer %s for this device, no FSR 4: the scene upscaler is off", list);
return;
}
F.version_id = ids[best];
snprintf(F.version, sizeof F.version, "FSR %s", names[best]);
F.available = 1;
rt_log("fsr4: upscaler versions for this device: %s; using %s", list, F.version);
}
int vk_ffx_tried(void) { return F.tried; }
int vk_ffx_available(void) { return vk_ffx_wanted() && F.available; }
const char *vk_ffx_version(void) { return F.available ? F.version : ""; }
// Messages from the upscaler (errors and warnings), in UTF-16; into the log as UTF-8.
static void on_message(uint32_t type, const wchar_t *msg) {
char s[512];
if (!msg || !WideCharToMultiByte(CP_UTF8, 0, msg, -1, s, (int)sizeof s, NULL, NULL)) return;
rt_log("fsr4: %s: %s", type == FFX_API_MESSAGE_TYPE_ERROR ? "error" : "warning", s);
}
// The context for an ow x oh output, any scene up to that size (DYNAMIC_RESOLUTION: the modes and the game's tiers
// change the scene without a new context), as vk_fsr3.cpp create makes FSR 3.1's.
static int create(uint32_t ow, uint32_t oh) {
struct ffxOverrideVersion ov = {.header = {FFX_API_DESC_TYPE_OVERRIDE_VERSION, NULL}, .versionId = F.version_id};
struct ffxCreateContextDescUpscaleVersion ver = {
.header = {FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE_VERSION, &ov.header}, .version = FFX_UPSCALER_VERSION};
struct ffxCreateBackendVKDesc be = {.header = {FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK, &ver.header},
.deviceContext = F.dev};
// Linear HDR scene light with the upscaler's own exposure; standard depth with a finite far plane, as FSR 3.1's
uint32_t flags = FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE | FFX_UPSCALE_ENABLE_AUTO_EXPOSURE |
FFX_UPSCALE_ENABLE_DYNAMIC_RESOLUTION;
if (rt_knob("FSR4_DEBUG", "0")) flags |= FFX_UPSCALE_ENABLE_DEBUG_CHECKING; // TOTK_FSR4_DEBUG=1: API checks
struct ffxCreateContextDescUpscale cd = {.header = {FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE, &be.header},
.flags = flags, .maxRenderSize = {ow, oh}, .maxUpscaleSize = {ow, oh},
.fpMessage = on_message};
ffxContext ctx = NULL;
ffxReturnCode_t r = F.create(&ctx, &cd.header, NULL);
if (r != FFX_API_RETURN_OK || !ctx) {
rt_log("fsr4: context creation failed (%u) at %ux%u: FSR 4 off for this run", (unsigned)r, ow, oh);
return 0;
}
struct ffxQueryGetProviderVersion pv = {.header = {FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION, NULL}};
F.query(&ctx, &pv.header);
rt_log("fsr4: context up to %ux%u -> %ux%u with %s (flags %#x)", ow, oh, ow, oh,
pv.versionName ? pv.versionName : F.version, flags);
F.ctx = ctx, F.ow = ow, F.oh = oh, F.n = 0;
memset(F.ring, 0, sizeof F.ring);
return 1;
}
static void destroy(void) {
if (F.ctx) F.destroy(&F.ctx, NULL);
F.ctx = NULL;
}
static uint32_t surface_format(VkFormat f) {
switch (f) {
case VK_FORMAT_B10G11R11_UFLOAT_PACK32: return FFX_API_SURFACE_FORMAT_R11G11B10_FLOAT;
case VK_FORMAT_R16G16B16A16_SFLOAT: return FFX_API_SURFACE_FORMAT_R16G16B16A16_FLOAT;
case VK_FORMAT_R16G16_SFLOAT: return FFX_API_SURFACE_FORMAT_R16G16_FLOAT;
case VK_FORMAT_D32_SFLOAT: return FFX_API_SURFACE_FORMAT_R32_FLOAT;
default: return FFX_API_SURFACE_FORMAT_UNKNOWN;
}
}
// Every image of the scene upscaler stays in VK_IMAGE_LAYOUT_GENERAL: GENERIC_READ and UNORDERED_ACCESS are the
// states the Vulkan backend maps to that layout (ffx_vk.cpp getVKImageLayoutFromResourceState), and it puts each
// resource back into the state it was given at the end of the dispatch.
static struct FfxApiResource resource(const VkFfxImage *im, uint32_t usage, uint32_t state) {
struct FfxApiResource r;
memset(&r, 0, sizeof r);
if (!im->image) return r;
r.resource = (void *)im->image;
r.description = (struct FfxApiResourceDescription){.type = FFX_API_RESOURCE_TYPE_TEXTURE2D,
.format = surface_format(im->format), .width = im->width,
.height = im->height, .depth = 1, .mipCount = 1, .usage = usage};
r.state = state;
return r;
}
// With the game's two or three frames in flight the dispatch FFX_QUEUED - 1 back is long done; should it not be, its
// submission is waited for here (counted), as vk_fsr3.cpp wait_ring does for FSR 3.1.
static void wait_ring(uint64_t fence) {
if (F.n >= FFX_QUEUED - 1) {
uint64_t back = F.ring[(F.n + 1) % FFX_QUEUED];
if (back && vk_sync_fence_done() < back) {
if (!F.waits++) rt_log("fsr4: waiting for the submission of a dispatch %d back (more frames in flight than "
"the SDK's rings hold)", FFX_QUEUED - 1);
vk_sync_fence_wait(back, 2000000000ull);
}
}
F.ring[F.n % FFX_QUEUED] = fence;
}
int vk_ffx_dispatch(VkCommandBuffer cb, const VkFfxDispatch *d) {
if (!F.available || F.failed) return 0;
uint32_t ow = d->out.width, oh = d->out.height;
if (!F.ctx || ow != F.ow || oh != F.oh) {
if (F.ctx) {
vkDeviceWaitIdle(vk_ctx()->device); // what the old context recorded is queued or submitted
destroy();
}
if (!create(ow, oh)) return F.failed = 1, 0;
}
if (d->color.width > F.ow || d->color.height > F.oh) {
rt_log("fsr4: a %ux%u scene is larger than the %ux%u output: FSR 4 off for this run", d->color.width,
d->color.height, F.ow, F.oh);
return F.failed = 1, 0;
}
wait_ring(d->fence);
struct ffxDispatchDescUpscale u;
memset(&u, 0, sizeof u);
u.header.type = FFX_API_DISPATCH_DESC_TYPE_UPSCALE;
u.commandList = (void *)cb;
u.color = resource(&d->color, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_GENERIC_READ);
u.depth = resource(&d->depth, FFX_API_RESOURCE_USAGE_DEPTHTARGET, FFX_API_RESOURCE_STATE_GENERIC_READ);
u.motionVectors = resource(&d->mv, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_GENERIC_READ);
u.output = resource(&d->out, FFX_API_RESOURCE_USAGE_UAV, FFX_API_RESOURCE_STATE_UNORDERED_ACCESS);
// (no reactive or transparency mask: FSR 3.1 gets none either)
u.jitterOffset = (struct FfxApiFloatCoords2D){d->jx, d->jy};
u.motionVectorScale = (struct FfxApiFloatCoords2D){1.0f, 1.0f}; // render pixels already
u.renderSize = (struct FfxApiDimensions2D){d->color.width, d->color.height};
u.upscaleSize = (struct FfxApiDimensions2D){ow, oh};
u.enableSharpening = d->sharpness > 0;
u.sharpness = d->sharpness > 1.0f ? 1.0f : d->sharpness;
u.frameTimeDelta = d->dt_ms;
u.preExposure = 1.0f;
u.reset = d->reset != 0;
u.cameraNear = d->cam_near;
u.cameraFar = d->cam_far;
u.cameraFovAngleVertical = d->fov_y;
u.viewSpaceToMetersFactor = 1.0f; // TotK's world units are metres
ffxReturnCode_t r = F.dispatch(&F.ctx, &u.header);
F.n++;
if (r != FFX_API_RETURN_OK) {
rt_log("fsr4: dispatch failed (%u) at %ux%u -> %ux%u: FSR 4 off for this run", (unsigned)r, d->color.width,
d->color.height, ow, oh);
return F.failed = 1, 0;
}
return 1;
}
void vk_ffx_release(void) {
const VkCtx *c = vk_ctx();
if (!F.ctx || !c || !c->device) return;
vkDeviceWaitIdle(c->device);
if (F.waits) rt_log("fsr4: %llu dispatches waited for an earlier one's submission", (unsigned long long)F.waits);
destroy();
}
#endif
+41
View File
@@ -0,0 +1,41 @@
// AMD FSR 4 (vk_ffx.c), the fourth engine of vk_dlaa.c's scene upscaler (scene_upscaler = fsr4): the frame DLSS and
// FSR 3.1 get goes to FSR 4 through AMD's FSR SDK 2.4 signed libraries, amd_fidelityfx_loader_vk.dll and
// amd_fidelityfx_upscaler_vk.dll next to the executable. Windows only; elsewhere every call does nothing.
#pragma once
#include "vk.h"
// FSR 4 is the scene upscaler picked at start (vk_dlaa.c vk_upscaler_engine); the device may still lack it.
int vk_ffx_wanted(void);
// vk_device.c, while it builds the device: the extensions FSR 4's shaders use (cooperative matrix, 8-bit floats) join
// the list when the device has them; their feature structures are chained there.
void vk_ffx_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max);
void vk_ffx_init(void); // vk_dlaa.c vk_dlaa_init, after the device exists: loads the loader and pins FSR 4
int vk_ffx_tried(void); // vk_ffx_init ran (FSR 4 picked at start, on Windows)
int vk_ffx_available(void); // vk_ffx_init found FSR 4 for this device
typedef struct { // one image FSR reads or writes, in VK_IMAGE_LAYOUT_GENERAL, level 0 and layer 0
VkImage image;
VkFormat format;
uint32_t width, height;
} VkFfxImage;
typedef struct {
VkFfxImage color; // the scene's light (R11G11B10F or RGBA16F, linear), the render size
VkFfxImage depth; // its D32F depth, standard direction (0 near), finite far plane
VkFfxImage mv; // RG16F motion vectors as vk_fsr3.h Fsr3Frame.mv (render pixels, without the jitter)
VkFfxImage out; // RGBA16F with storage, the output size
float jx, jy; // this frame's jitter, render pixels (window x right, y down), as the scene was drawn
float dt_ms; // time since the previous dispatch
float cam_near, cam_far; // the camera's planes (m)
float fov_y; // vertical field of view, radians
float sharpness; // FSR's own sharpening pass (RCAS) on its output, 0..1; 0: none
int reset; // a new history
uint64_t fence; // the submission's timeline value (VkExec.fence)
} VkFfxDispatch;
// Records FSR 4 into cb (every image in GENERAL, left so; no render pass open; recorder drained by the caller). The
// context is made at the first call and again when the output size changes; the scene may be any size up to the
// output. 0 when it failed (logged; FSR 4 stays off for the run). FSR binds pipelines and descriptors of its own.
int vk_ffx_dispatch(VkCommandBuffer cb, const VkFfxDispatch *d);
void vk_ffx_release(void); // vk_device.c destroy_all, before the device goes away; harmless when nothing was made
const char *vk_ffx_version(void); // "FSR 4.1.2" once vk_ffx_init pinned it, "" before or without
+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,
+25 -3
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);
@@ -1867,7 +1881,7 @@ static PlatMutex mirror_stat_lock = PLAT_MUTEX_INIT;
static volatile int64_t m_live_n, m_live_bytes, m_refused_n[MR_N], m_refused_bytes[MR_N];
static volatile int64_t m_flush_calls, m_flush_bytes, v_pages, v_skipped, v_mismatch;
static void mirror_mode(int discrete) {
static void mirror_mode(int discrete, int host_import) {
const char *e = cfg_value("TOTK_MEMORY");
int mode = discrete ? 1 : 0; // 0 import, 1 mirror, 2 verify
const char *why = discrete ? "auto, discrete gpu" : "auto, uma";
@@ -1902,6 +1916,14 @@ static void mirror_mode(int discrete) {
#else
shadow_on = !sh || !*sh || strcmp(sh, "0");
#endif
// Without VK_EXT_external_memory_host (Qualcomm Adreno's Windows driver, some mobile and older drivers, or
// TOTK_VK_NO_HOST_IMPORT=1) guest memory cannot be imported: every CPU-visible pool gets shadow storage, the path
// Wine already takes (import_pool -> shadow_pool), whatever TOTK_SHADOW says.
if (!host_import) {
if (!shadow_on) rt_log("mem: no host import (VK_EXT_external_memory_host): shadow storage%s",
sh && *sh ? ", TOTK_SHADOW=0 overridden" : "");
shadow_on = 1;
}
defer_on = shadow_on && cfg_bool("TOTK_SYNC_AHEAD") && strcmp(cfg_value("TOTK_SYNC_AHEAD"), "check") &&
cfg_bool("TOTK_SHADOW_DEFER"); // check: the wait stays exact, nothing is deferred
if (defer_on) rt_log("mem: TOTK_SHADOW_DEFER: shadow updates that wait for a reader are queued for the GPU instead");
@@ -2931,7 +2953,7 @@ static void vram_log(uint64_t frame) {
// Device class: INTEGRATED -> uma; a discrete GPU with a DEVICE_LOCAL heap of 1 GiB or more beside a
// heap that is not device-local (host memory) -> discrete; otherwise uma (import everywhere). Sets the mirror mode.
void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDeviceMemoryProperties *m) {
void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDeviceMemoryProperties *m, int host_import) {
int big_local = -1, host_heap = -1;
for (uint32_t h = 0; h < m->memoryHeapCount; h++) {
if (m->memoryHeaps[h].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) {
@@ -2973,7 +2995,7 @@ void vk_mem_class_log(const VkPhysicalDeviceProperties *p, const VkPhysicalDevic
if (host_backed == HB_UMA)
rt_log("mem: device memory against system memory: commit and physical memory (uma), reserve %llu MiB "
"(TOTK_MEM_RESERVE_MIB)", (unsigned long long)(room_reserve >> 20));
mirror_mode(discrete);
mirror_mode(discrete, host_import);
}
// ---------------------------------------------------------------- upload batches and deferred destruction
+58 -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;
@@ -1345,6 +1382,7 @@ static uint32_t target_wmask(const VkPipeState *s, int i) {
uint32_t m = s->chmask.mask >> (4 * i) & 0xf;
if (s->fs && !(gfx_shader_outputs(s->fs, NULL) >> i & 1)) m = 0;
if (i == 1 && s->fs && P.f_dual_src && uses_src1(s)) m = 0; // output 1 is the second blend source (spirv_dual_source)
if (!s->color_fmt[i] && vk_caps.null_attach) m = 0; // an empty slot's dummy attachment (vk_exec.c) takes no writes
return m;
}
@@ -1380,6 +1418,9 @@ static void gkey_fill(const VkPipeState *s, GKey *k) {
o[3] = (uint8_t)blend_factor(b->src_a), o[4] = (uint8_t)blend_factor(b->dst_a), o[5] = (uint8_t)blend_op(b->eq_a);
}
}
if (vk_caps.null_attach) // empty slots get the dummy attachment's format (vk_exec.c null_attach_view)
for (int i = 0; i < k->n_color; i++)
if (k->color[i] == VK_FORMAT_UNDEFINED) k->color[i] = VK_EXEC_NULL_ATTACH_FMT;
if (!P.dyn_vi) {
VtxInput v;
vertex_input(s, &v);
+61
View File
@@ -0,0 +1,61 @@
"""A/B log reports keep absolute timings when a percentage has a zero baseline."""
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def window(frame, interval, replay, b, n=60, world=20):
return (f'perf: frame {frame}: interval avg {interval:.2f} ms max 100.00 ms ({1000 / interval:.1f} fps); '
f'replay avg {replay:.2f} ms; ab {b}/{n}; world {world:.1f} s\n')
class AbSummaryTest(unittest.TestCase):
def summarize(self, text):
with tempfile.TemporaryDirectory() as tmp:
log = Path(tmp) / 'synthetic.log'
log.write_text(text, encoding='utf-8')
return subprocess.run([sys.executable, str(ROOT / 'tools' / 'ab_summary.py'), str(log)],
capture_output=True, text=True)
def test_no_replay_on_either_side_keeps_the_interval_comparison(self):
run = self.summarize(window(60, 20, 0, 0) + window(120, 10, 0, 60))
self.assertEqual(run.returncode, 0, run.stderr)
self.assertIn('B - A: interval -10.00 ms (-50.0%), replay +0.00 ms (n/a: A is zero)', run.stdout)
def test_replay_appearing_in_b_reports_its_absolute_cost(self):
run = self.summarize(window(60, 10, 0, 0) + window(120, 12, 2, 60))
self.assertEqual(run.returncode, 0, run.stderr)
self.assertIn('replay +2.00 ms (n/a: A is zero)', run.stdout)
def test_replay_disappearing_in_b_still_has_a_defined_percentage(self):
run = self.summarize(window(60, 12, 2, 0) + window(120, 10, 0, 60))
self.assertEqual(run.returncode, 0, run.stderr)
self.assertIn('replay -2.00 ms (-100.0%)', run.stdout)
def test_nonzero_means_remain_weighted_by_each_windows_frames(self):
text = window(60, 10, 2, 0, n=30) + window(120, 20, 4, 0)
text += window(180, 10, 2, 60)
run = self.summarize(text)
self.assertEqual(run.returncode, 0, run.stderr)
self.assertIn('interval -6.67 ms (-40.0%), replay -1.33 ms (-40.0%)', run.stdout)
def test_load_and_mixed_windows_stay_excluded(self):
text = window(60, 100, 100, 0, world=5) + window(120, 100, 100, 30)
text += window(180, 10, 2, 0) + window(240, 12, 3, 60)
run = self.summarize(text)
self.assertEqual(run.returncode, 0, run.stderr)
self.assertIn('interval +2.00 ms (+20.0%), replay +1.00 ms (+50.0%)', run.stdout)
def test_missing_side_keeps_the_diagnostic_and_failure_exit(self):
run = self.summarize(window(60, 10, 2, 0))
self.assertEqual(run.returncode, 1)
self.assertIn('no whole A and B windows', run.stdout)
self.assertEqual(run.stderr, '')
if __name__ == '__main__':
unittest.main()
+112
View File
@@ -0,0 +1,112 @@
"""Build command arguments through real Ninja and a POSIX shell, using only synthetic paths and source files."""
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools'))
import build_game as build # noqa: E402
NINJA, SHELL = shutil.which('ninja'), shutil.which('sh')
@unittest.skipUnless(NINJA, 'no Ninja on PATH')
class CommandTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory(prefix='build command ')
self.addCleanup(tmp.cleanup)
self.folder = Path(tmp.name)
self.probe = self.folder / 'arguments.py'
self.probe.write_text('import json, pathlib, sys\n'
'pathlib.Path(sys.argv[1]).write_text(json.dumps(sys.argv[2:]))\n')
def ninja(self, target, command, posix=False, bindings=''):
if posix:
# Ninja on Unix uses sh -c. An expanded response file lets Windows exercise those same shell bytes too.
shell = subprocess.list2cmdline([SHELL]) if os.name == 'nt' else shlex.quote(SHELL)
text = (f'rule probe\n command = {shell.replace("$", "$$")} $out.rsp\n'
f' rspfile = $out.rsp\n rspfile_content = {command}\n')
else:
text = f'rule probe\n command = {command}\n'
(self.folder / 'build.ninja').write_text(bindings + text + f'build {target}: probe\n', encoding='utf-8')
env = dict(os.environ, BUILD_QUOTE_TEST='expanded', MSYS2_ARG_CONV_EXCL='*')
run = subprocess.run([NINJA, '-f', 'build.ninja', target], cwd=self.folder, env=env,
capture_output=True, text=True, timeout=30)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
@unittest.skipUnless(SHELL, 'no POSIX shell on PATH')
def test_posix_arguments_survive_ninja_and_the_shell(self):
values = ('ordinary/path', 'path with spaces', 'path/$BUILD_QUOTE_TEST/include',
'path with spaces/$BUILD_QUOTE_TEST/include', "path/O'Reilly/include",
'path/(parentheses)/include', 'path/double"quote/include',
'path/$(printf expanded)/include')
for index, value in enumerate(values):
with self.subTest(value=value), patch.object(build, 'WIN', False):
target = f'posix-{index}.json'
command = ' '.join(build.cmd_arg(arg) for arg in
(Path(sys.executable).as_posix(), self.probe.as_posix(), target, value))
self.ninja(target, command, posix=True)
self.assertEqual(json.loads((self.folder / target).read_text()), [value])
@unittest.skipUnless(os.name == 'nt', 'native Windows command parsing')
def test_windows_paths_still_survive_native_ninja_commands(self):
values = ['ordinary/path', 'path with spaces', 'path/$BUILD_QUOTE_TEST/include', "path/O'Reilly/include"]
with patch.object(build, 'WIN', True):
command = ' '.join(build.cmd_arg(arg) for arg in
(Path(sys.executable).as_posix(), self.probe.as_posix(), 'windows.json', *values))
self.ninja('windows.json', command)
self.assertEqual(json.loads((self.folder / 'windows.json').read_text()), values)
@unittest.skipUnless(SHELL and (os.environ.get('CC') or shutil.which('clang')), 'needs a POSIX shell and clang')
def test_compiler_finds_headers_in_a_path_with_shell_metacharacters(self):
include = self.folder / "O'Reilly $BUILD_QUOTE_TEST (headers)"
include.mkdir()
(include / 'synthetic.h').write_text('#define SYNTHETIC_VALUE 42\n')
source = self.folder / 'probe.c'
source.write_text('#include <synthetic.h>\nint main(void) { return SYNTHETIC_VALUE != 42; }\n')
compiler = os.environ.get('CC') or shutil.which('clang')
target = 'probe.exe' if os.name == 'nt' else 'probe'
with patch.object(build, 'WIN', False):
command = f'{build.cmd_arg(Path(compiler).as_posix())} -I {build.cmd_path(include)} '
command += f'{build.cmd_path(source)} -o {build.cmd_arg(target)}'
self.ninja(target, command, posix=True)
run = subprocess.run([str(self.folder / target)], timeout=10)
self.assertEqual(run.returncode, 0)
@unittest.skipUnless(SHELL and (os.environ.get('CC') or shutil.which('clang')), 'needs a POSIX shell and clang')
def test_linker_writes_the_map_in_the_literal_build_directory(self):
self.link_map(posix=True)
@unittest.skipUnless(os.name == 'nt' and (os.environ.get('CC') or shutil.which('clang')), 'native Windows linker')
def test_windows_linker_keeps_the_map_path_as_one_argument(self):
self.link_map(posix=False)
def link_map(self, posix):
output = self.folder / "O'Reilly $BUILD_QUOTE_TEST (output), comma"
output.mkdir()
source = self.folder / 'link.c'
source.write_text('int main(void) { return 0; }\n')
compiler = os.environ.get('CC') or shutil.which('clang')
target = 'link.exe' if os.name == 'nt' else 'link'
with patch.object(build, 'WIN', not posix), patch.object(build, 'vma_include', return_value=self.folder), \
patch.object(build, 'runtime_sources', return_value=[]):
# Use production Ninja bindings, but link only our own tiny program, without runtime or game inputs.
ninja, _, _ = build.ninja_file(self.folder, output, {}, 1)
bindings = '\n'.join(line for line in ninja.splitlines()
if line.startswith(('builddir = ', 'ldflags = '))) + '\n'
command = (f'{build.cmd_arg(Path(compiler).as_posix())} {build.cmd_path(source)} '
f'$ldflags -o {build.cmd_arg(target)}')
self.ninja(target, command, posix=posix, bindings=bindings)
self.assertTrue((output / 'totk.map').is_file(), 'the linker must write the map at the requested path')
self.assertIn('main', (output / 'totk.map').read_text())
if __name__ == '__main__':
unittest.main(verbosity=2)
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more