mirror of
https://github.com/valentderah/totk-pc-recomp.git
synced 2026-11-19 20:25:57 +00:00
Compare commits
No files matched your search
@@ -31,7 +31,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
- Setup and in-game menu in English, Russian, Brazilian Portuguese and Simplified Chinese
|
||||
- Keyboard, mouse and gamepad with remapping, rumble and gyro
|
||||
- Stereo or 5.1 surround sound output
|
||||
- Xbox button prompts: LB, RB, LT, RT, Menu and View, and A, B, X and Y as labelled on the button to press, with either button layout
|
||||
- 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
|
||||
- Shaders prepared at install instead of during play
|
||||
- Mods made for emulators: unpack a mod into the `mods` folder next to `totk.exe`; switch and order them in the menu. RomFS
|
||||
mods, TKMM's merged output and ExeFS code patches (`.ips`, `.pchtxt`) work; the game rebuilds itself for code patches
|
||||
|
||||
@@ -53,6 +53,7 @@ scene you expected. Title menus on a slow boot eat presses, and runs of one scri
|
||||
| every render pass of one frame | `TOTK_DUMP=<frame>` and `TOTK_DUMP_DIR`: a PNG per pass target plus `passes.txt` (draws, bound textures with swizzles, storage buffers, copies, clears) and `images.txt`; `TOTK_DUMP_BUF` adds a guest buffer |
|
||||
| Vulkan misuse | `TOTK_VK_VALIDATION=1` (needs the Vulkan SDK), run into the world; compare the message kinds with a run without your change. The layer caps repeats, so counts are not totals |
|
||||
| which pass the GPU was in at a device lost | the `vk: pass marks` lines; on by default on AMD, `TOTK_PASS_CRUMBS=1` elsewhere |
|
||||
| which object held the address of a GPU memory fault | `TOTK_ADDR_REPORT=1` (off by default: it slows recording, on AMD's Windows driver more and more over a session); the `vk: fault address` lines after the device lost |
|
||||
| a crash | the crash report at the end of the log: exception, guest and host addresses, registers |
|
||||
| a run on a large card that acts like a small one | `TOTK_VRAM_LIMIT_MIB=<MiB>` |
|
||||
|
||||
|
||||
@@ -11,12 +11,14 @@ GPU semantics behind the graphics rows: [maxwell.md](../maxwell.md). The method
|
||||
| Symptom | Usual causes | First check |
|
||||
|---|---|---|
|
||||
| magenta, brown or stale textures; caves or sky wrong | the CPU filled the texture and the GPU never got the upload (no flush on the console) | frame dump: the texture's upload count and mirror state in `passes.txt` |
|
||||
| rain shows only its splashes on the ground, no falling drops; waterfall splashes and mist blink | a GPU write-back copies a whole range over particle records the CPU spawned in it (`vk_memory.c`: the write-back merge, and with `shadow = 1` the shadow's pending ranges) | a run with `TOTK_WB_MERGE=0` or `TOTK_SHADOW=0` against one without |
|
||||
| effects that never happen: cut grass stays up, fire does not spread | the CPU reads a GPU-rendered texture that was never written back | which texture the game reads after its fence; write-back of that target |
|
||||
| black scene, black dialog background or loading map | deferred binds read at record time; a 3D target rejected; a texture compare ignoring the channel mapping | frame dump: the first pass whose target goes black |
|
||||
| lime silhouettes, rectangles in the sky | a target outside the shader's output map overwritten instead of kept | dump: the target's previous contents versus after the pass |
|
||||
| dark or magenta 16x16 blocks, missing characters | a pass samples its own render targets (G-buffer feedback) | feedback-loop layout and barriers on that pass |
|
||||
| tile rectangles, wrong data in tiles | storage buffers bound in the wrong slot order | `passes.txt`: storage buffers with their c0 slots |
|
||||
| streaks on cliffs, characters stretched into streaks | primitive restart ignored; integer vertex inputs against a float format | validation run; the draw's topology and vertex formats in the dump |
|
||||
| huge stretched slabs over the ground, a ceiling over Link, the ground up to his chest, from the load on for the whole session (the Depths); some runs only, most at a high frame rate; with `sync_ahead`, `replay_workers` and a discrete GPU | a VRAM mirror copied from the shadow before the CPU's write reached it, and kept the old vertices while marked synced (fixed: `vk_memory.c` `vk_mem_mirror_seal`) | `TOTK_MEMORY=verify` mismatch lines; `memory = import` or `replay_workers = 0` makes it go; `fps_limit = 144` shows it in most runs |
|
||||
| garbage geometry on title or load screens | 8-bit indices widened on the CPU before a copy in the same submission wrote them | whether a copy to the index buffer precedes the draw in one submission |
|
||||
| black tiles, masks not cleared | clears with a partial channel or stencil mask skipped or done in full | `passes.txt` clears and their masks |
|
||||
| garbage in feedback effects at first use | new GPU-only images start undefined; the console starts them at zero | clear on creation and compare |
|
||||
@@ -25,7 +27,13 @@ GPU semantics behind the graphics rows: [maxwell.md](../maxwell.md). The method
|
||||
| no sun shadows, wrong lighting | unwritten vertex outputs read as zero instead of (0,0,0,1) | the shader's output map |
|
||||
| one flat ambient colour | a 1-layer 2D array sampled as 2D | the view type the shader expects |
|
||||
| upside-down text | lower-left window origin | origin mode in the log |
|
||||
| puddles and still water flicker: the reflection turns on and off in patches from frame to frame while the camera stands still, more with DLAA | the game's water volume mask: a volume's top face lies on the water surface and is tested LEQUAL against a depth rebuilt at quarter size, so rounding and the camera's sub-millimetre motion decide it (fixed: `vk_pipeline.c` `vk_pipeline_volume_bias` gives such draws a depth bias toward the viewer) | a `--capture` run: the puddle's brightness swing (`capture.py` frames, a region's mean) with `TOTK_VOLUME_MASK_BIAS=0` and without; in a frame dump, the quarter-size mask after the volume draw changes from frame to frame |
|
||||
| with DLAA on, water seen at a low angle (ponds, streams) flickers in large patches with a period of about three frames, between the reflection of the trees and that of the sky; without DLAA it is still | the jitter moved the viewport of the scene's draws but not the game's camera, so its full-screen passes rebuilt positions half a pixel off the surface and its screen-space reflections flipped between hit and miss with the jitter's phase (fixed on 1.4.3: `vk_dlaa.c` puts the jitter into the camera blocks where the game copies its matrices, `vk_dlaa_camera_copied`) | `TOTK_DLAA_CAM_JITTER=0` brings the viewport jitter back; a `--capture` run: the region's brightness swing with DLAA, against `TOTK_DLAA_JITTER=0` |
|
||||
| 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, 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
|
||||
|
||||
@@ -36,6 +44,8 @@ GPU semantics behind the graphics rows: [maxwell.md](../maxwell.md). The method
|
||||
| frame counter wanders 50-60 | two 60 Hz clocks (vsync event and present acquire) drifting apart | whether both follow one display tick |
|
||||
| a 30 Hz thread runs at 27 Hz, slow cutscenes | host sleep overshoot: Windows waitable timers wake 0.3-0.5 ms late | `TOTK_TRACE=sched` sleep asked versus took |
|
||||
| 20 fps after a scheduler change | a yield back-off that starts too early | yield handling against the console's |
|
||||
| in the Depths Link takes gloom damage and wears the gloom haze while standing on clean ground, some runs only; only with `sync_ahead = 1` | the game read a GPU result of the frame it was told is done before the GPU wrote it: its one-pixel readbacks go through a buffer per request, which then holds zeros or an answer from the ring's last round (fixed: `vk_memory.c` `vk_mem_shadow_read` waits at the invalidate) | `sync_ahead = 0`; the exit line `mem: the game waited for a GPU write it reads` |
|
||||
| in shrines the lamps' reflections on the floor go out for single frames, every other frame at some camera angles; only with `sync_ahead = 1`, more with DLAA (the GPU runs further behind) | the game reads its depth query results two frames later and refuses them unless their frame number is exactly the counter - 2; with sync_ahead it is the counter - 3 on frames where the GPU is behind (fixed: patch set `qstamp` in `recomp/patches-v143.txt` also takes the counter - 3) | `sync_ahead = 0`; a `--capture` run with `TOTK_SYNC_AHEAD` on, counting one-frame drops in floor regions |
|
||||
| climbing or movement wrong only above some fps | game code that assumes a fixed step count per frame | compare at 30, 60 and the failing rate |
|
||||
|
||||
## Threads and crashes
|
||||
|
||||
@@ -90,7 +90,7 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app
|
||||
- Memory pools. Apple's unified memory let MacNativeGames use the game's pools zero-copy. The back end imports the pools as host memory (`VK_EXT_external_memory_host`). 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. This is safe only 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; without it the switch is ignored): 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.2.1 and 1.4.3); results the game reads back from the GPU after it can be a frame old.
|
||||
- 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. This is safe only 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; without it the switch is ignored): 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.
|
||||
- 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).
|
||||
- Uniform snapshot. The game rewrites per-object uniform blocks on other threads soon after it submits the frame
|
||||
that reads them, while the replay still records it. At the start of a submission's replay every uniform range it
|
||||
@@ -109,11 +109,13 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app
|
||||
RCAS) on the present. An `output_res` that is not 16:9 (more than 1% off, `res_is_16x9`) also switches on the
|
||||
`aspect` patch set, which hands the output's ratio to the camera, and `romfs.c` `overlay_init` loads the
|
||||
`romfs-patches-<w>x<h>` overlay for it when it exists (`tools/make_romfs_patches.py --aspect`, laid out by
|
||||
`tools/ultrawide_layout.py`; the installer builds fifteen sizes: 21:9 2560x1080, 3440x1440, 3840x1600, 5120x2160,
|
||||
32:9 3840x1080, 5120x1440, 16:10 1280x800, 1680x1050, 1920x1200, 2560x1600 and 3:2 1920x1280, 2160x1440, 2256x1504,
|
||||
2880x1920, 3000x2000). A wider layout moves the HUD to the
|
||||
screen's corners, a narrower one to its top and bottom edges. Other sizes get the camera of their shape and the 16:9
|
||||
HUD stretched over it. The `aspect` setting (`fit`, the default; `stretch`) decides what the present does
|
||||
`tools/ultrawide_layout.py`; installer/steps.py Shapes builds one canonical folder per needed display/output shape,
|
||||
chosen by installer/screens.py). A wider layout moves the HUD to the
|
||||
screen's corners (`hud_width = 21:9` or `16:9` keeps it in the middle of the screen instead, from the `-hud21x9` or
|
||||
`-hud16x9` variant of the folder), a narrower one to its top and bottom edges. Shapes generates a capped variant
|
||||
only when selected, alongside the full layout and selected button prompts. `romfs.c` `shaped_name` checks the exact
|
||||
size then its canonical shape; a missing cap falls back to full, while the menu still offers preparation for the cap.
|
||||
Without any matching layout the output falls back to 16:9. The `aspect` setting (`fit`, the default; `stretch`) decides what the present does
|
||||
when the window's shape differs from the output's: `fit` letterboxes, where a 16:9 game in a wider window used to be
|
||||
stretched.
|
||||
- HDR (`hdr = 1`, `vk_hdr.c`). The game tonemaps its scene into an r11g11b10f target, upscales it and draws the HUD
|
||||
|
||||
+33
-6
@@ -111,18 +111,37 @@ of them.
|
||||
$env:SCCACHE = "path\to\sccache.exe"
|
||||
.venv\Scripts\python tools\build_game.py --version <ver>
|
||||
```
|
||||
|
||||
A build into another `--out` (a task build, or a private lift of a patch change with `--gen generated\<ver>-<tag>`)
|
||||
hardlinks the objects of the main build `build\<ver>` and compiles only `runtime/` and the generated files whose
|
||||
compile differs. An object is reused when the main `build.ninja` has the same compiler, flags and rule, the main
|
||||
build is up to date, and every file its compile read according to the main Ninja deps log (the `.c`, the `runtime/`
|
||||
and generated headers, the system headers) has the same bytes in this build's trees and has not changed since the
|
||||
object was written, and neither has the compiler. A lift that changes one patch site then compiles one or two chunks
|
||||
instead of all of them. The build prints `reused N of M generated objects`; `--verbose` lists the others with the
|
||||
reason, and `--full-build` compiles everything.
|
||||
`--patches` builds in the frame-rate, resolution and other patch sets, switchable at run time. The link copies
|
||||
`SDL3.dll`, `libiconv-2.dll` and `libopus-0.dll` next to the exe.
|
||||
For Xbox button prompts, run `make_romfs_patches.py` twice more, with `--prompts xbox` and `--prompts xbox-label`:
|
||||
they write `build\<ver>\romfs-patches-xbox` and `romfs-patches-xbox-label` ([controls.md](controls.md), "Xbox
|
||||
button prompts"), which `build_game.py` copies next to `totk.exe` like `romfs-patches`. `--prompts pc` writes
|
||||
`romfs-patches-pc`, the keyboard and mouse prompts ([controls.md](controls.md), "PC button prompts").
|
||||
For Xbox and PlayStation button prompts, run `make_romfs_patches.py` twice more for each, with `--prompts xbox`,
|
||||
`--prompts xbox-label`, `--prompts playstation` and `--prompts playstation-xbox`: they write
|
||||
`build\<ver>\romfs-patches-xbox`, `-xbox-label`, `-playstation` and `-playstation-xbox`
|
||||
([controls.md](controls.md), "Xbox and PlayStation button prompts"), which `build_game.py` copies next to `totk.exe`
|
||||
like `romfs-patches`. `--prompts pc` writes `romfs-patches-pc`, the keyboard and mouse prompts
|
||||
([controls.md](controls.md), "PC button prompts").
|
||||
`--aspect <w>x<h>` writes the UI laid out for a game resolution of another shape; with `--hud 16:9` or `--hud 21:9`
|
||||
(a screen wider than that) the HUD stays within the middle 16:9 or 21:9 instead of the screen's corners. The default
|
||||
`--out` then is `build\<ver>\romfs-patches-<w>x<h>-hud16x9` (`-hud21x9`), which the game loads for `hud_width = 16:9`
|
||||
(`21:9`) in `totk.ini` ([totk.ini.example](../totk.ini.example)).
|
||||
Setup's Shapes step builds only the currently selected cap for the canonical shapes needed by connected displays
|
||||
and `output_res`, together with the selected prompts. `full` generates no capped folders. After changing the HUD
|
||||
width, use the Screen tab's layout preparation action or rerun setup before restarting the game. Lookup prefers
|
||||
the selected cap at the exact or canonical size before falling back to a full-width layout.
|
||||
|
||||
A build from source has no layouts for other shapes than 16:9. At an `output_res` such as 5120x1440 the game then
|
||||
draws the largest 16:9 size inside it (2560x1440) and the present adds bars, instead of a wide camera over a
|
||||
stretched HUD (`runtime/resolution.c`, `shape_fallback`). For the full shape make `romfs-patches-<w>x<h>` once per
|
||||
size: `make_romfs_patches.py --version <ver> --aspect <w>x<h> --out build\<ver>\romfs-patches-<w>x<h>` (the sizes
|
||||
the installer makes are `ASPECT_SIZES` in `installer/steps.py`); `build_game.py` copies every `romfs-patches*`
|
||||
the installer maps to are in `installer/screens.py`); `build_game.py` copies every `romfs-patches*`
|
||||
folder next to `totk.exe`.
|
||||
|
||||
6. Prepare the shaders (once per build folder and translator). It needs `refs\MacNativeGames` (`tools\fetch_refs.sh`)
|
||||
@@ -217,7 +236,15 @@ Before a commit:
|
||||
A change to the button prompts (`tools/make_romfs_patches.py --prompts`, `tools/button_icons.py`) passes
|
||||
`.venv-py314\Scripts\python tests\romfs_prompts_test.py`, which runs the tool on a RomFS it makes itself (no game
|
||||
files); a change to the settings passes `totk.exe --probe-cfg` and `python tests\settings_doc_check.py`, which fails
|
||||
when a setting is described neither in `totk.ini.example` nor in [settings.md](settings.md). A change to the mods' ExeFS patches
|
||||
when a setting is described neither in `totk.ini.example` nor in [settings.md](settings.md).
|
||||
HUD pane/animation and generator naming regressions run with Python 3.14+: `tests/hud_layout_test.py`.
|
||||
Set `HUD_TEST_ROMFS` to a verified extracted RomFS directory to include a real-archive comparison against the
|
||||
pre-port layout generator; all game-derived temporary data stays under `build/`.
|
||||
`python tests/romfs_shapes_check.py --cc <clang>` compiles the production folder-selection and preparation helpers
|
||||
to check canonical aliases, capped/full fallback, prompt arguments, the missing 16:9 prompts and generation
|
||||
deduplication without game files. `tests/romfs_prompts_test.py` checks that two `--background` runs for one folder
|
||||
publish it once and that a folder with a manifest is kept.
|
||||
A change to the mods' ExeFS patches
|
||||
(`tools/exefs_patches.py`, `runtime/mods.c`, the `folded.txt` of `recomp/gen.py`) passes
|
||||
`.venv\Scripts\python tests\exefs_patches_test.py`, which makes its own modules and runs `gen.py` on one with a jump
|
||||
table (no game files), and `totk.exe --probe-mods`. A change to the cheat VM or the cheat opcode tables
|
||||
|
||||
+72
-8
@@ -8,7 +8,7 @@ Input comes from the first SDL3 gamepad, the keyboard and the mouse, merged into
|
||||
- `xbox`: south A, east B, west X, north Y, as an Xbox pad labels them; on a PlayStation pad cross is A, circle B, square X, triangle Y.
|
||||
- `auto` (default): `nintendo` for a pad whose east button SDL reports labelled A (Switch Pro Controller, Nintendo-layout pads), `xbox` for the others.
|
||||
|
||||
The log names the layout in effect (`input: gamepad layout ...`); the menu shows it under *Automatic*. Which controller's buttons the game's prompts show is `TOTK_PROMPTS` (see Xbox button prompts below). 0.1.9's `pad_layout = xbox_prompts` is read as `pad_layout = nintendo` with `prompts = xbox`, and the menu writes it that way.
|
||||
The log names the layout in effect (`input: gamepad layout ...`); the menu shows it under *Automatic*. Which controller's buttons the game's prompts show is `TOTK_PROMPTS` (see Button prompts below). 0.1.9's `pad_layout = xbox_prompts` is read as `pad_layout = nintendo` with `prompts = xbox`, and the menu writes it that way.
|
||||
|
||||
| Switch | Gamepad (by position, Nintendo layout) | Keyboard and mouse | Action in the world |
|
||||
|---|---|---|---|
|
||||
@@ -31,9 +31,9 @@ The log names the layout in effect (`input: gamepad layout ...`); the menu shows
|
||||
|
||||
Esc is unbound in the game; it opens the settings menu and releases the mouse cursor (see Mouse camera). Z and X duplicate ZL and ZR so menu pages turn with two neighbouring keys; the menu tabs (L, R) are Q and R. T duplicates Y for the game's menus, where the left mouse button is A while the pointer is shown (sort the inventory with T). The mouse wheel zooms the Purah Pad's map and its camera, steps the game's menus and the d-pad strips (see Mouse in the game's menus), and is unbound elsewhere. The bindings are the tables of `input_map` in `runtime/input_map.c`: the keys (platform-neutral key ids) and one gamepad table per layout (gamepad inputs by position); `runtime/input_win.c` translates Win32 virtual keys and SDL buttons.
|
||||
|
||||
## Xbox button prompts
|
||||
## Xbox and PlayStation button prompts
|
||||
|
||||
`TOTK_PROMPTS` (`prompts`, the *Button prompts* row on the Controls tab, read at start) picks the controller whose buttons the game's prompts show: `nintendo` (default) keeps the game's own, `xbox` shows an Xbox controller's, `pc` the keyboard and mouse (PC button prompts, below).
|
||||
`TOTK_PROMPTS` (`prompts`, the *Button prompts* row on the Controls tab, read at start) picks the controller whose buttons the game's prompts show: `nintendo` (default) keeps the game's own, `xbox` shows an Xbox controller's, `playstation` a PlayStation controller's, `pc` the keyboard and mouse (PC button prompts, below).
|
||||
|
||||
- L, R, ZL, ZR, Plus and Minus become LB, RB, LT, RT, Menu and View, and the d-pad prompts a cross with an arrow for each direction meant. The letters on the keys are cut out in the game's own text font.
|
||||
- A, B, X and Y name the label of the button the pad layout presses, so each prompt names the button to press. `pad_layout = nintendo` plays an Xbox pad by position: the right button, labelled B, does Switch A (interact, confirm), and the bottom one, labelled A, does Switch B (run, cancel), so the prompts swap A with B and X with Y. `xbox` and `auto` put Switch A on the button labelled A, and the letters stay.
|
||||
@@ -48,16 +48,34 @@ Esc is unbound in the game; it opens the settings menu and releases the mouse cu
|
||||
|
||||
The action prompt (`DoCommand_00`) shows its button in a diamond whose shape gives the face buttons' positions as on a Switch, with the other three letters around it. With `nintendo` its letters are swapped with the rest and every one names the button in that place. With `xbox` and `auto` the letters stay and the diamond is laid out as an Xbox pad: A at the bottom, B on the right, X on the left and Y at the top, the button the prompt names lit in its place, its bar reaching left from X and right from the others (`tools/make_romfs_patches.py`, `bflyt_xbox_diamond`: the panes of `blyt/DoCommand_00.bflyt` take their partner's place, A's of B and X's of Y). The sticks keep the Switch icons, and so do prompts drawn as fixed images (some tutorial animations).
|
||||
|
||||
The prompts are part of the game's fonts, textures and messages, so they follow the layout and not the bindings. A button remapped with a `bind_` line or on the Controls tab keeps the prompt the game draws for it, which then names the wrong button. Use the Xbox prompts with the default bindings.
|
||||
### PlayStation
|
||||
|
||||
`prompts = playstation` shows a PlayStation pad's buttons: the face buttons as ○ (circle), × (cross), △ (triangle) and □ (square), L1, R1, L2 and R2 on the shoulders and triggers, Options and Share on Plus and Minus, and the d-pad as a cross. Each prompt names the button to press, so the shapes follow `pad_layout`:
|
||||
|
||||
| Switch | `nintendo` layout | `xbox` or `auto` layout |
|
||||
|---|---|---|
|
||||
| A, B, X, Y | ○, ×, △, □ | ×, ○, □, △ |
|
||||
| L, R | L1, R1 | L1, R1 |
|
||||
| ZL, ZR | L2, R2 | L2, R2 |
|
||||
| Plus, Minus | Options, Share | Options, Share |
|
||||
| D-pad | cross | cross |
|
||||
|
||||
The game's text fonts already have the four shapes (U+25CB, U+00D7, U+25B3 and U+25A1), so the action prompt's diamond uses them as text; the action prompt's button image and the button guide's images are drawn with the same shapes. The game loads `romfs-patches-playstation` (`pad_layout = nintendo`) or `romfs-patches-playstation-xbox` (`xbox`, `auto`) in place of `romfs-patches`; the setup writes both with `tools/make_romfs_patches.py --prompts playstation` and `--prompts playstation-xbox` (`tools/button_icons.py`, `playstation_icons`). With `xbox` and `auto` the diamond is laid out as for the Xbox prompts: × at the bottom, ○ on the right, □ on the left and △ at the top. At a game resolution of another shape the prompts follow the shape's UI layout as the Xbox ones do (below).
|
||||
|
||||
The prompts are part of the game's fonts, textures and messages, so they follow the layout and not the bindings. A button remapped with a `bind_` line or on the Controls tab keeps the prompt the game draws for it, which then names the wrong button. Use the Xbox or PlayStation prompts with the default bindings.
|
||||
|
||||
The game reads its UI archive and fonts once at boot, so the prompts change at the next start, also after `pad_layout` changes between `nintendo` and the others (the menu says *prompts change after restart*); the buttons change at once. Under that note the menu offers *Restart now*: after a confirmation it writes `totk.ini`, closes the game as *Quit game* does and starts the game again with the same command line, which waits until the old process is gone before it opens the log and the saves (`runtime/gfx_present.c`, `gfx_window_closed`; `plat_restart` and `plat_restart_wait` in `runtime/platform/win32.c` and `linux.c`). Progress since the last save is lost, as with *Quit game*; while the game writes a save, the confirmation waits. With `prompts = xbox` the game loads `romfs-patches-xbox` (`pad_layout = nintendo`) or `romfs-patches-xbox-label` (`xbox`, `auto`) next to `romfs-index.bin` in place of `romfs-patches` (`runtime/romfs.c`, `overlay_init`; `runtime/input_map.c`, `input_prompts_folder`): the same 60 fps patches, with the prompts drawn from the game's own files by `tools/make_romfs_patches.py --prompts xbox` or `--prompts xbox-label` (`tools/button_icons.py`, after MacNativeGames' `make_button_icons.py`), which the setup runs next to the plain one:
|
||||
|
||||
- every prompt but the button guide in play is text in the button font, `scft/External.bfotf` in each `Font/Font*.Nin_NX_NVN.bfarc.zs`: glyphs U+E040 to U+E043 (A B X Y), U+E044 to U+E047 (L R ZL ZR), U+E04B and U+E04C (Plus, Minus), U+E049 and U+E060 to U+E065 (the d-pad). fontTools writes the font again, so the archives grow and the folder also carries the resource size table (`System/Resource/ResourceSizeTable.Product.<n>...rsizetable.zs`) with their entries raised by as much; without that the game stops at start.
|
||||
- the button guide in play draws L and ZL from the images `Nt_KeyTexL_00` and `Nt_KeyTexZL_00` of the Common archive's `timg/__Combined.bntx`, painted with the same icons. The action prompt draws its button from `Nt_KeyTexA/B/X/Y_00`, whose image data is swapped for `nintendo`, and the diamond's letters are text the game takes from `LayoutMsg/DoCommand_00.msbt` of each language's `Mals` archive (and the layout's own text panes behind it), swapped the same way.
|
||||
|
||||
The Switch prompts stay, with a note under *Button prompts* and a `RomFS overlay: ...` line in the log, when the folder is missing (an install made by an older setup, or one where the setup could not prepare it and showed a warning; running the setup again on the install folder writes it), when it fails its check, with a game resolution of another shape than 16:9 that has no folder of its own (below), and when the `romfs_mods` folder replaces one of its files: `romfs-patches` then loads in its place, where two overlays replacing one file would stop the game. In a source build, `.venv-py314\Scripts\python tools\make_romfs_patches.py --version <ver> --prompts xbox` (and `--prompts xbox-label`) writes `build\<ver>\romfs-patches-xbox` (`-label`); it needs fontTools from `tools/requirements-py314.txt`. `--xbox-prompts` is the older name of `--prompts xbox`.
|
||||
With `prompts = playstation` the game loads `romfs-patches-playstation` (`pad_layout = nintendo`) or `romfs-patches-playstation-xbox` (`xbox`, `auto`) the same way, written by `tools/make_romfs_patches.py --prompts playstation` and `--prompts playstation-xbox`: the same 60 fps patches, with the face buttons' images and the diamond's letters drawn as ○ × △ □, the shoulders and triggers as L1 R1 L2 R2, Options and Share, and the button guide's L and ZL images. The game's text fonts already have the four shapes, so the diamond's panes and messages hold those characters instead of the letters.
|
||||
|
||||
At a game resolution of another shape than 16:9 the game loads `romfs-patches-xbox-<w>x<h>` (or `romfs-patches-xbox-label-<w>x<h>`) in place of `romfs-patches-<w>x<h>`: the same prompts with that shape's UI layout, `make_romfs_patches.py --prompts xbox --aspect <w>x<h> --reuse <install>\romfs-patches-xbox --out <install>\romfs-patches-xbox-<w>x<h>`. The setup writes both for each of the fifteen sizes it lays the UI out for, as for the PC prompts below, so on a display of one of those shapes the game resolution follows the display with these prompts too. At another size, without that folder, the Switch prompts stay (*off at this game resolution*).
|
||||
The Switch prompts stay, with a note under *Button prompts* and a `RomFS overlay: ...` line in the log, when the folder is missing (an install made by an older setup, or one where the setup could not prepare it and showed a warning; running the setup again on the install folder writes it; an install whose setup's tools sit next to the game makes it itself, see below), when it fails its check, with a game resolution of another shape than 16:9 that has no folder of its own (below), and when the `romfs_mods` folder replaces one of its files: `romfs-patches` then loads in its place, where two overlays replacing one file would stop the game. In a source build, `.venv-py314\Scripts\python tools\make_romfs_patches.py --version <ver> --prompts xbox` (and `--prompts xbox-label`) writes `build\<ver>\romfs-patches-xbox` (`-label`); `--prompts playstation` and `--prompts playstation-xbox` write `build\<ver>\romfs-patches-playstation` and `-playstation-xbox` the same way. It needs fontTools from `tools/requirements-py314.txt`. `--xbox-prompts` is the older name of `--prompts xbox`.
|
||||
|
||||
A missing prompts folder, at 16:9 or of a game resolution's shape, is made by the game itself on an install whose setup left its tools next to the game (`build-cache/rebuild.txt`): choosing those prompts or a pad layout that needs it, or starting the game with them selected, starts `make_romfs_patches.py --background` for it (`runtime/romfs.c`, `romfs_folders_prepare`; `runtime/ui/menu.cpp`, `folders_tick`, once the choice has stayed for 1.5 seconds). The note says *prompt files being made in the background; used at the next start*; when the tools did not start it says so and *Try again* starts them again. A source build has no `rebuild.txt` and keeps the notes above.
|
||||
|
||||
At a game resolution of another shape than 16:9 the game loads `romfs-patches-<style>-<w>x<h>` (`romfs-patches-xbox-<w>x<h>`, `-xbox-label-`, `-playstation-` or `-playstation-xbox-`) in place of `romfs-patches-<w>x<h>`: the same prompts with that shape's UI layout, `make_romfs_patches.py --prompts <style> --aspect <w>x<h> --reuse <install>\romfs-patches-<style> --out <install>\romfs-patches-<style>-<w>x<h>`. The setup writes it for the shapes of the connected displays and `output_res`, for the selected prompts only (installer Shapes step), as for the PC prompts below. At another size, without that folder, the Switch prompts stay (*off at this game resolution*) until the game has made it in the background (above).
|
||||
|
||||
## PC button prompts
|
||||
|
||||
@@ -85,6 +103,7 @@ At a game resolution of another shape than 16:9 the game loads `romfs-patches-xb
|
||||
| F1 or Esc | Minus and Plus together | open or close the settings menu; the game gets no input while it is open |
|
||||
| F10 | L3 + R3 (both stick clicks) | performance overlay: off, frame rate, full panel |
|
||||
| F11 | | borderless fullscreen on or off, saved to `totk.ini` |
|
||||
| F6, F7 | | with `quicksave = 1`: quick save and quick load, as in Half-Life, with no menu; `quicksave_key` and `quickload_key` choose other keys ([Quick save](#quick-save)) |
|
||||
|
||||
The Minus+Plus combo never reaches the game. In the menu the arrow keys, the D-pad or the left stick move, Enter or A selects, Q and E or L and R switch tabs, Esc or B goes back (Switch button names, as in the table above).
|
||||
|
||||
@@ -135,6 +154,12 @@ degrees a count as the camera does elsewhere. The follow range is read from the
|
||||
once, the mouse is stick input there). The stick loads that only test for input keep the mouse in the stick. A step with mouse motion that no
|
||||
direct hook took is logged (`mouse: step N with mouse motion took the stick path`, the first 30, then one in 600, with
|
||||
the player's state), so the cameras still on stick input show in `logs/totk.log`.
|
||||
Some cameras run none of the direct hooks and read their turn from input the hooks never see: Autobuild's placement
|
||||
camera (games 1.4.3 and 1.2.1) turns by the right stick but, in direct mode, not by the mouse (issue #1300). After two
|
||||
camera steps in a row that ran no direct hook (none of the free orbit, the load sites above or Ultrahand's held-object
|
||||
input), the mouse acts as the right stick there, as with `mouse_mode = stick`, until a step runs a direct hook again
|
||||
(`mouse: the camera runs no direct hook; the mouse acts as the right stick` and `... runs a direct hook again` in the
|
||||
log, the first 6 changes; `camera_unhooked` in `runtime/mouse_direct.c`).
|
||||
Lock-on keeps pointing the camera at the target; the stick, and so the mouse, adds an offset around that direction,
|
||||
which the game limits and lets return: the mouse's degrees are the step's turn the game adds to the offset and judges
|
||||
the return by.
|
||||
@@ -213,6 +238,20 @@ With `map_click = 1` (off by default, so each key presses one controller button
|
||||
|
||||
With `dialogue_click = 1` (off by default, so each key presses one controller button as everywhere else), on game 1.4.3, while a dialogue box is open (the layout `MessageDialog_00`: a character's lines and the game's own messages), the left mouse button presses B and the right one A, instead of the buttons they are bound to. B continues the text as A does and also shows the rest of a line that is still scrolling in; the left button's default, Y, would open the dialogue log there, and the log stays in the way until B closes it. Dialogue choices are a menu with the focus box, so the pointer above takes their clicks and a left click is A on the choice under it: clicking through a conversation fast does not pick the choice the focus starts on. A press is the dialogue's button or the binding from the moment the button goes down until it is released: the click that closes the last box does not become an attack while it is still held, and a button held when the box opens does not skip its first line. Between two lines of a conversation the game closes the box and opens it again, so both buttons stay B and A for 500 ms after the box was last open (`DIALOGUE_GAP_MS`); the first clicks after a conversation fall in that time too, as they do for a player who taps the button through the last line. `TOTK_MENU_CURSOR_LOG=1` logs how long each such gap was. The dialogue window has no focus box of its own: the scan of `eui::ScreenMgr`'s open screens (every 100 ms) finds its screen, and from then on that screen's state is read at every pad read (`dialogue_shown` in `runtime/menu_cursor.c`), so the first click after a box opens is already the dialogue's. `dialogue_click = 1` (`TOTK_DIALOGUE_CLICK=1`, live; the *Clicks in dialogue* row of the Controls tab) turns it on and `0`, the default, leaves both buttons on their bindings; the setting does not depend on `menu_cursor`. The log names the first box it sees (`menu_cursor: a dialogue box is open ...`).
|
||||
|
||||
## Quick save
|
||||
|
||||
With `quicksave = 1` (off by default; the *Quick save and load* row of the Controls tab, live), on game 1.4.3, one key saves the game at once and another loads that save: F6 and F7 by default, the keys Half-Life has for them. No menu shows on the screen (`runtime/quicksave.c`). It is for the keyboard and the mouse only (a gamepad has no quick save button yet) and for game 1.4.3 only (the addresses below are 1.4.3's; on 1.2.1 the setting does nothing).
|
||||
|
||||
Quick save asks the game for one of its own autosaves, the way its event graphs do: it calls the AutoSaveMgr's request with the kind the sequence node `OneShotAutoSaveMgrRequestAutoSave` uses, after the game's own check whether it would autosave now. That check also holds autosaves back for some ten minutes after the game's last one; quick save, being the player's own, skips that wait (it sets the AutoSaveMgr's timer to 0, and puts it back when the game says no for another reason), as Save in the System tab does. The game then saves as it does after a shrine or a story event, its autosave icon included, into one of its autosave slots: the oldest autosave is replaced, as by any autosave of the game. The commit of that save names the slot folder it wrote (`fs_save_commits` in `runtime/fs_host.c`), and quick save keeps a copy of it: `<profile>/quicksave/slot`, with the slot's name in `<profile>/quicksave/slot.txt`. *Game saved* shows at the top of the picture for a few seconds (`menu_toast`, `runtime/ui/menu.cpp`). The game can take the request and still hold the autosave back (seen once in a fight in the Depths); when no save commit comes within 5 s, quick save takes its request back, so the game does not save some time later on its own, and says it is not possible right now. The game's manual save is not touched.
|
||||
|
||||
Quick load has no request in play to start from: the game starts a load only from its own load list (System tab) or its Game Over screen, and loads the slot that screen names. So quick load goes through the load list as a player with a controller would, but out of sight. *Loading the quick save* shows at the top of the picture, and from the next frames on the window keeps that picture (`gfx_present_hold` in `runtime/gfx_present.c`, as while the window is minimized) while quick load presses Plus, R until the System tab shows, Load, A on the list's first save and Load on the confirmation. From that confirmation on, every read the game makes of a file in a slot folder (`save:/slot_NN/<file>`) opens the quick save's file instead (`fs_save_read_from` in `runtime/fs_host.c`; the log names each one, `fs: quick load: ... read from ...`), so the game loads the quick save whichever slot the list offered first, and no slot of the save is written for it. The redirect ends with the load: once the game has read the quick save's files, its loading fade has closed and the HUD has been back for half a second (`quickload: slot reads go to the save again`); at once when a menu with the focus box opens, so a Load right after it lists and loads the slots as they are. The picture comes back with the game's loading fade, about 5 s after the key. When a step finds a screen it does not expect, or none within its time, the log names the step, B is pressed until no menu has the focus box, the picture comes back and the line says *Quick load failed*. The quick save stays in the profile, so F7 loads the same state again until F6 makes a new one.
|
||||
|
||||
Both start only in play: a save loaded, the HUD (`PlayerStatus_00`) open, no menu with the focus box, no dialogue box and no loading fade. Anywhere else, and wherever the game itself would not autosave (a cutscene, an event, a fight), nothing happens but a line at the top of the picture (*Quick save is not possible right now*), and the log says why (`quicksave: not now: ...`). Without a quick save F7 says so. Quick save's calls into the game run on the game thread in its pad read, between two of its own calls; while quick load runs the game gets only its presses, not the player's input. While the setting is on its two keys reach no binding; with it off nothing changes and nothing is logged.
|
||||
|
||||
The keys are `quicksave_key` and `quickload_key` (`TOTK_QUICKSAVE_KEY`, `TOTK_QUICKLOAD_KEY`, live). The *Quick save key* and *Quick load key* rows under the switch take any key or mouse button the way a binding's cell does: select the cell, press the key (Esc cancels); Delete, Backspace or X leaves that one without a key (`none`). In `totk.ini` the value is a key name of the [Remapping](#remapping) list, in any case, or `none`. A name the list does not have is logged (`quicksave: quickload_key: unknown key '...', f7 is used`) and the default is used; the same key for both saves and leaves loading without a key. With the setting on the log names the keys in use (`quicksave: f6 saves, f7 loads`). A key a binding also uses presses only quick save or quick load while the setting is on: the row says which button it took (*also A*).
|
||||
|
||||
`QUICKSAVE` and `QUICKLOAD` lines in an input script ([Scripted input](#scripted-input)) start it as the keys do.
|
||||
|
||||
## Gameplay tweaks
|
||||
|
||||
With `gameplay_tweaks_enabled = 1` (`TOTK_GAMEPLAY_TWEAKS_ENABLED=1`, live; off by default in `totk.ini`), the mouse wheel and keyboard can drive common gameplay interactions directly:
|
||||
@@ -231,6 +270,26 @@ Windows does not present the Switch 2 Pro Controller as a gamepad SDL can open (
|
||||
|
||||
Bridges that output a ViGEm DualShock 4 (ProCon2Windows, connectyourpro as tested) give buttons and rumble but no motion: their virtual DualShock 4 reports a gyro and an accelerometer that never change, so motion aiming and Ultrahand rotation do nothing. Run one bridge at a time; Steam Input can also claim the controller, so close Steam if the bridge does not find it.
|
||||
|
||||
## Steam Input and motion
|
||||
|
||||
A game Steam starts sees Steam's virtual gamepad in place of the controllers Steam Input reads (Steam lists them in
|
||||
`SDL_GAMECONTROLLER_IGNORE_DEVICES`), and that virtual pad has no gyro or accelerometer. With `motion = 1` the game
|
||||
clears that list before SDL starts (`runtime/input.c`, `steam_reveal`): buttons and sticks still come from the virtual
|
||||
pad, so Steam's remapping applies and nothing is read twice, and when the virtual pad has no sensors the motion thread
|
||||
opens the real controller behind it for its gyro and accelerometer only (`motion_source`). The log then shows
|
||||
`input: motion from "<name>" (<vendor>:<product>), the controller behind Steam Input's virtual gamepad`. This covers the
|
||||
Steam Controller and the Steam Deck's built-in controls, which Steam Input cannot be turned off for, and other
|
||||
controllers Steam Input wraps. A controller Steam hid serves for buttons only while no other gamepad is there (Steam's
|
||||
virtual pad can come up after the game starts); once the virtual pad is up the buttons move to it. With `motion = 0`
|
||||
at start Steam's list stays in force.
|
||||
|
||||
Steam switches the controller's gyro off while the game's layout binds nothing to it: the reports keep coming with the
|
||||
gyro at zero, and the game's request for it (SDL renews it every 3 s) does not win. The layout needs a gyro binding,
|
||||
for example Gyro Behavior "As Mouse"; its activation only decides when Steam itself moves the mouse, the game gets the
|
||||
gyro all the time. Pick an activation the game does not need (a back button), or Steam's mouse turns the camera on top
|
||||
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)").
|
||||
|
||||
## 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:
|
||||
@@ -238,12 +297,14 @@ Bridges that output a ViGEm DualShock 4 (ProCon2Windows, connectyourpro as teste
|
||||
```
|
||||
<frame> <button> [hold_frames] # A B X Y L R ZL ZR PLUS MINUS LEFT UP RIGHT DOWN LCLICK RCLICK; hold defaults to 4
|
||||
<frame> LSTICK|RSTICK <x> <y> [hold_frames] # -32767..32767, up is +y
|
||||
<frame> MOUSE <dx> <dy> # direct-mode raw counts, once; down is +dy
|
||||
<frame> MOUSE <dx> <dy> # raw mouse counts, once; down is +dy
|
||||
@<ms> <button> [hold_ms] # timed on the world clock
|
||||
@<ms> LSTICK|RSTICK <x> <y> [hold_ms]
|
||||
@<ms> MOUSE <dx> <dy>
|
||||
<frame> WHEEL <notches> # scroll wheel notches, once; + away from the player
|
||||
@<ms> WHEEL <notches>
|
||||
<frame> QUICKSAVE|QUICKLOAD # quicksave = 1's save or load key, once
|
||||
@<ms> QUICKSAVE|QUICKLOAD
|
||||
```
|
||||
|
||||
`<frame>` counts 60 Hz ticks of game time since the first frame (presented frames at 60 fps), so the title menus get the presses at the same game time at any frame limit. `@<ms>` counts milliseconds of the world clock: game time stepped since the end of the first save load (the player leaves the title screen's origin), so a timed event lands at the same game time at any frame rate and load length. A later load, such as fast travel, still shifts what follows. In a script with timed lines the untimed ones stop when the world clock starts, as the load ends at another tick in each run. Each event logs once (`input: script frame N tick T: A`). `tools/input/load_save.txt` loads the first save from the title screen.
|
||||
@@ -252,7 +313,10 @@ Bridges that output a ViGEm DualShock 4 (ProCon2Windows, connectyourpro as teste
|
||||
|
||||
In direct mouse mode the recording also writes one `MOUSE` event per consumed raw displacement. These are one-shot
|
||||
displacements rather than held stick segments. They replay without cursor capture, including with `input = none`;
|
||||
the game must be accepting camera input when the event reaches its camera update.
|
||||
the game must be accepting camera input when the event reaches its camera update. Where the mouse acts as the right
|
||||
stick (`mouse_mode = stick`, a camera with no direct hook, the game not accepting camera input), a script's `MOUSE`
|
||||
lines move the right stick as the mouse would, also without cursor capture or with `input = none`, for 100 ms after
|
||||
each line (`mouse_camera` in `runtime/input.c`); spread a turn over lines a frame apart, as a real mouse moves.
|
||||
|
||||
`TOTK_TEST_PAD=<lx>,<ly>,<rx>,<ry>` attaches an SDL virtual gamepad at start whose sticks rest at these raw SDL axis values (-32768 to 32767, down is +y), so a drifting or held stick can be tested without a controller: the values go through the gamepad mapping and `TOTK_STICK_DEADZONE` like a real pad's, and `TOTK_INPUT_RECORD` shows what reached the game.
|
||||
|
||||
|
||||
+75
-45
@@ -1,8 +1,9 @@
|
||||
# Installer
|
||||
|
||||
A public release that turns the player's own game files into a playable TotK folder. The release carries no game
|
||||
data and no code derived from the game: the installer builds the game on the player's machine. The installed folder
|
||||
holds only the game; the installer and its tools stay outside it.
|
||||
data and no code derived from the game: the installer builds the game on the player's machine. On Windows the
|
||||
installed folder also holds the build kit, the installer's tools the game rebuilds itself with for code mods, so the
|
||||
setup folder can be deleted after the install and the install folder moved.
|
||||
|
||||
## What the player does
|
||||
|
||||
@@ -16,7 +17,8 @@ holds only the game; the installer and its tools stay outside it.
|
||||
needed for Chinese, Korean and Traditional Chinese text;
|
||||
- the game language and the install folder.
|
||||
3. Waits for the setup, one time. The window shows each step and its progress.
|
||||
4. Plays `totk.exe` from the install folder. The installer and the source NSP or XCI (or NSZ, XCZ) can be deleted.
|
||||
4. Plays `totk.exe` from the install folder. The setup folder and the source NSP or XCI (or NSZ, XCZ) can be deleted,
|
||||
and the install folder can be moved: code mods rebuild the game with the build kit inside it.
|
||||
|
||||
The install folder (`main.c` `portable_paths()` reads this layout; it stays portable):
|
||||
|
||||
@@ -32,16 +34,25 @@ The install folder (`main.c` `portable_paths()` reads this layout; it stays port
|
||||
logs/ totk.log of the last run, totk.1.log to totk.4.log of the runs before it
|
||||
shader and pipeline caches prepared by the setup; shader-cache/shader-cache.pack holds the translations
|
||||
totk-install.json what built this folder: release version, input hashes, finished steps
|
||||
build-kit/ Windows: the release folder without TotK-Setup.exe (about 0.65 GB); the game's rebuild
|
||||
for code mods runs the setup window from it
|
||||
build-cache/ what the rebuild built in (cheats.status, exefs.status, plugins.status), rebuild.txt,
|
||||
and work/: the generated C, the lift cache and the objects (about 1.6 GB, Windows)
|
||||
```
|
||||
|
||||
## Updating the port
|
||||
|
||||
The player runs a newer installer on the same folder. It reads `totk-install.json`, keeps `romfs/`, `exefs/`,
|
||||
`shared-fonts/`, `profile/` and `totk.ini` after checking their hashes, rebuilds `totk.exe` and re-prepares the
|
||||
shaders. A newer release that changes nothing game-derived skips the rebuild. The window starts with the last install folder
|
||||
and the base, update, keys and firmware paths it ran with (paths only, never the keys file's contents), kept in
|
||||
`%LOCALAPPDATA%\TotK Recomp\setup.json` (`$XDG_STATE_HOME/totk-recomp/setup.json` elsewhere). Entries that no longer exist
|
||||
stay empty. A reinstall or a switch to another game version starts filled in.
|
||||
`shared-fonts/`, `profile/` and `totk.ini` after checking their hashes, replaces `build-kit/` with its own files,
|
||||
rebuilds `totk.exe` and re-prepares the shaders. The setup is an installer and updater: nothing after the install needs
|
||||
its folder. An install made by a setup before the build kit kept its temp folder in that setup's folder
|
||||
(`<setup>/temp/<install name>-<hash>`, the setup `build-cache/rebuild.txt` named); the first newer setup moves it into
|
||||
`build-cache/work` when both are on one disk (on another it starts empty) and writes the new `rebuild.txt`. Until then
|
||||
the old `rebuild.txt` keeps using the old setup folder. A newer release that changes nothing game-derived skips the
|
||||
rebuild. The window starts with the last install folder and the base, update, keys and firmware paths it ran with (paths
|
||||
only, never the keys file's contents), kept in `%LOCALAPPDATA%\TotK Recomp\setup.json`
|
||||
(`$XDG_STATE_HOME/totk-recomp/setup.json` elsewhere). Entries that no longer exist stay empty. A reinstall or a switch
|
||||
to another game version starts filled in.
|
||||
|
||||
Given an update file other than the recorded one (1.1.0, then 1.2.1, then 1.4.3), the installer extracts and builds again from it
|
||||
and keeps `profile/`. Saves carry over both ways between 1.2.1 and 1.4.3: 1.4.3 converts a 1.2.1 save on load, and 1.2.1
|
||||
@@ -53,36 +64,45 @@ loads the saves 1.4.3 wrote.
|
||||
`tools/extract.py`), the keys are new enough for the update, enough space is free on the target disk (about 36 GiB at the peak of a
|
||||
first install, 20 GiB after it), the CPU is at least x86-64-v2 (SSE4.2; with AVX2/FMA the faster `v3` build is used,
|
||||
otherwise the `v2` one), a Vulkan 1.3 GPU exists. Each failure is one clear message.
|
||||
2. **Fonts** with Chinese, Korean or Traditional Chinese text and a firmware folder: extract the Switch system fonts
|
||||
2. **Kit** (Windows): copy the release folder without `TotK-Setup.exe` into `build-kit/` in the install folder
|
||||
(`installer/steps.py` `Kit`, `installer/layout.py` `KIT_ITEMS`); every step after it runs its tools from there, so
|
||||
the commands the build records (the compiler's path in the Ninja file) are the ones the game's rebuild runs later.
|
||||
A newer setup replaces the kit; the kit's own rebuild keeps it. The steps' keys fingerprint file contents, not
|
||||
paths (`runtime_key` leaves out the lines of `clang --version` that name its folder), so a rebuild from the kit
|
||||
or from a moved install folder keeps every step the setup recorded.
|
||||
3. **Fonts** with Chinese, Korean or Traditional Chinese text and a firmware folder: extract the Switch system fonts
|
||||
from the firmware into `shared-fonts/` (MacNativeGames' `extract_shared_fonts.py`, which verifies every NCA layer
|
||||
and BFTTF header). Without a firmware folder the setup warns and goes on; the game then lacks those glyphs.
|
||||
3. **Extract** ExeFS and RomFS into the install folder and verify the hashes.
|
||||
4. **Lift** the ExeFS to C (`recomp/gen.py`, `recomp/patches-v121.txt` or `patches-v143.txt`) into a temp folder next
|
||||
to the installer. The code cheats of the mods' cheat files and the mods' ExeFS patch files become patch sets first
|
||||
(`tools/cheats.py`, `tools/exefs_patches.py`, status in `build-cache/cheats.status` and `exefs.status`); a file the
|
||||
tools refuse costs those cheats or patches, not the install. The patch files' writes into main's data go to
|
||||
`build-cache/exefs.data`, which the game stores into main at start; after the lift they are checked against the
|
||||
bytes the lifted code read as constants (`<gen>/main/folded.txt`, its jump tables).
|
||||
5. **Compile** the generated C, `modules.c`, `romfs.c`, `patches.c` and `ov_zstd.c` (they bake the per-install layout, RomFS
|
||||
4. **Extract** ExeFS and RomFS into the install folder and verify the hashes.
|
||||
5. **Lift** the ExeFS to C (`recomp/gen.py`, `recomp/patches-v121.txt` or `patches-v143.txt`) into the temp folder,
|
||||
`build-cache/work` in the install folder (`.setup-temp` on Linux, `--temp DIR` elsewhere). The code cheats of the
|
||||
mods' cheat files and the mods' ExeFS patch files become patch sets first (`tools/cheats.py`,
|
||||
`tools/exefs_patches.py`, status in `build-cache/cheats.status` and `exefs.status`); a file the tools refuse costs
|
||||
those cheats or patches, not the install. The patch files' writes into main's data go to `build-cache/exefs.data`,
|
||||
which the game stores into main at start; after the lift they are checked against the bytes the lifted code read as
|
||||
constants (`<gen>/main/folded.txt`, its jump tables).
|
||||
6. **Compile** the generated C, `modules.c`, `romfs.c`, `patches.c` and `ov_zstd.c` (they bake the per-install layout, RomFS
|
||||
hashes and the game version's patch page) and link
|
||||
them with the prebuilt runtime library for the host's level (`libtotkrt.a` or `libtotkrt-v2.a`) into `totk.exe`
|
||||
(`build_game.py --runtime-lib`; about 3 min on 24 cores).
|
||||
6. **Prepare** (only when the runtime, the translator or the game version changed, not for a new lift) the RomFS
|
||||
7. **Prepare** (only when the runtime, the translator or the game version changed, not for a new lift) the RomFS
|
||||
patches and the shaders (`tools/make_romfs_patches.py`, `tools/prepare_shaders.py`,
|
||||
`totk.exe --prepare-shaders`) in the install folder, then fold the shader cache's loose files (four per shader, about
|
||||
117,000) into `shader-cache/shader-cache.pack` (`tools/pack_shader_cache.py`). totk.exe reads the pack first and
|
||||
writes the translations it makes in play as loose files; running the tool again with the game closed folds those in.
|
||||
The patches are written three times: `romfs-patches`, `romfs-patches-xbox` and `romfs-patches-xbox-label`
|
||||
The patches are written five times: `romfs-patches`, `romfs-patches-xbox` and `romfs-patches-xbox-label`
|
||||
(`--prompts`: Xbox button prompts for `prompts = xbox`, the first for `pad_layout = nintendo`, the second for `xbox`
|
||||
and `auto`). The prompt folders are optional: when one cannot be made, the setup warns and finishes.
|
||||
and `auto`), `romfs-patches-playstation` and `romfs-patches-playstation-xbox` (PlayStation prompts for
|
||||
`prompts = playstation`, the same split). The prompt folders are optional: when one cannot be made, the setup warns
|
||||
and finishes.
|
||||
**PC prompts** (step `pc_prompts`): `romfs-patches-pc`, the keyboard and mouse prompts for `prompts = pc`, drawn
|
||||
from the `bind_` lines of `totk.ini` (`--binds`). Its key holds those lines, so a setup run after a change of the
|
||||
bindings draws only these again. Optional like the Xbox prompts. All four 16:9 folders are always written, so a
|
||||
bindings draws only these again. Optional like the Xbox prompts. All six 16:9 folders are always written, so a
|
||||
switch of the prompts style at 16:9 needs no setup run.
|
||||
When the graphics driver crashes while building the shaders, `prepare_shaders.py` runs that part again without the
|
||||
variants it was building ([building.md](building.md), step 6), and the setup finishes with a warning that names how
|
||||
many were left out.
|
||||
7. **Shapes**: the UI laid out for each screen shape this player needs, `romfs-patches-<w>x<h>`
|
||||
8. **Shapes**: the UI laid out for each screen shape this player needs, `romfs-patches-<w>x<h>`
|
||||
(`--aspect`), and with Xbox or PC prompts in `totk.ini` that layout with those prompts too,
|
||||
`romfs-patches-<style>-<w>x<h>` (`--prompts <style> --aspect --reuse romfs-patches-<style>`, which hard-links every
|
||||
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:
|
||||
@@ -90,42 +110,51 @@ loads the saves 1.4.3 wrote.
|
||||
`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
|
||||
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 the settings menu marks such sizes and can write the shape's folders in the
|
||||
background for the next start.
|
||||
8. **DLSS** (the window's tick box, on by default, or `--dlss`; Windows with an NVIDIA RTX GPU): download
|
||||
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
|
||||
when the settings menu changes the resolution, the HUD width, the prompts or the pad layout
|
||||
(`runtime/romfs.c`, `romfs_folders_prepare`, with the Python and tools that `build-cache/rebuild.txt` names; a
|
||||
missing 16:9 prompts folder too). Those runs use `--background`: below-normal priority, and a folder that has a
|
||||
manifest is never written into. Every `make_romfs_patches.py` run writes `<folder>.part-<pid>` and renames it into
|
||||
place when complete; the clean-up step removes the `.part` folders of stopped runs once they are an hour old.
|
||||
9. **DLSS** (the window's tick box, on by default, or `--dlss`; Windows with an NVIDIA RTX GPU): download
|
||||
`nvngx_dlss.dll` from NVIDIA's own DLSS SDK repository (github.com/NVIDIA/DLSS, a pinned tag, NVIDIA RTX SDK
|
||||
license) into the install folder and check its size and SHA-256 (`steps.py`, `Dlss`). The release does not ship
|
||||
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.
|
||||
9. **Clean up** the temp folder, except the generated C and the objects (about 1.3 GB), and write
|
||||
10. **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`).
|
||||
|
||||
## Rebuilding for the mods
|
||||
|
||||
The generated C and the objects stay in the temp folder. The next lift lifts again only the chunks whose inputs
|
||||
changed (the lift cache of `recomp/gen.py`: the patch sites inside a chunk, with their set indices) and rewrites only
|
||||
those whose C changed, and Ninja recompiles only those. A new or edited code cheat costs a few seconds of lift
|
||||
(discovery and a hash of the kept chunks; 7 s for one changed cheat word on 12 cores, against 102 s for the whole lift)
|
||||
and the compile of the chunks that hold its sites, not a full compile, and the shaders stay prepared. A cheat set added
|
||||
or removed before others in the patch file moves their set indices, so the chunks of their sites are lifted too. A
|
||||
change to `recomp/*.py` lifts everything.
|
||||
The generated C and the objects stay in the temp folder, inside the install folder. The next lift lifts again only the
|
||||
chunks whose inputs changed (the lift cache of `recomp/gen.py`: the patch sites inside a chunk, with their set indices)
|
||||
and rewrites only those whose C changed, and Ninja recompiles only those. A new or edited code cheat costs a few seconds
|
||||
of lift (discovery and a hash of the kept chunks; 7 s for one changed cheat word on 12 cores, against 102 s for the
|
||||
whole lift) and the compile of the chunks that hold its sites, not a full compile, and the shaders stay prepared. A
|
||||
cheat set added or removed before others in the patch file moves their set indices, so the chunks of their sites are
|
||||
lifted too. A change to `recomp/*.py` lifts everything.
|
||||
|
||||
`build-cache/rebuild.txt` holds the command that opens the setup window in its rebuild mode on the install folder
|
||||
(`installer/gui.py --rebuild <install folder>`, started through `python -c` so the release folder is on `sys.path`
|
||||
whatever the working folder), one argument per line. When an enabled mod has code cheats or ExeFS patch files the build
|
||||
lacks, `totk.exe` runs it at start and exits (`runtime/cheats.c` `rebuild_if_needed`); the
|
||||
window runs the setup on the folder at once and starts the game again when it succeeds. A failed or cancelled rebuild
|
||||
offers to start the game with the code it has; `build-cache/rebuild.skip` then keeps the same files from starting it
|
||||
again, until "Rebuild the game now" on the Cheats or Mods tab. A command that does not start at all leaves no
|
||||
`rebuild.skip`, so the next start tries it again. `[mods] mods_rebuild = off` turns it off. The rebuild needs the
|
||||
release folder the setup ran from: a moved or deleted release folder means running a setup again. On Linux the command
|
||||
starts the AppImage file itself (`$APPIMAGE --rebuild <install folder>`), because the AppImage's mounted folder is gone
|
||||
once the setup exits; a moved or deleted AppImage means running a setup again. Installs set up by an AppImage before
|
||||
this change hold a command into that mount: running the new setup once on the install folder writes the new one.
|
||||
whatever the working folder), one argument per line. On Windows it names the build kit relative to the install folder
|
||||
(`build-kit\python\pythonw.exe`, `build-kit`, `--rebuild .`): `totk.exe` takes the program from its own folder and
|
||||
starts the command there, so no path of the setup or of the install folder is stored. When an enabled mod has code
|
||||
cheats or ExeFS patch files the build lacks, `totk.exe` runs it at start and exits (`runtime/cheats.c`
|
||||
`rebuild_if_needed`); the window runs the setup on the folder at once and starts the game again when it succeeds. A
|
||||
failed or cancelled rebuild offers to start the game with the code it has; `build-cache/rebuild.skip` then keeps the
|
||||
same files from starting it again, until "Rebuild the game now" on the Cheats or Mods tab. A command that does not start
|
||||
at all leaves no `rebuild.skip`, so the next start tries it again. `[mods] mods_rebuild = off` turns it off. A moved
|
||||
install folder keeps its incremental rebuild: the kit's builds run `tools/build_game.py --portable`, whose Ninja file
|
||||
and deps log name every path relative to the kit (3.5 s to rebuild after a move instead of a full compile). A build with
|
||||
a mod plugin names the plugin's file by its absolute path (`recomp/layout.py`), so after a move the game finds it gone
|
||||
and runs the rebuild once. On Linux the command starts the AppImage file itself (`$APPIMAGE --rebuild <install
|
||||
folder>`), because the AppImage's mounted folder is gone once the setup exits; a moved or deleted AppImage means running
|
||||
a setup again. Installs set up by an AppImage before this change hold a command into that mount: running the new setup
|
||||
once on the install folder writes the new one.
|
||||
|
||||
## Command line
|
||||
|
||||
@@ -170,7 +199,8 @@ python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR
|
||||
The unpacked release; `tools/make_release.py` assembles it and `--zip` packs it:
|
||||
|
||||
```
|
||||
TotK-Setup.exe starts python/pythonw.exe -m installer.gui (installer/launcher/launcher.c, no console)
|
||||
TotK-Setup.exe starts python/pythonw.exe -m installer.gui (installer/launcher/launcher.c, no console); the
|
||||
rest is what the Kit step copies into the install folder's build-kit/
|
||||
installer/ the installer: steps, CLI, window, en/ru/zh-Hans text catalog
|
||||
python/ Python 3.14.9 embeddable + numpy, lz4, cryptography, cffi, pycparser (+ tkinter for the window)
|
||||
recomp/, tools/ the lifter and the build, extraction and shader scripts the steps run (copied from the repo)
|
||||
|
||||
+69
-9
@@ -34,11 +34,27 @@ packs, gameplay and text changes from GameBanana and similar sites, TKMM's merge
|
||||
## Order and switches
|
||||
|
||||
The Mods tab lists every folder in `mods`. Select a mod and press A or Enter to switch it on or off. The top face button
|
||||
or Ctrl+Up moves it up, the left face button or Ctrl+Down moves it down. When two mods change the same file, the
|
||||
higher one wins; the lower mod's row says how many of its files the higher one covers. Changes apply after a restart.
|
||||
or Ctrl+Up moves it up, the left face button or Ctrl+Down moves it down. Changes apply after a restart.
|
||||
|
||||
The menu saves the order and the switches in `totk.ini`, under `[mods]`, by folder name: `mods_order` and
|
||||
`mods_disabled`. A folder the list does not name yet, such as a new or renamed one, goes below the named ones.
|
||||
The order decides every conflict, as in PC mod managers: when two mods change the same game file, the same bytes of the
|
||||
game's data or the same instruction of the game's code, the higher one wins. Moving a mod and restarting is enough; the
|
||||
game is not rebuilt for it. Each row lists what the mod wins and loses, by mod: "3 of its files come from X, which is
|
||||
higher in the list", "It overrides 2 code patch sites of Y, which is lower in the list", and the same for game data.
|
||||
`logs\totk.log` has the same as `mods: X: overrides Y at 2 code sites` and `mods: Y: 2 code sites overridden by X`, and
|
||||
one line per contested code site.
|
||||
|
||||
The menu saves the order and the switches in `totk.ini`, under `[mods]`, by folder name: `mods_order`,
|
||||
`mods_disabled` and `mods_no_code`. A folder the list does not name yet, such as a new or renamed one, goes below the
|
||||
named ones.
|
||||
|
||||
### Mods with code the port cannot run
|
||||
|
||||
Some mods bring code the port cannot run: their own Switch code (a replaced main, or a subsdk plugin the rebuild
|
||||
refused, as it refuses UltraCam's) or a code patch in a form the port cannot apply. Such a mod stays off as a whole, because its other files may expect
|
||||
that code. Under its row the Mods tab then shows **Use <mod> without its code** (off by default). Switched on, the code
|
||||
the port cannot run is left out and the rest of the mod loads after a restart: its game files, cheats and the code
|
||||
patches that work. The mod's row says which part is left out and why. If the game misbehaves with it, switch it off
|
||||
again. `mods_without_code = 1` under `[mods]` holds the switch on for every mod.
|
||||
|
||||
### Mods that change the same files
|
||||
|
||||
@@ -64,17 +80,59 @@ ahead of time, so these patches are built into `totk.exe`:
|
||||
2. Until the rebuild succeeds, the whole mod stays off, its other files included.
|
||||
3. After the rebuild the mod switches on and off from the Mods tab like any other, without another rebuild.
|
||||
|
||||
The rebuild needs the setup folder the game was installed from. When that folder was moved or deleted, run
|
||||
`TotK-Setup.exe` again on the same install folder: it does the same job. `mods_rebuild = off` under `[mods]` in
|
||||
`totk.ini` turns the automatic rebuild off.
|
||||
The rebuild runs from `build-kit` in the game folder, which the setup put there: the setup folder can be deleted
|
||||
and the game folder moved. After a move, a game with a code plugin mod rebuilds once at its next start. A game
|
||||
installed by an older setup (no `build-kit` in its folder) still rebuilds from that setup folder until a newer
|
||||
setup runs once on it.
|
||||
`mods_rebuild = off` under `[mods]` in `totk.ini` turns the automatic rebuild off.
|
||||
|
||||
A code patch over one of the port's own patches (the 60 FPS patch, the resolution patch and the other entries under
|
||||
**Built into the port**) turns that built-in patch off while the mod is on. The mod's row names it.
|
||||
|
||||
When two mods patch the same instruction, the code of the higher one runs there; the other mod's patches run
|
||||
everywhere else. The rebuild builds every mod's patch in, so a new order needs only a restart. Two patch files of one
|
||||
mod that patch the same instruction: the one later by path inside the mod wins, as emulators apply a mod's files in
|
||||
name order, each over the one before. A cheat that changes the same instruction runs instead of both while it is on.
|
||||
|
||||
A patch file may also change the game's data (constants and tables in its `.rodata` and `.data`). Those bytes are
|
||||
stored into the loaded game at start, before it runs. When two mods write the same bytes, the higher one wins,
|
||||
as with files.
|
||||
|
||||
## Code plugins (exefs subsdk)
|
||||
|
||||
Some mods ship their own Switch code as an exlaunch plugin: a file `exefs\subsdk<N>` (The Second Quest's MSFix, Full
|
||||
Inventory Expansion's sort fixer, Quick Weapon Durability). On the Switch the plugin starts with the game and
|
||||
redirects some of the game's instructions into its own code. The port does the same with the plugin's code compiled
|
||||
ahead of time, after the design in [#845](https://github.com/valentderah/totk-pc-recomp/issues/845) by itaskaev2:
|
||||
|
||||
1. The rebuild (the same one as for code patches above) compiles the plugins with the game, then starts the game's
|
||||
code in a service mode that runs only one plugin's start-up (`totk.exe --plugin-init`), twice per plugin, and
|
||||
records which instructions it redirects. Each redirect becomes a code site of the mod, built into `totk.exe`. Each
|
||||
plugin is judged on its own: one that is refused, or whose start-up crashes or never returns, stays off with its
|
||||
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.
|
||||
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
|
||||
it (half a minute on 12 cores with the lift cache). A plugin mod switched off on the Mods tab only stays off.
|
||||
|
||||
The Mods tab order decides between a plugin and another mod's patch on the same instruction, as for code patches. A
|
||||
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,
|
||||
reads input and opens sockets.
|
||||
|
||||
`plugin_trace = 1` in `totk.ini` logs the first call into each of a plugin's hooks (`plugins: hook entry ... reached`).
|
||||
|
||||
## Cheats
|
||||
|
||||
A cheat file is part of a mod: `mods\<mod>\cheats\<build id>.txt`, switched cheat by cheat on the Cheats tab. Cheats
|
||||
@@ -113,8 +171,10 @@ keeps its textures at a quarter of the size.
|
||||
| This folder has no romfs, exefs or cheats files. | The archive was unpacked one level too deep (`mods\Mod\Mod\romfs`), or it holds no game files. | Move the folders up so `romfs` sits directly in the mod's folder. |
|
||||
| ... files carry another game version in their names. | The files are named for another update (`.Product.<number>.`) and the game's own files have no such name. They are still served under those names, as on a console, because the game sometimes asks for one; another update's resource size table is the exception and only lends its entries. | Nothing if the mod works. If it does nothing, download its release for your game update. |
|
||||
| Its code patches (exefs) are made for another game version. | The patch files name another update's build id. | Same: get the release for your update. |
|
||||
| This mod brings its own game code (a subsdk plugin or a replaced main). | Mods such as UltraCam ship compiled Switch code. The port cannot load it. | No workaround; the whole mod stays off. |
|
||||
| This mod patches the game code (exefs) in a way the port cannot apply. | The patch writes the game's data, not its code, or changes code in a form the port cannot build. | No workaround; the reason follows on the row. |
|
||||
| This mod brings its own game code (a subsdk plugin or a replaced main). | The mod replaces the game's main code, which the port cannot load. | The whole mod stays off. **Use <mod> without its code** under its row uses the rest of it, which may expect the missing code (see Mods with code the port cannot run). |
|
||||
| Its plugin ... cannot run in the port: ... | The rebuild refused the mod's code plugin; the reason follows (see Code plugins). | The whole mod stays off. **Use <mod> without its code** under its row uses the rest of it. |
|
||||
| Its plugin stays off this time: it started differently from the build. | The plugin redirected other instructions at this start than in the rebuild, for example after the mod was updated in place. | Nothing: the next start runs the rebuild. |
|
||||
| This mod patches the game code (exefs) in a way the port cannot apply. | The patch changes code in a form the port cannot build, or bytes the port cannot change at start. The reason follows on the row. | The whole mod stays off. **Use <mod> without its code** under its row leaves that patch file out and uses the rest of the mod. |
|
||||
| The folder name contains \|. | The mod list uses `\|` between names. | Rename the folder. |
|
||||
|
||||
A mod never stops the game from starting. Whatever the port cannot use is left out and shown on the Mods tab.
|
||||
|
||||
+27
-1
@@ -13,8 +13,10 @@ The built-in table is [recomp/patches-v110.txt](../recomp/patches-v110.txt). The
|
||||
| pooloff | 2 | Widen texture-pool offsets unsigned, covering 2..4 GiB without changing offsets below 2 GiB. Enabled by default; `TOTK_POOL_OFFSET_PATCH=0` retains the original path. |
|
||||
| shadow | 1 | The sun shadow map takes its fixed size from page +92 before rounding. The shadow-resolution setting enables it; `shadow_res=game` leaves the game's sizing. |
|
||||
| cascade | 4 | Read the four sun shadow cascade defaults from page +64..76. Shadow range 100 leaves the original constructor. |
|
||||
| climb | 1 | Climbing speed above 60 fps: the 1.2.1 climb factor in the 1.1.0 climb controller. Follows `TOTK_CLIMB_FIX` and needs the real-time step. |
|
||||
| gears | 2 | The gear rotation check scales its one-frame threshold by the update's frame delta, so shrine gears read as turning above 30 fps. Follows `TOTK_HIGHFPS_FIX`. |
|
||||
|
||||
The table has 12 sets and 50 instruction sites in total. Its existing 889 spin back-edges are unchanged. The new sets use the existing runtime page and settings; no new setting, allocator or renderer path is introduced.
|
||||
The table has 16 sets and 54 instruction sites in total. Its 889 spin back-edges are unchanged. The sets use the existing runtime page and settings; no new setting, allocator or renderer path is introduced.
|
||||
|
||||
The camera sites were cross-checked by normalized instruction-window matching from the local 1.0.0 main. The viewport routine has two matching copies: both are patched. Other sites were checked through their data flow: the equipment timer and its gate, the map clock, the ability clock, the NVN texture storage/package calls, the shadow size publication and the cascade parameter constructor. FOV's s8 is overwritten by the next original instruction; x10 is saved. The cursor sites use the same scratch registers as their 1.2.1 counterparts.
|
||||
|
||||
@@ -39,3 +41,27 @@ python tests/patches_v110_check.py --exefs <local ExeFS directory>
|
||||
Without ExeFS, the test uses synthetic memory and the patch table only. It compares the complete integer/SIMD register state, SP and NZCV of the lifted C and Unicorn for all 17 additions, on and off, at 30/60/120 Hz, including pool offsets immediately below and above 2 GiB and at the end of the 32-bit range. Windows test mappings respect its 64 KiB allocation granularity. With ExeFS it additionally validates every original word and spin target. Extracted images and generated C are local build artifacts, never repository content.
|
||||
|
||||
These checks establish instruction and code-generation contracts. World-scene visual acceptance, texture packs allocating a pool above 2 GiB, physical gyro and comparisons of shadow quality still require gameplay checks.
|
||||
|
||||
## Climbing and gears
|
||||
|
||||
Both sets port their 1.2.1 counterparts in [recomp/patches-v121.txt](../recomp/patches-v121.txt); the comments there explain the formulas.
|
||||
|
||||
**climb**, one site at main+0x19279f0 (1.2.1: main+0x19182cc) in the climb controller's velocity step at main+0x1927948. The site replaces `fmov s1, #1.5` after the shipping factor 1.272 - 0.362 (r - 1), r in s9, s8 = 0.5. The body between prologue and epilogue is word for word the 1.2.1 one: it reads u = max(page +0, r) and gives s0 = max(s0, h), s1 = max(1.5, h). At r >= 1 h stays at or below the shipping factor, so 30 fps and slower keep it bit for bit; at 60 fps the factor becomes 1.4.3's, about 1.8665 instead of 1.453; above 60 fps g(u) takes over. Unlike 1.2.1, the site does not rely on dead registers: a 96-byte stack frame saves x8 and full q5, q6, q7, q16 and q17 and restores them before the original code continues, so only s0 and s1 change. `TOTK_CLIMB_FIX=0` runs the original `fmov`; [frame_step_init](../runtime/frame_rate.c) switches the set off without the real-time step, where the page is not written.
|
||||
|
||||
**gears**, two sites in the ActorCheckRotateModule update at main+0x213eec4 (vtable 0x347e8e8 slot +0x110; 1.2.1: main+0x21350c0). The first, main+0x213eee4, loads the update context's frame delta (x1 + 8) into s12 before the function overwrites x1; the prologue saved d12 at main+0x213eec8, nothing writes s12 before the second site, and callees preserve the low 64 bits of v12. The second, main+0x213f0d4, turns `fdiv s12, s0, s4` into s12 = (s0 / s4) * delta, the RotateStartDeg / 30 threshold scaled by the delta, which the three `fcmp s8, s12` at main+0x213f10c, +0x213f174 and +0x213f1b0 read. It saves full q4 in a 16-byte stack slot and restores it and SP. The set does not read the patch page and works with or without the real-time step; `TOTK_HIGHFPS_FIX=0` keeps both original sites.
|
||||
|
||||
Each original window below occurs once in the 1.1.0 main (addresses and hashes, not game bytes):
|
||||
|
||||
| Window | Length | SHA-256 |
|
||||
| --- | ---: | --- |
|
||||
| +0x19279b0 | 108 bytes | 8262a11c180c734f2692a74e9563140f26d743f0f1f95d31732f975b46c27331 |
|
||||
| +0x213eee4 | 32 bytes | 17487c0fe195655e9a1bcaf49835208bd1ebca86eeef9a2ca0059752f503e378 |
|
||||
| +0x213f0d0 | 28 bytes | d07279a2abea53cffbd8861e95034cd1a5c85edf90f6094c5261ba55da203577 |
|
||||
|
||||
```sh
|
||||
python tests/patches_v110_highfps_check.py
|
||||
python tests/patches_v110_highfps_check.py --cflags=-march=x86-64-v2
|
||||
python tests/patches_v110_highfps_check.py --exefs <local ExeFS directory>
|
||||
```
|
||||
|
||||
The test lifts both sets and runs them against Unicorn on and off, at 30, 60, 120 and 240 Hz and slower steps, with zero and tiny deltas, adjacent ULPs around 0.5 and at each compare threshold, and all 16 NZCV values (3240 cases). It compares all general and full 128-bit SIMD registers, SP, NZCV and the whole scratch memory: only s0/s1 (climb), x1/s12 (gears) and the exact save slots may change. It also compiles [patches.c](../runtime/patches.c) with frame_step_init for the nine combinations of the three switches. With `--exefs` it checks every original word, the shipping constants, the d12 save, the vtable entry and the three compares with their branch targets. These are instruction and switch contracts; climbing and the shrine gears still need checks in the game.
|
||||
@@ -30,6 +30,7 @@ If a PR touches this code, confirm the fix still holds.
|
||||
| lime silhouettes in grass; rectangles in the sky | a target outside the output map must keep its texel; zero-filling it wiped the half-res depth | `vk_pipeline.c` `target_wmask` |
|
||||
| stale grass maps in the far terrain for a second after a hit | write-back of a texture the CPU had rewritten | `vk_texture.c` `write_back` |
|
||||
| cut grass stays standing; fire does not spread (#132) | CPU reads of GPU-rendered textures without an invalidate | `vk_texture.c` `vk_texture_write_back_small`, `nvn_ext.c` `nvn_pool_invalidate` |
|
||||
| gloom damage on clean ground in the Depths with `sync_ahead` | the game read a one-request pixel buffer before the GPU of the frame in flight wrote it | `vk_memory.c` `vk_mem_shadow_read`, from `nvn_ext.c` `nvn_pool_invalidate` |
|
||||
| cloud and fog volumes empty for the session | a one-shot draw skipped instead of waiting for its pipeline | `vk_exec_draw.c` `prepare_draw` |
|
||||
| tile rectangles | storage buffers bound by Ryujinx first-use order, not the c0 slot | `vk_exec_draw.c` `ssbo_slot` |
|
||||
| black dialog background and loading map | 3D targets rejected, the grading LUT never written | `vk_exec.c` `resolve_target` |
|
||||
|
||||
+24
-4
@@ -14,15 +14,24 @@ Many rows below are developer tools that only act together with another setting
|
||||
|
||||
`tests/settings_doc_check.py` fails when a name in `known[]` (`runtime/cfg.c`) is described neither here nor in `totk.ini.example`, or when a default here differs from the code.
|
||||
|
||||
## HUD placement
|
||||
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `hud_width` (default `full`) | `full` places the HUD at the screen's edges; `21:9` or `16:9` constrains it to that centered area on a wider game resolution. A cap that is not narrower than the screen, and 16:9 or taller output, keep the full layout. | Read at start. The Shapes installer step builds the selected cap only for needed screen shapes and button prompts. After a change in the Screen tab an install makes a missing layout in the background; it loads at the next start. If a capped folder is missing the full layout loads with a log message. Explicit overlay overrides and player UI mods keep their precedence. | Safe |
|
||||
|
||||
## Diagnostics and logging
|
||||
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `astc_time` | `1` times the GPU dispatches of each ASTC texture decode and logs the time per block footprint and the largest call. | Adds GPU timestamp queries around every decode; if the queue has no timestamps or no `hostQueryReset`, the log says the decodes are not timed and nothing is measured. | Caution |
|
||||
| `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. | The frame shows a grey debug image while it is set; has no effect when contact shadows are off. | 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 |
|
||||
| `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 |
|
||||
| `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 |
|
||||
@@ -79,6 +88,7 @@ Many rows below are developer tools that only act together with another setting
|
||||
| `swkbd_test` | `ok` or `cancel` opens the keyboard window and presses OK or Cancel on the first timer tick. | The keyboard window closes by itself. | Caution |
|
||||
| `test_oom` | `<site>:<n>[,...]` fails the first n allocations at a site: `commit` (guest memory), `staging` (upload buffers), `image` (texture images), `chunk` (draw data buffers). | Each forced failure takes the out-of-memory path: a memory release, a wait of 10 ms per retry and log lines; a large n stalls up to 30 s and then ends the game. | Caution |
|
||||
| `test_pad` | `<lx>,<ly>,<rx>,<ry>` attaches a virtual gamepad whose sticks rest at these raw SDL axis values (-32768 to 32767). | The game sees a controller with that drift or deflection; a malformed value is logged and ignored. | Caution |
|
||||
| `test_pad_rumble_ms` | `<n>` gives the `test_pad` gamepad rumble, and each rumble write to it takes n ms, as a slow Bluetooth write does. | Only with `test_pad`; checks that a slow rumble write does not hold up the game thread. | Caution |
|
||||
| `test_prepare_shaders` | `1` translates every recorded shader on all usable CPUs during start. | Start takes longer and fills the shader cache folder; the CPU is fully used while it runs. | Caution |
|
||||
|
||||
## Input
|
||||
@@ -86,6 +96,9 @@ Many rows below are developer tools that only act together with another setting
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `bind_<button>` | Remaps one Switch button or stick direction to `pad:<name>` or `key:<name>` entries; covers `bind_a`, `bind_b`, `bind_x`, `bind_y`, `bind_l`, `bind_r`, `bind_zl`, `bind_zr`, `bind_plus`, `bind_minus`, `bind_left`, `bind_up`, `bind_right`, `bind_down`, `bind_lclick`, `bind_rclick`, `bind_lstick_left`, `bind_lstick_up`, `bind_lstick_right`, `bind_lstick_down`, `bind_rstick_left`, `bind_rstick_up`, `bind_rstick_right`, `bind_rstick_down` and `bind_shake`. | A line replaces every default of that button; button prompts in the game still show the default layout. The Controls tab of the menu writes these lines; `docs/controls.md` lists the entry names. | Safe |
|
||||
| `quicksave` (default `0`) | `1`: `quicksave_key` makes one of the game's autosaves at once and keeps a copy as the quick save (`<profile>/quicksave`), `quickload_key` loads that copy (`runtime/quicksave.c`, game 1.4.3, keyboard and mouse keys only; `docs/controls.md`, "Quick save"). | No menu shows; a line at the top of the picture says *Game saved* or why nothing was saved. Quick save takes one of the game's autosave slots and so replaces the oldest autosave, as the game's own autosaves do (the manual save stays); quick load (about 5 s, the picture held while it runs the game's load list underneath) reloads the quick save, losing the progress since. | Save risk |
|
||||
| `quicksave_key` (default `f6`) | The key of quick save with `quicksave = 1`: a key name of the remapping list (`docs/controls.md`, "Remapping") or `none`; an unknown name is logged and `f6` is used. | While `quicksave = 1` the key reaches no binding. | Safe |
|
||||
| `quickload_key` (default `f7`) | The key of quick load with `quicksave = 1`, as `quicksave_key`; an unknown name is logged and `f7` is used, the same key as `quicksave_key` leaves loading without a key. | While `quicksave = 1` the key reaches no binding; it reloads the quick save, losing the progress since. | Safe |
|
||||
|
||||
## Paths and files
|
||||
|
||||
@@ -96,7 +109,9 @@ Many rows below are developer tools that only act together with another setting
|
||||
| `menu_font_fontconfig` (default `1`) | On Linux, `1` asks fontconfig which font file draws each menu language's name, and `0` keeps the fixed distribution paths (`/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc` and four more). The menu merges that file into its font atlas. | `0` is for a system whose fontconfig resolves to a font the menu's parser cannot read; the log then says `menu: system font ... left out`. Has no effect on Windows, where the file names are fixed, and none on a language the ASCII font already draws. The atlas is rebuilt when the window size or the menu language changes. `TOTK_MENU_FONT` names a file directly and wins over both. | Safe |
|
||||
| `mods_dir` (default `mods`) | Folder that holds one subfolder per player mod, beside `totk.exe`. | Mods found there replace game files; see `docs/mods.md`. | Caution |
|
||||
| `mods_disabled` | Names of mods that are switched off, separated by `\|`. | Listed mods are not applied; the Mods tab writes this line. | Safe |
|
||||
| `mods_order` | Mod names, top first, separated by `\|`; the top mod wins a file that two mods replace. | Changes which mod's file the game gets; unlisted mods go below the listed ones, by name. | Safe |
|
||||
| `mods_no_code` | Names of mods used without their code part, separated by `\|`; the Mods tab's switch "Use ... without its code" writes it. | A listed mod's code modules and the ExeFS patch files the port cannot apply are left out and the rest of the mod loads, where otherwise the whole mod stays off. Its files may expect the missing code. | Caution |
|
||||
| `mods_order` | Mod names, top first, separated by `\|`; the top mod wins a file, a byte of game data or an instruction of game code that two mods change. | Changes which mod's file, data or code the game gets, at the next start; unlisted mods go below the listed ones, by name. | Safe |
|
||||
| `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 |
|
||||
| `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 |
|
||||
@@ -150,15 +165,18 @@ Many rows below are developer tools that only act together with another setting
|
||||
| `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_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 |
|
||||
| `vram_headroom` (default `1`) | `0` turns off the spare half-block of video memory that a background thread keeps per memory type. | Texture allocations on the render thread can wait for a new block again. | Caution |
|
||||
| `vs_outs` | `all` declares all 32 vertex shader output locations; otherwise only the union of the paired fragment inputs. | Larger vertex shaders and new pipelines; unwritten outputs read the same as before. | Caution |
|
||||
| `wb_eager` (default `1`) | With `sync_ahead` on, `1` copies small GPU-drawn targets that the game reads back to CPU-readable memory at the end of the frame that drew them, so the write-back at a fence wait does not wait for the GPU; `0` waits as before; `check` reads both ways and compares. Without `sync_ahead` it does nothing. | With `0` the game thread stalls about every ninth frame while the copy queues behind the frame on the GPU, which takes back part of the frame-ahead gain. `check` is slow and for testing. | Caution |
|
||||
| `wb_exact` (default `1`) | `0` decides write-back of GPU-written textures by page only. | A target that shares a page with data the CPU writes can go unwritten, so a name label next to the reticle can blink. | Caution |
|
||||
| `wb_merge` (default `1`) | `0` copies GPU-written ranges back as plain copies instead of writing word by word the words that changed. | In mirror memory mode the GPU's copy can overwrite words the CPU wrote, which breaks effects such as falling rain and waterfall splashes. | Caution |
|
||||
| `wb_merge` (default `1`) | `0` copies GPU-written ranges back as plain copies instead of writing word by word the words that changed; with `shadow = 1` it also leaves ranges the GPU has yet to write back out of the copy into the shadow. | In mirror memory mode, and with `shadow = 1`, the GPU's copy can overwrite words the CPU wrote, which breaks effects such as falling rain and waterfall splashes. | Caution |
|
||||
|
||||
## Motion vectors and DLSS
|
||||
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `dlaa_cam_jitter` (default `1`) | Game 1.4.3: `1` puts the jitter fed to DLSS into the game's camera (the projection's centre terms and the view-projection, where the game copies them into its camera blocks); `0` moves the viewport of the scene's draws instead, as on the other game versions. Needs `ubo_snapshot`. | With `0`, water seen at a low angle flickers with DLAA: the game's full-screen passes rebuild positions with a camera the scene was not drawn with; a test setting. | Caution |
|
||||
| `dlaa_jitter` (default `1`) | `0` turns off the camera jitter fed to DLSS. | DLSS gets no jitter between frames; a test setting. | Caution |
|
||||
| `dlaa_maskdebug` (default `0`) | `1` shows the reactive mask in place of the picture. | The frame shows a debug image while it is set. | Caution |
|
||||
| `dlaa_mv` (default `1`) | `0` sends zero motion vectors to DLSS. | DLSS sees no motion, so moving content can smear; a test setting. | Caution |
|
||||
@@ -180,7 +198,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; `boost` keeps GPU clocks high in CPU-bound scenes. Has no effect on non-NVIDIA GPUs. | Safe |
|
||||
| `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 |
|
||||
|
||||
## Scheduling and host
|
||||
|
||||
@@ -212,6 +230,7 @@ These names are code patch sets built into the generated game code (`recomp/patc
|
||||
| --- | --- | --- | --- |
|
||||
| `ability_guard` (default `1`) | Patch set that checks the target a Recall or Ultrahand pick hands to the game (1.4.3 main+0x1bd01c4, 1.2.1 main+0x1622bf0) and drops it for that frame where the game's own code would fault on it: the holder, the actor or its component unreadable, or the word the game's reference writes not writable (`runtime/ov_ability.c`). Every other target goes on unchanged; a target that fails UltraTears' live-actor test is only logged (`ability: target kept although ...`). | `0` runs the game's code as shipped: the random crash reading `0xffffffffffffffff` during an ability pick can return. | Risky |
|
||||
| `aspect_patch` (default `0`) | Patch set that feeds the camera the output's aspect ratio when it is not 16:9. | The resolution code switches this set on or off itself at start, so a value here is replaced; the code does not settle what a manual value does. | Unknown |
|
||||
| `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 |
|
||||
| `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 |
|
||||
| `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 |
|
||||
@@ -219,3 +238,4 @@ These names are code patch sets built into the generated game code (`recomp/patc
|
||||
| `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 |
|
||||
| `patch_scene` (default `0`) | Patch set that makes the game use the configured scene render size. | The resolution code switches this set from the render size setting; a manual value is replaced. | Unknown |
|
||||
| `report_guard` (default `1`) | Patch set on 1.4.3 only: in the model scene's report loop (main+0xa22d8, main+0xa2310) an object whose report handle is negative or whose row index is 0x8000 or more gets coverage 0 for that frame and its handle reset, the path the game takes after every read, instead of reading past the report rows. On valid rows the game's code runs unchanged. | `0` runs the game's code as shipped: a bad row index reads far past the rows and crashes, the class Weeping of the Empire met while using Ultrahand and aiming. | Risky |
|
||||
| `shutter_fix` (default `1`) | Patch set on 1.4.3 only (set `shutter`, main+0x25e55d0): the speed the AI node QueryBlackboardGetF32FromActorForOunce returns is scaled by 1 + 0.065 x (1 - frame ratio)^2 when the actor's shouldUseOunceSpeed flag is set, which only the two launchers of Tenbez Shrine (Dungeon034) set (#1215). Every other actor gets its value unchanged; 1.0 at 30 fps and below. | `0` runs the game's code: above about 45 fps the ball leaves the launcher too slowly and stays on the rim of the other launcher or falls into the pit. Measured: on dev at 60 fps the ball stuck from the first shots; with the set at 60 and 120 fps it went back and forth as at 30. | Safe |
|
||||
@@ -42,6 +42,8 @@ do one run with it and one without (`set TOTK_VK_VALIDATION=`).
|
||||
If the game stops with a lost device (the log says `device lost` or `VK_ERROR_DEVICE_LOST`), the lines starting with
|
||||
`vk: pass marks` name the render pass or dispatch the GPU was running. AMD GPUs write them by default. On an NVIDIA GPU,
|
||||
`set TOTK_PASS_CRUMBS=1` (or GPU pass marks: On in the Advanced tab) before the run that reproduces the crash.
|
||||
`set TOTK_ADDR_REPORT=1` adds `vk: fault address` lines naming the image or buffer at the faulting address; it slows
|
||||
the game down over a session, so use it only for that run.
|
||||
|
||||
The game keeps running behind other windows (`assume_focus = 0` in `totk.ini` pauses it instead). Shaders the preparation did not cover compile on first use, so
|
||||
the first minutes of play can stutter.
|
||||
|
||||
+7
-17
@@ -12,7 +12,6 @@ line, 3 cancelled (Ctrl+C or Ctrl+Break).
|
||||
Windows with an NVIDIA RTX GPU (steps.py, Dlss).
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
@@ -22,7 +21,7 @@ from . import layout as layouts
|
||||
from . import state as statefile
|
||||
from .events import Reporter
|
||||
from .runner import Context, run_steps
|
||||
from .steps import all_steps, migrate_state
|
||||
from .steps import adopt_old_temp, all_steps, migrate_state
|
||||
|
||||
EXIT = {'ok': 0, 'failed': 1, 'cancelled': 3}
|
||||
|
||||
@@ -33,17 +32,6 @@ class Parser(argparse.ArgumentParser):
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
# The temp folder inside the install folder when the layout names none (the Linux release); the check step does not
|
||||
# count it when it requires an empty install folder
|
||||
TEMP_IN_DEST = '.setup-temp'
|
||||
|
||||
|
||||
def temp_folder(base, dest):
|
||||
"""One temp folder per install folder, so two installs never share generated files."""
|
||||
tag = hashlib.sha256(str(dest).lower().encode()).hexdigest()[:8]
|
||||
return base / f'{dest.name or "root"}-{tag}'
|
||||
|
||||
|
||||
def cancel(signum, frame):
|
||||
raise KeyboardInterrupt
|
||||
|
||||
@@ -58,8 +46,8 @@ def main(argv=None):
|
||||
ap.add_argument('--lang', help='game language, a Switch language code (en-US, en-GB, ja, de, ru, ...)')
|
||||
ap.add_argument('--dest', type=Path, required=True, help='install folder')
|
||||
ap.add_argument('--root', type=Path, help='release folder or repository (default: the folder above installer/)')
|
||||
ap.add_argument('--temp', type=Path, help='temp folder (default: temp/ of the release on Windows, .setup-temp in '
|
||||
'the install folder on Linux, build/install-temp in a repository)')
|
||||
ap.add_argument('--temp', type=Path, help='temp folder (default: build-cache/work in the install folder on Windows, '
|
||||
'.setup-temp there on Linux, build/install-temp in a repository)')
|
||||
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')
|
||||
@@ -72,10 +60,12 @@ def main(argv=None):
|
||||
signal.signal(getattr(signal, name), cancel)
|
||||
layout = layouts.find(args.root)
|
||||
dest = args.dest.resolve()
|
||||
base = args.temp or layout.temp
|
||||
temp = temp_folder(base.resolve(), dest) if base else dest / TEMP_IN_DEST
|
||||
temp = layouts.temp_for(layout, dest, args.temp)
|
||||
adopted = adopt_old_temp(layout, dest, temp)
|
||||
log = temp / 'logs' / time.strftime('install-%Y%m%d-%H%M%S.log')
|
||||
rep = Reporter(log_path=log)
|
||||
if adopted:
|
||||
rep.log(adopted)
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
state = statefile.load(dest)
|
||||
|
||||
+3
-1
@@ -746,7 +746,9 @@ def main(argv=None):
|
||||
return selftest(layout, args.shots)
|
||||
fix_tcl_paths()
|
||||
root = tk.Tk()
|
||||
App(root, args.lang or windows_ui_language(), layout, rebuild=args.rebuild)
|
||||
# resolved now: the game starts the build kit's rebuild with the install folder as '.' and the working folder
|
||||
rebuild = args.rebuild.resolve() if args.rebuild else None
|
||||
App(root, args.lang or windows_ui_language(), layout, rebuild=rebuild)
|
||||
root.mainloop()
|
||||
return 0
|
||||
|
||||
|
||||
@@ -27,7 +27,8 @@ TEXT = Path(__file__).resolve().parent / 'text'
|
||||
UI_LANGUAGES = ('en', 'ru', 'pt-BR', 'zh-Hans')
|
||||
# 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': '简体中文'}
|
||||
STEP_ORDER = ('check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss', 'cleanup')
|
||||
STEP_ORDER = ('check', 'kit', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss',
|
||||
'cleanup')
|
||||
# message parameter -> catalog id prefix of the names that replace its raw values
|
||||
PARAM_NAMES = {'lang': 'lang.', 'known': 'lang.', 'step': 'step.', 'input': 'param.input.'}
|
||||
LANG_RU = 0x19 # primary language id of Russian in a Windows LANGID
|
||||
|
||||
+46
-6
@@ -16,7 +16,13 @@ Release (docs/installer.md "Release layout"), root = the unpacked folder:
|
||||
without one the game is built at -O1
|
||||
totk.ini.example
|
||||
VERSION the release version, one line
|
||||
temp/ the default temp folder (created)
|
||||
|
||||
Build kit (Windows release): the setup copies the release folder without TotK-Setup.exe into <install>/build-kit
|
||||
(KIT_ITEMS, steps.py Kit) and runs every later step from it, so the game's rebuild for its mods
|
||||
(build-cache/rebuild.txt, relative to the install folder) needs neither the setup folder nor its path: the setup can be
|
||||
deleted and the install folder moved. The kit is a release folder itself (release_layout). The temp folder with the
|
||||
rebuild's working state (gen/, build/, the lift cache) is <install>/build-cache/work (TEMP_IN_DEST), so it moves
|
||||
with the install and survives a newer setup's kit.
|
||||
|
||||
Linux release (the AppImage's folder, docs/installer.md "Linux release"): python/bin/python3 (python-build-standalone,
|
||||
with tkinter), llvm/ with clang, lld and llvm-ar plus llvm/sysroot (the glibc headers and libraries the game links
|
||||
@@ -26,9 +32,11 @@ Dev mode, root = a repository checkout (no python/python.exe): build/py314-embed
|
||||
Python the release ships, with the same packages), else this Python; toolchain/llvm-mingw-*/ and toolchain/deps-mingw;
|
||||
runtime/ as the sources with build/install-rtlib/libtotkrt.a and libtotkrt-v2.a (tools/build_game.py --make-runtime-lib
|
||||
--out build/install-rtlib, once per --cpu); MSYS2 UCRT64 ninja.exe; toolchain/hactool; build/xlate/totk_xlate.exe; the shader list from
|
||||
refs/MacNativeGames; build/pgo/pgo-<v>.profdata when there is one; build/install-temp. The version is VERSION with -dev and the commit: 0.1.0-dev+973c626. On Linux,
|
||||
dev mode takes clang, lld and ninja from PATH and the system's libraries (no deps folder, no SDL3 copy).
|
||||
refs/MacNativeGames; build/pgo/pgo-<v>.profdata when there is one; build/install-temp/<install name>-<hash>. The
|
||||
version is VERSION with -dev and the commit: 0.1.0-dev+973c626. Dev mode and the Linux release install no build kit:
|
||||
the repository, or the AppImage file, is what the rebuild runs. On Linux, dev mode takes clang, lld and ninja from PATH and the system's libraries (no deps folder, no SDL3 copy).
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
@@ -40,6 +48,14 @@ WIN = os.name == 'nt'
|
||||
EXE = '.exe' if WIN else ''
|
||||
UCRT = Path(r'C:\msys64\ucrt64\bin')
|
||||
SUPPORTED = ('1.2.1', '1.4.3', '1.1.0') # updates the installer builds; the check identifies the player's by hash
|
||||
KIT = 'build-kit' # the build kit's folder in the install folder
|
||||
# What the build kit holds of a release folder (tools/make_release.py writes them): all but TotK-Setup.exe. licenses/
|
||||
# and THIRD_PARTY_NOTICES.md go along with the binaries they cover.
|
||||
KIT_ITEMS = ('python', 'llvm', 'runtime', 'bin', 'recomp', 'tools', 'data', 'installer', 'licenses',
|
||||
'THIRD_PARTY_NOTICES.md', 'totk.ini.example', 'VERSION')
|
||||
# The temp folder inside the install folder, for a layout that names none (every release); the check step does not
|
||||
# count it when it requires an empty install folder. Linux keeps the name its installs already use.
|
||||
TEMP_IN_DEST = Path('build-cache', 'work') if WIN else Path('.setup-temp')
|
||||
|
||||
|
||||
def version_tag(version):
|
||||
@@ -139,9 +155,10 @@ def release_layout(root):
|
||||
dlls=(root / 'bin' / 'SDL3.dll', root / 'bin' / 'libopus-0.dll') if WIN else (root / 'bin' / 'libSDL3.so.0',),
|
||||
shader_list=root / 'data' / 'shader_list.tsv', ini_example=root / 'totk.ini.example',
|
||||
pgo_dir=root / 'data' if WIN else None,
|
||||
# Linux: None, the install folder's .setup-temp (installer/cli.py): the AppImage is mounted read-only, and on
|
||||
# a Steam Deck /home is often too full for the generated C while the install folder is on the SD card
|
||||
temp=root / 'temp' if WIN else None,
|
||||
# None: the install folder's TEMP_IN_DEST (temp_for). Windows: the rebuild's working state stays with the install
|
||||
# and its build kit. Linux: the AppImage is mounted read-only, and on a Steam Deck /home is often too full for
|
||||
# the generated C while the install folder is on the SD card
|
||||
temp=None,
|
||||
sysroot=None if WIN else root / 'llvm' / 'sysroot')
|
||||
|
||||
|
||||
@@ -191,3 +208,26 @@ def find(root=None):
|
||||
"""The layout of root (default: the folder above this package)."""
|
||||
root = Path(root or Path(__file__).resolve().parent.parent).resolve()
|
||||
return release_layout(root) if is_release(root) else dev_layout(root)
|
||||
|
||||
|
||||
def uses_kit(layout):
|
||||
"""True when the setup installs a build kit (Windows release); dev mode and the Linux AppImage run from where they
|
||||
are."""
|
||||
return WIN and not layout.dev
|
||||
|
||||
|
||||
def kit_folder(dest):
|
||||
return Path(dest) / KIT
|
||||
|
||||
|
||||
def temp_folder(base, dest):
|
||||
"""One temp folder per install folder below a shared base (dev mode, --temp), so two installs never share
|
||||
generated files."""
|
||||
tag = hashlib.sha256(str(dest).lower().encode()).hexdigest()[:8]
|
||||
return base / f'{dest.name or "root"}-{tag}'
|
||||
|
||||
|
||||
def temp_for(layout, dest, override=None):
|
||||
"""The temp folder of a run on dest: below --temp or the layout's, else TEMP_IN_DEST in the install folder."""
|
||||
base = override or layout.temp
|
||||
return temp_folder(Path(base).resolve(), dest) if base else dest / TEMP_IN_DEST
|
||||
@@ -49,6 +49,10 @@ class Step:
|
||||
"""Do the work. Returns fields to record with the step."""
|
||||
return {}
|
||||
|
||||
def settle(self, ctx):
|
||||
"""After the step ran or was skipped: a step whose output the later steps run from (the build kit) points the
|
||||
context at it."""
|
||||
|
||||
|
||||
class Context:
|
||||
def __init__(self, layout, dest, temp, reporter, options, state=None, verify=False):
|
||||
@@ -121,6 +125,7 @@ def run_steps(steps, ctx):
|
||||
for s in steps:
|
||||
if not ctx.runs[s.id]:
|
||||
rep.step(s.id, 'skipped', reason=ctx.reasons[s.id])
|
||||
s.settle(ctx)
|
||||
continue
|
||||
current = s.id
|
||||
rep.step(s.id, 'started')
|
||||
@@ -133,6 +138,7 @@ def run_steps(steps, ctx):
|
||||
ctx.save() # the first save, after the check, creates the install folder
|
||||
rep.step(s.id, 'done', seconds=seconds)
|
||||
current = None
|
||||
s.settle(ctx)
|
||||
ctx.state['release'] = ctx.layout.release
|
||||
ctx.save()
|
||||
return 'ok'
|
||||
|
||||
+16
-6
@@ -140,16 +140,26 @@ def ini_value(text, name):
|
||||
return value
|
||||
|
||||
|
||||
# The pad prompts' folder suffixes (make_romfs_patches.py --prompts), each written at 16:9 on every install
|
||||
# (steps.Prepare): the Xbox and PlayStation ones, for the Nintendo pad layout and for xbox and auto
|
||||
PAD_PROMPTS = ('xbox', 'xbox-label', 'playstation', 'playstation-xbox')
|
||||
# Every prompts folder suffix: the pad ones and the keyboard and mouse one (steps.PcPrompts)
|
||||
PROMPTS_STYLES = PAD_PROMPTS + ('pc',)
|
||||
|
||||
|
||||
def prompts_style(text):
|
||||
"""The prompts' folder suffix the settings select, as runtime/input_map.c input_prompts_pick and
|
||||
input_prompts_folder pick it at start: 'pc', 'xbox' (Nintendo pad layout), 'xbox-label' (any other) or None for the
|
||||
game's own prompts, the default without a totk.ini."""
|
||||
p, layout = ini_value(text, 'prompts'), (ini_value(text, 'pad_layout') or '').lower()
|
||||
if p and p.lower() == 'pc':
|
||||
input_prompts_folder pick it at start: 'pc', 'xbox' or 'playstation' (Nintendo pad layout), 'xbox-label' or
|
||||
'playstation-xbox' (any other), or None for the game's own prompts, the default without a totk.ini."""
|
||||
p, layout = (ini_value(text, 'prompts') or '').lower(), (ini_value(text, 'pad_layout') or '').lower()
|
||||
if p == 'pc':
|
||||
return 'pc'
|
||||
if not (p.lower() == 'xbox' if p else layout == 'xbox_prompts'):
|
||||
nintendo = layout in ('nintendo', 'xbox_prompts')
|
||||
if p in ('playstation', 'ps'):
|
||||
return 'playstation' if nintendo else 'playstation-xbox'
|
||||
if not (p == 'xbox' if p else layout == 'xbox_prompts'):
|
||||
return None
|
||||
return 'xbox' if layout in ('nintendo', 'xbox_prompts') else 'xbox-label'
|
||||
return 'xbox' if nintendo else 'xbox-label'
|
||||
|
||||
|
||||
def wanted(dest, screens=None):
|
||||
|
||||
+330
-59
@@ -1,5 +1,5 @@
|
||||
"""The ten setup steps of docs/installer.md: check, fonts, extract, lift, compile, prepare, pc_prompts, shapes, dlss,
|
||||
cleanup.
|
||||
"""The eleven setup steps of docs/installer.md: check, kit, fonts, extract, lift, compile, prepare, pc_prompts, shapes,
|
||||
dlss, 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
|
||||
@@ -11,18 +11,21 @@ Install folder: exefs/, romfs/ (romfs.bin, index.json), profile/, shared-fonts/
|
||||
and its DLLs, nvngx_dlss.dll (with --dlss), 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.
|
||||
Temp folder (<temp>/<dest name>-<hash>): check/ (ExeFS of both inputs, the host check), unpacked/ (the NSP of an NSZ
|
||||
or XCZ input until the extraction is done), gen/ (C), build/ (objects), logs/. The cleanup keeps gen/, build/ and
|
||||
shader state of totk.exe --prepare-shaders, totk.ini, totk-install.json, and on Windows build-kit/ (Kit): the release
|
||||
folder the steps after the kit step run from, and the game's rebuild with them.
|
||||
Temp folder (build-cache/work in the install folder on Windows, .setup-temp there on Linux, <temp>/<dest name>-<hash>
|
||||
with --temp or in a repository; installer/layout.py temp_for): check/ (ExeFS of both inputs, the host check),
|
||||
unpacked/ (the NSP of an NSZ or XCZ input until the extraction is done), gen/ (C), build/ (objects), logs/. The cleanup keeps gen/, build/ and
|
||||
logs/: the next run lifts into the same gen/, where recomp/gen.py lifts again only the chunks whose inputs changed (its
|
||||
lift cache, gen/<mod>/lift_cache.json) and rewrites only those whose C changed, and Ninja in build/ recompiles only
|
||||
those. A change of the mods' code cheats then costs a few seconds of lift and the chunks holding its sites, not a full
|
||||
lift or compile.
|
||||
|
||||
Install folder build-cache/: cheats.status (tools/cheats.py), exefs.status and exefs.data (tools/exefs_patches.py) and
|
||||
Install folder build-cache/: cheats.status (tools/cheats.py), exefs.status and exefs.data (tools/exefs_patches.py),
|
||||
plugins.status (tools/exefs_plugins.py; plugins.stale is the game's list of plugins whose start differed) and
|
||||
rebuild.txt, the command that starts this setup in its rebuild mode on the install folder (installer/gui.py --rebuild),
|
||||
one argument per line; totk.exe runs it at start when an enabled mod has code cheats the build lacks
|
||||
(runtime/cheats.c).
|
||||
one argument per line, relative to the install folder for the build kit; totk.exe runs it at start when an enabled mod
|
||||
has code cheats the build lacks (runtime/cheats.c).
|
||||
"""
|
||||
import hashlib
|
||||
import http.client
|
||||
@@ -39,6 +42,7 @@ import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from . import ini, screens
|
||||
from . import layout as layouts
|
||||
from .layout import EXE, SUPPORTED, version_tag
|
||||
from .runner import InstallError, Step
|
||||
|
||||
@@ -52,6 +56,7 @@ from extract_exefs import (common_tickets, container_entries, load_keys, nca_ctr
|
||||
GiB = 1 << 30
|
||||
DEST_EXTRA = 4 * GiB # beside the RomFS: shader and pipeline caches (about 2 GB), exefs, totk.exe, seed files
|
||||
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'
|
||||
|
||||
@@ -597,6 +602,8 @@ class Check(Step):
|
||||
dest_need -= romfs.stat().st_size
|
||||
if ctx.will_run('fonts'):
|
||||
dest_need += FONTS_NEED
|
||||
if ctx.will_run('kit') and layouts.uses_kit(ctx.layout):
|
||||
dest_need += KIT_NEED
|
||||
if ctx.will_run('prepare') or ctx.will_run('extract'):
|
||||
dest_need += DEST_EXTRA
|
||||
if ctx.will_run('lift') or ctx.will_run('compile'):
|
||||
@@ -649,6 +656,114 @@ class Check(Step):
|
||||
ctx.state['version'] = found
|
||||
|
||||
|
||||
# ---- 1b. build kit
|
||||
|
||||
class Kit(Step):
|
||||
"""The build kit (installer/layout.py, Windows release): the release folder without TotK-Setup.exe, copied into
|
||||
<install>/build-kit. Every step after this one runs its tools from there (settle), and the game's rebuild for its
|
||||
mods starts the setup window from there, so the setup folder can go once the install is done and the install
|
||||
folder can move. A newer setup replaces the kit; the kit's own rebuild keeps it. The steps' keys fingerprint file
|
||||
contents, not paths, so the kit, a copy of the setup's files, keeps every step the setup recorded."""
|
||||
|
||||
id = 'kit'
|
||||
|
||||
def key(self, ctx):
|
||||
return fingerprint('kit-1', ctx.layout.release if layouts.uses_kit(ctx.layout) else 'none')
|
||||
|
||||
def current(self, ctx, record):
|
||||
if not layouts.uses_kit(ctx.layout):
|
||||
return True
|
||||
kit = layouts.kit_folder(ctx.dest)
|
||||
if not layouts.is_release(kit):
|
||||
return False
|
||||
found = layouts.release_layout(kit)
|
||||
return found.release == ctx.layout.release and not found.missing(getattr(ctx, 'cpu', 'v3'))
|
||||
|
||||
def run(self, ctx):
|
||||
layout, rep = ctx.layout, ctx.reporter
|
||||
if not layouts.uses_kit(layout):
|
||||
return {}
|
||||
kit = layouts.kit_folder(ctx.dest)
|
||||
if layout.root.resolve() == kit.resolve(): # the kit's own rebuild: it is in place
|
||||
return {}
|
||||
new, old = kit.with_name(layouts.KIT + '.new'), kit.with_name(layouts.KIT + '.old')
|
||||
try:
|
||||
remove(new) # what a cancelled or failed run left
|
||||
remove(old)
|
||||
except OSError as e:
|
||||
raise InstallError('kit.in_use', path=str(e.filename or old)) from None
|
||||
files = []
|
||||
for name in layouts.KIT_ITEMS:
|
||||
src = layout.root / name
|
||||
if src.is_dir():
|
||||
files += [f for f in sorted(src.rglob('*')) if f.is_file() and '__pycache__' not in f.parts]
|
||||
elif src.is_file():
|
||||
files.append(src)
|
||||
total, done = size_of(files), 0
|
||||
rep.progress('kit', 'copy', 0, total, 'bytes', force=True)
|
||||
try:
|
||||
for f in files:
|
||||
dst = new / f.relative_to(layout.root)
|
||||
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(f, dst)
|
||||
done += f.stat().st_size
|
||||
rep.progress('kit', 'copy', done, total, 'bytes')
|
||||
except OSError as e:
|
||||
raise InstallError('kit.copy_failed', path=str(e.filename or new), detail=str(e)) from None
|
||||
# An open rebuild window, or a layout generator the game's settings menu started, holds files of the old kit:
|
||||
# then nothing is replaced, and the message asks to close the game and run the setup again
|
||||
moved = False
|
||||
try:
|
||||
if kit.exists():
|
||||
os.replace(kit, old)
|
||||
moved = True
|
||||
os.replace(new, kit)
|
||||
except OSError:
|
||||
if moved and not kit.exists():
|
||||
os.replace(old, kit) # the game keeps the kit it had
|
||||
raise InstallError('kit.in_use', path=str(kit)) from None
|
||||
try:
|
||||
remove(old)
|
||||
except OSError as e:
|
||||
rep.log(f'kit: the old kit stays until the next run: {e}')
|
||||
rep.log(f'kit: {len(files)} files, {total / GiB:.2f} GiB in {kit}')
|
||||
return {'bytes': total}
|
||||
|
||||
def settle(self, ctx):
|
||||
if not layouts.uses_kit(ctx.layout):
|
||||
return
|
||||
kit = layouts.kit_folder(ctx.dest).resolve()
|
||||
if ctx.layout.root.resolve() != kit:
|
||||
ctx.layout = layouts.release_layout(kit)
|
||||
ctx.reporter.log(f'kit: the next steps run from {kit}')
|
||||
|
||||
|
||||
def adopt_old_temp(layout, dest, temp):
|
||||
"""An install by a setup before the build kit has its temp folder (generated C, lift cache, objects) in that
|
||||
setup's folder: <setup>/temp/<install name>-<hash>, the setup build-cache/rebuild.txt names. The first run of a
|
||||
setup with the build kit moves it into the install folder when both are on one disk, and the steps' keys decide
|
||||
what of it still holds. On another disk the new temp folder starts empty: an update recompiles everything anyway
|
||||
(the compiler's path is in every compile command), so a copy would save only part of the lift.
|
||||
Runs before the run's log opens in temp; returns the line for the log, None when there was nothing to move."""
|
||||
if not layouts.uses_kit(layout) or temp != dest / layouts.TEMP_IN_DEST or temp.exists():
|
||||
return None
|
||||
try:
|
||||
lines = (dest / 'build-cache' / 'rebuild.txt').read_text(encoding='utf-8').splitlines()
|
||||
except OSError:
|
||||
return None
|
||||
if len(lines) < 4 or lines[1] != '-c' or not os.path.isabs(lines[3]):
|
||||
return None
|
||||
old = layouts.temp_folder(Path(lines[3]) / 'temp', dest)
|
||||
if not (old / 'gen').is_dir():
|
||||
return None
|
||||
try:
|
||||
temp.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(old, temp)
|
||||
return f'temp: moved the temp folder of the setup in {lines[3]} to {temp}'
|
||||
except OSError as e:
|
||||
return f'temp: the temp folder {old} stays where it is ({e}); {temp} starts empty'
|
||||
|
||||
|
||||
# ---- 2. fonts
|
||||
|
||||
class Fonts(Step):
|
||||
@@ -866,6 +981,43 @@ def exefs_files(ctx):
|
||||
return sorted(out)
|
||||
|
||||
|
||||
def plugin_files(ctx):
|
||||
"""The exlaunch plugins of the mods folder (each mod's exefs/subsdk*, in the first ExeFS place, as
|
||||
tools/exefs_plugins.py finds them), by mod name, for the lift key and the plugin stage."""
|
||||
mods = ctx.dest / 'mods'
|
||||
if not mods.is_dir():
|
||||
return []
|
||||
out = []
|
||||
for mod in sorted((m for m in mods.iterdir() if m.is_dir()), key=lambda m: m.name):
|
||||
exefs = next((mod / w for w in EXEFS_PLACES if (mod / w).is_dir()), None)
|
||||
if exefs:
|
||||
out += sorted((f for f in exefs.iterdir() if f.is_file() and f.name.lower().startswith('subsdk')),
|
||||
key=lambda f: f.name.lower())
|
||||
return out
|
||||
|
||||
|
||||
def plugins_status(ctx):
|
||||
"""The build's plugin status file (tools/exefs_plugins.py --status), which runtime/mods.c reads."""
|
||||
return ctx.dest / 'build-cache' / 'plugins.status'
|
||||
|
||||
|
||||
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."""
|
||||
if not status.is_file():
|
||||
return []
|
||||
built = {line.split('\t')[0] for line in status.read_text(encoding='utf-8').splitlines()
|
||||
if len(line.split('\t')) >= 3 and line.split('\t')[2] == 'plugin'}
|
||||
|
||||
def key(f):
|
||||
rel = f.relative_to(mods).as_posix()
|
||||
h = 0x811C9DC5
|
||||
for b in rel.encode():
|
||||
h = ((h ^ b) * 0x01000193) & 0xFFFFFFFF
|
||||
return f'{h:08X}'
|
||||
return [f for f in files if key(f) in built]
|
||||
|
||||
|
||||
def exefs_status(ctx):
|
||||
"""The build's ExeFS patch status file (tools/exefs_patches.py --status), which runtime/mods.c reads."""
|
||||
return ctx.dest / 'build-cache' / 'exefs.status'
|
||||
@@ -890,9 +1042,13 @@ class Lift(Step):
|
||||
def key(self, ctx):
|
||||
# fingerprint takes a file's name and content only; the paths under mods/ go in too, because tools/cheats.py
|
||||
# and tools/exefs_patches.py name each patch set after its mod folder, so a renamed folder needs a lift
|
||||
files = cheat_files(ctx) + exefs_files(ctx)
|
||||
# A mod plugin is built by running its init on a totk.exe of this build (tools/exefs_plugins.py), so the
|
||||
# runtime is in the key too when there is one, and this file, which runs that stage: a plugin stage that failed
|
||||
# (warn.plugins_skipped, the game built without the plugins) runs again once a release changes it.
|
||||
files = cheat_files(ctx) + exefs_files(ctx) + plugin_files(ctx)
|
||||
extra = [ctx.layout.tools / 'exefs_plugins.py', Path(__file__), runtime_key(ctx)] if plugin_files(ctx) else []
|
||||
return fingerprint('lift-5', ctx.keys['extract'], ctx.layout.recomp, ctx.layout.patches(game_version(ctx)),
|
||||
ctx.layout.tools / 'cheats.py', ctx.layout.tools / 'exefs_patches.py', *files,
|
||||
ctx.layout.tools / 'cheats.py', ctx.layout.tools / 'exefs_patches.py', *extra, *files,
|
||||
*(f.relative_to(ctx.dest / 'mods').as_posix() for f in files))
|
||||
|
||||
def current(self, ctx, record):
|
||||
@@ -943,12 +1099,50 @@ class Lift(Step):
|
||||
else:
|
||||
patches = ctx.temp / out
|
||||
args = ['--exefs', ctx.dest / 'exefs', '--out', gen]
|
||||
# The mods' exlaunch plugins (tools/exefs_plugins.py, after the design in #845 by itaskaev2): a lift with the
|
||||
# plugins in the layout, a totk.exe of it in build/ (the compile step's folder, so it recompiles only what
|
||||
# the hook sites change after), the plugin service run, and the plugins' patch sets for the lift below. A
|
||||
# refused plugin gets its reason in plugins.status; a failed stage costs the plugins, not the install.
|
||||
plugins = plugin_files(ctx)
|
||||
drop([plugins_status(ctx), ctx.dest / 'build-cache' / 'plugins.stale'])
|
||||
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
|
||||
if code:
|
||||
drop([plugins_status(ctx)])
|
||||
skipped['warn.plugins_skipped'] = log
|
||||
else:
|
||||
patches = ctx.temp / 'patches-plugins.txt'
|
||||
# With one plugin built, the layout keeps every plugin of the service runs: the records hold addresses
|
||||
# of that layout. A refused plugin stays loaded at play, its init never runs (no patch set).
|
||||
if built_plugins(plugins_status(ctx), plugins, ctx.dest / 'mods'):
|
||||
lift_plugins = plugins
|
||||
if lift_plugins:
|
||||
args += ['--plugins', ','.join(str(f) for f in lift_plugins)]
|
||||
code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', args + ['--patches', patches], parse)
|
||||
if code and patches != plain:
|
||||
for tool, out, outputs, inputs, warn in stages:
|
||||
if inputs and warn not in skipped:
|
||||
drop(outputs)
|
||||
skipped[warn] = log
|
||||
if lift_plugins:
|
||||
drop([plugins_status(ctx)])
|
||||
skipped.setdefault('warn.plugins_skipped', log)
|
||||
args = ['--exefs', ctx.dest / 'exefs', '--out', gen]
|
||||
code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', args + ['--patches', plain], parse)
|
||||
if code:
|
||||
raise InstallError('lift.failed', code=code, log=str(log))
|
||||
@@ -976,17 +1170,40 @@ def runtime_key(ctx):
|
||||
"""Fingerprint of what totk.exe is built from besides the lifted code: the runtime, the toolchain and the build
|
||||
tools. Shader preparation depends on these, not on the code cheats a lift adds."""
|
||||
layout, cpu = ctx.layout, getattr(ctx, 'cpu', 'v3')
|
||||
clang = subprocess.run([str(layout.clang), '--version'], capture_output=True, text=True).stdout
|
||||
# without the lines that name clang's folder: the build kit of a moved install folder is the same toolchain
|
||||
clang = '\n'.join(line for line in subprocess.run([str(layout.clang), '--version'], capture_output=True,
|
||||
text=True).stdout.splitlines()
|
||||
if not line.startswith(('InstalledDir:', 'Configuration file:')))
|
||||
tools = [layout.tools / n for n in ('build_game.py', 'romfs_index.py', 'check_content.py', 'check_isa.py')]
|
||||
return fingerprint('runtime-1', cpu, layout.runtime_lib_for(cpu), layout.runtime, layout.deps or 'system',
|
||||
layout.sysroot or 'host', *tools, clang, *[d.name for d in layout.dlls])
|
||||
|
||||
|
||||
def build_args(ctx, gen):
|
||||
"""tools/build_game.py's arguments for a totk.exe of the lifted C in gen, built in <temp>/build."""
|
||||
layout, dest = ctx.layout, ctx.dest
|
||||
cpu = getattr(ctx, 'cpu', 'v3')
|
||||
lib = layout.runtime_lib_for(cpu)
|
||||
pgo = layout.pgo(game_version(ctx))
|
||||
return ['--gen', gen, '--out', ctx.temp / 'build', '--toolchain', layout.llvm, '--cpu', cpu,
|
||||
*(['--deps', layout.deps] if layout.deps else []), *(['--sysroot', layout.sysroot] if layout.sysroot else []),
|
||||
'--runtime', layout.runtime, *(['--runtime-lib', lib] if lib else ()), *(['--pgo', pgo] if pgo else ()),
|
||||
'--ninja', layout.ninja,
|
||||
'--version', version_tag(game_version(ctx)), '--expected', layout.expected(game_version(ctx)),
|
||||
'--exefs', dest / 'exefs', '--romfs', dest / 'romfs',
|
||||
'--profile', dest / 'profile',
|
||||
# the build kit and the temp folder move with the install folder: Ninja's paths relative to the kit
|
||||
*(['--portable'] if layouts.uses_kit(layout) else [])]
|
||||
|
||||
|
||||
class Compile(Step):
|
||||
id = 'compile'
|
||||
|
||||
def key(self, ctx):
|
||||
return fingerprint('compile-3', ctx.keys['lift'], runtime_key(ctx),
|
||||
# The release string too: build_game.py bakes the VERSION of the tools' folder into totk.exe (the menu's title
|
||||
# line), and a release that leaves the lift and the runtime alone would otherwise keep the old exe and its
|
||||
# old version.
|
||||
return fingerprint('compile-4', ctx.keys['lift'], runtime_key(ctx), ctx.layout.release,
|
||||
ctx.layout.pgo(game_version(ctx)) or 'no profile')
|
||||
|
||||
def current(self, ctx, record):
|
||||
@@ -1012,16 +1229,7 @@ class Compile(Step):
|
||||
|
||||
rep.progress('compile', 'compile', force=True)
|
||||
cpu = getattr(ctx, 'cpu', 'v3')
|
||||
lib = layout.runtime_lib_for(cpu)
|
||||
pgo = layout.pgo(game_version(ctx))
|
||||
code, log = run_tool(ctx, 'compile', layout.tools / 'build_game.py', [
|
||||
'--gen', ctx.temp / 'gen', '--out', build, '--toolchain', layout.llvm, '--cpu', cpu,
|
||||
*(['--deps', layout.deps] if layout.deps else []), *(['--sysroot', layout.sysroot] if layout.sysroot else []),
|
||||
'--runtime', layout.runtime, *(['--runtime-lib', lib] if lib else ()), *(['--pgo', pgo] if pgo else ()),
|
||||
'--ninja', layout.ninja,
|
||||
'--version', version_tag(game_version(ctx)), '--expected', layout.expected(game_version(ctx)),
|
||||
'--exefs', dest / 'exefs', '--romfs', dest / 'romfs',
|
||||
'--profile', dest / 'profile'], parse)
|
||||
code, log = run_tool(ctx, 'compile', layout.tools / 'build_game.py', build_args(ctx, ctx.temp / 'gen'), parse)
|
||||
exe = build / ('totk' + EXE)
|
||||
if code and link_output_locked(log):
|
||||
raise InstallError('compile.exe_locked', path=str(exe), log=str(log))
|
||||
@@ -1095,14 +1303,15 @@ class Prepare(Step):
|
||||
dest / 'romfs-patches'])
|
||||
if code:
|
||||
raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log))
|
||||
# The same with Xbox button icons in the prompts, for prompts = xbox (make_romfs_patches.py --prompts):
|
||||
# romfs-patches-xbox for the Nintendo pad layout, romfs-patches-xbox-label for xbox and auto (runtime/input_map.c
|
||||
# input_prompts_folder). Both are written on every install, so the menu choices work without another run of
|
||||
# The same with Xbox and PlayStation button icons in the prompts, for prompts = xbox and playstation
|
||||
# (make_romfs_patches.py --prompts): romfs-patches-xbox for the Nintendo pad layout, romfs-patches-xbox-label
|
||||
# for xbox and auto, and romfs-patches-playstation / -playstation-xbox likewise (runtime/input_map.c
|
||||
# input_prompts_folder). All are written on every install, so the menu choices work without another run of
|
||||
# the setup. Optional: when one fails, the game keeps the Switch prompts with that layout and the menu says the
|
||||
# files are missing, so the setup warns once and goes on. The keyboard and mouse prompts are the PcPrompts
|
||||
# step's: they follow totk.ini's bindings.
|
||||
failed = None
|
||||
for style in ('xbox', 'xbox-label'):
|
||||
for style in screens.PAD_PROMPTS:
|
||||
out = dest / f'romfs-patches-{style}'
|
||||
remove(out)
|
||||
code, log = run_tool(ctx, f'prepare-{style}', layout.tools / 'make_romfs_patches.py',
|
||||
@@ -1199,17 +1408,59 @@ class PcPrompts(Step):
|
||||
|
||||
# ---- 6b. screen shapes
|
||||
|
||||
SHAPED_FOLDER = re.compile(r'^romfs-patches(?:-xbox|-xbox-label|-pc)?-\d+x\d+$')
|
||||
SHAPED_FOLDER = re.compile(r'^romfs-patches(?:-(?:%s))?-\d+x\d+(?:-hud(?:16|21)x9)?$'
|
||||
% '|'.join(map(re.escape, screens.PROMPTS_STYLES)))
|
||||
# make_romfs_patches.py writes <folder>.part-<pid> and renames it to <folder> when it is complete. A run that was
|
||||
# stopped (the PC turned off under a generator the game started, runtime/romfs.c romfs_folders_prepare) leaves its
|
||||
# folder behind: one whose files did not change for PART_STALE_S is such a leftover, a younger one may belong to a
|
||||
# generator running now. SHAPED_FOLDER matches neither.
|
||||
PART_FOLDER = re.compile(r'^romfs-patches[\w.-]*\.part-[\w-]+$')
|
||||
PART_STALE_S = 3600
|
||||
|
||||
|
||||
def stale_parts(dest, now=None):
|
||||
"""The leftover .part folders of make_romfs_patches.py runs in dest."""
|
||||
now = time.time() if now is None else now
|
||||
found = []
|
||||
for folder in dest.iterdir() if dest.is_dir() else ():
|
||||
if not (folder.is_dir() and not folder.is_symlink() and PART_FOLDER.match(folder.name)):
|
||||
continue
|
||||
try:
|
||||
newest = max([folder.stat().st_mtime] + [f.stat().st_mtime for f in folder.rglob('*')])
|
||||
except OSError:
|
||||
continue
|
||||
if now - newest > PART_STALE_S:
|
||||
found.append(folder)
|
||||
return found
|
||||
|
||||
|
||||
def hud_width(dest):
|
||||
"""The selected HUD cap, with the same default as runtime/cfg.c."""
|
||||
try:
|
||||
text = (dest / 'totk.ini').read_text(encoding='utf-8-sig', errors='replace')
|
||||
except OSError:
|
||||
text = ''
|
||||
value = (screens.ini_value(text, 'hud_width') or 'full').lower()
|
||||
return value if value in ('16:9', '21:9') else 'full'
|
||||
|
||||
|
||||
def shape_hud(size, hud):
|
||||
"""The selected cap when at least 1% narrower than the shape, as make_romfs_patches.py requires."""
|
||||
w, h = (int(v) for v in size.split('x'))
|
||||
cap = {'16:9': 16 / 9, '21:9': 21 / 9}.get(hud)
|
||||
return hud if cap and cap < w / h * 0.99 else None
|
||||
|
||||
|
||||
class Shapes(Step):
|
||||
"""romfs-patches-<w>x<h> (the UI laid out for a shape, make_romfs_patches.py --aspect) and, with Xbox or PC prompts
|
||||
"""romfs-patches-<w>x<h> (the UI laid out for a shape, make_romfs_patches.py --aspect) and, with Xbox, PlayStation or
|
||||
PC prompts
|
||||
in totk.ini, romfs-patches-<style>-<w>x<h> (that layout with those prompts), for the shapes this player needs:
|
||||
those of the connected displays and of the totk.ini output_res, one folder per shape (installer/screens.py; the
|
||||
game maps its resolution to the folder in runtime/romfs.c overlay_init). A setup before this step wrote all 15
|
||||
sizes for every prompts style, 64 folders. The key holds the shapes and the style, so a run of the setup after a
|
||||
monitor or settings change (or its rebuild mode) writes only these again; the game's settings menu can also start
|
||||
the generator for the shape in use (runtime/ui/menu.cpp row_output_res)."""
|
||||
sizes for every prompts style, 64 folders. The key holds the shapes, prompts style and selected HUD width, so a run after a
|
||||
monitor or settings change (or its rebuild mode) writes only these again; the game also starts the generator for a
|
||||
folder its settings need and the install lacks, at start and from its menu (runtime/romfs.c romfs_folders_prepare,
|
||||
make_romfs_patches.py --background), whose unfinished .part folders the clean-up below leaves alone."""
|
||||
|
||||
id = 'shapes'
|
||||
|
||||
@@ -1222,10 +1473,16 @@ class Shapes(Step):
|
||||
sizes, style = self.wanted(ctx)
|
||||
# The pc prompts' shaped folders are drawn from the same bindings as romfs-patches-pc, so they follow its key
|
||||
prompts = ctx.keys.get('pc_prompts', '') if style == 'pc' else ''
|
||||
return fingerprint('shapes-2', ctx.keys.get('prepare', ''), prompts, style or 'nintendo', *sizes)
|
||||
# Without a capped folder to write (hud_width full, or no shape wider than the cap) the key stays the one a
|
||||
# setup before hud_width wrote, so an existing install does not prepare its shaped folders again
|
||||
hud = hud_width(ctx.dest)
|
||||
if not any(shape_hud(size, hud) for size in sizes):
|
||||
return fingerprint('shapes-2', ctx.keys.get('prepare', ''), prompts, style or 'nintendo', *sizes)
|
||||
return fingerprint('shapes-3', ctx.keys.get('prepare', ''), prompts, style or 'nintendo', hud, *sizes)
|
||||
|
||||
def current(self, ctx, record):
|
||||
return all((ctx.dest / name / 'manifest.tsv').is_file() for name in record.get('folders', []))
|
||||
return not record.get('failed') and all((ctx.dest / name / 'manifest.tsv').is_file()
|
||||
for name in record.get('folders', []))
|
||||
|
||||
def run(self, ctx):
|
||||
layout, rep, dest = ctx.layout, ctx.reporter, ctx.dest
|
||||
@@ -1237,31 +1494,38 @@ class Shapes(Step):
|
||||
version = version_tag(game_version(ctx))
|
||||
plain = dest / f'romfs-patches-{style}' if style else None
|
||||
folders, failed = [], None
|
||||
hud = hud_width(dest)
|
||||
for i, size in enumerate(sizes):
|
||||
rep.progress('shapes', 'layouts', i, len(sizes), 'shapes', force=True)
|
||||
out = dest / f'romfs-patches-{size}'
|
||||
code, log = run_tool(ctx, 'shapes', layout.tools / 'make_romfs_patches.py',
|
||||
['--version', version, '--romfs', dest / 'romfs', '--out', out, '--aspect', size])
|
||||
if code:
|
||||
raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log))
|
||||
folders.append(out.name)
|
||||
# Only the Common archive differs from romfs-patches-<style>: --reuse links the fonts, messages and size
|
||||
# table from there. Optional like that folder: the game keeps the Switch prompts with this layout.
|
||||
if not plain or not (plain / 'manifest.tsv').is_file():
|
||||
continue
|
||||
out = dest / f'romfs-patches-{style}-{size}'
|
||||
code, log = run_tool(ctx, f'shapes-{style}', layout.tools / 'make_romfs_patches.py',
|
||||
['--version', version, '--romfs', dest / 'romfs', '--out', out, '--prompts', style,
|
||||
'--aspect', size, '--reuse', plain, *(pc_binds(dest) if style == 'pc' else ())])
|
||||
if code:
|
||||
remove(out)
|
||||
failed = failed or (code, log)
|
||||
else:
|
||||
cap = shape_hud(size, hud)
|
||||
# Keep the full layout as a fallback, plus only the cap this player selected for this shape.
|
||||
for variant in (None, cap) if cap else (None,):
|
||||
suffix = '-hud' + variant.replace(':', 'x') if variant else ''
|
||||
hud_args = ['--hud', variant] if variant else []
|
||||
out = dest / f'romfs-patches-{size}{suffix}'
|
||||
code, log = run_tool(ctx, 'shapes', layout.tools / 'make_romfs_patches.py',
|
||||
['--version', version, '--romfs', dest / 'romfs', '--out', out, '--aspect', size,
|
||||
*hud_args])
|
||||
if code:
|
||||
raise InstallError('prepare.romfs_patches_failed', code=code, log=str(log))
|
||||
folders.append(out.name)
|
||||
# Reuse the selected prompts' fonts/messages/table; PC layouts retain the player's bindings.
|
||||
if not plain or not (plain / 'manifest.tsv').is_file():
|
||||
continue
|
||||
out = dest / f'romfs-patches-{style}-{size}{suffix}'
|
||||
code, log = run_tool(ctx, f'shapes-{style}', layout.tools / 'make_romfs_patches.py',
|
||||
['--version', version, '--romfs', dest / 'romfs', '--out', out, '--prompts', style,
|
||||
'--aspect', size, *hud_args, '--reuse', plain,
|
||||
*(pc_binds(dest) if style == 'pc' else ())])
|
||||
if code:
|
||||
remove(out)
|
||||
failed = failed or (code, log)
|
||||
else:
|
||||
folders.append(out.name)
|
||||
rep.progress('shapes', 'layouts', len(sizes), len(sizes), 'shapes', force=True)
|
||||
if failed:
|
||||
rep.warning('warn.xbox_prompts_failed', code=failed[0], log=str(failed[1]))
|
||||
return {'folders': folders, 'sizes': sizes, 'style': style}
|
||||
return {'folders': folders, 'sizes': sizes, 'style': style, 'hud': hud, 'failed': bool(failed)}
|
||||
|
||||
|
||||
# ---- 7. NVIDIA DLSS
|
||||
@@ -1355,7 +1619,7 @@ class Cleanup(Step):
|
||||
ctx.state['lang'] = ctx.lang
|
||||
(dest / 'profile').mkdir(exist_ok=True)
|
||||
rep.progress('cleanup', 'temp', force=True)
|
||||
for stale in dest.glob('update-merge-*'):
|
||||
for stale in [*dest.glob('update-merge-*'), *stale_parts(dest)]:
|
||||
remove(stale)
|
||||
for name in ('check', 'unpacked', 'shader_list.tsv', 'shared-fonts'): # gen/ and build/ stay for the next rebuild
|
||||
remove(ctx.temp / name)
|
||||
@@ -1364,10 +1628,11 @@ class Cleanup(Step):
|
||||
return {}
|
||||
|
||||
|
||||
# Puts the release folder (the argument after -c) on sys.path and runs installer.gui with the rest. `-m installer.gui`
|
||||
# finds the package only through the release Python's ._pth: the Linux release's Python and the dev-mode embeddable one
|
||||
# lack that entry, and totk.exe starts the command in the install folder.
|
||||
REBUILD_BOOT = ('import runpy, sys; sys.path.insert(0, sys.argv.pop(1)); '
|
||||
# Puts the release folder or the build kit (the argument after -c, made absolute: the kit's is relative to the install
|
||||
# folder) on sys.path and runs installer.gui with the rest. `-m installer.gui` finds the package only through the
|
||||
# release Python's ._pth: the Linux release's Python and the dev-mode embeddable one lack that entry, and totk.exe
|
||||
# starts the command in the install folder.
|
||||
REBUILD_BOOT = ('import os, runpy, sys; sys.path.insert(0, os.path.abspath(sys.argv.pop(1))); '
|
||||
"runpy.run_module('installer.gui', run_name='__main__', alter_sys=True)")
|
||||
|
||||
|
||||
@@ -1386,7 +1651,13 @@ def rebuild_command(ctx):
|
||||
python = Path(sys.executable) if layout.dev else layout.python
|
||||
if os.name == 'nt' and python.with_name('pythonw.exe').is_file():
|
||||
python = python.with_name('pythonw.exe')
|
||||
return [str(python), '-c', REBUILD_BOOT, str(layout.root), '--root', str(layout.root), '--rebuild', str(ctx.dest)]
|
||||
root, dest = str(layout.root), str(ctx.dest)
|
||||
if layouts.uses_kit(layout) and layout.root.resolve() == layouts.kit_folder(ctx.dest).resolve():
|
||||
# the build kit: paths relative to the install folder, which totk.exe resolves against its own folder and
|
||||
# starts the command in, so a moved install folder keeps its rebuild
|
||||
python = Path(layouts.KIT) / python.relative_to(layout.root)
|
||||
root, dest = layouts.KIT, '.'
|
||||
return [str(python), '-c', REBUILD_BOOT, root, '--root', root, '--rebuild', dest]
|
||||
|
||||
|
||||
def write_rebuild_command(ctx):
|
||||
@@ -1414,4 +1685,4 @@ def romfs_problem(romfs, expected):
|
||||
|
||||
|
||||
def all_steps():
|
||||
return [Check(), Fonts(), Extract(), Lift(), Compile(), Prepare(), PcPrompts(), Shapes(), Dlss(), Cleanup()]
|
||||
return [Check(), Kit(), Fonts(), Extract(), Lift(), Compile(), Prepare(), PcPrompts(), Shapes(), Dlss(), Cleanup()]
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"step.check": "Checking the computer and the game files",
|
||||
"step.kit": "Copying the build kit into the game folder",
|
||||
"step.fonts": "Extracting the system fonts",
|
||||
"step.extract": "Extracting the game",
|
||||
"step.lift": "Translating the game code to C",
|
||||
@@ -17,6 +18,7 @@
|
||||
"phase.check.unpack_base": "Unpacking the compressed base game",
|
||||
"phase.check.unpack_update": "Unpacking the compressed update",
|
||||
"phase.check.versions": "Checking the game versions",
|
||||
"phase.kit.copy": "Copying the tools the game rebuilds itself with for code mods",
|
||||
"phase.fonts.extract": "Extracting the shared fonts from the firmware",
|
||||
"phase.fonts.copy": "Copying the shared fonts into the install folder",
|
||||
"phase.extract.hash_base": "Computing the checksum of the base game",
|
||||
@@ -95,6 +97,8 @@
|
||||
"lift.failed": "Translating the game code failed (exit code {code}). Details: {log}",
|
||||
"compile.failed": "Compiling {game_exe} failed (exit code {code}). Details: {log}",
|
||||
"compile.exe_in_use": "{path} is in use. Close the game and run the installer again.",
|
||||
"kit.in_use": "{path} is in use. Close the game and any open setup or rebuild window, then run the installer again.",
|
||||
"kit.copy_failed": "The build kit cannot be copied to {path}: {detail}",
|
||||
"compile.exe_locked": "{path} cannot be written: another program holds it, a game started from that folder or an antivirus that flagged the file. Close the game, add the setup's folder and the install folder to the antivirus exclusions, restart Windows, then run the installer again. Details: {log}",
|
||||
"prepare.xlate_in_use": "{path} is in use. Close the game, end any totk_xlate process left from an earlier run, then run the installer again.",
|
||||
"prepare.shader_list_missing": "The shader list is missing.",
|
||||
@@ -108,7 +112,8 @@
|
||||
"warn.npdm_differs": "main.npdm differs from the reference {version} dump; only the code modules are used.",
|
||||
"warn.cheats_skipped": "The cheats of the mods folder that change the game's code could not be built; the game installs without them. Details: {log}",
|
||||
"warn.exefs_skipped": "The mods' ExeFS patches (.ips, .pchtxt) could not be built; the game installs without them. Details: {log}",
|
||||
"warn.xbox_prompts_failed": "The Xbox or PC button prompts could not be prepared (exit code {code}); the game keeps the Switch prompts. Details: {log}",
|
||||
"warn.plugins_skipped": "The mods' code plugins (exefs subsdk) could not be built; the game installs without them. Details: {log}",
|
||||
"warn.xbox_prompts_failed": "The Xbox, PlayStation or PC button prompts could not be prepared (exit code {code}); the game keeps the Switch prompts. Details: {log}",
|
||||
"warn.shaders_skipped": "The graphics driver crashed while building some shaders, so {count} were left out of the preparation. The game builds them when it first needs them, and the driver may crash there too; a driver update may fix it. Details: {log}",
|
||||
"warn.kernel_old": "Linux {version} lacks the write tracking the game relies on (6.7 or later); the game may run very slowly. Updating the system fixes this.",
|
||||
"warn.dlss_kept": "A DLSS library is already in the install folder ({path}); the setup keeps it.",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"step.check": "Verificando o computador e os arquivos do jogo",
|
||||
"step.kit": "Copiando o kit de compilação para a pasta do jogo",
|
||||
"step.fonts": "Extraindo as fontes do sistema",
|
||||
"step.extract": "Extraindo o jogo",
|
||||
"step.lift": "Traduzindo o código do jogo para C",
|
||||
@@ -17,6 +18,7 @@
|
||||
"phase.check.unpack_base": "Descompactando o jogo base compactado",
|
||||
"phase.check.unpack_update": "Descompactando a atualização compactada",
|
||||
"phase.check.versions": "Verificando as versões do jogo",
|
||||
"phase.kit.copy": "Copiando as ferramentas com que o jogo se recompila para mods de código",
|
||||
"phase.fonts.extract": "Extraindo as fontes compartilhadas do firmware",
|
||||
"phase.fonts.copy": "Copiando as fontes compartilhadas para a pasta de instalação",
|
||||
"phase.extract.hash_base": "Calculando o checksum do jogo base",
|
||||
@@ -95,6 +97,8 @@
|
||||
"lift.failed": "Falha ao traduzir o código do jogo (código de saída {code}). Detalhes: {log}",
|
||||
"compile.failed": "Falha ao compilar o {game_exe} (código de saída {code}). Detalhes: {log}",
|
||||
"compile.exe_in_use": "{path} está em uso. Feche o jogo e execute o instalador de novo.",
|
||||
"kit.in_use": "{path} está em uso. Feche o jogo e qualquer janela de instalação ou recompilação aberta, depois execute o instalador de novo.",
|
||||
"kit.copy_failed": "Não foi possível copiar o kit de compilação para {path}: {detail}",
|
||||
"compile.exe_locked": "Não é possível gravar {path}: outro programa o está usando, um jogo aberto dessa pasta ou um antivírus que marcou o arquivo. Feche o jogo, adicione a pasta do instalador e a pasta de instalação às exceções do antivírus, reinicie o Windows e execute o instalador de novo. Detalhes: {log}",
|
||||
"prepare.xlate_in_use": "{path} está em uso. Feche o jogo, encerre qualquer processo totk_xlate que tenha sobrado de uma execução anterior e execute o instalador de novo.",
|
||||
"prepare.shader_list_missing": "A lista de shaders está faltando.",
|
||||
@@ -107,8 +111,9 @@
|
||||
"warn.lang_needs_fonts": "Textos em {lang} precisam das fontes de sistema do Switch, e nenhuma foi informada. O jogo não inicia neste idioma até que sejam adicionadas. Escolha a pasta do firmware (Contents/registered) ou veja \"Switch system fonts\" em docs/installer.md.",
|
||||
"warn.cheats_skipped": "Não foi possível compilar os cheats da pasta de mods que alteram o código do jogo; o jogo é instalado sem eles. Detalhes: {log}",
|
||||
"warn.exefs_skipped": "Não foi possível compilar os patches ExeFS dos mods (.ips, .pchtxt); o jogo é instalado sem eles. Detalhes: {log}",
|
||||
"warn.plugins_skipped": "Não foi possível compilar os plugins de código dos mods (exefs subsdk); o jogo é instalado sem eles. Detalhes: {log}",
|
||||
"warn.npdm_differs": "O main.npdm difere do dump de referência da versão {version}; só os módulos de código são usados.",
|
||||
"warn.xbox_prompts_failed": "Não foi possível preparar os ícones de botão do Xbox ou do PC (código de saída {code}); o jogo mantém os ícones do Switch. Detalhes: {log}",
|
||||
"warn.xbox_prompts_failed": "Não foi possível preparar os ícones de botão do Xbox, do PlayStation ou do PC (código de saída {code}); o jogo mantém os ícones do Switch. Detalhes: {log}",
|
||||
"warn.shaders_skipped": "O driver gráfico travou ao compilar alguns shaders, então {count} ficaram fora da preparação. O jogo os compila quando precisar deles pela primeira vez, e o driver pode travar ali também; uma atualização do driver pode resolver. Detalhes: {log}",
|
||||
"warn.kernel_old": "O Linux {version} não tem o rastreamento de escrita de que o jogo depende (6.7 ou mais novo); o jogo pode rodar muito devagar. Atualizar o sistema resolve.",
|
||||
"warn.dlss_kept": "Já existe uma biblioteca DLSS na pasta de instalação ({path}); a instalação a mantém.",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"step.check": "Проверка компьютера и игровых файлов",
|
||||
"step.kit": "Копирование набора сборки в папку игры",
|
||||
"step.fonts": "Извлечение системных шрифтов",
|
||||
"step.extract": "Распаковка игры",
|
||||
"step.lift": "Перевод кода игры в C",
|
||||
@@ -17,6 +18,7 @@
|
||||
"phase.check.unpack_base": "Распаковка сжатой базовой игры",
|
||||
"phase.check.unpack_update": "Распаковка сжатого обновления",
|
||||
"phase.check.versions": "Проверка версий игры",
|
||||
"phase.kit.copy": "Копирование инструментов, которыми игра пересобирает себя для модов с кодом",
|
||||
"phase.fonts.extract": "Извлечение общих шрифтов из прошивки",
|
||||
"phase.fonts.copy": "Копирование общих шрифтов в папку установки",
|
||||
"phase.extract.hash_base": "Подсчёт контрольной суммы базовой игры",
|
||||
@@ -95,6 +97,8 @@
|
||||
"lift.failed": "Не удалось перевести код игры (код выхода {code}). Подробности: {log}",
|
||||
"compile.failed": "Не удалось собрать {game_exe} (код выхода {code}). Подробности: {log}",
|
||||
"compile.exe_in_use": "Файл {path} занят. Закройте игру и запустите установку снова.",
|
||||
"kit.in_use": "{path} занят другой программой. Закройте игру и все окна установки или пересборки, затем запустите установку снова.",
|
||||
"kit.copy_failed": "Не удалось скопировать набор сборки в {path}: {detail}",
|
||||
"compile.exe_locked": "Файл {path} не удаётся записать: его держит другая программа — игра, запущенная из этой папки, или антивирус, который пометил файл. Закройте игру, добавьте папку установщика и папку установки в исключения антивируса, перезагрузите Windows и запустите установку снова. Подробности: {log}",
|
||||
"prepare.xlate_in_use": "Файл {path} занят. Закройте игру, завершите процесс totk_xlate, оставшийся от прошлого запуска, и запустите установку снова.",
|
||||
"prepare.shader_list_missing": "Нет списка шейдеров.",
|
||||
@@ -108,7 +112,8 @@
|
||||
"warn.npdm_differs": "main.npdm отличается от эталонного дампа {version}; используются только модули с кодом.",
|
||||
"warn.cheats_skipped": "Не удалось собрать читы из папки модов, меняющие код игры; игра установится без них. Подробности: {log}",
|
||||
"warn.exefs_skipped": "Не удалось собрать ExeFS-патчи модов (.ips, .pchtxt); игра установится без них. Подробности: {log}",
|
||||
"warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox или PC (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}",
|
||||
"warn.plugins_skipped": "Не удалось собрать плагины кода модов (exefs subsdk); игра установится без них. Подробности: {log}",
|
||||
"warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox, PlayStation или PC (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}",
|
||||
"warn.shaders_skipped": "Графический драйвер аварийно завершился при сборке части шейдеров, поэтому {count} из них пропущены при подготовке. Игра соберёт их, когда они впервые понадобятся, и драйвер может упасть и там; обновление драйвера может это исправить. Подробности: {log}",
|
||||
"warn.kernel_old": "В Linux {version} нет отслеживания записи, на которое опирается игра (нужна версия 6.7 или новее); игра может работать очень медленно. Обновление системы это исправит.",
|
||||
"warn.dlss_kept": "В папке установки уже есть библиотека DLSS ({path}); установка её оставляет.",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"step.check": "检查电脑和游戏文件",
|
||||
"step.kit": "正在把构建工具包复制到游戏文件夹",
|
||||
"step.fonts": "正在提取系统字体",
|
||||
"step.extract": "解包游戏",
|
||||
"step.lift": "将游戏代码转换为 C 代码",
|
||||
@@ -17,6 +18,7 @@
|
||||
"phase.check.unpack_base": "正在解压压缩的游戏本体",
|
||||
"phase.check.unpack_update": "正在解压压缩的更新",
|
||||
"phase.check.versions": "检查游戏版本",
|
||||
"phase.kit.copy": "正在复制游戏为代码模组重新构建自身所用的工具",
|
||||
"phase.fonts.extract": "正在从固件中提取共享字体",
|
||||
"phase.fonts.copy": "正在将共享字体复制到安装文件夹",
|
||||
"phase.extract.hash_base": "计算游戏本体的校验和",
|
||||
@@ -95,6 +97,8 @@
|
||||
"lift.failed": "游戏代码转换失败(退出代码 {code})。详情:{log}",
|
||||
"compile.failed": "编译 {game_exe} 失败(退出代码 {code})。详情:{log}",
|
||||
"compile.exe_in_use": "{path} 正在使用中。请关闭游戏后重新运行安装程序。",
|
||||
"kit.in_use": "{path} 正在被占用。请关闭游戏以及所有打开的安装或重新构建窗口,再重新运行安装程序。",
|
||||
"kit.copy_failed": "无法把构建工具包复制到 {path}:{detail}",
|
||||
"compile.exe_locked": "无法写入 {path}:另一个程序正在占用它,可能是从该文件夹启动的游戏,或标记了该文件的杀毒软件。请关闭游戏,将安装程序文件夹和安装文件夹加入杀毒软件的排除项,重启 Windows,然后重新运行安装程序。详情:{log}",
|
||||
"prepare.xlate_in_use": "{path} 正在被占用。请关闭游戏,结束上次残留的 totk_xlate 进程,再重新运行安装程序。",
|
||||
"prepare.shader_list_missing": "缺少着色器列表。",
|
||||
@@ -107,8 +111,9 @@
|
||||
"warn.lang_needs_fonts": "{lang}文本需要 Switch 系统字体,但未提供。在添加这些字体之前,游戏无法以该语言启动。请选择固件文件夹(Contents/registered),或参阅 docs/installer.md 中的“Switch system fonts”一节。",
|
||||
"warn.cheats_skipped": "无法构建 mods 文件夹中修改游戏代码的金手指;游戏将不含它们进行安装。详情:{log}",
|
||||
"warn.exefs_skipped": "无法构建模组的 ExeFS 补丁(.ips、.pchtxt);游戏将不含它们进行安装。详情:{log}",
|
||||
"warn.plugins_skipped": "无法构建模组的代码插件(exefs subsdk);游戏将不含它们进行安装。详情:{log}",
|
||||
"warn.npdm_differs": "main.npdm 与参考的 {version} 导出不同;只使用其中的代码模块。",
|
||||
"warn.xbox_prompts_failed": "无法准备 Xbox 或 PC 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}",
|
||||
"warn.xbox_prompts_failed": "无法准备 Xbox、PlayStation 或 PC 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}",
|
||||
"warn.shaders_skipped": "显卡驱动在编译部分着色器时崩溃,因此有 {count} 个着色器未被预先准备。游戏会在首次需要时编译它们,驱动在那时也可能崩溃;更新驱动可能会解决。详情:{log}",
|
||||
"warn.kernel_old": "Linux {version} 缺少游戏依赖的写入跟踪功能(需要 6.7 或更新版本);游戏可能运行得很慢。更新系统即可解决。",
|
||||
"warn.dlss_kept": "安装文件夹中已有 DLSS 库({path});安装程序将保留它。",
|
||||
|
||||
+132
-30
@@ -3,7 +3,11 @@
|
||||
|
||||
Usage: gen.py --exefs build/extracted/v121/exefs --out generated/v121 [--modules main,subsdk0,sdk] [--jobs N]
|
||||
[--limit N] [--chunk-fns N] [--chunk-bytes B] [--big-fn B] [--patches FILE] [--v-locals K [--v-trust]]
|
||||
[--no-cache] [--fn-enter-all]
|
||||
[--no-cache] [--fn-enter-all] [--plugins NSO[,NSO...]]
|
||||
|
||||
--plugins places a mod's code modules (exlaunch plugins) after sdk as plugin0..N (recomp/layout.py) and lifts them with
|
||||
the game modules; their DT_INIT and init_array entries are seeds too (Module.init_functions). Without it the output is
|
||||
what it was before plugins existed.
|
||||
|
||||
Output, under --out:
|
||||
layout.h, layout.json module bases (recomp/layout.py)
|
||||
@@ -63,8 +67,8 @@ import patches # noqa: E402
|
||||
import regs # noqa: E402
|
||||
import vlocals # noqa: E402
|
||||
from check_content import GENERATED_MARKER # noqa: E402
|
||||
from layout import layout, write as write_layout # noqa: E402
|
||||
from lifter import hx # noqa: E402
|
||||
from layout import layout, plugin_files, write as write_layout # noqa: E402
|
||||
from lifter import Insn, hx # noqa: E402
|
||||
from module import Module # noqa: E402
|
||||
|
||||
TERMINATORS = ('b', 'br', 'ret', 'trap')
|
||||
@@ -85,6 +89,30 @@ def fname(a):
|
||||
return f'f_{a:x}'
|
||||
|
||||
|
||||
def orig_name(a):
|
||||
"""The unpatched copy of the function at a that a plugin's replace hook reaches as its original (patches.py `orig`)."""
|
||||
return f'fo_{a:x}'
|
||||
|
||||
|
||||
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."""
|
||||
p = table.plugins.get(name)
|
||||
if not p:
|
||||
return Module(name, path, base, 'c', plugin=plugin)
|
||||
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']))
|
||||
t0, t1 = mod.nso.text[0], mod.nso.text[0] + mod.nso.text[1]
|
||||
if hashlib.sha256(image[t0:t1]).hexdigest() != p['sha256']:
|
||||
raise patches.PatchError(f'{name}: {p["image"]} is not the image whose .text the patch table names')
|
||||
for o in p['stubs']:
|
||||
w = int.from_bytes(image[o + 12:o + 16], 'little')
|
||||
if not mod.in_text(base + o) or w >> 26 != 0x05:
|
||||
raise patches.PatchError(f'{name}+{o:#x}: no inline-hook stub (its fourth word {w:08x} is no b)')
|
||||
return mod
|
||||
|
||||
|
||||
def header(what):
|
||||
return f'// {GENERATED_MARKER}: {what}, generated by recomp/gen.py from game code. Do not edit or commit.\n'
|
||||
|
||||
@@ -229,11 +257,13 @@ class Emitter:
|
||||
the C (an argument here, or anything else it reads) must go into the lift cache's key: chunk_key."""
|
||||
|
||||
def __init__(self, mod, starts, patched=None, reg_locals=regs.LOCALS, callee_saved=True, spins=None,
|
||||
v_locals=vlocals.LOCALS, v_trust=False, hooks=None, fn_enter_all=False):
|
||||
v_locals=vlocals.LOCALS, v_trust=False, hooks=None, fn_enter_all=False, picks=None, origs=None):
|
||||
self.mod = mod
|
||||
self.starts = starts
|
||||
self.patched = patched or {} # {address: [(set index, [replacement words])]} (recomp/patches.py)
|
||||
self.picks = picks or {} # {contested site: (pick index, {ordered set: value})} (recomp/patches.py)
|
||||
self.spins = spins or {} # {spin wait back-edge: its head} (recomp/patches.py `spin`)
|
||||
self.origs = origs or set() # functions also emitted unpatched, as orig_name() (recomp/patches.py `orig`)
|
||||
self.reg_locals = reg_locals # recomp/regs.py: registers per function in C locals
|
||||
self.kept = regs.CALLEE_SAVED if callee_saved else frozenset() # not reloaded after a call
|
||||
self.v_locals = v_locals # recomp/vlocals.py: V registers per function in C locals (0: all in c->v)
|
||||
@@ -241,6 +271,7 @@ class Emitter:
|
||||
# Functions that start with FN_ENTER (recomp/patches.py `hook`): None is every function
|
||||
self.hooks = None if fn_enter_all else hooks
|
||||
self.uses_patches = False
|
||||
self.uses_picks = False
|
||||
self.stats = Counter()
|
||||
self.unsupported = Counter()
|
||||
|
||||
@@ -288,9 +319,12 @@ class Emitter:
|
||||
alternative may branch (bl, b, b.cond / cbz / tbz, ret)."""
|
||||
out = []
|
||||
for _, words in self.patched[a]:
|
||||
lifted = [self.mod.lifter.lift(w, a) for w in words]
|
||||
# ('call', target): a plugin's inline hook (recomp/patches.py @call), before the site's own instruction
|
||||
lifted = [Insn('hook', target=w[1]) if isinstance(w, tuple) else self.mod.lifter.lift(w, a) for w in words]
|
||||
for j, r in enumerate(lifted):
|
||||
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')):
|
||||
raise patches.PatchError(f'{a:#x}: replacement word {words[j]:08x} is a {r.kind}')
|
||||
out.append(lifted)
|
||||
@@ -369,6 +403,22 @@ class Emitter:
|
||||
raise patches.PatchError(f'{a:#x}: a patched call that uses flags')
|
||||
return reads, alts[0][1]
|
||||
|
||||
def unpatched_copy(self, entry, end, refs):
|
||||
"""C of the function [entry, end) without its patched sites, named orig_name(entry): what a plugin's replace
|
||||
hook calls as the original (its trampoline, recomp/patches.py `orig`). Its own fall-back fb_ is renamed too."""
|
||||
kept = self.patched
|
||||
self.patched = {a: alts for a, alts in kept.items() if not entry <= a < end}
|
||||
try:
|
||||
lines, r = self.function(entry, end)
|
||||
finally:
|
||||
self.patched = kept
|
||||
refs |= r
|
||||
text = '\n'.join(lines).replace(f'fb_{entry:x}(', f'fbo_{entry:x}(')
|
||||
head = f'void {fname(entry)}(Cpu *c) {{'
|
||||
if head not in text:
|
||||
raise patches.PatchError(f'{entry:#x}: no function head to rename for its unpatched copy')
|
||||
return text.replace(head, f'void {orig_name(entry)}(Cpu *c) {{', 1)
|
||||
|
||||
def function(self, entry, end):
|
||||
"""(lines of C, referenced function starts) for the guest function [entry, end)."""
|
||||
mod, starts = self.mod, self.starts
|
||||
@@ -451,16 +501,26 @@ class Emitter:
|
||||
return f'if ({fx(i, r.cond)}) {{ {jump(r.target, i)} }}'
|
||||
if r.kind == 'ret':
|
||||
return f'{spill}return;'
|
||||
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
|
||||
refs.add(r.target)
|
||||
self.stats['plugin_hook_calls'] += 1
|
||||
return f'{spill}{fname(r.target)}(c);{reload}'
|
||||
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)."""
|
||||
"""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'):
|
||||
raise patches.PatchError(f'{a:#x}: patched instruction is a {ins.kind}')
|
||||
line = ' '
|
||||
n, values = self.picks.get(a, (None, {}))
|
||||
for (k, _), words in zip(self.patched[a], self.replacements(a)):
|
||||
line += f' if (rt_patch_on[{k}]) {{ {" ".join(one(i, r, a) for r in words)} }} else'
|
||||
test = f'rt_patch_pick[{n}] == {values[k]}' if k in values else f'rt_patch_on[{k}]'
|
||||
line += f' if ({test}) {{ {" ".join(one(i, r, a) for r in words)} }} else'
|
||||
self.uses_patches = True
|
||||
self.uses_picks |= bool(values)
|
||||
self.stats['patched_sites'] += 1
|
||||
return f'{line} {{ {one(i, ins, a)} }}'
|
||||
|
||||
@@ -537,15 +597,19 @@ class Emitter:
|
||||
def chunk_text(name, number, emitter, fns):
|
||||
"""C text of one chunk. fns: [(entry, end)]."""
|
||||
body, refs = [], set()
|
||||
emitter.uses_patches = False
|
||||
emitter.uses_patches = emitter.uses_picks = False
|
||||
for entry, end in fns:
|
||||
lines, r = emitter.function(entry, end)
|
||||
body.append('\n'.join(lines))
|
||||
refs |= r
|
||||
if entry in emitter.origs:
|
||||
body.append(emitter.unpatched_copy(entry, end, refs))
|
||||
# Every referenced function gets a prototype, including ones defined later in this chunk.
|
||||
protos = ''.join(f'void {fname(r)}(Cpu *c);\n' for r in sorted(refs))
|
||||
if emitter.uses_patches:
|
||||
protos += 'extern uint8_t rt_patch_on[];\n'
|
||||
if emitter.uses_picks:
|
||||
protos += 'extern uint8_t rt_patch_pick[];\n'
|
||||
vdef = '#define RT_VLOCALS 1\n' if emitter.v_locals else '' # runtime/simd.h: the V-locals accessors
|
||||
return (header(f'{name} chunk {number:04d}') + vdef + '#include "cpu.h"\n#include "simd.h"\n\n' + protos
|
||||
+ '\n' + '\n\n'.join(body) + '\n')
|
||||
@@ -606,7 +670,7 @@ def _emitter(name):
|
||||
e = _W['emitters'].get(name)
|
||||
if e is None:
|
||||
path, base = _W['mods'][name]
|
||||
mod = Module(name, path, base, 'c')
|
||||
mod = open_module(name, path, base, _W['patches'])
|
||||
# Module.read is how the jump tables (recomp/jumptables.py _eval) read .text and .rodata at lift time: the
|
||||
# bytes it returns become part of the generated code, so <mod>/folded.txt lists them
|
||||
read, reads = mod.read, _W['reads'].setdefault(name, [])
|
||||
@@ -618,7 +682,9 @@ def _emitter(name):
|
||||
e = _W['emitters'][name] = Emitter(mod, set(_W['starts'][name].tolist()),
|
||||
_W['patches'].for_module(name, base),
|
||||
spins=_W['patches'].spins_for(name, base),
|
||||
hooks=_W['patches'].hooks_for(name, base), **_W['opts'])
|
||||
hooks=_W['patches'].hooks_for(name, base),
|
||||
picks=_W['patches'].picks_for(name, base),
|
||||
origs=_W['patches'].origs_for(name, base), **_W['opts'])
|
||||
return e
|
||||
|
||||
|
||||
@@ -663,13 +729,19 @@ def _emit_chunk(task):
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ driver
|
||||
|
||||
def table_text(name, addrs):
|
||||
def table_text(name, addrs, extra=None):
|
||||
"""<mod>_table.c: the function starts and their C; extra {address: C function name} adds entries of functions
|
||||
lifted elsewhere (a plugin's trampoline reaching the unpatched copy of a game function, recomp/patches.py `orig`)."""
|
||||
extra = extra or {}
|
||||
names = {a: fname(a) for a in addrs if a not in extra}
|
||||
names.update(extra)
|
||||
addrs = sorted(names)
|
||||
lines = [header(f'{name} function table'), '#include "cpu.h"\n\n']
|
||||
lines += [f'void {fname(a)}(Cpu *c);\n' for a in addrs]
|
||||
lines += [f'void {names[a]}(Cpu *c);\n' for a in addrs]
|
||||
lines.append(f'\nconst uint64_t {name}_fn_addrs[] = {{\n')
|
||||
lines.append(',\n'.join(hx(a) for a in addrs))
|
||||
lines.append(f'\n}};\nconst GuestFn {name}_fn_ptrs[] = {{\n')
|
||||
lines.append(',\n'.join(fname(a) for a in addrs))
|
||||
lines.append(',\n'.join(names[a] for a in addrs))
|
||||
lines.append(f'\n}};\nconst uint64_t {name}_fn_count = {len(addrs)};\n')
|
||||
return ''.join(lines)
|
||||
|
||||
@@ -733,16 +805,23 @@ def in_span(addrs, lo, hi):
|
||||
return addrs[bisect.bisect_left(addrs, lo):bisect.bisect_left(addrs, hi)]
|
||||
|
||||
|
||||
def chunk_key(mod_key, number, fns, patched, site_addrs, spins, spin_addrs, hook_addrs):
|
||||
def chunk_key(mod_key, number, fns, patched, site_addrs, spins, spin_addrs, hook_addrs, picks=None, origs=None):
|
||||
"""Key of one chunk: its module, number (in its header) and functions, and the patch sites (set index and
|
||||
replacement words, @page resolved, so the patch page is in them), spin waits and hooked functions inside its
|
||||
address range; hook_addrs None (FN_ENTER in every function) keys apart from an empty list. Every input of the
|
||||
chunk text that is not in generator_key or module_key must be added here, with a case in
|
||||
tests/lift_cache_test.py."""
|
||||
replacement words, @page resolved, so the patch page is in them), the pick index and values of its contested
|
||||
sites, spin waits and hooked functions inside its address range; hook_addrs None (FN_ENTER in every function) keys
|
||||
apart from an empty list. Every input of the chunk text that is not in generator_key or module_key must be added
|
||||
here, with a case in tests/lift_cache_test.py."""
|
||||
lo, hi = fns[0][0], fns[-1][1]
|
||||
sites = [[a, [[k, words] for k, words in patched[a]]] for a in in_span(site_addrs, lo, hi)]
|
||||
in_chunk = in_span(site_addrs, lo, hi)
|
||||
sites = [[a, [[k, [list(w) if isinstance(w, tuple) else w for w in words]] for k, words in patched[a]]]
|
||||
for a in in_chunk]
|
||||
hooks = None if hook_addrs is None else in_span(hook_addrs, lo, hi)
|
||||
return _key(mod_key, number, fns, sites, [[b, spins[b]] for b in in_span(spin_addrs, lo, hi)], hooks)
|
||||
contested = [[a, picks[a][0], sorted(picks[a][1].items())] for a in in_chunk if a in (picks or {})]
|
||||
parts = [mod_key, number, fns, sites, [[b, spins[b]] for b in in_span(spin_addrs, lo, hi)], hooks, contested]
|
||||
copies = [e for e, _ in fns if e in (origs or ())]
|
||||
if copies: # none: the key it had before plugins
|
||||
parts.append(copies)
|
||||
return _key(*parts)
|
||||
|
||||
|
||||
def _entry_check(file, entry):
|
||||
@@ -842,7 +921,10 @@ def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
ap.add_argument('--exefs', type=Path, required=True)
|
||||
ap.add_argument('--out', type=Path, required=True)
|
||||
ap.add_argument('--modules', default='main,subsdk0,sdk')
|
||||
ap.add_argument('--modules', default='main,subsdk0,sdk', help='modules to lift (default main,subsdk0,sdk and every '
|
||||
'--plugins module)')
|
||||
ap.add_argument('--plugins', default='', help='comma-separated plugin NSOs (exefs/subsdk* of a mod), in mod load '
|
||||
'order: lifted as plugin0..N after sdk')
|
||||
ap.add_argument('--jobs', type=int, help='emit workers (default: by free memory and CPU count)')
|
||||
ap.add_argument('--limit', type=int, default=0, help='emit only the first N functions of each module')
|
||||
ap.add_argument('--chunk-fns', type=int, default=3000, help='functions per chunk at most')
|
||||
@@ -876,11 +958,13 @@ def main():
|
||||
gen_key = generator_key(opts)
|
||||
|
||||
t0 = time.perf_counter()
|
||||
mods = layout(args.exefs)
|
||||
write_layout(mods, args.out)
|
||||
plugins = [Path(p) for p in args.plugins.split(',') if p]
|
||||
mods = layout(args.exefs, plugins)
|
||||
files = plugin_files(plugins)
|
||||
write_layout(mods, args.out, files)
|
||||
table = patches.load(args.patches, mods) if args.patches else patches.Table()
|
||||
write_if_changed(args.out / 'patches.h', patches.header_text(table, GENERATED_MARKER))
|
||||
want = args.modules.split(',')
|
||||
want = args.modules.split(',') + list(files)
|
||||
unknown = set(want) - {n for n, _, _ in mods}
|
||||
if unknown:
|
||||
raise SystemExit(f'not in {args.exefs}: {", ".join(sorted(unknown))}')
|
||||
@@ -890,8 +974,8 @@ def main():
|
||||
if name not in want:
|
||||
continue
|
||||
t = time.perf_counter()
|
||||
path = args.exefs / name
|
||||
mod = Module(name, path, base, 'c')
|
||||
path = Path(files[name][0]) if name in files else args.exefs / name
|
||||
mod = open_module(name, path, base, table, plugin=name in files)
|
||||
patches.check(table, mod, name)
|
||||
starts, dstats = discover(mod)
|
||||
est = estimate_sizes(mod, starts)
|
||||
@@ -901,8 +985,25 @@ def main():
|
||||
chunks = partition(est[:n], args.chunk_fns, args.chunk_bytes, args.big_fn)
|
||||
moddir = args.out / name
|
||||
moddir.mkdir(parents=True, exist_ok=True)
|
||||
extra = table.orig_entries(name, {n: b for n, b, _ in mods})
|
||||
if extra: # a trampoline reaches another function's unpatched copy, not a lift of its own words
|
||||
keep = ~np.isin(abs_starts, np.array(sorted(extra), dtype=abs_starts.dtype))
|
||||
starts, est, abs_starts = starts[keep], est[keep], abs_starts[keep]
|
||||
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()))
|
||||
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)
|
||||
patched, spins = table.for_module(name, base), table.spins_for(name, base)
|
||||
if table.plugin_inputs(name):
|
||||
mkey = _key(mkey, table.plugin_inputs(name), _sha256(Path(table.plugins[name]['image']).read_bytes()))
|
||||
patched, spins, picks = table.for_module(name, base), table.spins_for(name, base), table.picks_for(name, base)
|
||||
origs = table.origs_for(name, base)
|
||||
bad = sorted(origs - set(abs_starts.tolist()))
|
||||
if bad:
|
||||
raise SystemExit(f'{args.patches}: orig {", ".join(hex(a) for a in bad)} is no function start of {name}')
|
||||
site_addrs, spin_addrs = sorted(patched), sorted(spins)
|
||||
hooks = None if args.fn_enter_all else table.hooks_for(name, base)
|
||||
stray = sorted(set(hooks or ()) - set(abs_starts.tolist()))
|
||||
@@ -912,11 +1013,11 @@ def main():
|
||||
hook_addrs = None if hooks is None else sorted(hooks)
|
||||
for number, (i0, i1) in enumerate(chunks):
|
||||
fns = list(zip(abs_starts[i0:i1].tolist(), ends[i0:i1].tolist()))
|
||||
key = chunk_key(mkey, number, fns, patched, site_addrs, spins, spin_addrs, hook_addrs)
|
||||
key = chunk_key(mkey, number, fns, patched, site_addrs, spins, spin_addrs, hook_addrs, picks, origs)
|
||||
tasks.append((int(est[i0:i1].sum()), (name, number, str(moddir / f'{name}_{number:04d}.c'), fns, key)))
|
||||
paths[name] = (str(path), base)
|
||||
starts_abs[name] = abs_starts
|
||||
info[name] = {'base': base, 'lo': mod.lo, 'hi': mod.hi, 'emitted': abs_starts[:n].tolist(),
|
||||
info[name] = {'base': base, 'lo': mod.lo, 'hi': mod.hi, 'emitted': abs_starts[:n].tolist(), 'extra': extra,
|
||||
'chunks': len(chunks), 'discover': dstats, 'discover_seconds': time.perf_counter() - t,
|
||||
'moddir': moddir}
|
||||
print(f'{name}: {dstats["functions"]} functions ({dstats["seeds"]} seeds, {dstats["rounds"]} rounds), '
|
||||
@@ -981,7 +1082,8 @@ def main():
|
||||
stats.update(r['stats'])
|
||||
unsupported.update(r['unsupported'])
|
||||
t = time.perf_counter()
|
||||
table_written = write_if_changed(moddir / f'{name}_table.c', table_text(name, d['emitted']))
|
||||
table_written = write_if_changed(moddir / f'{name}_table.c', table_text(
|
||||
name, d['emitted'], {t: orig_name(f) for t, f in d['extra'].items()}))
|
||||
write_if_changed(moddir / 'folded.txt', folded_text(name, merge_ranges(folded[name])))
|
||||
removed = remove_stale(moddir, name, d['chunks'], errors)
|
||||
manifest = {
|
||||
|
||||
+35
-13
@@ -6,9 +6,12 @@ calls layout() and writes the result into generated/<version>/layout.h and layou
|
||||
build read.
|
||||
|
||||
Modules are placed in Horizon's load order (rtld is dropped; the host links the modules):
|
||||
main, subsdk0..9, sdk. Each base is aligned to 2 MiB. Everything must stay below 2^39, the limit of the addresses
|
||||
IPC buffers can encode.
|
||||
main, subsdk0..9, sdk. A mod's code modules (exlaunch plugins such as an exefs/subsdk9) follow sdk as plugin0, plugin1,
|
||||
... in mod load order, so the game modules keep their bases with or without them (after the plugin design in #845 by
|
||||
itaskaev2). Each base is aligned to 2 MiB. Everything must stay below 2^39, the limit of the addresses IPC buffers can
|
||||
encode.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
@@ -24,14 +27,18 @@ def align_up(v, a=ALIGN):
|
||||
return (v + a - 1) & ~(a - 1)
|
||||
|
||||
|
||||
def layout(exefs):
|
||||
"""[(name, base, size)] for the modules present in the ExeFS directory, in load order."""
|
||||
def plugin_name(i):
|
||||
return f'plugin{i}'
|
||||
|
||||
|
||||
def layout(exefs, plugins=()):
|
||||
"""[(name, base, size)] for the modules present in the ExeFS directory, then the plugin NSOs (paths, in mod load
|
||||
order) as plugin0..N, in load order."""
|
||||
exefs = Path(exefs)
|
||||
paths = [(name, exefs / name) for name in ORDER if (exefs / name).exists()]
|
||||
paths += [(plugin_name(i), Path(p)) for i, p in enumerate(plugins)]
|
||||
out, base = [], FIRST_BASE
|
||||
for name in ORDER:
|
||||
path = exefs / name
|
||||
if not path.exists():
|
||||
continue
|
||||
for name, path in paths:
|
||||
size = Nso(str(path)).size
|
||||
out.append((name, base, size))
|
||||
base = align_up(base + size)
|
||||
@@ -40,12 +47,27 @@ def layout(exefs):
|
||||
return out
|
||||
|
||||
|
||||
def write(mods, outdir):
|
||||
"""layout.json for Python tools and layout.h for the runtime."""
|
||||
def plugin_files(plugins):
|
||||
"""{plugin<N>: (absolute path, SHA-256 of the NSO)} for layout.json: the build and the runtime read a plugin from its
|
||||
mod folder, not from the ExeFS directory, and check that it is the file the code was lifted from."""
|
||||
return {plugin_name(i): (Path(p).resolve().as_posix(), hashlib.sha256(Path(p).read_bytes()).hexdigest())
|
||||
for i, p in enumerate(plugins)}
|
||||
|
||||
|
||||
def write(mods, outdir, files=None):
|
||||
"""layout.json for Python tools and layout.h for the runtime. files: plugin_files() for the plugin entries, which
|
||||
carry them as "file" and "sha256"; without plugins both files are what they were before plugins existed."""
|
||||
files = files or {}
|
||||
outdir = Path(outdir)
|
||||
outdir.mkdir(parents=True, exist_ok=True)
|
||||
(outdir / 'layout.json').write_text(json.dumps(
|
||||
[{'name': n, 'base': f'{b:#x}', 'size': f'{s:#x}'} for n, b, s in mods], indent=1) + '\n')
|
||||
|
||||
def entry(n, b, s):
|
||||
e = {'name': n, 'base': f'{b:#x}', 'size': f'{s:#x}'}
|
||||
if n in files:
|
||||
e['file'], e['sha256'] = files[n]
|
||||
return e
|
||||
|
||||
(outdir / 'layout.json').write_text(json.dumps([entry(n, b, s) for n, b, s in mods], indent=1) + '\n')
|
||||
lines = ['// Module layout chosen by recomp/layout.py. Generated; do not edit.', '#pragma once', '']
|
||||
for n, b, s in mods:
|
||||
lines.append(f'#define MOD_{n.upper()}_BASE {b:#x}ull')
|
||||
@@ -56,6 +78,6 @@ def write(mods, outdir):
|
||||
|
||||
|
||||
def read(outdir):
|
||||
"""[(name, base, size)] from a layout.json written by write()."""
|
||||
"""[(name, base, size)] from a layout.json written by write() (a plugin's file and hash left out)."""
|
||||
data = json.loads((Path(outdir) / 'layout.json').read_text())
|
||||
return [(m['name'], int(m['base'], 16), int(m['size'], 16)) for m in data]
|
||||
+37
-4
@@ -10,8 +10,9 @@ from collections import OrderedDict
|
||||
import numpy as np
|
||||
|
||||
from lifter import Insn, Lifter, Unsupported, hx
|
||||
from nso import Nso, R_AARCH64_RELATIVE
|
||||
from nso import DT_INIT, DT_INIT_ARRAY, DT_INIT_ARRAYSZ, Nso, R_AARCH64_RELATIVE
|
||||
|
||||
RET = 0xD65F03C0
|
||||
LIFT_CACHE = 1 << 16 # lifted instructions kept per module; analyses revisit nearby addresses only
|
||||
|
||||
|
||||
@@ -33,12 +34,27 @@ def _read_encoded(img, off, enc, pc_base):
|
||||
|
||||
|
||||
class Module:
|
||||
def __init__(self, name, path, base, simd='c'):
|
||||
def __init__(self, name, path, base, simd='c', plugin=False, image=None, rets=(), seeds=()):
|
||||
"""image, rets, seeds: a plugin's lift (recomp/patches.py `plugin`): its .text is taken from image (the plugin's
|
||||
image after its init, holding the hook stubs and trampolines the file has as zeros), the words at the image
|
||||
offsets rets become `ret` (an inline-hook stub's b to its trampoline), and the image offsets seeds are function
|
||||
starts too."""
|
||||
self.name = name
|
||||
self.nso = Nso(str(path))
|
||||
self.base = base
|
||||
self.plugin = plugin # a mod's code module (recomp/layout.py plugin<N>): its init functions are seeds too
|
||||
n = self.nso
|
||||
self.image = bytes(n.image)
|
||||
if image is not None:
|
||||
t0, t1 = n.text[0], n.text[0] + n.text[1]
|
||||
if len(image) < t1:
|
||||
raise ValueError(f'{name}: the image after the init is shorter than its .text')
|
||||
img = bytearray(self.image)
|
||||
img[t0:t1] = image[t0:t1]
|
||||
for o in rets:
|
||||
img[o:o + 4] = RET.to_bytes(4, 'little')
|
||||
self.image = bytes(img)
|
||||
self.extra_seeds = [base + o for o in seeds]
|
||||
self.lo = base + n.text[0]
|
||||
self.hi = self.lo + n.text[1]
|
||||
self.words = np.frombuffer(self.image, dtype='<u4', count=n.text[1] // 4, offset=n.text[0])
|
||||
@@ -83,7 +99,7 @@ class Module:
|
||||
def eh_frame_functions(self):
|
||||
"""Function starts from .eh_frame_hdr's binary search table (absolute addresses)."""
|
||||
img, hdr = self.image, self.nso.eh_start
|
||||
if not hdr or hdr >= len(img):
|
||||
if not hdr or hdr >= len(img) or self.nso.eh_end <= hdr: # MOD0 with an empty .eh_frame_hdr range (exlaunch)
|
||||
return []
|
||||
_, ptr_enc, cnt_enc, tbl_enc = img[hdr:hdr + 4]
|
||||
off = hdr + 4
|
||||
@@ -100,9 +116,26 @@ class Module:
|
||||
starts.append(self.base + loc)
|
||||
return starts
|
||||
|
||||
def init_functions(self):
|
||||
"""DT_INIT and the DT_INIT_ARRAY entries (absolute addresses). rtld calls DT_INIT only; the module's DT_INIT
|
||||
runs the array through blr (SDK and exlaunch modules alike), so the entries are seeds too. An entry holds its
|
||||
target as the addend of its R_AARCH64_RELATIVE relocation, or as the word itself when no relocation names it."""
|
||||
dyn, out = self.nso.dyn, []
|
||||
if dyn.get(DT_INIT):
|
||||
out.append(self.base + dyn[DT_INIT])
|
||||
if dyn.get(DT_INIT_ARRAY):
|
||||
addends = {off: add for off, typ, _, add in self.nso.relocs if typ == R_AARCH64_RELATIVE}
|
||||
for off in range(dyn[DT_INIT_ARRAY], dyn[DT_INIT_ARRAY] + dyn.get(DT_INIT_ARRAYSZ, 0), 8):
|
||||
out.append(self.base + addends.get(off, self.nso.u64(off)))
|
||||
return out
|
||||
|
||||
def seeds(self):
|
||||
"""Known function starts: .eh_frame_hdr, exported FUNC symbols, R_AARCH64_RELATIVE targets in .text."""
|
||||
"""Known function starts: .eh_frame_hdr, exported FUNC symbols, R_AARCH64_RELATIVE targets in .text; for a
|
||||
plugin also its init functions (exlaunch's DT_INIT starts inside a function discovery would merge it into)."""
|
||||
starts = set(self.eh_frame_functions())
|
||||
if self.plugin:
|
||||
starts.update(self.init_functions())
|
||||
starts.update(self.extra_seeds)
|
||||
for _, info, shndx, value, _ in self.nso.syms:
|
||||
if shndx and (info & 0xF) == 2:
|
||||
starts.add(self.base + value)
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ from collections import Counter
|
||||
import lz4.block
|
||||
|
||||
DT_NULL, DT_NEEDED, DT_PLTRELSZ, DT_HASH, DT_STRTAB, DT_SYMTAB, DT_RELA, DT_RELASZ = 0, 1, 2, 4, 5, 6, 7, 8
|
||||
DT_STRSZ, DT_JMPREL, DT_RELACOUNT = 10, 23, 0x6FFFFFF9
|
||||
DT_STRSZ, DT_INIT, DT_JMPREL, DT_INIT_ARRAY, DT_INIT_ARRAYSZ, DT_RELACOUNT = 10, 12, 23, 25, 27, 0x6FFFFFF9
|
||||
DT_RELRSZ, DT_RELR, DT_GNU_HASH = 0x23, 0x24, 0x6FFFFEF5
|
||||
R_AARCH64_ABS64, R_AARCH64_GLOB_DAT, R_AARCH64_JUMP_SLOT, R_AARCH64_RELATIVE = 257, 1025, 1026, 1027
|
||||
|
||||
|
||||
@@ -103,6 +103,11 @@ set pooloff TOTK_POOL_OFFSET_PATCH 1
|
||||
site pooloff main 9b93a8 93407f22 2a1903e2
|
||||
site pooloff main 9b93c4 8b39c101 8b394101
|
||||
|
||||
# Fixed scene tier: the 1.1.0 controller (main+0xce8d74, 1.2.1 main+0xcc26f4) returns its scale through w23 in
|
||||
# the shared epilogue. res_dynres_live enables this set when dynamic_res is off, preserving the configured render_scale.
|
||||
set fixres TOTK_FIXED_RES_PATCH 0
|
||||
site fixres main ce9280 2a1703e9 52a7f009 # mov w9, w23 -> mov w9, #0x3f800000 (1.0f)
|
||||
|
||||
# Sun shadow map: the size rounded here is used for width (+0x3d8), height (+0x3f8) and viewport together.
|
||||
# runtime/resolution.c shadow_init supplies the fixed size at page +92; the default remains the game's size.
|
||||
site shadow main d0760c 11001d6b @page:x11 b9405d6b 11001d6b
|
||||
@@ -114,6 +119,23 @@ site cascade main 1158040 52a84408 @page:x8 b9404508
|
||||
site cascade main 11580c8 52a85408 @page:x8 b9404908
|
||||
site cascade main 115814c 52a86408 @page:x8 b9404d08
|
||||
|
||||
# High-frame-rate climbing (#35, #276, #1001): r is in s9 in the local 1.1.0 controller at main+0x1927948.
|
||||
# The shipping formula multiplies by -0.181, doubles with fadd, then adds 1.272; keep its rounding and [0.5, 1.5] clamp.
|
||||
# For r<1 use the 1.2.1 climb h(r,u), u=max(page+0,r); the normal 30 Hz factor stays unchanged.
|
||||
# runtime/frame_rate.c disables climb when realtime=0; TOTK_CLIMB_FIX=0 keeps the original instruction.
|
||||
# A 96-byte, 16-byte-aligned stack frame saves x8 and full q5/q6/q7/q16/q17; only s0/s1 are outputs.
|
||||
set climb TOTK_CLIMB_FIX 1
|
||||
site climb main 19279f0 1e2f1001 d10183ff f90003e8 ad009be5 ad01c3e7 3d8017f1 @page:x8 bd400111 1e296a31 1e2e1005 1e3138a5 52862508 72a7e308 1e270106 1e2608a5 1e2528a5 529a1ca8 72a7f448 1e270106 1e2628a5 1e201006 1e2678a5 52946dc8 72a7e528 1e270106 1e3118c6 52828248 72a7dfe8 1e270107 1e2728c6 529573e8 72a7b5a8 1e270107 1f1118e6 1e283a27 2f00e410 1e3068e7 1e261010 1f1098e6 1e241010 1e3078c6 1e2668a5 1e256800 1e2f1001 1e256821 3dc017f1 ad41c3e7 ad409be5 f94003e8 910183ff
|
||||
|
||||
# Gear rotation check (#330, #984): main+0x213eec4, vtable 0x347e8e8 slot +0x110.
|
||||
# AI dispatchers 0x1205b90 / 0x2ae29ac pass a context with frame delta at +8; keep it in the already-saved s12.
|
||||
# Scale RotateStartDeg/30 by that delta for all three angle compares: 0x213f10c/0x213f174/0x213f1b0.
|
||||
# The second site saves full q4 in a 16-byte stack slot, without relying on a later callee killing it.
|
||||
# This set does not read the patch page and works with realtime=0; TOTK_HIGHFPS_FIX=0 keeps both original sites.
|
||||
set gears TOTK_HIGHFPS_FIX 1
|
||||
site gears main 213eee4 f9402001 bd40082c f9402001
|
||||
site gears main 213f0d4 1e24180c 3c9f0fe4 1e241804 1e2c088c 3cc107e4
|
||||
|
||||
# Spin waits, from tools/spin_waits.py --exefs build/extracted/v110/exefs --patches recomp/patches-v110.txt: loops that only
|
||||
# another thread can end; their back-edges pass rt_spin_gate (runtime/kernel.c), TOTK_SPIN=0 keeps the core.
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ set output TOTK_PATCH_OUTPUT 0
|
||||
set scene TOTK_PATCH_SCENE 0
|
||||
set shadow TOTK_PATCH_SHADOW 0
|
||||
set grass TOTK_PATCH_GRASS 0
|
||||
set cascade TOTK_PATCH_CASCADE 0
|
||||
|
||||
# 60 fps: the adaptive present-interval controller (main+0x8f26c8, 1.0.0 0x8f6bec) gets the minimum interval 1.
|
||||
site fps60 main 8f273c 6b08015f 7100055f # clamp: cmp w10, #1 (was cmp w10, w8 = minimum)
|
||||
@@ -132,6 +133,22 @@ site aspect main 12521cc bd414260 f81f0fea @page:x10 bd403940 f84107ea # ldr s0
|
||||
site aspect main 19b36f0 1e211800 f81f0fea @page:x10 bd403940 f84107ea # fdiv s0, s0, s1 (viewport)
|
||||
site aspect main 1ecdf68 1e211800 f81f0fea @page:x10 bd403940 f84107ea # fdiv s0, s0, s1 (viewport)
|
||||
|
||||
# Field of view (runtime/resolution.c res_fov_live writes TOTK_FOV / 100 to page +60 and switches the set). The same two
|
||||
# camera routines as the aspect set (update main+0xcb4208, setup main+0x1252024; 1.4.3 main+0x628460, main+0xb432bc)
|
||||
# load the camera's vertical view angle (+0x13c, radians) a few words before the ratio and hand it to sead's perspective
|
||||
# projection (+0xa0, then sinf / cosf / tanf of half of it at +0xa4..+0xac); 1.4.3's setup reads the same fields through
|
||||
# x22 = camera + 0xd8. Eight more places fill a perspective projection the same way, 1.4.3 has the same eight, and
|
||||
# neither version patches them: one more inlined copy that scales an angle of another object (main+0x6c5548, 1.4.3
|
||||
# main+0x4e9754), three projection routines (main+0xdde89c, main+0x1141ce8, main+0x1a5e994; 1.4.3 main+0xc02690,
|
||||
# main+0xd42730, main+0x27d53d8) and four that fill a projection on the stack (main+0x7800f0, main+0x7805fc,
|
||||
# main+0xc764cc, main+0x21ee474; 1.4.3 main+0x63e2b4, main+0x63e744, main+0x79344, main+0x2804fec). The replacement is
|
||||
# the one of patches-v143.txt (word for word the sites of patches-v110.txt): it loads the angle as before and
|
||||
# multiplies it by the factor on the page; s8 holds the factor because the next instruction (fmul s8, s0, s1) overwrites
|
||||
# it, and x10 is kept on the stack.
|
||||
set fov TOTK_FOV_PATCH 0
|
||||
site fov main cb4ad8 bd413e60 f81f0fea @page:x10 bd413e60 bd403d48 1e280800 f84107ea # ldr s0, [x19, #0x13c] (camera update)
|
||||
site fov main 1252194 bd413e60 f81f0fea @page:x10 bd413e60 bd403d48 1e280800 f84107ea # ldr s0, [x19, #0x13c] (camera setup)
|
||||
|
||||
# Texture pool offsets past 2 GiB (MacNativeGames ca311e2d). The texture loader keeps a texture's place in its pool as a
|
||||
# 32-bit offset (main+0xad4294: sub x25, x9, x10, stored as the word w25) and widens it as a signed number for
|
||||
# nvnTextureBuilderSetStorage's offset and for SetPackagedTextureData's source (the pool's CPU address + offset). The
|
||||
@@ -1128,6 +1145,18 @@ spin sdk 3d3250 3d3270 # 9 instructions; loads
|
||||
# computation). Found by a write watch on the size field (the writer was this function, and no other).
|
||||
site shadow main cec22c 11001d6b @page:x11 b9405d6b 11001d6b # add w11, w11, #7 -> adrp x11, page; ldr w11, [x11, #92]; add w11, w11, #7
|
||||
|
||||
# Sun shadow cascade distances (runtime/resolution.c res_shadow_range switches the set on; issue #606). On 1.2.1 the
|
||||
# depth shadow parameters (depth_shadow_near_0_0..3 and depth_shadow_far_0, whose constructor defaults at
|
||||
# main+0x114c2f8.. are 20, 40, 80, 160 and 2000 m) do not reach the sun's cascades: the game's shadow controller sets
|
||||
# bit 1 of the scene's depth shadow flags when it starts (main+0xc7b0e8), and with that bit the per-view update
|
||||
# (main+0xa2cff4) skips its copy of those parameters into the cascade boundaries. The controller writes the boundaries
|
||||
# itself each frame in main+0xcebdf4: d[0] at main+0xcec2ac, d[1..n-1] at main+0xcec314 and the far d[n] at
|
||||
# main+0xcec36c (d = [cascade set + 0x308], read by main+0xa2d6ec). The set multiplies d[1..n] where they are stored,
|
||||
# by page +64 (20 m times shadow_range / 100) over 20; d[0], the first cascade's start, stays. x3, s16 and s17 are
|
||||
# dead at both sites.
|
||||
site cascade main cec314 bd000446 @page:x3 bd404070 1e269011 1e311a10 1e3008d0 bd000450 # str s6, [x2, #4] -> adrp x3, page; ldr s16, [x3, #64]; fmov s17, #20.0; fdiv s16, s16, s17; fmul s16, s6, s16; str s16, [x2, #4]
|
||||
site cascade main cec36c bc29d945 @page:x3 bd404070 1e269011 1e311a10 1e3008b0 bc29d950 # str s5, [x10, w9, sxtw #2] -> the same with fmul s16, s5, s16; str s16, [x10, w9, sxtw #2]
|
||||
|
||||
# Grass range (runtime/resolution.c res_grass_range; patches-v143.txt describes the set and the page). The near grass
|
||||
# map's constructor loads its extent, step and texture sizes at main+0xfe58b4..0xfe5950, and main+0x1a30a28 sets the
|
||||
# extent to 62.5 or 31.25 m, as on 1.4.3.
|
||||
@@ -1151,3 +1180,32 @@ site optref main 1622bec b4000188 937ffd09 8a290108 b4000188 # cbz x8 -> asr x
|
||||
set ability TOTK_ABILITY_GUARD 1
|
||||
site ability main 1622bf0 f9400115 94c424dc # ldr x21, [x8] -> bl page+0xf60
|
||||
site ability main 1622bf4 b4000155 aa0903f5 b4000155 # cbz x21 -> mov x21, x9; cbz x21 (x9 dead after it)
|
||||
|
||||
# Sound command lists above 200 updates a second (issue #337). The game thread hands its sound commands to the audio
|
||||
# thread in lists: 16 of them, of which 4 are always held (one being filled by the game thread, the others on the audio
|
||||
# thread's side), so at most 12 wait in the command ring. The game thread submits at most one list per update
|
||||
# (main+0x9bd144, when a free list is there), and the audio thread takes one per pass of its loop, one 5 ms audio frame:
|
||||
# after a list main+0x883780 goes on past the ring's check (b 0x883318). Above about 200 updates a second the ring
|
||||
# fills. A guard in the game (main+0x9bcdc4, at the end of each update) counts the updates that find the ring of free
|
||||
# lists empty and exactly 12 lists in the command ring (0x9bce1c cmp w9, #0xc); the count goes back to 0 whenever a free
|
||||
# list is there (0x9bce00), which takes two audio frames between two updates: the game thread picks up one of the two
|
||||
# lists, the other is still free at the guard. At every multiple of 300 (10 s at 30 fps, 1.25 s at 240) the guard clears
|
||||
# the sound command switch, the byte at [[engine + 0x1a0] + 8] (main+0x2268bfc), and stops every active voice
|
||||
# (main+0x226f29c). The switch is set to 1 only by its constructor (main+0xf31ce8, from the engine's init
|
||||
# main+0xf31530), so the game stays silent until it is restarted. By this reading the guard fires only when the audio
|
||||
# frames come evenly, 5 ms apart, through 300 updates in a row at more than 200 a second: that is the mixer pacing its
|
||||
# render thread by its own timer (runtime/audio_mixer.c, audio_mixer_pace_ns), with audio = none or while a device takes
|
||||
# nothing. While a device paces the rendering the frames come in bursts after each device period: on Linux with
|
||||
# PipeWire's 1024-frame periods 76% of the frames were measured 4 ms after the one before (audren.c, gap_ns), two of
|
||||
# them fall between two updates several times a second, and the game kept its sound in every run. On Windows gap_ns is 0
|
||||
# and the frames of a burst are rendered back to back: read from the code, not measured here. A device with periods of
|
||||
# 240 frames or less was not tried and may pace as evenly as the timer. The count and the switch have not been read in a
|
||||
# run. The site sends the audio thread back to the ring's check (0x8832e8, where the game's own 0x883c18 also branches;
|
||||
# x21, the engine, is not written between the check and the site), so it takes every queued list in the pass and the
|
||||
# ring does not stay full. Measured on 1.2.1 at fps_limit 240 (Linux, PipeWire), same save and input script, seconds
|
||||
# with sound in the mix with the set off and on: 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) while the game ran
|
||||
# at 240 fps 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 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
|
||||
@@ -1104,6 +1104,18 @@ site cascade main 6fabb8 52a83408 @page:x8 b9404108 # mov w8, #20.0 -> ldr w8
|
||||
site cascade main 6fac40 52a84408 @page:x8 b9404508 # mov w8, #40.0 -> ldr w8, [page+68]
|
||||
site cascade main 6facc8 52a85408 @page:x8 b9404908 # mov w8, #80.0 -> ldr w8, [page+72]
|
||||
site cascade main 6fad4c 52a86408 @page:x8 b9404d08 # mov w8, #160.0 -> ldr w8, [page+76]
|
||||
# The four sites above reach the cascades only through the copy of the parameters into the cascade boundaries
|
||||
# (main+0x5680ec, in the per-view update). The game's shadow controller sets bit 1 of the scene's depth shadow flags
|
||||
# when it starts (main+0xb74494), with that bit the per-view update skips the copy (main+0x567f6c), and the controller
|
||||
# writes the boundaries itself each frame in main+0x68318c: d[0] at main+0x683680, d[1..n-1] at main+0x6836ec and the
|
||||
# far d[n] at main+0x683740 (d = [cascade set + 0x308]). In Hyrule Field the four sites alone leave the cascades as
|
||||
# they are at 100 (issue #606 has the same on 1.2.1). These two multiply d[1..n] where the controller stores them, by
|
||||
# page +64 (20 m times shadow_range / 100) over 20; d[0], the first cascade's start, stays. The function computes the
|
||||
# boundaries from the controller's own fields and its arguments and reads neither the parameters nor d, so a boundary
|
||||
# is scaled once on either path. x25 (written at main+0x683704 before any read), x16, s18 and s19 are dead at the
|
||||
# sites.
|
||||
site cascade main 6836ec bd000711 @page:x25 bd404332 1e269013 1e331a52 1e320a32 bd000712 # str s17, [x24, #4] -> adrp x25, page; ldr s18, [x25, #64]; fmov s19, #20.0; fdiv s18, s18, s19; fmul s18, s17, s18; str s18, [x24, #4]
|
||||
site cascade main 683740 bc2ed9b0 @page:x16 bd404212 1e269013 1e331a52 1e320a12 bc2ed9b2 # str s16, [x13, w14, sxtw #2] -> the same through x16 with fmul s18, s16, s18; str s18, [x13, w14, sxtw #2]
|
||||
|
||||
# Climbing (issues #35, #276, #1001): the climb controller's velocity step (main+0x1f49754, shared by wall and ladder
|
||||
# climbing, climb jumps and climb-overs) multiplies the requested velocity by a factor that makes up for a movement loss
|
||||
@@ -1173,7 +1185,59 @@ set report TOTK_REPORT_GUARD 1
|
||||
site report main a22d8 2a010571 2a010571 37f80341 # orr w17, w11, w1, lsl #1; tbnz w1, #31, 0xa2340
|
||||
site report main a2310 531f7821 530f7c24 531f7821 35000184 # lsr w4, w1, #15; lsl w1, w1, #1; cbnz w4, 0xa2340
|
||||
|
||||
# Depth query results one frame older (TOTK_SYNC_AHEAD). A compute pass at the start of each frame samples the scene
|
||||
# depth for the world queries and writes their results, with the frame number of the request, into a 23232-byte
|
||||
# CPU-cached buffer that main+0x6e1220 invalidates and reads two frames later. It takes the results as this frame's
|
||||
# (bit 2 of obj+0x10) only when the number at buffer +0x58e4 is exactly the frame counter (obj+0x14) - 2. With
|
||||
# sync_ahead the game's frame wait covers the frame before, so on frames where the GPU runs behind the number read is
|
||||
# the counter - 3 (the frame after it has not come back yet) and the results were refused: in shrines the reflections
|
||||
# of the lamps on the floor went out on those frames, every other frame where the GPU was slow, which looked like
|
||||
# flicker at some camera angles. The set also accepts the counter - 3: d = counter - 2 - number, unsigned d <= 1.
|
||||
# Waiting for that frame when the buffer is invalidated (vk_memory.c vk_mem_shadow_read) also ends the flicker, but
|
||||
# gives back the frame rate sync_ahead brings (63 against 86 fps on a field macro at 4K).
|
||||
# w11 is loaded again on both paths at 0x6e1340 before any read; x8, the number's address, stays for 0x6e1420.
|
||||
set qstamp TOTK_SYNC_AHEAD 0
|
||||
site qstamp main 6e1320 6b0b015f 4b0b014b 7100057f # cmp w10, w11 -> sub w11, w10, w11; cmp w11, #1
|
||||
site qstamp main 6e1324 540000c1 540000c8 # b.ne 0x6e133c -> b.hi 0x6e133c
|
||||
|
||||
# Function-entry hooks (FN_ENTER, runtime/cpu.h): only these functions check g_fnprof on entry, the others carry no
|
||||
# hook. main+0x585bd0 sets the render size (runtime/resolution.c SET_RENDER_SIZE): res_fn_hit takes the renderer from
|
||||
# the game's own call at start, so a DLSS mode can change while the game runs.
|
||||
hook main 585bd0
|
||||
|
||||
# Sound command lists above 200 updates a second (issue #337): as in patches-v121.txt, which also says when the game's
|
||||
# guard fires. The audio thread's check of the command ring is main+0x148aec, which wants x8 = the engine (as 0x148ae0
|
||||
# loads it from [x19]); after a list the site goes back to it instead of on to 0x148b14, with the two instructions the
|
||||
# game itself has at 0x149700. Measured on 1.4.3 at fps_limit 240 (Linux, PipeWire), same save and input script, seconds
|
||||
# with sound in the mix: without a device 3 of 119 with the set off and 113 of 120 with it on; with a device 111 of 119
|
||||
# with the set off; with the game's stream paused for 5 s from outside at 240 fps, in 60 s runs, 3 of 59 with the set
|
||||
# off (silent from the pause on) and 51 of 59 with it on; a pause of 2 s with the set off, 4 of 59.
|
||||
set audiodrain TOTK_AUDIO_DRAIN_FIX 1
|
||||
site audiodrain main 149244 17fffe34 f9400268 17fffe2a # b 0x148b14 -> ldr x8, [x19]; b 0x148aec
|
||||
|
||||
# Tenbez Shrine launchers (issue #1215). The two DgnObj_BoxShutter_4x4x4 that throw the stone ball across the room move
|
||||
# 3 m at Speed (1.0 m per 30 Hz frame, 30 m/s): their AI (AI/ShutterFence.root.ainb) advances the target by Speed *
|
||||
# frame ratio each frame and sets the kinematic body's velocity to reach it. The shorter the frame, the slower the ball
|
||||
# leaves. Measured on the flight's apex (the ball rests at y = -4.42): 6.33 at 30 fps, 6.11 at 45, 6.00 at 60, 5.79 at
|
||||
# 90, 5.61 at 120. Below about 6.1 the ball lands more and more often on the rim of the receiving launcher instead
|
||||
# of its seat, and the next shots juggle it there or knock it into the pit. The data suggest Nintendo tuned this by
|
||||
# hand for a 60 fps build ("Ounce", which looks like the Switch 2): in
|
||||
# the shrine's map both actors carry SpeedForOunce = 1.01 and shouldUseOunceSpeed, read by the node
|
||||
# QueryBlackboardGetF32FromActorForOunce (also in AI/ShutterFence_WithVibration.root.ainb of the
|
||||
# FldObj_RuinStoneWall_A_20/30_Shutter walls, where the flag is never set). The Switch build of the node ignores the
|
||||
# pair: its evaluation (main+0x25e557c) looks up the base key alone. With 1.01 the apex is 6.20 at 60 fps, but 5.96 at 90 and
|
||||
# 5.81 at 120, so the site scales by the frame instead. It is where the evaluation loads the value: when the node's
|
||||
# shouldUseOunceKey input (+0x58) is true, the value is multiplied by 1 + 0.065 * (1 - ratio)^2, ratio being the time
|
||||
# object's +0x38 (the frame in 30 Hz frames; [[main+0x3ad27c8] + 0xc8], the object the set bounce reads) clamped to
|
||||
# 0..1. That is 1.016 at 60 fps and 1.037 at 120, and exactly 1 at 30 fps and below. Measured apex with it: 6.25 at
|
||||
# 45 fps, 6.33 at 60, 6.23 at 90, 6.33 at 120, 6.35 at 144. Every other user of the node has the input false and gets
|
||||
# its value unchanged. x9, x10 and s1-s4 are free: after the site the function only moves x19 to x0, restores the
|
||||
# saved registers and tail-calls the output setter (main+0xb9b818), which reads x0 and s0. Its own switch,
|
||||
# shutter_fix (TOTK_SHUTTER_FIX); 0 runs the game's instruction.
|
||||
set shutter TOTK_SHUTTER_FIX 1
|
||||
site shutter main 25e55d0 bc605900 bc605900 f9402ea9 927ef529 39400129 1e230123 b000a76a f943e54a f940654a bd403941 1e2e1002 1e213841 2f00e404 1e246821 1e227821 1e210821 5283d709 72a7b0a9 1e270124 1e240821 1e230821 1f010000
|
||||
# ldr s0, [x8, w0, uxtw #2]; ldr x9, [x21, #0x58]; and x9, x9, #~3; ldrb w9, [x9]; ucvtf s3, w9 (the input, 0 or 1);
|
||||
# adrp x10, main+0x3ad2000; ldr x10, [x10, #0x7c8]; ldr x10, [x10, #0xc8]; ldr s1, [x10, #0x38] (ratio);
|
||||
# fmov s2, #1.0; fsub s1, s2, s1; movi d4, #0; fmaxnm s1, s1, s4; fminnm s1, s1, s2; fmul s1, s1, s1;
|
||||
# mov w9, #0x1eb8; movk w9, #0x3d85, lsl #16; fmov s4, w9 (0.065); fmul s1, s1, s4; fmul s1, s1, s3;
|
||||
# fmadd s0, s0, s1, s0
|
||||
+174
-14
@@ -3,13 +3,19 @@
|
||||
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:
|
||||
|
||||
set <name> <env> <default> a patch set: a run-time switch <env>=0/1, <default> when it is unset
|
||||
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> ...]
|
||||
|
||||
spin <module> <head> <back-edge> [<back-edge> ...]
|
||||
|
||||
hook <module> <function> [<function> ...]
|
||||
|
||||
plugin <set> <module> <text sha256> <image>
|
||||
expect <set> <module> <offset> <old> <new>
|
||||
stub <module> <offset>
|
||||
seed <module> <offset> [<offset> ...]
|
||||
orig <set> <module> <offset> <function module> <function 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>`
|
||||
encoded for the site's address. The patch page is the first 4 KiB page after main's image (layout.py leaves the rest
|
||||
@@ -22,16 +28,50 @@ the field-of-view factor (runtime/resolution.c res_fov_live, set fov), +92..95 t
|
||||
The replacement words are lifted at the site's address in place of the original instruction, and the generated C reads
|
||||
`if (rt_patch_on[<set>]) { replacement } else { original }`: one byte load and a branch per executed site. Several
|
||||
sets may patch one address (cheats that write different values there): `if (a) {..} else if (b) {..} else {..}`, the
|
||||
first set in file order wins. The original may be any instruction but br, blr and ret; a replacement's last word may be
|
||||
first set in file order wins.
|
||||
|
||||
An `ordered` set belongs to something the player puts in an order (a mod of the Mods tab: tools/exefs_patches.py marks
|
||||
its sets so). A site that two or more ordered sets patch is contested: the run time, not the file order, picks which
|
||||
of them runs. Each contested site gets a byte rt_patch_pick[<n>] (n counts the contested sites, by module name and
|
||||
offset), and each of its ordered alternatives tests `rt_patch_pick[<n>] == <j>`, j being the alternative's place
|
||||
among the site's ordered sets in file order (1 up; 0 runs none of them): one byte load for the whole group. The
|
||||
runtime fills the bytes from the sets that are on and their ranks (runtime/patches.c rt_patch_picks: the lowest rank
|
||||
wins, a tie goes to the set later in the file). The other alternatives of a contested site keep their place and
|
||||
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
|
||||
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) next to layout.h for the runtime.
|
||||
writes patches.h (set names, switches, the page address, the contested sites) next to layout.h for the runtime.
|
||||
|
||||
A `spin` line names a spin wait found by tools/spin_waits.py: a loop with head <head> that only another thread can end,
|
||||
and the direct branches back to it (module offsets). Each back-edge (checked: a b, b.cond, cbz / cbnz or tbz / tbnz to
|
||||
<head>) is lifted as `rt_spin_gate(c, <head>); goto <head>`, which keeps every register and only adds time
|
||||
(runtime/kernel.c kern_spin_gate).
|
||||
|
||||
The plugin lines carry a mod's exlaunch plugin (layout.py plugin<N>), whose init runs at every start
|
||||
(runtime/plugin_init.c) and whose hooks are sites of its set (tools/exefs_plugins.py writes them from the plugin service
|
||||
run's record; the design follows #845 by itaskaev2):
|
||||
- `plugin`: <module> belongs to the set <set>; it is lifted from <image>, the plugin's image after its init (the
|
||||
service run's plugin<N>.img), whose .text holds the hook stubs and trampolines the NSO file has as zeros. <text
|
||||
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.
|
||||
- `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.
|
||||
- `seed`: function starts of the module the lift must have (the callbacks, the hook impls, branch targets).
|
||||
- `orig`: the plugin calls its replace hook's original through the trampoline at <module>+<offset>; the generator
|
||||
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.
|
||||
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.
|
||||
|
||||
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
|
||||
@@ -40,6 +80,7 @@ without any keeps it in every function, as does gen.py --fn-enter-all (a whole-g
|
||||
from pathlib import Path
|
||||
|
||||
PAGE = 0x1000
|
||||
PICK_MAX = 255 # ordered sets on one site: rt_patch_pick is a byte, 0 for none
|
||||
|
||||
|
||||
class PatchError(ValueError):
|
||||
@@ -56,15 +97,58 @@ def adrp(pc, target, rd):
|
||||
|
||||
class Table:
|
||||
"""sets: [(name, env, default)]; sites: {module: {offset: [(set index, [word | ('page', reg)], original)]}} (the
|
||||
alternatives of a site in file order); page. What the generated C takes from here (for_module, 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."""
|
||||
alternatives of a site in file order); page; ordered: the indices of the ordered sets. What the generated C takes
|
||||
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):
|
||||
def __init__(self, sets=(), sites=None, page=0, spins=None, hooks=None, ordered=(), plugins=None):
|
||||
self.sets = list(sets)
|
||||
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},
|
||||
# 'seeds': {offset}, 'origs': {trampoline offset: (function module, function offset)}}}; empty without
|
||||
# plugin lines
|
||||
self.plugins = plugins or {}
|
||||
self.bases = {} # {module: base} of the layout load() read
|
||||
|
||||
def plugin_inputs(self, name):
|
||||
"""What the lift of module name takes from its plugin lines (for the lift cache's key), or None."""
|
||||
p = self.plugins.get(name)
|
||||
if not p:
|
||||
return None
|
||||
return [p['image'], p['sha256'], sorted(p['stubs']), sorted(p['seeds']), sorted(p['origs'])]
|
||||
|
||||
def origs_for(self, name, base):
|
||||
"""The absolute addresses of module name's functions that a plugin's `orig` line copies."""
|
||||
return {base + fo for p in self.plugins.values() for fm, fo in p['origs'].values() if fm == name}
|
||||
|
||||
def orig_entries(self, name, bases):
|
||||
"""{trampoline address in module name: absolute address of the function it reaches} (`orig`)."""
|
||||
p = self.plugins.get(name)
|
||||
if not p:
|
||||
return {}
|
||||
return {bases[name] + t: bases[fm] + fo for t, (fm, fo) in p['origs'].items()}
|
||||
|
||||
def picks(self):
|
||||
"""The contested sites, by module name and offset: [(module, offset, [ordered set index in file order])]; the
|
||||
list index is the site's rt_patch_pick byte."""
|
||||
out = []
|
||||
for name in sorted(self.sites):
|
||||
for off in sorted(self.sites[name]):
|
||||
sets = [k for k, _, _ in self.sites[name][off] if k in self.ordered]
|
||||
if len(sets) > 1:
|
||||
if len(sets) > PICK_MAX:
|
||||
raise PatchError(f'{name}+{off:#x}: {len(sets)} ordered sets, at most {PICK_MAX}')
|
||||
out.append((name, off, sets))
|
||||
return out
|
||||
|
||||
def picks_for(self, name, base):
|
||||
"""{absolute address of a contested site: (its pick index, {ordered set index: the value that runs it})}."""
|
||||
return {base + off: (n, {k: j + 1 for j, k in enumerate(sets)})
|
||||
for n, (mod, off, sets) in enumerate(self.picks()) if mod == name}
|
||||
|
||||
def hooks_for(self, name, base):
|
||||
"""The absolute addresses of the module's hooked functions, or None when the table has no hook line at all
|
||||
@@ -77,29 +161,42 @@ class Table:
|
||||
"""{absolute back-edge address: absolute head address}."""
|
||||
return {base + b: base + h for b, h in self.spins.get(name, {}).items()}
|
||||
|
||||
def for_module(self, name, base):
|
||||
"""{absolute address: [(set index, [words])]} with @page resolved."""
|
||||
def for_module(self, name, base, bases=None):
|
||||
"""{absolute address: [(set index, [words])]} with @page resolved; an @call word becomes ('call', absolute
|
||||
address), which needs bases ({module: base})."""
|
||||
out = {}
|
||||
|
||||
def word(a, w):
|
||||
if not isinstance(w, tuple):
|
||||
return w
|
||||
if w[0] == 'page':
|
||||
return adrp(a, self.page, w[1])
|
||||
known = bases or self.bases
|
||||
if w[1] not in known:
|
||||
raise PatchError(f'{name}+{a - base:#x}: @call into {w[1]}, which is not in the layout')
|
||||
return ('call', known[w[1]] + w[2])
|
||||
|
||||
for off, alts in self.sites.get(name, {}).items():
|
||||
a = base + off
|
||||
out[a] = [(k, [adrp(a, self.page, w[1]) if isinstance(w, tuple) else w for w in repl])
|
||||
for k, repl, _ in alts]
|
||||
out[a] = [(k, [word(a, w) for w in repl]) for k, repl, _ in alts]
|
||||
return out
|
||||
|
||||
|
||||
def load(path, mods):
|
||||
"""Table from a patch file; mods is layout() output [(name, base, size)]."""
|
||||
sets, index, sites, spins, hooks = [], {}, {}, {}, {}
|
||||
sets, index, sites, spins, hooks, ordered, plugins = [], {}, {}, {}, {}, set(), {}
|
||||
bases = {n: (b, s) for n, b, s in mods}
|
||||
for no, raw in enumerate(Path(path).read_text().splitlines(), 1):
|
||||
for no, raw in enumerate(Path(path).read_text(encoding='utf-8').splitlines(), 1):
|
||||
f = raw.split('#', 1)[0].split()
|
||||
if not f:
|
||||
continue
|
||||
where = f'{path}:{no}'
|
||||
if f[0] == 'set' and len(f) == 4:
|
||||
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')
|
||||
index[f[1]] = len(sets)
|
||||
if len(f) == 5:
|
||||
ordered.add(len(sets))
|
||||
sets.append((f[1], f[2], int(f[3])))
|
||||
elif f[0] == 'site' and len(f) >= 6:
|
||||
if f[1] not in index:
|
||||
@@ -111,6 +208,11 @@ def load(path, mods):
|
||||
for w in f[5:]:
|
||||
if w.startswith('@page:x'):
|
||||
repl.append(('page', int(w[7:])))
|
||||
elif w.startswith('@call:') and '+' in w:
|
||||
target, at = w[6:].split('+', 1)
|
||||
if target not in bases:
|
||||
raise PatchError(f'{where}: @call into {target}, which is not in the layout')
|
||||
repl.append(('call', target, int(at, 16)))
|
||||
else:
|
||||
repl.append(int(w, 16))
|
||||
alts = sites.setdefault(f[2], {}).setdefault(off, [])
|
||||
@@ -128,6 +230,15 @@ def load(path, mods):
|
||||
if b in mod:
|
||||
raise PatchError(f'{where}: {f[1]}+{b:#x} is a back-edge twice')
|
||||
mod[b] = head
|
||||
elif f[0] == 'plugin' and len(f) == 5:
|
||||
if f[1] not in index or f[2] not in bases:
|
||||
raise PatchError(f'{where}: unknown set {f[1]} or module {f[2]}')
|
||||
if f[2] in plugins:
|
||||
raise PatchError(f'{where}: module {f[2]} has two plugin lines')
|
||||
plugins[f[2]] = {'set': index[f[1]], 'sha256': f[3], 'image': f[4], 'expect': [], 'stubs': set(),
|
||||
'seeds': set(), 'origs': {}}
|
||||
elif f[0] in ('expect', 'stub', 'seed', 'orig'):
|
||||
plugin_line(f, where, index, bases, plugins)
|
||||
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')
|
||||
@@ -139,7 +250,36 @@ 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})')
|
||||
return Table(sets, sites, page, spins, hooks)
|
||||
table = Table(sets, sites, page, spins, hooks, ordered, plugins)
|
||||
table.bases = {n: b for n, (b, _) in bases.items()}
|
||||
return table
|
||||
|
||||
|
||||
def plugin_line(f, where, index, bases, plugins):
|
||||
"""An expect, stub, seed or orig line into the plugin entry it belongs to (its `plugin` line comes first)."""
|
||||
def plugin(name):
|
||||
if name not in plugins:
|
||||
raise PatchError(f'{where}: {name} has no plugin line before this one')
|
||||
return plugins[name]
|
||||
|
||||
if f[0] == 'expect' and len(f) == 6:
|
||||
if f[1] not in index or f[2] not in bases:
|
||||
raise PatchError(f'{where}: unknown set {f[1]} or module {f[2]}')
|
||||
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)))
|
||||
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:
|
||||
plugin(f[1])['seeds'].update(int(o, 16) for o in f[2:])
|
||||
elif f[0] == 'orig' and len(f) == 6:
|
||||
p = plugin(f[2])
|
||||
if f[1] not in index or p['set'] != index[f[1]] or f[4] not in bases:
|
||||
raise PatchError(f'{where}: orig of set {f[1]} for {f[2]}, which another set owns, or module {f[4]}')
|
||||
p['origs'][int(f[3], 16)] = (f[4], int(f[5], 16))
|
||||
else:
|
||||
raise PatchError(f'{where}: cannot parse {" ".join(f)!r}')
|
||||
|
||||
|
||||
def check(table, mod, name):
|
||||
@@ -175,4 +315,24 @@ def header_text(table, marker):
|
||||
'// X(index, name, env switch, default)',
|
||||
'#define RT_PATCH_SETS(X) ' + ' '.join(f'X({i}, {n}, "{e}", {d})' for i, (n, e, d) in
|
||||
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'])]
|
||||
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',
|
||||
'#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
|
||||
for o in sorted(table.plugins[n]['seeds'])), '']
|
||||
picks = table.picks()
|
||||
if picks: # none: the header is what it was before ordered sets
|
||||
lines += [f'#define RT_PATCH_PICK_COUNT {len(picks)}',
|
||||
'// X(index, module, module offset, its ordered sets in the order its C tests them: rt_patch_pick 1 up)',
|
||||
'#define RT_PATCH_PICKS(X) ' + ' '.join(f'X({i}, "{m}", {o:#x}, {", ".join(map(str, s))})'
|
||||
for i, (m, o, s) in enumerate(picks)), '']
|
||||
return '\n'.join(lines)
|
||||
+39
-5
@@ -30,6 +30,7 @@
|
||||
#define CHECKPOINT_RET (RT_V143 ? 0xbdb48cull : RT_V110 ? 0xeb8c14ull : 0xe7a954ull)
|
||||
#define NVN_RET (RT_V143 ? 0xbe0360ull : RT_V110 ? 0xebcdecull : 0xe7eb2cull)
|
||||
#define CTOR_DONE 2 // a module's constructor flag after its DT_INIT ran the init_array
|
||||
#define CTOR_WAITING 1 // after a DT_INIT that musl deferred (sdk's, called before main's)
|
||||
|
||||
// The init_array sizes (1.1.0 and 1.2.1: counted in the modules; 1.4.3: DT_INIT_ARRAYSZ); MacNativeGames' boot check
|
||||
// expects the same. The three tables carry the same rows, so cb_module_inits walks them by the size of one.
|
||||
@@ -40,6 +41,7 @@ static const InitCount inits_143[] = {{"main", 10717}, {"subsdk0", 45}, {"sdk",
|
||||
#define expected_inits (RT_V143 ? inits_143 : RT_V110 ? inits_110 : inits_121)
|
||||
|
||||
static volatile int32_t inits_done, checkpoint_seen;
|
||||
static int sdk_first; // a mod plugin ran: sdk's DT_INIT came first (cb_module_inits)
|
||||
uint64_t rt_guest_start_ns;
|
||||
|
||||
static const RtLoaded *module_named(const char *name) {
|
||||
@@ -77,15 +79,28 @@ static void cb_loader_ready(Cpu *c) {
|
||||
// afterwards (MacNativeGames loader.c:458-462).
|
||||
static void cb_module_inits(Cpu *c) {
|
||||
if (plat_cas32(&inits_done, 0, 0)) rt_fatal("boot: module constructors requested twice");
|
||||
if (rt_config()->plugin_init) plugin_init_run(c, module_named("sdk")); // the plugin service run ends there
|
||||
// A mod plugin's init runs after sdk's and before the game's (plugin_init.c plugins_start): sdk's DT_INIT then
|
||||
// comes first, as on the Switch; without a plugin the order stays main, subsdk0, sdk. Called first, sdk's DT_INIT
|
||||
// only registers sdk with its own musl (__nnmusl_init_dso returns 1: deferred), and main's DT_INIT then finishes
|
||||
// sdk from musl's list of waiting modules (the log shows sdk's RELRO protected and 44 pages of sdk's data written
|
||||
// during it on 1.4.3): sdk's flag stays 1 and its DT_INIT is not called again (a second call would protect its
|
||||
// locked RELRO again, and the SDK aborts).
|
||||
sdk_first = plugins_start(c, module_named("sdk"));
|
||||
for (unsigned k = 0; k < sizeof inits_121 / sizeof *inits_121; k++) {
|
||||
const RtLoaded *m = module_named(expected_inits[k].name);
|
||||
uint64_t entries = m->init_array_size / 8;
|
||||
if (!m->init) rt_fatal("boot: %s has no DT_INIT", m->name);
|
||||
rt_log("boot: ENTER %s DT_INIT (%llu init_array entries)", m->name, (unsigned long long)entries);
|
||||
rt_call(c, m->init, 0);
|
||||
int deferred = sdk_first && m == module_named("sdk");
|
||||
if (!deferred) {
|
||||
rt_log("boot: ENTER %s DT_INIT (%llu init_array entries)", m->name, (unsigned long long)entries);
|
||||
rt_call(c, m->init, 0);
|
||||
}
|
||||
uint32_t state = ctor_state(m);
|
||||
rt_logf("boot: DT_INIT %s state=%u (%llu)\n", m->name, state, (unsigned long long)entries);
|
||||
if (state != CTOR_DONE) rt_fatal("boot: %s DT_INIT left its constructor flag at %u, not 2", m->name, state);
|
||||
if (state != (deferred ? CTOR_WAITING : CTOR_DONE))
|
||||
rt_fatal("boot: %s DT_INIT left its constructor flag at %u, not %d", m->name, state,
|
||||
deferred ? CTOR_WAITING : CTOR_DONE);
|
||||
if (entries != expected_inits[k].entries)
|
||||
rt_fatal("boot: %s has %llu init_array entries, this game version has %llu", m->name, (unsigned long long)entries,
|
||||
(unsigned long long)expected_inits[k].entries);
|
||||
@@ -118,8 +133,9 @@ void rt_boot_event(const char *what, Cpu *c, const char *detail) {
|
||||
rt_fatal("boot: checkpoint %s reached from %s, expected main+%#llx", detail, at,
|
||||
(unsigned long long)CHECKPOINT_RET);
|
||||
if (!plat_cas32(&inits_done, 0, 0)) rt_fatal("boot: checkpoint %s before DT_INIT", detail);
|
||||
for (int i = 0; i < ldr_count(); i++)
|
||||
if (ctor_state(ldr_module(i)) != CTOR_DONE)
|
||||
for (int i = 0; i < ldr_count(); i++) // a plugin's init does not run at play time (plugin_init.c)
|
||||
if (!ldr_module(i)->plugin && ctor_state(ldr_module(i)) != CTOR_DONE &&
|
||||
!(sdk_first && !strcmp(ldr_module(i)->name, "sdk") && ctor_state(ldr_module(i)) == CTOR_WAITING))
|
||||
rt_fatal("boot: checkpoint %s: %s constructor flag reads %u", detail, ldr_module(i)->name,
|
||||
ctor_state(ldr_module(i)));
|
||||
plat_xchg32(&checkpoint_seen, 1);
|
||||
@@ -341,11 +357,29 @@ static void prewarm_main(void *arg) {
|
||||
return;
|
||||
}
|
||||
|
||||
// --plugin-init DIR: the modules load and nn::init::Start runs as at boot, and its module-init callback runs sdk's
|
||||
// DT_INIT and each plugin's instead of the game's constructors, writes the record and exits (plugin_init.c). No game
|
||||
// constructor, nnMain, shader prewarm, graphics or audio runs.
|
||||
void rt_boot_plugin_init(void) {
|
||||
check_npdm();
|
||||
plugin_init_setup();
|
||||
ldr_load(rt_config()->exefs);
|
||||
rt_patches_init(); // the generated code reads the patch page
|
||||
cb_addr[0] = hostfn_register("<rtld loader_ready>", cb_loader_ready);
|
||||
cb_addr[1] = hostfn_register("<rtld module_inits>", cb_module_inits);
|
||||
cb_addr[2] = hostfn_register("<rtld module_finis>", cb_module_finis);
|
||||
hostfn_seal();
|
||||
rt_guest_start_ns = kern_now_ns();
|
||||
kern_run_on_guest_main(guest_main);
|
||||
rt_fatal("boot: the guest main thread ended");
|
||||
}
|
||||
|
||||
void rt_boot(void) {
|
||||
check_npdm();
|
||||
if (!rt_config()->shot) vk_pipeline_async_enable(); // a --shot image must not depend on build timing
|
||||
// Shaders and pipelines recorded in earlier runs are made ready while the modules load; the guest waits for them.
|
||||
PlatThread *warm = plat_thread_new(prewarm_main, NULL, "prewarm");
|
||||
plugins_setup(); // a mod plugin's environment (plugin_init.c), before its imports bind
|
||||
ldr_load(rt_config()->exefs);
|
||||
rt_patches_init();
|
||||
mods_exefs_switch(); // after the patch sets' settings: an enabled mod's ExeFS patches on
|
||||
|
||||
+59
-43
@@ -14,6 +14,7 @@
|
||||
|
||||
#include "cfg.h"
|
||||
#include "host.h"
|
||||
#include "input_map.h"
|
||||
#include "platform/platform.h"
|
||||
|
||||
#define PREFIX "TOTK_"
|
||||
@@ -32,15 +33,15 @@ 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", "AMIIBO_DIR", "ANISO", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "AUDIO_CHANNELS", "AUDIO_DEVICE", "AUDIO_OFF", "AUDIO_PREFILL_MS",
|
||||
"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",
|
||||
"BACKGROUND_WINDOW", "BIND_A", "BIND_B", "BIND_DOWN", "BIND_L", "BIND_LCLICK", "BIND_LEFT", "BIND_LSTICK_DOWN", "BIND_LSTICK_LEFT",
|
||||
"BIND_LSTICK_RIGHT", "BIND_LSTICK_UP", "BIND_MINUS",
|
||||
"BIND_PLUS", "BIND_R", "BIND_RCLICK", "BIND_RIGHT", "BIND_RSTICK_DOWN", "BIND_RSTICK_LEFT", "BIND_RSTICK_RIGHT", "BIND_RSTICK_UP",
|
||||
"BIND_SHAKE",
|
||||
"BIND_INC", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y",
|
||||
"BIND_ZL", "BIND_ZR", "BLOCK_VIEWS_3D", "CLIMB_FIX", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA",
|
||||
"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_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR",
|
||||
"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", "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_QUEUE",
|
||||
"FREEZE_IDLE", "FREE_CORES",
|
||||
@@ -50,24 +51,24 @@ static const char *const known[] = {
|
||||
"GAMEPLAY_ULTRAHAND_C_AXIS", "GAMEPLAY_ULTRAHAND_DISTANCE", "GAMEPLAY_ULTRAHAND_ROTATE", "GAMEPLAY_WEAPON_SENSITIVITY",
|
||||
"GAMEPLAY_WEAPON_WHEEL",
|
||||
"GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "GRASS_RANGE",
|
||||
"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", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "KSPIN_US", "LANG", "LIB_PREBUILD",
|
||||
"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",
|
||||
"MEM_RESERVE_MIB", "MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MODS_REBUILD", "MOTION", "MOUSE_AIM_SCALE", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_ASPECT", "MOVIE_HOST", "MOVIE_PACE",
|
||||
"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_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "POINTER_IMAGE",
|
||||
"ONE_PER_CORE", "OPERATION_MODE", "OPTREF_GUARD", "OUTPUT_RES", "PAD_LAYOUT", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_SCENE", "PCORE", "PCSS", "PCSS_K", "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", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_ASYNC", "REC_END", "REC_SPIN_US", "REEXEC", "REFLEX",
|
||||
"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",
|
||||
"ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RSTICK_DEADZONE", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE",
|
||||
"SHADER_MEMO", "SHADOW", "SHADOW_DEFER", "SHADOW_RANGE", "SHADOW_RES", "SHADOW_SCALE", "SHADOW_SNAP", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR",
|
||||
"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",
|
||||
"SWKBD_ANSWER", "SYNC_AHEAD",
|
||||
"SWKBD_TEST", "TEST_OOM", "TEST_PAD", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_BLOCK_MIB", "TEX_HEAP_EXTRA_MB", "TEX_MEMO", "TEX_RELEASED_MIB", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "UB_OVERLAY", "UB_OVERLAY_OUT", "UPSCALER", "VB_USED", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64",
|
||||
"VK_PRESENT", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VMA_BLOCK_MIB", "VOLUME", "VOLUME_MUSIC", "VOLUME_SFX", "VOLUME_VOICE", "VRAM_HEADROOM", "VRAM_LIMIT_MIB", "VS_OUTS",
|
||||
"WALK_KEY", "WALK_SCALE", "WB_EXACT", "WB_FENCE_LIMIT", "WB_MERGE", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_KEEP", "XLATE_PROCS",
|
||||
"SWKBD_TEST", "TEST_OOM", "TEST_PAD", "TEST_PAD_RUMBLE_MS", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_BLOCK_MIB", "TEX_HEAP_EXTRA_MB", "TEX_MEMO", "TEX_RELEASED_MIB", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "UB_OVERLAY", "UB_OVERLAY_OUT", "UPSCALER", "VB_USED", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64",
|
||||
"VK_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",
|
||||
};
|
||||
|
||||
@@ -75,29 +76,30 @@ static const char *const known[] = {
|
||||
static const struct { const char *key, *section; } sections[] = {
|
||||
{"FPS_LIMIT", "frame rate"}, {"FPS60", "frame rate"}, {"FRAME_QUEUE", "frame rate"},
|
||||
{"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"},
|
||||
{"CLIMB_FIX", "frame rate"},
|
||||
{"CLIMB_FIX", "frame rate"}, {"AUDIO_DRAIN_FIX", "frame rate"}, {"SHUTTER_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"},
|
||||
{"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"},
|
||||
{"HDR_UI_NITS", "display"}, {"HDR_HUE", "display"}, {"SHADOW_RES", "display"},
|
||||
{"DLAA", "display"}, {"DLSS", "display"}, {"DLSS_PRESET", "display"}, {"DLSS_CHAR_MASK", "display"}, {"REFLEX", "display"}, {"FXAA", "display"},
|
||||
{"DLAA", "display"}, {"DLSS", "display"}, {"DLSS_PRESET", "display"}, {"DLSS_CHAR_MASK", "display"}, {"DLSS_FIXED_EXPOSURE", "display"}, {"DLAA_EFFECTS_AFTER", "display"}, {"REFLEX", "display"}, {"FXAA", "display"},
|
||||
{"DEVICE_PROFILE", "display"}, {"ASSUME_FOCUS", "display"},
|
||||
{"DISCORD_RPC", "discord"}, {"DISCORD_APP_ID", "discord"}, {"DISCORD_IMAGE", "discord"},
|
||||
{"SHADOW_SCALE", "display"}, {"SHADOW_RANGE", "display"}, {"GRASS_RANGE", "display"}, {"CONTACT_SHADOWS", "display"},
|
||||
{"PCSS", "display"},
|
||||
{"MODS_DIR", "mods"}, {"MODS_ORDER", "mods"}, {"MODS_DISABLED", "mods"}, {"MODS_REBUILD", "mods"},
|
||||
{"MODS_DIR", "mods"}, {"MODS_ORDER", "mods"}, {"MODS_DISABLED", "mods"}, {"MODS_NO_CODE", "mods"}, {"MODS_REBUILD", "mods"}, {"MODS_WITHOUT_CODE", "mods"},
|
||||
{"TEX_HEAP_EXTRA_MB", "mods"},
|
||||
{"MENU_LANG", "language"}, {"MENU_FONT_FONTCONFIG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"},
|
||||
{"VOLUME", "audio"}, {"VOLUME_MUSIC", "audio"}, {"VOLUME_SFX", "audio"}, {"VOLUME_VOICE", "audio"}, {"AUDIO_CHANNELS", "audio"},
|
||||
{"AUDIO_DEVICE", "audio"},
|
||||
{"MOTION", "input"}, {"GYRO_CALIBRATION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"},
|
||||
{"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"},
|
||||
{"STICK_SENS", "input"},
|
||||
{"MENU_CURSOR", "input"}, {"MAP_CLICK", "input"}, {"DIALOGUE_CLICK", "input"}, {"POINTER_IMAGE", "input"}, {"MOUSE_MODE", "input"}, {"MOUSE_SENS", "input"}, {"MOUSE_AIM_SCALE", "input"}, {"WALK_KEY", "input"}, {"WALK_SCALE", "input"}, {"INPUT_RECORD", "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"}, {"INPUT_RECORD", "input"},
|
||||
{"BIND_A", "input"}, {"BIND_B", "input"}, {"BIND_X", "input"}, {"BIND_Y", "input"}, {"BIND_LCLICK", "input"},
|
||||
{"BIND_RCLICK", "input"}, {"BIND_L", "input"}, {"BIND_R", "input"}, {"BIND_ZL", "input"}, {"BIND_ZR", "input"},
|
||||
{"BIND_PLUS", "input"}, {"BIND_MINUS", "input"}, {"BIND_LEFT", "input"}, {"BIND_UP", "input"},
|
||||
@@ -106,16 +108,16 @@ static const struct { const char *key, *section; } sections[] = {
|
||||
{"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"},
|
||||
{"TIMER_1MS", "performance"}, {"PIPE_WAIT", "performance"}, {"PIPE_SKIP", "performance"},
|
||||
{"LIB_PREBUILD", "performance"}, {"LIB_PREBUILD_THREADS", "performance"}, {"PIPE_PREBUILD", "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"},
|
||||
{"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"},
|
||||
{"OPTREF_GUARD", "performance"}, {"ABILITY_GUARD", "performance"}, {"REPORT_GUARD", "performance"},
|
||||
{"TRACE", "diagnostics"}, {"FLIGHT", "diagnostics"}, {"PASS_CRUMBS", "diagnostics"}, {"FLIGHT_SPIKE_MS", "diagnostics"},
|
||||
{"WB_FENCE_LIMIT", "diagnostics"}, {"WB_MERGE", "diagnostics"}, {"WB_EXACT", "diagnostics"},
|
||||
{"MV_SURVEY", "diagnostics"},
|
||||
{"TRACE", "diagnostics"}, {"FLIGHT", "diagnostics"}, {"PASS_CRUMBS", "diagnostics"}, {"ADDR_REPORT", "diagnostics"}, {"FLIGHT_SPIKE_MS", "diagnostics"},
|
||||
{"WB_FENCE_LIMIT", "diagnostics"}, {"WB_MERGE", "diagnostics"}, {"WB_EXACT", "diagnostics"}, {"WB_EAGER", "diagnostics"},
|
||||
{"MV_SURVEY", "diagnostics"}, {"PLUGIN_TRACE", "diagnostics"},
|
||||
{"GAMEPLAY_TWEAKS_ENABLED", "gameplay tweaks"}, {"GAMEPLAY_ULTRAHAND_ROTATE", "gameplay tweaks"},
|
||||
{"GAMEPLAY_ULTRAHAND_C_AXIS", "gameplay tweaks"}, {"GAMEPLAY_ULTRAHAND_DISTANCE", "gameplay tweaks"},
|
||||
{"GAMEPLAY_ITEM_WHEEL", "gameplay tweaks"}, {"GAMEPLAY_ITEM_AD", "gameplay tweaks"},
|
||||
@@ -136,10 +138,11 @@ static const CfgMeta metas[] = {
|
||||
{"VK_PRESENT", "mailbox", "mailbox|fifo|immediate", LIVE}, {"GPU_INDEX", "", NULL, RESTART},
|
||||
{"PERF_OVERLAY", "off", "off|fps|full", LIVE},
|
||||
{"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART},
|
||||
{"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},
|
||||
{"DLAA", "0", "0|1", RESTART}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance|ultra_performance", LIVE},
|
||||
{"DLSS_PRESET", "default", "default|k|j", LIVE},
|
||||
{"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},
|
||||
{"LOD_STEADY", "0", "0|1", RESTART}, // sets steady
|
||||
{"ASPECT", "fit", "fit|stretch", LIVE}, {"MOVIE_ASPECT", "keep", "keep|stretch", LIVE}, {"FOV", "100", "70..140", LIVE},
|
||||
@@ -160,21 +163,23 @@ static const CfgMeta metas[] = {
|
||||
{"FPS_LIMIT", "60", "30|40|45|60|90|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"FRAME_QUEUE", "0", "0|1", LIVE},
|
||||
{"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART},
|
||||
{"MODS_REBUILD", "auto", "auto|off", RESTART},
|
||||
{"HIGHFPS_FIX", "1", "0|1", RESTART}, {"CLIMB_FIX", "1", "0|1", 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},
|
||||
{"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)
|
||||
// Sound, Controls, Menu
|
||||
{"VOLUME", "100", "0..100", LIVE}, {"VOLUME_MUSIC", "100", "0..100", LIVE}, {"VOLUME_SFX", "100", "0..100", LIVE}, {"VOLUME_VOICE", "100", "0..100", LIVE}, {"AUDIO_CHANNELS", "stereo", "auto|stereo|5.1", RESTART},
|
||||
{"AUDIO_DEVICE", "", NULL, LIVE}, // audio_mixer.c output_worker: a device name, empty for the system default
|
||||
{"MOTION", "1", "0|1", LIVE}, {"GYRO_CALIBRATION", "1", "0|1", LIVE},
|
||||
{"MOTION", "1", "0|1", LIVE}, {"GYRO_CALIBRATION", "1", "0|1", LIVE}, {"GYRO_AUTO_BIAS", "0", "0|1", LIVE},
|
||||
{"RUMBLE_STRENGTH", "130", "0..300", LIVE}, {"RUMBLE_CURVE", "0.6", "0.2..1.5", LIVE},
|
||||
// Written by the Calibrate gyro row (motion_fusion.c save_bias), not by hand; read by input.c pad_bias_select when a
|
||||
// controller connects and gyro_bias_pad names it.
|
||||
{"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},
|
||||
{"PROMPTS", "nintendo", "nintendo|xbox|pc", RESTART},
|
||||
{"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},
|
||||
{"MOUSE_MODE", "direct", "stick|direct", LIVE},
|
||||
@@ -182,6 +187,8 @@ static const CfgMeta metas[] = {
|
||||
{"MAP_CLICK", "0", "0|1", LIVE}, // input.c: the left mouse button is A on the Purah Pad's map
|
||||
{"DIALOGUE_CLICK", "0", "0|1", LIVE}, // menu_cursor.c: in a dialogue box left click is B, right click A
|
||||
{"POINTER_IMAGE", "0", "0|1", LIVE}, // input_win.c / input_sdl.c: the game window's own pointer (cursor_art.c)
|
||||
{"QUICKSAVE", "0", "0|1", LIVE}, // quicksave.c: one key saves (an autosave), another loads it
|
||||
{"QUICKSAVE_KEY", "f6", NULL, LIVE}, {"QUICKLOAD_KEY", "f7", NULL, LIVE}, // Half-Life's keys; a key name or none
|
||||
{"WALK_KEY", "none", NULL, LIVE}, {"WALK_SCALE", "0.51", "0.2..0.9", LIVE},
|
||||
// Gameplay Tweaks
|
||||
{"GAMEPLAY_TWEAKS_ENABLED", "0", "0|1", LIVE},
|
||||
@@ -209,7 +216,7 @@ static const CfgMeta metas[] = {
|
||||
{"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},
|
||||
{"LIB_PREBUILD", "1", "0|1", RESTART}, {"LIB_PREBUILD_THREADS", "", "1..64", RESTART},
|
||||
{"BARRIER_MERGE", "0", "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},
|
||||
@@ -230,7 +237,10 @@ static const CfgMeta metas[] = {
|
||||
// diagnostics
|
||||
{"TRACE", "", NULL, RESTART}, {"FLIGHT", "0", "0|1", RESTART}, {"FLIGHT_SPIKE_MS", "100", "0..60000", RESTART},
|
||||
{"WB_FENCE_LIMIT", "65536", "0..1073741824", RESTART}, {"WB_MERGE", "1", "0|1", RESTART}, {"WB_EXACT", "1", "0|1", RESTART},
|
||||
{"WB_EAGER", "1", "0|1|check", RESTART}, // vk_texture.c: part of sync_ahead; 0 and check for comparing
|
||||
{"PASS_CRUMBS", "", "0|1", RESTART}, // vk_crumbs.c pass marks; unset: VK_AMD_buffer_marker only
|
||||
{"ADDR_REPORT", "0", "0|1", RESTART}, // vk_device.c GPU address map for device faults
|
||||
{"PLUGIN_TRACE", "0", "0|1", RESTART}, // plugin_init.c: the first call of each mod plugin hook entry
|
||||
{"INPUT_RECORD", "", NULL, RESTART},
|
||||
};
|
||||
|
||||
@@ -383,8 +393,8 @@ static const char *raw_get(const char *name) {
|
||||
// picture between black bars. The sizes are the ones the installer lays the HUD out for (installer/steps.py
|
||||
// ASPECT_SIZES, ui/menu.cpp row_output_res): of the display's shape within 1%, the smallest at least 1080 high that fits
|
||||
// the display, else the largest that fits. A 16:9 display, an unknown one or one of another shape keeps 1920x1080.
|
||||
// Xbox and keyboard prompts need their folder for that size's shape too (romfs-patches-xbox-<w>x<h>, -xbox-label-,
|
||||
// -pc-, written by installer/steps.py Shapes for the style totk.ini selects and the connected displays' shapes): they
|
||||
// Xbox, PlayStation and keyboard prompts need their folder for that size's shape too (romfs-patches-<style>-<w>x<h>,
|
||||
// written by installer/steps.py Shapes for the style totk.ini selects and the connected displays' shapes): they
|
||||
// keep 1920x1080 when it is missing, as in a source build without make_romfs_patches.py --prompts <style> --aspect or
|
||||
// after a switch of prompts in the menu, where a default of another shape would trade the prompts the player chose for
|
||||
// the Switch ones.
|
||||
@@ -414,22 +424,21 @@ int cfg_shape_size(unsigned w, unsigned h, unsigned out[2]) {
|
||||
}
|
||||
|
||||
static char screen_res[16]; // set once by cfg_init, "" for none
|
||||
// romfs-patches-xbox-, romfs-patches-xbox-label- and romfs-patches-pc-<screen_res> have a manifest (set once by
|
||||
// cfg_init)
|
||||
static const char *const screen_folders[3] = {"romfs-patches-xbox", "romfs-patches-xbox-label", "romfs-patches-pc"};
|
||||
static int screen_prompts[3];
|
||||
// Which pad and keyboard prompts' folders have a manifest at screen_res's shape (<folder>-<screen_res>; set once by
|
||||
// cfg_init): the folders input_map.c input_prompts_folder names
|
||||
static const char *const screen_folders[5] = {"romfs-patches-xbox", "romfs-patches-xbox-label",
|
||||
"romfs-patches-playstation", "romfs-patches-playstation-xbox",
|
||||
"romfs-patches-pc"};
|
||||
static int screen_prompts[5];
|
||||
|
||||
// Whether the prompts in effect have their folder at screen_res. The same picks as input_map.c input_prompts_pick and
|
||||
// input_prompts_folder: an unknown or empty value is the Nintendo prompts, an unset one Xbox while the pad layout is
|
||||
// "xbox_prompts"; the Xbox prompts take romfs-patches-xbox with the Nintendo pad layout (or "xbox_prompts") and
|
||||
// romfs-patches-xbox-label with any other.
|
||||
// Whether the prompts in effect have their folder at screen_res: the folder input_map.c input_prompts_pick and
|
||||
// input_prompts_folder pick at start. The game's own prompts need none.
|
||||
static int shape_keeps_prompts(void) {
|
||||
const char *p = raw_get(PREFIX "PROMPTS"), *l = raw_get(PREFIX "PAD_LAYOUT");
|
||||
if (p && *p && !strcasecmp(p, "pc")) return screen_prompts[2];
|
||||
int xbox = p && *p ? !strcasecmp(p, "xbox") : l && !strcasecmp(l, "xbox_prompts");
|
||||
if (!xbox) return 1;
|
||||
int by_position = l && (!strcasecmp(l, "nintendo") || !strcasecmp(l, "xbox_prompts"));
|
||||
return screen_prompts[by_position ? 0 : 1];
|
||||
const char *layout = raw_get(PREFIX "PAD_LAYOUT");
|
||||
const char *want = input_prompts_folder(input_prompts_pick(raw_get(PREFIX "PROMPTS"), layout), layout);
|
||||
for (int i = 0; want && i < 5; i++)
|
||||
if (!strcmp(screen_folders[i], want)) return screen_prompts[i];
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void screen_default(void) {
|
||||
@@ -447,13 +456,20 @@ static void screen_default(void) {
|
||||
if (best < 0) best = fit;
|
||||
if (best < 0) return;
|
||||
snprintf(screen_res, sizeof screen_res, "%ux%u", SHAPED[best][0], SHAPED[best][1]);
|
||||
for (int i = 0; i < 3; i++)
|
||||
for (int i = 0; i < 5; i++)
|
||||
screen_prompts[i] = romfs_shaped_prompts_ready(screen_folders[i], SHAPED[best][0], SHAPED[best][1]);
|
||||
if (!raw_get(PREFIX "OUTPUT_RES") && shape_keeps_prompts())
|
||||
rt_log("cfg: the display is %dx%d: output_res defaults to %s, its shape (totk.ini output_res sets another)", sw,
|
||||
sh, screen_res);
|
||||
}
|
||||
|
||||
int cfg_screen_size(unsigned out[2]) {
|
||||
unsigned w = 0, h = 0;
|
||||
if (raw_get(PREFIX "OUTPUT_RES") || !screen_res[0] || sscanf(screen_res, "%ux%u", &w, &h) != 2) return 0;
|
||||
out[0] = w, out[1] = h;
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char *cfg_get(const char *name) {
|
||||
const char *v = raw_get(name);
|
||||
if (v || strncmp(name, PREFIX, PREFIX_LEN)) return v;
|
||||
|
||||
@@ -26,6 +26,12 @@ 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.
|
||||
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
|
||||
// starts for missing folders (romfs.c romfs_folders_prepare) makes them for this size, so after a prompts change the
|
||||
// next start takes the display's shape again. 0 when the player set output_res, a device profile is in use or the
|
||||
// display is 16:9.
|
||||
int cfg_screen_size(unsigned out[2]);
|
||||
// The device profile in use, "deck" or "desktop" (TOTK_DEVICE_PROFILE, else what the machine is).
|
||||
const char *cfg_device_profile(void);
|
||||
// Writes the keys cfg_set changed since the last save into totk.ini next to totk.exe (cfg_save_to: the file at path).
|
||||
|
||||
+79
-2
@@ -6,6 +6,7 @@
|
||||
#include <string.h>
|
||||
|
||||
#include "cfg.h"
|
||||
#include "fs.h"
|
||||
#include "host.h"
|
||||
#include "input.h"
|
||||
#include "input_map.h"
|
||||
@@ -135,6 +136,9 @@ int probe_cfg(void) {
|
||||
CHECK(m && EQ(m->def, "1") && m->live, "meta: fps60 defaults to 1 and is live");
|
||||
m = cfg_meta("ASYNC_PREEMPT");
|
||||
CHECK(m && EQ(m->values, "0|1|2") && !m->live, "meta: async_preempt takes 0|1|2 and needs a restart");
|
||||
m = cfg_meta("HUD_WIDTH");
|
||||
CHECK(m && EQ(m->def, "full") && EQ(m->values, "full|21:9|16:9") && !m->live,
|
||||
"meta: HUD width defaults to full and changes after restart");
|
||||
m = cfg_meta("totk_vk_present");
|
||||
CHECK(m && EQ(m->key, "VK_PRESENT") && EQ(m->values, "mailbox|fifo|immediate") && m->live,
|
||||
"meta: prefix and case are accepted");
|
||||
@@ -330,14 +334,27 @@ int probe_cfg(void) {
|
||||
EQ(input_prompts_folder(PROMPTS_XBOX, "auto"), "romfs-patches-xbox-label") &&
|
||||
EQ(input_prompts_folder(PROMPTS_XBOX, NULL), "romfs-patches-xbox-label"),
|
||||
"prompts: the face buttons by position for the Nintendo layout, by label for xbox and auto");
|
||||
CHECK(input_prompts_pick("PlayStation", "nintendo") == PROMPTS_PLAYSTATION &&
|
||||
input_prompts_pick("playstation", "xbox") == PROMPTS_PLAYSTATION &&
|
||||
input_prompts_pick("ps", "auto") == PROMPTS_PLAYSTATION,
|
||||
"prompts: PlayStation, any case");
|
||||
CHECK(EQ(input_prompts_folder(PROMPTS_PLAYSTATION, "nintendo"), "romfs-patches-playstation") &&
|
||||
EQ(input_prompts_folder(PROMPTS_PLAYSTATION, "xbox_prompts"), "romfs-patches-playstation") &&
|
||||
EQ(input_prompts_folder(PROMPTS_PLAYSTATION, "xbox"), "romfs-patches-playstation-xbox") &&
|
||||
EQ(input_prompts_folder(PROMPTS_PLAYSTATION, "auto"), "romfs-patches-playstation-xbox") &&
|
||||
EQ(input_prompts_folder(PROMPTS_PLAYSTATION, NULL), "romfs-patches-playstation-xbox"),
|
||||
"prompts: the PlayStation shapes by position for the Nintendo layout, by label for xbox and auto");
|
||||
// romfs-patches-xbox shows A as B (tests/romfs_prompts_test.py checks the folders' contents). It is right exactly
|
||||
// where the layout puts A on the east button, which an Xbox pad labels B.
|
||||
// where the layout puts A on the east button, which an Xbox pad labels B. The PlayStation folder shows A as the
|
||||
// circle there, so its name follows the same split.
|
||||
input_map_reset();
|
||||
static const char *const layouts[] = {"nintendo", "xbox", "auto", "xbox_prompts"};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
int a_east = input_map_pad_buttons((uint8_t[PAD_COUNT]){[PAD_EAST] = 1}, input_pad_layout_pick(layouts[i], 0)) == 1ull << B_A;
|
||||
CHECK(a_east == EQ(input_prompts_folder(PROMPTS_XBOX, layouts[i]), "romfs-patches-xbox"),
|
||||
"prompts: the folder names A as B exactly when the layout puts A on the button labelled B");
|
||||
CHECK(a_east == EQ(input_prompts_folder(PROMPTS_PLAYSTATION, layouts[i]), "romfs-patches-playstation"),
|
||||
"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.
|
||||
@@ -363,12 +380,68 @@ int probe_cfg(void) {
|
||||
}
|
||||
snprintf(f, sizeof f, "%s/romfs-index.bin", dir);
|
||||
plat_setenv("TOTK_ROMFS_INDEX", f);
|
||||
plat_setenv("TOTK_HUD_WIDTH", NULL);
|
||||
static const char *const capped[] = {"romfs-patches-2560x1080-hud16x9",
|
||||
"romfs-patches-xbox-2560x1080-hud16x9",
|
||||
"romfs-patches-3840x1080-hud21x9"};
|
||||
for (size_t i = 0; i < sizeof capped / sizeof *capped; i++) {
|
||||
snprintf(f, sizeof f, "%s/%s/manifest.tsv", dir, capped[i]);
|
||||
plat_file_delete(f);
|
||||
}
|
||||
cfg_set("TOTK_HUD_WIDTH", "full");
|
||||
CHECK(romfs_shaped_ready(2560, 1080) && romfs_shaped_ready(5120, 2160) && !romfs_shaped_ready(3440, 1440),
|
||||
"shape: 5120x2160 finds 2560x1080's layout folder, 3440x1440 does not");
|
||||
CHECK(romfs_shaped_prompts_ready("romfs-patches-xbox", 5120, 2160) &&
|
||||
!romfs_shaped_prompts_ready("romfs-patches-xbox", 2560, 1080) &&
|
||||
!romfs_shaped_prompts_ready("romfs-patches-pc", 5120, 2160),
|
||||
"shape: an older install's exact-size prompts folder serves that size only");
|
||||
cfg_set("TOTK_HUD_WIDTH", "16:9");
|
||||
CHECK(romfs_shaped_ready(5120, 2160) && romfs_folders_missing(5120, 2160, NULL) == ROMFS_NEED_LAYOUT,
|
||||
"HUD: a full layout allows wide output but does not hide a missing selected cap");
|
||||
for (size_t i = 0; i < sizeof capped / sizeof *capped; i++) {
|
||||
snprintf(f, sizeof f, "%s/%s", dir, capped[i]);
|
||||
plat_file_mkdir_p(f);
|
||||
snprintf(f, sizeof f, "%s/%s/manifest.tsv", dir, capped[i]);
|
||||
plat_file_write(f, "#\n", 2);
|
||||
}
|
||||
CHECK(romfs_folders_missing(5120, 2160, "romfs-patches-xbox") == ROMFS_NEED_PROMPTS &&
|
||||
romfs_folders_missing(5120, 2160, "romfs-patches-pc") ==
|
||||
(ROMFS_NEED_PROMPTS | ROMFS_NEED_SHAPED_PROMPTS),
|
||||
"HUD: canonical capped layouts serve aliases, including Xbox; missing PC prompts still need preparation");
|
||||
cfg_set("TOTK_HUD_WIDTH", "21:9");
|
||||
CHECK(romfs_folders_missing(5120, 2160, NULL) && !romfs_folders_missing(5120, 1440, NULL),
|
||||
"HUD: a different cap needs a different folder; 5120x1440 uses the 3840x1080 shape");
|
||||
cfg_set("TOTK_HUD_WIDTH", "full");
|
||||
CHECK(!romfs_shaped_ready(5120, 1440), "HUD: switching to full does not reuse a capped-only layout");
|
||||
cfg_set("TOTK_HUD_WIDTH", "21:9");
|
||||
CHECK(!romfs_folders_missing(1920, 1080, NULL), "HUD: 16:9 output ignores a wider cap");
|
||||
// The 16:9 prompts' folder is needed at every shape (an older setup or a failed step left it out); at 16:9
|
||||
// nothing shaped is
|
||||
CHECK(romfs_folders_missing(1920, 1080, "romfs-patches-playstation") == ROMFS_NEED_PROMPTS &&
|
||||
romfs_folders_missing(2560, 1440, "romfs-patches-playstation") == ROMFS_NEED_PROMPTS,
|
||||
"folders: missing 16:9 prompts are asked for at 16:9, without a shaped folder");
|
||||
snprintf(f, sizeof f, "%s/romfs-patches-playstation", dir);
|
||||
plat_file_mkdir_p(f);
|
||||
snprintf(f, sizeof f, "%s/romfs-patches-playstation/manifest.tsv", dir);
|
||||
plat_file_write(f, "#\n", 2);
|
||||
CHECK(!romfs_folders_missing(1920, 1080, "romfs-patches-playstation") &&
|
||||
(romfs_folders_missing(5120, 2160, "romfs-patches-playstation") &
|
||||
(ROMFS_NEED_PROMPTS | ROMFS_NEED_SHAPED_PROMPTS)) == ROMFS_NEED_SHAPED_PROMPTS,
|
||||
"folders: present 16:9 prompts leave only the shaped folder to make");
|
||||
plat_file_delete(f);
|
||||
plat_setenv("TOTK_ROMFS_PATCHES", "0");
|
||||
CHECK(!romfs_folders_missing(5120, 2160, NULL) && !romfs_folders_missing(1920, 1080, "romfs-patches-pc"),
|
||||
"HUD: explicit overlay overrides do not request generated layouts or prompts");
|
||||
plat_setenv("TOTK_ROMFS_PATCHES", NULL);
|
||||
// Without build-cache/rebuild.txt (a source build) nothing starts: the menu's notes keep "run the setup
|
||||
// again" and the start spawns nothing (romfs.c overlay_init)
|
||||
CHECK(!romfs_folders_can_prepare() && !romfs_folders_prepare(5120, 2160, "romfs-patches-pc"),
|
||||
"folders: no setup's tools, no generator");
|
||||
cfg_set("TOTK_HUD_WIDTH", "full");
|
||||
for (size_t i = 0; i < sizeof capped / sizeof *capped; i++) {
|
||||
snprintf(f, sizeof f, "%s/%s/manifest.tsv", dir, capped[i]);
|
||||
plat_file_delete(f);
|
||||
}
|
||||
plat_setenv("TOTK_ROMFS_INDEX", NULL);
|
||||
}
|
||||
uint8_t pd[PAD_COUNT] = {0};
|
||||
@@ -496,7 +569,11 @@ int probe_cfg(void) {
|
||||
char name[96];
|
||||
snprintf(name, sizeof name, "TOTK_%s", m->key);
|
||||
plat_setenv(name, "");
|
||||
CHECK(EQ(cfg_value(name), m->def), "cfg_value returns the table default");
|
||||
// cfg_get may supply a display or device-profile default (notably OUTPUT_RES on an ultrawide monitor).
|
||||
// The metadata default is used only when those leave the setting unset.
|
||||
const char *effective = cfg_get(name);
|
||||
CHECK(EQ(cfg_value(name), effective && *effective ? effective : m->def),
|
||||
"cfg_value uses the effective default, falling back to the metadata table");
|
||||
int ok = 0;
|
||||
if (!m->values) ok = 1;
|
||||
else if (strstr(m->values, "..")) {
|
||||
|
||||
+16
-7
@@ -516,9 +516,13 @@ static void plain_name(char *s) {
|
||||
|
||||
// ---- rebuild: code cheats and ExeFS patches the build lacks
|
||||
// The setup writes build-cache\rebuild.txt (installer/steps.py write_rebuild_command), the command that starts its
|
||||
// window in rebuild mode on this install folder, one argument per line. When an enabled mod has code cheats this build
|
||||
// lacks (CHEAT_REBUILD) or ExeFS patch files it lacks (mods_exefs_pending), the game runs it and exits; the setup lifts
|
||||
// and compiles them in and starts the game again.
|
||||
// window in rebuild mode on this install folder, one argument per line. The build kit's command (installer/layout.py)
|
||||
// is relative to the install folder: its program is taken from this exe's folder, and the command runs with that
|
||||
// folder as its working folder, against which the setup resolves its other arguments. When an enabled mod has code
|
||||
// cheats this build
|
||||
// lacks (CHEAT_REBUILD) or ExeFS patch files it lacks (mods_exefs_pending), or the build has a mod plugin whose file is
|
||||
// gone (ldr_plugins_gone: its mod was removed), the game runs it and exits; the setup lifts and compiles them in (or the
|
||||
// plugin out) and starts the game again.
|
||||
// build-cache\rebuild.skip holds the key of the cheats a rebuild was started for: a rebuild that failed or was
|
||||
// cancelled leaves them unbuilt, and the same set does not start it again. TOTK_MODS_REBUILD=off never starts it.
|
||||
// Scripted runs (--seconds, --boot) never start it.
|
||||
@@ -532,7 +536,7 @@ static void rebuild_if_needed(const char *dir) {
|
||||
key = (key ^ fnv(c->info.key, strlen(c->info.key))) * 0x01000193u;
|
||||
key = (key ^ c->content) * 0x01000193u;
|
||||
}
|
||||
int patches = mods_exefs_pending(&key);
|
||||
int patches = mods_exefs_pending(&key) + ldr_plugins_gone(&key);
|
||||
if (!need && !patches) return;
|
||||
char cmd_path[PLAT_PATH_MAX + 64], skip_path[PLAT_PATH_MAX + 64], skip[16] = "", want[16];
|
||||
snprintf(cmd_path, sizeof cmd_path, "%sbuild-cache" SEP "rebuild.txt", dir);
|
||||
@@ -548,12 +552,13 @@ static void rebuild_if_needed(const char *dir) {
|
||||
char *cmd = why ? NULL : read_text(cmd_path);
|
||||
if (!why && !cmd) why = "no build-cache/rebuild.txt (a build without the setup)";
|
||||
if (why) {
|
||||
rt_log("cheats: %d code cheats and %d ExeFS patch files are not built into the game; no rebuild: %s", need,
|
||||
rt_log("cheats: %d code cheats and %d ExeFS patch files or plugins differ from the build; no rebuild: %s", need,
|
||||
patches, why);
|
||||
free(cmd);
|
||||
return;
|
||||
}
|
||||
const char *argv[32];
|
||||
char program[PLAT_PATH_MAX + 64];
|
||||
int argc = 0;
|
||||
for (char *line = cmd; line && *line && argc < 31;) {
|
||||
char *end = strchr(line, '\n'), *next = end ? end + 1 : NULL;
|
||||
@@ -564,13 +569,17 @@ static void rebuild_if_needed(const char *dir) {
|
||||
line = next;
|
||||
}
|
||||
argv[argc] = NULL;
|
||||
// CreateProcess resolves a relative program against this process's working folder, which a shortcut may set
|
||||
if (argc && !plat_path_absolute(argv[0]) &&
|
||||
snprintf(program, sizeof program, "%s%s", dir, argv[0]) < (int)sizeof program)
|
||||
argv[0] = program;
|
||||
if (argc < 2 || !plat_file_write(skip_path, want, strlen(want))) {
|
||||
rt_log("cheats: %d code cheats and %d ExeFS patch files are not built into the game; cannot start the "
|
||||
rt_log("cheats: %d code cheats and %d ExeFS patch files or plugins differ from the build; cannot start the "
|
||||
"rebuild (%s)", need, patches, cmd_path);
|
||||
free(cmd);
|
||||
return;
|
||||
}
|
||||
rt_log("cheats: %d code cheats and %d ExeFS patch files are not built into the game; starting the rebuild: %s",
|
||||
rt_log("cheats: %d code cheats and %d ExeFS patch files or plugins differ from the build; starting the rebuild: %s",
|
||||
need, patches, argv[0]);
|
||||
int ok = plat_spawn(argv, dir);
|
||||
free(cmd);
|
||||
|
||||
+218
-199
@@ -1,9 +1,9 @@
|
||||
// Generated by tools/build_shaders.py from runtime/shaders/contact_shadow.comp; do not edit.
|
||||
// source sha256 88275d28f96ea19281dbcd08a440ff79821716210894596ffb05ba7bc572dc9a
|
||||
// source sha256 e44a73a42aed3d5c2ac3a0a7e8809234f6175f8e331d30f93331ae9ca32fda71
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
static const uint32_t contact_shadow_spv[] = {
|
||||
0x07230203, 0x00010300, 0x000d000b, 0x000003e4, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
|
||||
0x07230203, 0x00010300, 0x000d000b, 0x0000040b, 0x00000000, 0x00020011, 0x00000001, 0x00020011,
|
||||
0x00000031, 0x0006000b, 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e,
|
||||
0x00000000, 0x00000001, 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000011f,
|
||||
0x00060010, 0x00000004, 0x00000011, 0x00000008, 0x00000008, 0x00000001, 0x00030047, 0x00000033,
|
||||
@@ -11,8 +11,9 @@ static const uint32_t contact_shadow_spv[] = {
|
||||
0x00000001, 0x00000023, 0x00000010, 0x00050048, 0x00000033, 0x00000002, 0x00000023, 0x00000020,
|
||||
0x00050048, 0x00000033, 0x00000003, 0x00000023, 0x00000030, 0x00040047, 0x00000086, 0x00000021,
|
||||
0x00000000, 0x00040047, 0x00000086, 0x00000022, 0x00000000, 0x00040047, 0x0000011f, 0x0000000b,
|
||||
0x0000001c, 0x00040047, 0x000001ff, 0x00000021, 0x00000001, 0x00040047, 0x000001ff, 0x00000022,
|
||||
0x00000000, 0x00040047, 0x0000021c, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 0x00030021,
|
||||
0x0000001c, 0x00040047, 0x00000162, 0x00000021, 0x00000002, 0x00040047, 0x00000162, 0x00000022,
|
||||
0x00000000, 0x00040047, 0x00000172, 0x00000021, 0x00000001, 0x00040047, 0x00000172, 0x00000022,
|
||||
0x00000000, 0x00040047, 0x00000242, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, 0x00030021,
|
||||
0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006,
|
||||
0x00000002, 0x00040017, 0x0000000a, 0x00000006, 0x00000003, 0x00040015, 0x00000019, 0x00000020,
|
||||
0x00000001, 0x00040017, 0x0000001a, 0x00000019, 0x00000002, 0x0004002b, 0x00000006, 0x00000027,
|
||||
@@ -34,22 +35,23 @@ static const uint32_t contact_shadow_spv[] = {
|
||||
0x00000000, 0x00040017, 0x0000011d, 0x0000002c, 0x00000003, 0x00040020, 0x0000011e, 0x00000001,
|
||||
0x0000011d, 0x0004003b, 0x0000011e, 0x0000011f, 0x00000001, 0x00040017, 0x00000120, 0x0000002c,
|
||||
0x00000002, 0x0004002b, 0x00000006, 0x00000140, 0x3f7fbe77, 0x0004002b, 0x00000006, 0x0000014c,
|
||||
0x42a00000, 0x0004002b, 0x00000006, 0x00000161, 0x3e99999a, 0x0004002b, 0x0000002c, 0x00000173,
|
||||
0x00000003, 0x0004002b, 0x00000006, 0x00000179, 0x3ecccccd, 0x0004002b, 0x00000006, 0x0000017a,
|
||||
0x40400000, 0x0004002b, 0x00000006, 0x0000017e, 0x3e19999a, 0x0004002b, 0x00000006, 0x00000180,
|
||||
0x3c23d70a, 0x0004002b, 0x00000006, 0x00000189, 0x3e800000, 0x0004002b, 0x00000019, 0x00000198,
|
||||
0x00000010, 0x0004002b, 0x00000006, 0x000001a4, 0xbd4ccccd, 0x0005002c, 0x00000007, 0x000001ae,
|
||||
0x00000110, 0x00000110, 0x00040017, 0x000001af, 0x000000b1, 0x00000002, 0x0005002c, 0x00000007,
|
||||
0x000001b6, 0x00000029, 0x00000029, 0x0004002b, 0x00000006, 0x000001d2, 0x3ca3d70a, 0x0004002b,
|
||||
0x00000006, 0x000001d4, 0x3b03126f, 0x0004002b, 0x00000006, 0x000001e9, 0x42200000, 0x0004002b,
|
||||
0x00000019, 0x000001f7, 0x00000003, 0x00090019, 0x000001fd, 0x00000006, 0x00000001, 0x00000000,
|
||||
0x00000000, 0x00000000, 0x00000002, 0x00000008, 0x00040020, 0x000001fe, 0x00000000, 0x000001fd,
|
||||
0x0004003b, 0x000001fe, 0x000001ff, 0x00000000, 0x0004002b, 0x0000002c, 0x0000021b, 0x00000008,
|
||||
0x0006002c, 0x0000011d, 0x0000021c, 0x0000021b, 0x0000021b, 0x0000003b, 0x0005002c, 0x00000007,
|
||||
0x000003df, 0x0000004e, 0x0000004e, 0x0005002c, 0x0000001a, 0x000003e0, 0x00000077, 0x00000077,
|
||||
0x0004002b, 0x00000006, 0x000003e2, 0x3dcccccd, 0x0004002b, 0x00000006, 0x000003e3, 0x3d800000,
|
||||
0x42a00000, 0x0004002b, 0x00000019, 0x0000015b, 0x00000003, 0x0004003b, 0x00000085, 0x00000162,
|
||||
0x00000000, 0x0004002b, 0x0000002c, 0x00000166, 0x00000003, 0x0004002b, 0x00000006, 0x0000016c,
|
||||
0x3fc00000, 0x00090019, 0x00000170, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000,
|
||||
0x00000002, 0x00000008, 0x00040020, 0x00000171, 0x00000000, 0x00000170, 0x0004003b, 0x00000171,
|
||||
0x00000172, 0x00000000, 0x0004002b, 0x00000006, 0x0000018a, 0x3e99999a, 0x0004002b, 0x00000006,
|
||||
0x000001a1, 0x3ecccccd, 0x0004002b, 0x00000006, 0x000001a2, 0x40400000, 0x0004002b, 0x00000006,
|
||||
0x000001a6, 0x3e19999a, 0x0004002b, 0x00000006, 0x000001a8, 0x3c23d70a, 0x0004002b, 0x00000006,
|
||||
0x000001b1, 0x3e800000, 0x0004002b, 0x00000019, 0x000001c0, 0x00000010, 0x0004002b, 0x00000006,
|
||||
0x000001cc, 0xbd4ccccd, 0x0005002c, 0x00000007, 0x000001d6, 0x00000110, 0x00000110, 0x00040017,
|
||||
0x000001d7, 0x000000b1, 0x00000002, 0x0005002c, 0x00000007, 0x000001de, 0x00000029, 0x00000029,
|
||||
0x0004002b, 0x00000006, 0x000001fa, 0x3ca3d70a, 0x0004002b, 0x00000006, 0x000001fc, 0x3b03126f,
|
||||
0x0004002b, 0x00000006, 0x00000211, 0x42200000, 0x0004002b, 0x0000002c, 0x00000241, 0x00000008,
|
||||
0x0006002c, 0x0000011d, 0x00000242, 0x00000241, 0x00000241, 0x0000003b, 0x0005002c, 0x00000007,
|
||||
0x00000406, 0x0000004e, 0x0000004e, 0x0005002c, 0x0000001a, 0x00000407, 0x00000077, 0x00000077,
|
||||
0x0004002b, 0x00000006, 0x00000409, 0x3dcccccd, 0x0004002b, 0x00000006, 0x0000040a, 0x3d800000,
|
||||
0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x000300f7,
|
||||
0x0000021d, 0x00000000, 0x000300fb, 0x0000002d, 0x0000021e, 0x000200f8, 0x0000021e, 0x0004003d,
|
||||
0x00000243, 0x00000000, 0x000300fb, 0x0000002d, 0x00000244, 0x000200f8, 0x00000244, 0x0004003d,
|
||||
0x0000011d, 0x00000121, 0x0000011f, 0x0007004f, 0x00000120, 0x00000122, 0x00000121, 0x00000121,
|
||||
0x00000000, 0x00000001, 0x0004007c, 0x0000001a, 0x00000123, 0x00000122, 0x00050051, 0x00000019,
|
||||
0x00000125, 0x00000123, 0x00000000, 0x00060041, 0x00000037, 0x00000126, 0x00000035, 0x00000071,
|
||||
@@ -60,196 +62,213 @@ static const uint32_t contact_shadow_spv[] = {
|
||||
0x00060041, 0x00000037, 0x0000012f, 0x00000035, 0x00000071, 0x0000003b, 0x0004003d, 0x00000006,
|
||||
0x00000130, 0x0000012f, 0x0004006e, 0x00000019, 0x00000131, 0x00000130, 0x000500af, 0x000000b1,
|
||||
0x00000132, 0x0000012e, 0x00000131, 0x000200f9, 0x0000012c, 0x000200f8, 0x0000012c, 0x000700f5,
|
||||
0x000000b1, 0x00000133, 0x00000129, 0x0000021e, 0x00000132, 0x0000012b, 0x000300f7, 0x00000135,
|
||||
0x000000b1, 0x00000133, 0x00000129, 0x00000244, 0x00000132, 0x0000012b, 0x000300f7, 0x00000135,
|
||||
0x00000000, 0x000400fa, 0x00000133, 0x00000134, 0x00000135, 0x000200f8, 0x00000134, 0x000200f9,
|
||||
0x0000021d, 0x000200f8, 0x00000135, 0x0004003d, 0x00000084, 0x00000138, 0x00000086, 0x00040064,
|
||||
0x00000243, 0x000200f8, 0x00000135, 0x0004003d, 0x00000084, 0x00000138, 0x00000086, 0x00040064,
|
||||
0x00000083, 0x0000013a, 0x00000138, 0x0007005f, 0x00000032, 0x0000013b, 0x0000013a, 0x00000123,
|
||||
0x00000002, 0x00000036, 0x00050051, 0x00000006, 0x0000013c, 0x0000013b, 0x00000000, 0x000500bc,
|
||||
0x000000b1, 0x0000013e, 0x0000013c, 0x00000110, 0x000500be, 0x000000b1, 0x00000141, 0x0000013c,
|
||||
0x00000140, 0x000500a6, 0x000000b1, 0x00000142, 0x0000013e, 0x00000141, 0x000300f7, 0x00000144,
|
||||
0x00000000, 0x000400fa, 0x00000142, 0x00000143, 0x00000144, 0x000200f8, 0x00000143, 0x000200f9,
|
||||
0x0000021d, 0x000200f8, 0x00000144, 0x00060041, 0x00000037, 0x00000148, 0x00000035, 0x00000036,
|
||||
0x00000243, 0x000200f8, 0x00000144, 0x00060041, 0x00000037, 0x00000148, 0x00000035, 0x00000036,
|
||||
0x0000004a, 0x0004003d, 0x00000006, 0x00000149, 0x00000148, 0x00050085, 0x00000006, 0x0000014a,
|
||||
0x0000013c, 0x00000149, 0x000500ba, 0x000000b1, 0x0000014d, 0x0000014a, 0x0000014c, 0x000300f7,
|
||||
0x0000014f, 0x00000000, 0x000400fa, 0x0000014d, 0x0000014e, 0x0000014f, 0x000200f8, 0x0000014e,
|
||||
0x000200f9, 0x0000021d, 0x000200f8, 0x0000014f, 0x0004006f, 0x00000007, 0x00000153, 0x00000123,
|
||||
0x00050081, 0x00000007, 0x00000155, 0x00000153, 0x000003df, 0x00050041, 0x00000072, 0x00000156,
|
||||
0x000200f9, 0x00000243, 0x000200f8, 0x0000014f, 0x0004006f, 0x00000007, 0x00000153, 0x00000123,
|
||||
0x00050081, 0x00000007, 0x00000155, 0x00000153, 0x00000406, 0x00050041, 0x00000072, 0x00000156,
|
||||
0x00000035, 0x00000071, 0x0004003d, 0x00000032, 0x00000157, 0x00000156, 0x0007004f, 0x00000007,
|
||||
0x00000158, 0x00000157, 0x00000157, 0x00000002, 0x00000003, 0x00050085, 0x00000007, 0x00000159,
|
||||
0x00000155, 0x00000158, 0x0005008e, 0x00000007, 0x00000226, 0x00000159, 0x00000027, 0x00050083,
|
||||
0x00000007, 0x00000228, 0x00000226, 0x000001b6, 0x00050051, 0x00000006, 0x0000022a, 0x00000228,
|
||||
0x00000000, 0x00050085, 0x00000006, 0x0000022c, 0x0000022a, 0x0000014a, 0x00060041, 0x00000037,
|
||||
0x0000022d, 0x00000035, 0x00000036, 0x0000002d, 0x0004003d, 0x00000006, 0x0000022e, 0x0000022d,
|
||||
0x00050088, 0x00000006, 0x0000022f, 0x0000022c, 0x0000022e, 0x00050051, 0x00000006, 0x00000231,
|
||||
0x00000228, 0x00000001, 0x0004007f, 0x00000006, 0x00000232, 0x00000231, 0x00050085, 0x00000006,
|
||||
0x00000234, 0x00000232, 0x0000014a, 0x00060041, 0x00000037, 0x00000235, 0x00000035, 0x00000036,
|
||||
0x0000003b, 0x0004003d, 0x00000006, 0x00000236, 0x00000235, 0x00050088, 0x00000006, 0x00000237,
|
||||
0x00000234, 0x00000236, 0x0004007f, 0x00000006, 0x00000239, 0x0000014a, 0x00060050, 0x0000000a,
|
||||
0x0000023a, 0x0000022f, 0x00000237, 0x00000239, 0x0007004f, 0x00000007, 0x00000250, 0x00000157,
|
||||
0x00000157, 0x00000000, 0x00000001, 0x0004006e, 0x0000001a, 0x00000251, 0x00000250, 0x00050082,
|
||||
0x0000001a, 0x00000253, 0x00000251, 0x000003e0, 0x00050082, 0x0000001a, 0x00000255, 0x00000123,
|
||||
0x0000009d, 0x0008000c, 0x0000001a, 0x000002c8, 0x00000001, 0x0000002d, 0x00000255, 0x00000070,
|
||||
0x00000253, 0x0004006f, 0x00000007, 0x000002ca, 0x000002c8, 0x00050081, 0x00000007, 0x000002cc,
|
||||
0x000002ca, 0x000003df, 0x00050085, 0x00000007, 0x000002d0, 0x000002cc, 0x00000158, 0x0004003d,
|
||||
0x00000084, 0x000002d1, 0x00000086, 0x00040064, 0x00000083, 0x000002d3, 0x000002d1, 0x0007005f,
|
||||
0x00000032, 0x000002d4, 0x000002d3, 0x000002c8, 0x00000002, 0x00000036, 0x00050051, 0x00000006,
|
||||
0x000002d5, 0x000002d4, 0x00000000, 0x00050085, 0x00000006, 0x000002d8, 0x000002d5, 0x00000149,
|
||||
0x0005008e, 0x00000007, 0x000002de, 0x000002d0, 0x00000027, 0x00050083, 0x00000007, 0x000002e0,
|
||||
0x000002de, 0x000001b6, 0x00050051, 0x00000006, 0x000002e2, 0x000002e0, 0x00000000, 0x00050085,
|
||||
0x00000006, 0x000002e4, 0x000002e2, 0x000002d8, 0x00050088, 0x00000006, 0x000002e7, 0x000002e4,
|
||||
0x0000022e, 0x00050051, 0x00000006, 0x000002e9, 0x000002e0, 0x00000001, 0x0004007f, 0x00000006,
|
||||
0x000002ea, 0x000002e9, 0x00050085, 0x00000006, 0x000002ec, 0x000002ea, 0x000002d8, 0x00050088,
|
||||
0x00000006, 0x000002ef, 0x000002ec, 0x00000236, 0x0004007f, 0x00000006, 0x000002f1, 0x000002d8,
|
||||
0x00060050, 0x0000000a, 0x000002f2, 0x000002e7, 0x000002ef, 0x000002f1, 0x00050080, 0x0000001a,
|
||||
0x00000258, 0x00000123, 0x0000009d, 0x0008000c, 0x0000001a, 0x000002fe, 0x00000001, 0x0000002d,
|
||||
0x00000258, 0x00000070, 0x00000253, 0x0004006f, 0x00000007, 0x00000300, 0x000002fe, 0x00050081,
|
||||
0x00000007, 0x00000302, 0x00000300, 0x000003df, 0x00050085, 0x00000007, 0x00000306, 0x00000302,
|
||||
0x00000158, 0x0004003d, 0x00000084, 0x00000307, 0x00000086, 0x00040064, 0x00000083, 0x00000309,
|
||||
0x00000307, 0x0007005f, 0x00000032, 0x0000030a, 0x00000309, 0x000002fe, 0x00000002, 0x00000036,
|
||||
0x00050051, 0x00000006, 0x0000030b, 0x0000030a, 0x00000000, 0x00050085, 0x00000006, 0x0000030e,
|
||||
0x0000030b, 0x00000149, 0x0005008e, 0x00000007, 0x00000314, 0x00000306, 0x00000027, 0x00050083,
|
||||
0x00000007, 0x00000316, 0x00000314, 0x000001b6, 0x00050051, 0x00000006, 0x00000318, 0x00000316,
|
||||
0x00000000, 0x00050085, 0x00000006, 0x0000031a, 0x00000318, 0x0000030e, 0x00050088, 0x00000006,
|
||||
0x0000031d, 0x0000031a, 0x0000022e, 0x00050051, 0x00000006, 0x0000031f, 0x00000316, 0x00000001,
|
||||
0x0004007f, 0x00000006, 0x00000320, 0x0000031f, 0x00050085, 0x00000006, 0x00000322, 0x00000320,
|
||||
0x0000030e, 0x00050088, 0x00000006, 0x00000325, 0x00000322, 0x00000236, 0x0004007f, 0x00000006,
|
||||
0x00000327, 0x0000030e, 0x00060050, 0x0000000a, 0x00000328, 0x0000031d, 0x00000325, 0x00000327,
|
||||
0x00050082, 0x0000001a, 0x0000025b, 0x00000123, 0x000000a8, 0x0008000c, 0x0000001a, 0x00000334,
|
||||
0x00000001, 0x0000002d, 0x0000025b, 0x00000070, 0x00000253, 0x0004006f, 0x00000007, 0x00000336,
|
||||
0x00000334, 0x00050081, 0x00000007, 0x00000338, 0x00000336, 0x000003df, 0x00050085, 0x00000007,
|
||||
0x0000033c, 0x00000338, 0x00000158, 0x0004003d, 0x00000084, 0x0000033d, 0x00000086, 0x00040064,
|
||||
0x00000083, 0x0000033f, 0x0000033d, 0x0007005f, 0x00000032, 0x00000340, 0x0000033f, 0x00000334,
|
||||
0x00000002, 0x00000036, 0x00050051, 0x00000006, 0x00000341, 0x00000340, 0x00000000, 0x00050085,
|
||||
0x00000006, 0x00000344, 0x00000341, 0x00000149, 0x0005008e, 0x00000007, 0x0000034a, 0x0000033c,
|
||||
0x00000027, 0x00050083, 0x00000007, 0x0000034c, 0x0000034a, 0x000001b6, 0x00050051, 0x00000006,
|
||||
0x0000034e, 0x0000034c, 0x00000000, 0x00050085, 0x00000006, 0x00000350, 0x0000034e, 0x00000344,
|
||||
0x00050088, 0x00000006, 0x00000353, 0x00000350, 0x0000022e, 0x00050051, 0x00000006, 0x00000355,
|
||||
0x0000034c, 0x00000001, 0x0004007f, 0x00000006, 0x00000356, 0x00000355, 0x00050085, 0x00000006,
|
||||
0x00000358, 0x00000356, 0x00000344, 0x00050088, 0x00000006, 0x0000035b, 0x00000358, 0x00000236,
|
||||
0x0004007f, 0x00000006, 0x0000035d, 0x00000344, 0x00060050, 0x0000000a, 0x0000035e, 0x00000353,
|
||||
0x0000035b, 0x0000035d, 0x00050080, 0x0000001a, 0x0000025e, 0x00000123, 0x000000a8, 0x0008000c,
|
||||
0x0000001a, 0x0000036a, 0x00000001, 0x0000002d, 0x0000025e, 0x00000070, 0x00000253, 0x0004006f,
|
||||
0x00000007, 0x0000036c, 0x0000036a, 0x00050081, 0x00000007, 0x0000036e, 0x0000036c, 0x000003df,
|
||||
0x00050085, 0x00000007, 0x00000372, 0x0000036e, 0x00000158, 0x0004003d, 0x00000084, 0x00000373,
|
||||
0x00000086, 0x00040064, 0x00000083, 0x00000375, 0x00000373, 0x0007005f, 0x00000032, 0x00000376,
|
||||
0x00000375, 0x0000036a, 0x00000002, 0x00000036, 0x00050051, 0x00000006, 0x00000377, 0x00000376,
|
||||
0x00000000, 0x00050085, 0x00000006, 0x0000037a, 0x00000377, 0x00000149, 0x0005008e, 0x00000007,
|
||||
0x00000380, 0x00000372, 0x00000027, 0x00050083, 0x00000007, 0x00000382, 0x00000380, 0x000001b6,
|
||||
0x00050051, 0x00000006, 0x00000384, 0x00000382, 0x00000000, 0x00050085, 0x00000006, 0x00000386,
|
||||
0x00000384, 0x0000037a, 0x00050088, 0x00000006, 0x00000389, 0x00000386, 0x0000022e, 0x00050051,
|
||||
0x00000006, 0x0000038b, 0x00000382, 0x00000001, 0x0004007f, 0x00000006, 0x0000038c, 0x0000038b,
|
||||
0x00050085, 0x00000006, 0x0000038e, 0x0000038c, 0x0000037a, 0x00050088, 0x00000006, 0x00000391,
|
||||
0x0000038e, 0x00000236, 0x0004007f, 0x00000006, 0x00000393, 0x0000037a, 0x00060050, 0x0000000a,
|
||||
0x00000394, 0x00000389, 0x00000391, 0x00000393, 0x000500aa, 0x000000b1, 0x00000262, 0x00000125,
|
||||
0x00000036, 0x000400a8, 0x000000b1, 0x00000263, 0x00000262, 0x000300f7, 0x0000027a, 0x00000000,
|
||||
0x000400fa, 0x00000263, 0x00000264, 0x0000027a, 0x000200f8, 0x00000264, 0x00050051, 0x00000019,
|
||||
0x00000268, 0x00000253, 0x00000000, 0x000500b1, 0x000000b1, 0x00000269, 0x00000125, 0x00000268,
|
||||
0x000300f7, 0x00000278, 0x00000000, 0x000400fa, 0x00000269, 0x0000026a, 0x00000278, 0x000200f8,
|
||||
0x0000026a, 0x00050083, 0x00000006, 0x0000026f, 0x0000014a, 0x0000030e, 0x0006000c, 0x00000006,
|
||||
0x00000270, 0x00000001, 0x00000004, 0x0000026f, 0x00050083, 0x00000006, 0x00000275, 0x000002d8,
|
||||
0x0000014a, 0x0006000c, 0x00000006, 0x00000276, 0x00000001, 0x00000004, 0x00000275, 0x000500b8,
|
||||
0x000000b1, 0x00000277, 0x00000270, 0x00000276, 0x000200f9, 0x00000278, 0x000200f8, 0x00000278,
|
||||
0x000700f5, 0x000000b1, 0x00000279, 0x00000269, 0x00000264, 0x00000277, 0x0000026a, 0x000200f9,
|
||||
0x0000027a, 0x000200f8, 0x0000027a, 0x000700f5, 0x000000b1, 0x0000027b, 0x00000262, 0x0000014f,
|
||||
0x00000279, 0x00000278, 0x00050051, 0x00000019, 0x0000027d, 0x00000123, 0x00000001, 0x000500aa,
|
||||
0x000000b1, 0x0000027e, 0x0000027d, 0x00000036, 0x000400a8, 0x000000b1, 0x0000027f, 0x0000027e,
|
||||
0x000300f7, 0x00000296, 0x00000000, 0x000400fa, 0x0000027f, 0x00000280, 0x00000296, 0x000200f8,
|
||||
0x00000280, 0x00050051, 0x00000019, 0x00000284, 0x00000253, 0x00000001, 0x000500b1, 0x000000b1,
|
||||
0x00000285, 0x0000027d, 0x00000284, 0x000300f7, 0x00000294, 0x00000000, 0x000400fa, 0x00000285,
|
||||
0x00000286, 0x00000294, 0x000200f8, 0x00000286, 0x00050083, 0x00000006, 0x0000028b, 0x0000014a,
|
||||
0x0000037a, 0x0006000c, 0x00000006, 0x0000028c, 0x00000001, 0x00000004, 0x0000028b, 0x00050083,
|
||||
0x00000006, 0x00000291, 0x00000344, 0x0000014a, 0x0006000c, 0x00000006, 0x00000292, 0x00000001,
|
||||
0x00000004, 0x00000291, 0x000500b8, 0x000000b1, 0x00000293, 0x0000028c, 0x00000292, 0x000200f9,
|
||||
0x00000294, 0x000200f8, 0x00000294, 0x000700f5, 0x000000b1, 0x00000295, 0x00000285, 0x00000280,
|
||||
0x00000293, 0x00000286, 0x000200f9, 0x00000296, 0x000200f8, 0x00000296, 0x000700f5, 0x000000b1,
|
||||
0x00000297, 0x0000027e, 0x0000027a, 0x00000295, 0x00000294, 0x000300f7, 0x000002a1, 0x00000000,
|
||||
0x000400fa, 0x0000027b, 0x00000299, 0x0000029d, 0x000200f8, 0x00000299, 0x00050083, 0x0000000a,
|
||||
0x0000029c, 0x00000328, 0x0000023a, 0x000200f9, 0x000002a1, 0x000200f8, 0x0000029d, 0x00050083,
|
||||
0x0000000a, 0x000002a0, 0x0000023a, 0x000002f2, 0x000200f9, 0x000002a1, 0x000200f8, 0x000002a1,
|
||||
0x000700f5, 0x0000000a, 0x000003d5, 0x0000029c, 0x00000299, 0x000002a0, 0x0000029d, 0x000300f7,
|
||||
0x000002ac, 0x00000000, 0x000400fa, 0x00000297, 0x000002a4, 0x000002a8, 0x000200f8, 0x000002a4,
|
||||
0x00050083, 0x0000000a, 0x000002a7, 0x00000394, 0x0000023a, 0x000200f9, 0x000002ac, 0x000200f8,
|
||||
0x000002a8, 0x00050083, 0x0000000a, 0x000002ab, 0x0000023a, 0x0000035e, 0x000200f9, 0x000002ac,
|
||||
0x000200f8, 0x000002ac, 0x000700f5, 0x0000000a, 0x000003d6, 0x000002a7, 0x000002a4, 0x000002ab,
|
||||
0x000002a8, 0x0007000c, 0x0000000a, 0x000002b0, 0x00000001, 0x00000044, 0x000003d5, 0x000003d6,
|
||||
0x0006000c, 0x0000000a, 0x000002b1, 0x00000001, 0x00000045, 0x000002b0, 0x00050094, 0x00000006,
|
||||
0x000002b4, 0x000002b1, 0x0000023a, 0x000500ba, 0x000000b1, 0x000002b5, 0x000002b4, 0x00000110,
|
||||
0x000300f7, 0x000002bb, 0x00000000, 0x000400fa, 0x000002b5, 0x000002b6, 0x000002b9, 0x000200f8,
|
||||
0x000002b6, 0x0004007f, 0x0000000a, 0x000002b8, 0x000002b1, 0x000200f9, 0x000002bb, 0x000200f8,
|
||||
0x000002b9, 0x000200f9, 0x000002bb, 0x000200f8, 0x000002bb, 0x000700f5, 0x0000000a, 0x000003d7,
|
||||
0x000002b8, 0x000002b6, 0x000002b1, 0x000002b9, 0x00050041, 0x00000072, 0x00000167, 0x00000035,
|
||||
0x00000077, 0x0004003d, 0x00000032, 0x00000168, 0x00000167, 0x0008004f, 0x0000000a, 0x00000169,
|
||||
0x00000168, 0x00000168, 0x00000000, 0x00000001, 0x00000002, 0x00050094, 0x00000006, 0x0000016a,
|
||||
0x000003d7, 0x00000169, 0x0008000c, 0x00000006, 0x0000016b, 0x00000001, 0x00000031, 0x00000110,
|
||||
0x00000161, 0x0000016a, 0x000500bd, 0x000000b1, 0x0000016e, 0x0000016b, 0x00000110, 0x000300f7,
|
||||
0x00000170, 0x00000000, 0x000400fa, 0x0000016e, 0x0000016f, 0x00000170, 0x000200f8, 0x0000016f,
|
||||
0x000200f9, 0x0000021d, 0x000200f8, 0x00000170, 0x00060041, 0x00000037, 0x00000174, 0x00000035,
|
||||
0x00000077, 0x00000173, 0x0004003d, 0x00000006, 0x00000175, 0x00000174, 0x00050085, 0x00000006,
|
||||
0x00000178, 0x0000014a, 0x000003e2, 0x0008000c, 0x00000006, 0x0000017b, 0x00000001, 0x0000002b,
|
||||
0x00000178, 0x00000179, 0x0000017a, 0x00050085, 0x00000006, 0x0000017c, 0x00000175, 0x0000017b,
|
||||
0x00050085, 0x00000006, 0x00000181, 0x0000014a, 0x00000180, 0x00050081, 0x00000006, 0x00000182,
|
||||
0x0000017e, 0x00000181, 0x00050085, 0x00000006, 0x00000186, 0x0000017c, 0x000003e3, 0x00050094,
|
||||
0x00000006, 0x00000398, 0x00000153, 0x00000068, 0x0006000c, 0x00000006, 0x00000399, 0x00000001,
|
||||
0x0000000a, 0x00000398, 0x00050085, 0x00000006, 0x0000039a, 0x00000064, 0x00000399, 0x0006000c,
|
||||
0x00000006, 0x0000039b, 0x00000001, 0x0000000a, 0x0000039a, 0x00050081, 0x00000006, 0x0000018e,
|
||||
0x00000189, 0x0000039b, 0x00050085, 0x00000006, 0x0000018f, 0x00000186, 0x0000018e, 0x000200f9,
|
||||
0x00000192, 0x000200f8, 0x00000192, 0x000700f5, 0x00000006, 0x000003d9, 0x0000018f, 0x00000170,
|
||||
0x000001e7, 0x00000195, 0x000700f5, 0x00000019, 0x000003d8, 0x00000036, 0x00000170, 0x000001e4,
|
||||
0x00000195, 0x000500b1, 0x000000b1, 0x00000199, 0x000003d8, 0x00000198, 0x000400f6, 0x00000194,
|
||||
0x00000195, 0x00000000, 0x000400fa, 0x00000199, 0x00000193, 0x00000194, 0x000200f8, 0x00000193,
|
||||
0x0005008e, 0x0000000a, 0x000001a0, 0x00000169, 0x000003d9, 0x00050081, 0x0000000a, 0x000001a1,
|
||||
0x0000023a, 0x000001a0, 0x00050051, 0x00000006, 0x000001a3, 0x000001a1, 0x00000002, 0x000500be,
|
||||
0x000000b1, 0x000001a5, 0x000001a3, 0x000001a4, 0x000300f7, 0x000001a7, 0x00000000, 0x000400fa,
|
||||
0x000001a5, 0x000001a6, 0x000001a7, 0x000200f8, 0x000001a6, 0x000200f9, 0x00000194, 0x000200f8,
|
||||
0x000001a7, 0x0004007f, 0x00000006, 0x000003a1, 0x000001a3, 0x00050051, 0x00000006, 0x000003a3,
|
||||
0x000001a1, 0x00000000, 0x00050085, 0x00000006, 0x000003a4, 0x0000004e, 0x000003a3, 0x00050085,
|
||||
0x00000006, 0x000003a7, 0x000003a4, 0x0000022e, 0x00050088, 0x00000006, 0x000003a9, 0x000003a7,
|
||||
0x000003a1, 0x00050081, 0x00000006, 0x000003aa, 0x0000004e, 0x000003a9, 0x00050051, 0x00000006,
|
||||
0x000003ac, 0x000001a1, 0x00000001, 0x00050085, 0x00000006, 0x000003ad, 0x0000004e, 0x000003ac,
|
||||
0x00050085, 0x00000006, 0x000003b0, 0x000003ad, 0x00000236, 0x00050088, 0x00000006, 0x000003b2,
|
||||
0x000003b0, 0x000003a1, 0x00050083, 0x00000006, 0x000003b3, 0x0000004e, 0x000003b2, 0x00050050,
|
||||
0x00000007, 0x000003b4, 0x000003aa, 0x000003b3, 0x000500b8, 0x000001af, 0x000001b0, 0x000003b4,
|
||||
0x000001ae, 0x0004009a, 0x000000b1, 0x000001b1, 0x000001b0, 0x000400a8, 0x000000b1, 0x000001b2,
|
||||
0x000001b1, 0x000300f7, 0x000001b4, 0x00000000, 0x000400fa, 0x000001b2, 0x000001b3, 0x000001b4,
|
||||
0x000200f8, 0x000001b3, 0x000500ba, 0x000001af, 0x000001b7, 0x000003b4, 0x000001b6, 0x0004009a,
|
||||
0x000000b1, 0x000001b8, 0x000001b7, 0x000200f9, 0x000001b4, 0x000200f8, 0x000001b4, 0x000700f5,
|
||||
0x000000b1, 0x000001b9, 0x000001b1, 0x000001a7, 0x000001b8, 0x000001b3, 0x000300f7, 0x000001bb,
|
||||
0x00000000, 0x000400fa, 0x000001b9, 0x000001ba, 0x000001bb, 0x000200f8, 0x000001ba, 0x000200f9,
|
||||
0x00000194, 0x000200f8, 0x000001bb, 0x0004003d, 0x00000084, 0x000001be, 0x00000086, 0x00050085,
|
||||
0x00000007, 0x000001c3, 0x000003b4, 0x00000250, 0x0004006e, 0x0000001a, 0x000001c4, 0x000001c3,
|
||||
0x00040064, 0x00000083, 0x000001c5, 0x000001be, 0x0007005f, 0x00000032, 0x000001c6, 0x000001c5,
|
||||
0x000001c4, 0x00000002, 0x00000036, 0x00050051, 0x00000006, 0x000001c7, 0x000001c6, 0x00000000,
|
||||
0x00050085, 0x00000006, 0x000001ca, 0x000001c7, 0x00000149, 0x00050083, 0x00000006, 0x000001d0,
|
||||
0x000003a1, 0x000001ca, 0x00050085, 0x00000006, 0x000001d5, 0x0000014a, 0x000001d4, 0x00050081,
|
||||
0x00000006, 0x000001d6, 0x000001d2, 0x000001d5, 0x000500ba, 0x000000b1, 0x000001d7, 0x000001d0,
|
||||
0x000001d6, 0x000500b8, 0x000000b1, 0x000001da, 0x000001d0, 0x00000182, 0x000500a7, 0x000000b1,
|
||||
0x000001db, 0x000001d7, 0x000001da, 0x000300f7, 0x000001dd, 0x00000000, 0x000400fa, 0x000001db,
|
||||
0x000001dc, 0x000001dd, 0x000200f8, 0x000001dc, 0x0004006f, 0x00000006, 0x000001df, 0x000003d8,
|
||||
0x00050085, 0x00000006, 0x000001e0, 0x000001df, 0x000003e3, 0x00050083, 0x00000006, 0x000001e1,
|
||||
0x00000029, 0x000001e0, 0x000200f9, 0x00000194, 0x000200f8, 0x000001dd, 0x000200f9, 0x00000195,
|
||||
0x000200f8, 0x00000195, 0x00050080, 0x00000019, 0x000001e4, 0x000003d8, 0x00000077, 0x00050081,
|
||||
0x00000006, 0x000001e7, 0x000003d9, 0x00000186, 0x000200f9, 0x00000192, 0x000200f8, 0x00000194,
|
||||
0x000b00f5, 0x00000006, 0x000003dc, 0x00000110, 0x00000192, 0x00000110, 0x000001a6, 0x00000110,
|
||||
0x000001ba, 0x000001e1, 0x000001dc, 0x0008000c, 0x00000006, 0x000001eb, 0x00000001, 0x00000031,
|
||||
0x000001e9, 0x0000014c, 0x0000014a, 0x00050083, 0x00000006, 0x000001ec, 0x00000029, 0x000001eb,
|
||||
0x00060041, 0x00000037, 0x000001ee, 0x00000035, 0x00000036, 0x00000173, 0x0004003d, 0x00000006,
|
||||
0x000001ef, 0x000001ee, 0x00050085, 0x00000006, 0x000001f1, 0x000001ef, 0x000003dc, 0x00050085,
|
||||
0x00000006, 0x000001f3, 0x000001f1, 0x000001ec, 0x00050085, 0x00000006, 0x000001f5, 0x000001f3,
|
||||
0x0000016b, 0x00050083, 0x00000006, 0x000001f6, 0x00000029, 0x000001f5, 0x00060041, 0x00000037,
|
||||
0x000001f8, 0x00000035, 0x000001f7, 0x0000002d, 0x0004003d, 0x00000006, 0x000001f9, 0x000001f8,
|
||||
0x000500ba, 0x000000b1, 0x000001fa, 0x000001f9, 0x0000004e, 0x000300f7, 0x000001fc, 0x00000000,
|
||||
0x000400fa, 0x000001fa, 0x000001fb, 0x000001fc, 0x000200f8, 0x000001fb, 0x0004003d, 0x000001fd,
|
||||
0x00000200, 0x000001ff, 0x00070050, 0x00000032, 0x00000203, 0x000001f6, 0x000001f6, 0x000001f6,
|
||||
0x00000029, 0x00040063, 0x00000200, 0x00000123, 0x00000203, 0x000200f9, 0x0000021d, 0x000200f8,
|
||||
0x000001fc, 0x000500be, 0x000000b1, 0x00000206, 0x000001f6, 0x00000140, 0x000300f7, 0x00000208,
|
||||
0x00000000, 0x000400fa, 0x00000206, 0x00000207, 0x00000208, 0x000200f8, 0x00000207, 0x000200f9,
|
||||
0x0000021d, 0x000200f8, 0x00000208, 0x0004003d, 0x000001fd, 0x0000020c, 0x000001ff, 0x00050062,
|
||||
0x00000032, 0x0000020e, 0x0000020c, 0x00000123, 0x0004003d, 0x000001fd, 0x0000020f, 0x000001ff,
|
||||
0x0008004f, 0x0000000a, 0x00000212, 0x0000020e, 0x0000020e, 0x00000000, 0x00000001, 0x00000002,
|
||||
0x0005008e, 0x0000000a, 0x00000214, 0x00000212, 0x000001f6, 0x00050051, 0x00000006, 0x00000216,
|
||||
0x0000020e, 0x00000003, 0x00050051, 0x00000006, 0x00000217, 0x00000214, 0x00000000, 0x00050051,
|
||||
0x00000006, 0x00000218, 0x00000214, 0x00000001, 0x00050051, 0x00000006, 0x00000219, 0x00000214,
|
||||
0x00000002, 0x00070050, 0x00000032, 0x0000021a, 0x00000217, 0x00000218, 0x00000219, 0x00000216,
|
||||
0x00040063, 0x0000020f, 0x00000123, 0x0000021a, 0x000200f9, 0x0000021d, 0x000200f8, 0x0000021d,
|
||||
0x00000155, 0x00000158, 0x00060041, 0x00000037, 0x0000015c, 0x00000035, 0x0000015b, 0x0000003b,
|
||||
0x0004003d, 0x00000006, 0x0000015d, 0x0000015c, 0x000500ba, 0x000000b1, 0x0000015e, 0x0000015d,
|
||||
0x0000004e, 0x000300f7, 0x00000161, 0x00000000, 0x000400fa, 0x0000015e, 0x00000160, 0x00000168,
|
||||
0x000200f8, 0x00000160, 0x0004003d, 0x00000084, 0x00000163, 0x00000162, 0x00070058, 0x00000032,
|
||||
0x00000165, 0x00000163, 0x00000159, 0x00000002, 0x00000110, 0x00050051, 0x00000006, 0x00000167,
|
||||
0x00000165, 0x00000003, 0x000200f9, 0x00000161, 0x000200f8, 0x00000168, 0x000200f9, 0x00000161,
|
||||
0x000200f8, 0x00000161, 0x000700f5, 0x00000006, 0x000003fb, 0x00000167, 0x00000160, 0x00000029,
|
||||
0x00000168, 0x00060041, 0x00000037, 0x0000016a, 0x00000035, 0x0000015b, 0x0000002d, 0x0004003d,
|
||||
0x00000006, 0x0000016b, 0x0000016a, 0x000500ba, 0x000000b1, 0x0000016d, 0x0000016b, 0x0000016c,
|
||||
0x000300f7, 0x0000016f, 0x00000000, 0x000400fa, 0x0000016d, 0x0000016e, 0x0000016f, 0x000200f8,
|
||||
0x0000016e, 0x0004003d, 0x00000170, 0x00000173, 0x00000172, 0x00070050, 0x00000032, 0x00000176,
|
||||
0x000003fb, 0x000003fb, 0x000003fb, 0x00000029, 0x00040063, 0x00000173, 0x00000123, 0x00000176,
|
||||
0x000200f9, 0x00000243, 0x000200f8, 0x0000016f, 0x000500bc, 0x000000b1, 0x00000179, 0x000003fb,
|
||||
0x00000110, 0x000300f7, 0x0000017b, 0x00000000, 0x000400fa, 0x00000179, 0x0000017a, 0x0000017b,
|
||||
0x000200f8, 0x0000017a, 0x000500b8, 0x000000b1, 0x0000017e, 0x0000016b, 0x0000004e, 0x000200f9,
|
||||
0x0000017b, 0x000200f8, 0x0000017b, 0x000700f5, 0x000000b1, 0x0000017f, 0x00000179, 0x0000016f,
|
||||
0x0000017e, 0x0000017a, 0x000300f7, 0x00000181, 0x00000000, 0x000400fa, 0x0000017f, 0x00000180,
|
||||
0x00000181, 0x000200f8, 0x00000180, 0x000200f9, 0x00000243, 0x000200f8, 0x00000181, 0x0005008e,
|
||||
0x00000007, 0x0000024c, 0x00000159, 0x00000027, 0x00050083, 0x00000007, 0x0000024e, 0x0000024c,
|
||||
0x000001de, 0x00050051, 0x00000006, 0x00000250, 0x0000024e, 0x00000000, 0x00050085, 0x00000006,
|
||||
0x00000252, 0x00000250, 0x0000014a, 0x00060041, 0x00000037, 0x00000253, 0x00000035, 0x00000036,
|
||||
0x0000002d, 0x0004003d, 0x00000006, 0x00000254, 0x00000253, 0x00050088, 0x00000006, 0x00000255,
|
||||
0x00000252, 0x00000254, 0x00050051, 0x00000006, 0x00000257, 0x0000024e, 0x00000001, 0x0004007f,
|
||||
0x00000006, 0x00000258, 0x00000257, 0x00050085, 0x00000006, 0x0000025a, 0x00000258, 0x0000014a,
|
||||
0x00060041, 0x00000037, 0x0000025b, 0x00000035, 0x00000036, 0x0000003b, 0x0004003d, 0x00000006,
|
||||
0x0000025c, 0x0000025b, 0x00050088, 0x00000006, 0x0000025d, 0x0000025a, 0x0000025c, 0x0004007f,
|
||||
0x00000006, 0x0000025f, 0x0000014a, 0x00060050, 0x0000000a, 0x00000260, 0x00000255, 0x0000025d,
|
||||
0x0000025f, 0x0007004f, 0x00000007, 0x00000276, 0x00000157, 0x00000157, 0x00000000, 0x00000001,
|
||||
0x0004006e, 0x0000001a, 0x00000277, 0x00000276, 0x00050082, 0x0000001a, 0x00000279, 0x00000277,
|
||||
0x00000407, 0x00050082, 0x0000001a, 0x0000027b, 0x00000123, 0x0000009d, 0x0008000c, 0x0000001a,
|
||||
0x000002ee, 0x00000001, 0x0000002d, 0x0000027b, 0x00000070, 0x00000279, 0x0004006f, 0x00000007,
|
||||
0x000002f0, 0x000002ee, 0x00050081, 0x00000007, 0x000002f2, 0x000002f0, 0x00000406, 0x00050085,
|
||||
0x00000007, 0x000002f6, 0x000002f2, 0x00000158, 0x0004003d, 0x00000084, 0x000002f7, 0x00000086,
|
||||
0x00040064, 0x00000083, 0x000002f9, 0x000002f7, 0x0007005f, 0x00000032, 0x000002fa, 0x000002f9,
|
||||
0x000002ee, 0x00000002, 0x00000036, 0x00050051, 0x00000006, 0x000002fb, 0x000002fa, 0x00000000,
|
||||
0x00050085, 0x00000006, 0x000002fe, 0x000002fb, 0x00000149, 0x0005008e, 0x00000007, 0x00000304,
|
||||
0x000002f6, 0x00000027, 0x00050083, 0x00000007, 0x00000306, 0x00000304, 0x000001de, 0x00050051,
|
||||
0x00000006, 0x00000308, 0x00000306, 0x00000000, 0x00050085, 0x00000006, 0x0000030a, 0x00000308,
|
||||
0x000002fe, 0x00050088, 0x00000006, 0x0000030d, 0x0000030a, 0x00000254, 0x00050051, 0x00000006,
|
||||
0x0000030f, 0x00000306, 0x00000001, 0x0004007f, 0x00000006, 0x00000310, 0x0000030f, 0x00050085,
|
||||
0x00000006, 0x00000312, 0x00000310, 0x000002fe, 0x00050088, 0x00000006, 0x00000315, 0x00000312,
|
||||
0x0000025c, 0x0004007f, 0x00000006, 0x00000317, 0x000002fe, 0x00060050, 0x0000000a, 0x00000318,
|
||||
0x0000030d, 0x00000315, 0x00000317, 0x00050080, 0x0000001a, 0x0000027e, 0x00000123, 0x0000009d,
|
||||
0x0008000c, 0x0000001a, 0x00000324, 0x00000001, 0x0000002d, 0x0000027e, 0x00000070, 0x00000279,
|
||||
0x0004006f, 0x00000007, 0x00000326, 0x00000324, 0x00050081, 0x00000007, 0x00000328, 0x00000326,
|
||||
0x00000406, 0x00050085, 0x00000007, 0x0000032c, 0x00000328, 0x00000158, 0x0004003d, 0x00000084,
|
||||
0x0000032d, 0x00000086, 0x00040064, 0x00000083, 0x0000032f, 0x0000032d, 0x0007005f, 0x00000032,
|
||||
0x00000330, 0x0000032f, 0x00000324, 0x00000002, 0x00000036, 0x00050051, 0x00000006, 0x00000331,
|
||||
0x00000330, 0x00000000, 0x00050085, 0x00000006, 0x00000334, 0x00000331, 0x00000149, 0x0005008e,
|
||||
0x00000007, 0x0000033a, 0x0000032c, 0x00000027, 0x00050083, 0x00000007, 0x0000033c, 0x0000033a,
|
||||
0x000001de, 0x00050051, 0x00000006, 0x0000033e, 0x0000033c, 0x00000000, 0x00050085, 0x00000006,
|
||||
0x00000340, 0x0000033e, 0x00000334, 0x00050088, 0x00000006, 0x00000343, 0x00000340, 0x00000254,
|
||||
0x00050051, 0x00000006, 0x00000345, 0x0000033c, 0x00000001, 0x0004007f, 0x00000006, 0x00000346,
|
||||
0x00000345, 0x00050085, 0x00000006, 0x00000348, 0x00000346, 0x00000334, 0x00050088, 0x00000006,
|
||||
0x0000034b, 0x00000348, 0x0000025c, 0x0004007f, 0x00000006, 0x0000034d, 0x00000334, 0x00060050,
|
||||
0x0000000a, 0x0000034e, 0x00000343, 0x0000034b, 0x0000034d, 0x00050082, 0x0000001a, 0x00000281,
|
||||
0x00000123, 0x000000a8, 0x0008000c, 0x0000001a, 0x0000035a, 0x00000001, 0x0000002d, 0x00000281,
|
||||
0x00000070, 0x00000279, 0x0004006f, 0x00000007, 0x0000035c, 0x0000035a, 0x00050081, 0x00000007,
|
||||
0x0000035e, 0x0000035c, 0x00000406, 0x00050085, 0x00000007, 0x00000362, 0x0000035e, 0x00000158,
|
||||
0x0004003d, 0x00000084, 0x00000363, 0x00000086, 0x00040064, 0x00000083, 0x00000365, 0x00000363,
|
||||
0x0007005f, 0x00000032, 0x00000366, 0x00000365, 0x0000035a, 0x00000002, 0x00000036, 0x00050051,
|
||||
0x00000006, 0x00000367, 0x00000366, 0x00000000, 0x00050085, 0x00000006, 0x0000036a, 0x00000367,
|
||||
0x00000149, 0x0005008e, 0x00000007, 0x00000370, 0x00000362, 0x00000027, 0x00050083, 0x00000007,
|
||||
0x00000372, 0x00000370, 0x000001de, 0x00050051, 0x00000006, 0x00000374, 0x00000372, 0x00000000,
|
||||
0x00050085, 0x00000006, 0x00000376, 0x00000374, 0x0000036a, 0x00050088, 0x00000006, 0x00000379,
|
||||
0x00000376, 0x00000254, 0x00050051, 0x00000006, 0x0000037b, 0x00000372, 0x00000001, 0x0004007f,
|
||||
0x00000006, 0x0000037c, 0x0000037b, 0x00050085, 0x00000006, 0x0000037e, 0x0000037c, 0x0000036a,
|
||||
0x00050088, 0x00000006, 0x00000381, 0x0000037e, 0x0000025c, 0x0004007f, 0x00000006, 0x00000383,
|
||||
0x0000036a, 0x00060050, 0x0000000a, 0x00000384, 0x00000379, 0x00000381, 0x00000383, 0x00050080,
|
||||
0x0000001a, 0x00000284, 0x00000123, 0x000000a8, 0x0008000c, 0x0000001a, 0x00000390, 0x00000001,
|
||||
0x0000002d, 0x00000284, 0x00000070, 0x00000279, 0x0004006f, 0x00000007, 0x00000392, 0x00000390,
|
||||
0x00050081, 0x00000007, 0x00000394, 0x00000392, 0x00000406, 0x00050085, 0x00000007, 0x00000398,
|
||||
0x00000394, 0x00000158, 0x0004003d, 0x00000084, 0x00000399, 0x00000086, 0x00040064, 0x00000083,
|
||||
0x0000039b, 0x00000399, 0x0007005f, 0x00000032, 0x0000039c, 0x0000039b, 0x00000390, 0x00000002,
|
||||
0x00000036, 0x00050051, 0x00000006, 0x0000039d, 0x0000039c, 0x00000000, 0x00050085, 0x00000006,
|
||||
0x000003a0, 0x0000039d, 0x00000149, 0x0005008e, 0x00000007, 0x000003a6, 0x00000398, 0x00000027,
|
||||
0x00050083, 0x00000007, 0x000003a8, 0x000003a6, 0x000001de, 0x00050051, 0x00000006, 0x000003aa,
|
||||
0x000003a8, 0x00000000, 0x00050085, 0x00000006, 0x000003ac, 0x000003aa, 0x000003a0, 0x00050088,
|
||||
0x00000006, 0x000003af, 0x000003ac, 0x00000254, 0x00050051, 0x00000006, 0x000003b1, 0x000003a8,
|
||||
0x00000001, 0x0004007f, 0x00000006, 0x000003b2, 0x000003b1, 0x00050085, 0x00000006, 0x000003b4,
|
||||
0x000003b2, 0x000003a0, 0x00050088, 0x00000006, 0x000003b7, 0x000003b4, 0x0000025c, 0x0004007f,
|
||||
0x00000006, 0x000003b9, 0x000003a0, 0x00060050, 0x0000000a, 0x000003ba, 0x000003af, 0x000003b7,
|
||||
0x000003b9, 0x000500aa, 0x000000b1, 0x00000288, 0x00000125, 0x00000036, 0x000400a8, 0x000000b1,
|
||||
0x00000289, 0x00000288, 0x000300f7, 0x000002a0, 0x00000000, 0x000400fa, 0x00000289, 0x0000028a,
|
||||
0x000002a0, 0x000200f8, 0x0000028a, 0x00050051, 0x00000019, 0x0000028e, 0x00000279, 0x00000000,
|
||||
0x000500b1, 0x000000b1, 0x0000028f, 0x00000125, 0x0000028e, 0x000300f7, 0x0000029e, 0x00000000,
|
||||
0x000400fa, 0x0000028f, 0x00000290, 0x0000029e, 0x000200f8, 0x00000290, 0x00050083, 0x00000006,
|
||||
0x00000295, 0x0000014a, 0x00000334, 0x0006000c, 0x00000006, 0x00000296, 0x00000001, 0x00000004,
|
||||
0x00000295, 0x00050083, 0x00000006, 0x0000029b, 0x000002fe, 0x0000014a, 0x0006000c, 0x00000006,
|
||||
0x0000029c, 0x00000001, 0x00000004, 0x0000029b, 0x000500b8, 0x000000b1, 0x0000029d, 0x00000296,
|
||||
0x0000029c, 0x000200f9, 0x0000029e, 0x000200f8, 0x0000029e, 0x000700f5, 0x000000b1, 0x0000029f,
|
||||
0x0000028f, 0x0000028a, 0x0000029d, 0x00000290, 0x000200f9, 0x000002a0, 0x000200f8, 0x000002a0,
|
||||
0x000700f5, 0x000000b1, 0x000002a1, 0x00000288, 0x00000181, 0x0000029f, 0x0000029e, 0x00050051,
|
||||
0x00000019, 0x000002a3, 0x00000123, 0x00000001, 0x000500aa, 0x000000b1, 0x000002a4, 0x000002a3,
|
||||
0x00000036, 0x000400a8, 0x000000b1, 0x000002a5, 0x000002a4, 0x000300f7, 0x000002bc, 0x00000000,
|
||||
0x000400fa, 0x000002a5, 0x000002a6, 0x000002bc, 0x000200f8, 0x000002a6, 0x00050051, 0x00000019,
|
||||
0x000002aa, 0x00000279, 0x00000001, 0x000500b1, 0x000000b1, 0x000002ab, 0x000002a3, 0x000002aa,
|
||||
0x000300f7, 0x000002ba, 0x00000000, 0x000400fa, 0x000002ab, 0x000002ac, 0x000002ba, 0x000200f8,
|
||||
0x000002ac, 0x00050083, 0x00000006, 0x000002b1, 0x0000014a, 0x000003a0, 0x0006000c, 0x00000006,
|
||||
0x000002b2, 0x00000001, 0x00000004, 0x000002b1, 0x00050083, 0x00000006, 0x000002b7, 0x0000036a,
|
||||
0x0000014a, 0x0006000c, 0x00000006, 0x000002b8, 0x00000001, 0x00000004, 0x000002b7, 0x000500b8,
|
||||
0x000000b1, 0x000002b9, 0x000002b2, 0x000002b8, 0x000200f9, 0x000002ba, 0x000200f8, 0x000002ba,
|
||||
0x000700f5, 0x000000b1, 0x000002bb, 0x000002ab, 0x000002a6, 0x000002b9, 0x000002ac, 0x000200f9,
|
||||
0x000002bc, 0x000200f8, 0x000002bc, 0x000700f5, 0x000000b1, 0x000002bd, 0x000002a4, 0x000002a0,
|
||||
0x000002bb, 0x000002ba, 0x000300f7, 0x000002c7, 0x00000000, 0x000400fa, 0x000002a1, 0x000002bf,
|
||||
0x000002c3, 0x000200f8, 0x000002bf, 0x00050083, 0x0000000a, 0x000002c2, 0x0000034e, 0x00000260,
|
||||
0x000200f9, 0x000002c7, 0x000200f8, 0x000002c3, 0x00050083, 0x0000000a, 0x000002c6, 0x00000260,
|
||||
0x00000318, 0x000200f9, 0x000002c7, 0x000200f8, 0x000002c7, 0x000700f5, 0x0000000a, 0x000003fc,
|
||||
0x000002c2, 0x000002bf, 0x000002c6, 0x000002c3, 0x000300f7, 0x000002d2, 0x00000000, 0x000400fa,
|
||||
0x000002bd, 0x000002ca, 0x000002ce, 0x000200f8, 0x000002ca, 0x00050083, 0x0000000a, 0x000002cd,
|
||||
0x000003ba, 0x00000260, 0x000200f9, 0x000002d2, 0x000200f8, 0x000002ce, 0x00050083, 0x0000000a,
|
||||
0x000002d1, 0x00000260, 0x00000384, 0x000200f9, 0x000002d2, 0x000200f8, 0x000002d2, 0x000700f5,
|
||||
0x0000000a, 0x000003fd, 0x000002cd, 0x000002ca, 0x000002d1, 0x000002ce, 0x0007000c, 0x0000000a,
|
||||
0x000002d6, 0x00000001, 0x00000044, 0x000003fc, 0x000003fd, 0x0006000c, 0x0000000a, 0x000002d7,
|
||||
0x00000001, 0x00000045, 0x000002d6, 0x00050094, 0x00000006, 0x000002da, 0x000002d7, 0x00000260,
|
||||
0x000500ba, 0x000000b1, 0x000002db, 0x000002da, 0x00000110, 0x000300f7, 0x000002e1, 0x00000000,
|
||||
0x000400fa, 0x000002db, 0x000002dc, 0x000002df, 0x000200f8, 0x000002dc, 0x0004007f, 0x0000000a,
|
||||
0x000002de, 0x000002d7, 0x000200f9, 0x000002e1, 0x000200f8, 0x000002df, 0x000200f9, 0x000002e1,
|
||||
0x000200f8, 0x000002e1, 0x000700f5, 0x0000000a, 0x000003fe, 0x000002de, 0x000002dc, 0x000002d7,
|
||||
0x000002df, 0x00050041, 0x00000072, 0x00000190, 0x00000035, 0x00000077, 0x0004003d, 0x00000032,
|
||||
0x00000191, 0x00000190, 0x0008004f, 0x0000000a, 0x00000192, 0x00000191, 0x00000191, 0x00000000,
|
||||
0x00000001, 0x00000002, 0x00050094, 0x00000006, 0x00000193, 0x000003fe, 0x00000192, 0x0008000c,
|
||||
0x00000006, 0x00000194, 0x00000001, 0x00000031, 0x00000110, 0x0000018a, 0x00000193, 0x000500bd,
|
||||
0x000000b1, 0x00000197, 0x00000194, 0x00000110, 0x000300f7, 0x00000199, 0x00000000, 0x000400fa,
|
||||
0x00000197, 0x00000198, 0x00000199, 0x000200f8, 0x00000198, 0x000200f9, 0x00000243, 0x000200f8,
|
||||
0x00000199, 0x00060041, 0x00000037, 0x0000019c, 0x00000035, 0x00000077, 0x00000166, 0x0004003d,
|
||||
0x00000006, 0x0000019d, 0x0000019c, 0x00050085, 0x00000006, 0x000001a0, 0x0000014a, 0x00000409,
|
||||
0x0008000c, 0x00000006, 0x000001a3, 0x00000001, 0x0000002b, 0x000001a0, 0x000001a1, 0x000001a2,
|
||||
0x00050085, 0x00000006, 0x000001a4, 0x0000019d, 0x000001a3, 0x00050085, 0x00000006, 0x000001a9,
|
||||
0x0000014a, 0x000001a8, 0x00050081, 0x00000006, 0x000001aa, 0x000001a6, 0x000001a9, 0x00050085,
|
||||
0x00000006, 0x000001ae, 0x000001a4, 0x0000040a, 0x00050094, 0x00000006, 0x000003be, 0x00000153,
|
||||
0x00000068, 0x0006000c, 0x00000006, 0x000003bf, 0x00000001, 0x0000000a, 0x000003be, 0x00050085,
|
||||
0x00000006, 0x000003c0, 0x00000064, 0x000003bf, 0x0006000c, 0x00000006, 0x000003c1, 0x00000001,
|
||||
0x0000000a, 0x000003c0, 0x00050081, 0x00000006, 0x000001b6, 0x000001b1, 0x000003c1, 0x00050085,
|
||||
0x00000006, 0x000001b7, 0x000001ae, 0x000001b6, 0x000200f9, 0x000001ba, 0x000200f8, 0x000001ba,
|
||||
0x000700f5, 0x00000006, 0x00000400, 0x000001b7, 0x00000199, 0x0000020f, 0x000001bd, 0x000700f5,
|
||||
0x00000019, 0x000003ff, 0x00000036, 0x00000199, 0x0000020c, 0x000001bd, 0x000500b1, 0x000000b1,
|
||||
0x000001c1, 0x000003ff, 0x000001c0, 0x000400f6, 0x000001bc, 0x000001bd, 0x00000000, 0x000400fa,
|
||||
0x000001c1, 0x000001bb, 0x000001bc, 0x000200f8, 0x000001bb, 0x0005008e, 0x0000000a, 0x000001c8,
|
||||
0x00000192, 0x00000400, 0x00050081, 0x0000000a, 0x000001c9, 0x00000260, 0x000001c8, 0x00050051,
|
||||
0x00000006, 0x000001cb, 0x000001c9, 0x00000002, 0x000500be, 0x000000b1, 0x000001cd, 0x000001cb,
|
||||
0x000001cc, 0x000300f7, 0x000001cf, 0x00000000, 0x000400fa, 0x000001cd, 0x000001ce, 0x000001cf,
|
||||
0x000200f8, 0x000001ce, 0x000200f9, 0x000001bc, 0x000200f8, 0x000001cf, 0x0004007f, 0x00000006,
|
||||
0x000003c7, 0x000001cb, 0x00050051, 0x00000006, 0x000003c9, 0x000001c9, 0x00000000, 0x00050085,
|
||||
0x00000006, 0x000003ca, 0x0000004e, 0x000003c9, 0x00050085, 0x00000006, 0x000003cd, 0x000003ca,
|
||||
0x00000254, 0x00050088, 0x00000006, 0x000003cf, 0x000003cd, 0x000003c7, 0x00050081, 0x00000006,
|
||||
0x000003d0, 0x0000004e, 0x000003cf, 0x00050051, 0x00000006, 0x000003d2, 0x000001c9, 0x00000001,
|
||||
0x00050085, 0x00000006, 0x000003d3, 0x0000004e, 0x000003d2, 0x00050085, 0x00000006, 0x000003d6,
|
||||
0x000003d3, 0x0000025c, 0x00050088, 0x00000006, 0x000003d8, 0x000003d6, 0x000003c7, 0x00050083,
|
||||
0x00000006, 0x000003d9, 0x0000004e, 0x000003d8, 0x00050050, 0x00000007, 0x000003da, 0x000003d0,
|
||||
0x000003d9, 0x000500b8, 0x000001d7, 0x000001d8, 0x000003da, 0x000001d6, 0x0004009a, 0x000000b1,
|
||||
0x000001d9, 0x000001d8, 0x000400a8, 0x000000b1, 0x000001da, 0x000001d9, 0x000300f7, 0x000001dc,
|
||||
0x00000000, 0x000400fa, 0x000001da, 0x000001db, 0x000001dc, 0x000200f8, 0x000001db, 0x000500ba,
|
||||
0x000001d7, 0x000001df, 0x000003da, 0x000001de, 0x0004009a, 0x000000b1, 0x000001e0, 0x000001df,
|
||||
0x000200f9, 0x000001dc, 0x000200f8, 0x000001dc, 0x000700f5, 0x000000b1, 0x000001e1, 0x000001d9,
|
||||
0x000001cf, 0x000001e0, 0x000001db, 0x000300f7, 0x000001e3, 0x00000000, 0x000400fa, 0x000001e1,
|
||||
0x000001e2, 0x000001e3, 0x000200f8, 0x000001e2, 0x000200f9, 0x000001bc, 0x000200f8, 0x000001e3,
|
||||
0x0004003d, 0x00000084, 0x000001e6, 0x00000086, 0x00050085, 0x00000007, 0x000001eb, 0x000003da,
|
||||
0x00000276, 0x0004006e, 0x0000001a, 0x000001ec, 0x000001eb, 0x00040064, 0x00000083, 0x000001ed,
|
||||
0x000001e6, 0x0007005f, 0x00000032, 0x000001ee, 0x000001ed, 0x000001ec, 0x00000002, 0x00000036,
|
||||
0x00050051, 0x00000006, 0x000001ef, 0x000001ee, 0x00000000, 0x00050085, 0x00000006, 0x000001f2,
|
||||
0x000001ef, 0x00000149, 0x00050083, 0x00000006, 0x000001f8, 0x000003c7, 0x000001f2, 0x00050085,
|
||||
0x00000006, 0x000001fd, 0x0000014a, 0x000001fc, 0x00050081, 0x00000006, 0x000001fe, 0x000001fa,
|
||||
0x000001fd, 0x000500ba, 0x000000b1, 0x000001ff, 0x000001f8, 0x000001fe, 0x000500b8, 0x000000b1,
|
||||
0x00000202, 0x000001f8, 0x000001aa, 0x000500a7, 0x000000b1, 0x00000203, 0x000001ff, 0x00000202,
|
||||
0x000300f7, 0x00000205, 0x00000000, 0x000400fa, 0x00000203, 0x00000204, 0x00000205, 0x000200f8,
|
||||
0x00000204, 0x0004006f, 0x00000006, 0x00000207, 0x000003ff, 0x00050085, 0x00000006, 0x00000208,
|
||||
0x00000207, 0x0000040a, 0x00050083, 0x00000006, 0x00000209, 0x00000029, 0x00000208, 0x000200f9,
|
||||
0x000001bc, 0x000200f8, 0x00000205, 0x000200f9, 0x000001bd, 0x000200f8, 0x000001bd, 0x00050080,
|
||||
0x00000019, 0x0000020c, 0x000003ff, 0x00000077, 0x00050081, 0x00000006, 0x0000020f, 0x00000400,
|
||||
0x000001ae, 0x000200f9, 0x000001ba, 0x000200f8, 0x000001bc, 0x000b00f5, 0x00000006, 0x00000403,
|
||||
0x00000110, 0x000001ba, 0x00000110, 0x000001ce, 0x00000110, 0x000001e2, 0x00000209, 0x00000204,
|
||||
0x0008000c, 0x00000006, 0x00000213, 0x00000001, 0x00000031, 0x00000211, 0x0000014c, 0x0000014a,
|
||||
0x00050083, 0x00000006, 0x00000214, 0x00000029, 0x00000213, 0x00060041, 0x00000037, 0x00000216,
|
||||
0x00000035, 0x00000036, 0x00000166, 0x0004003d, 0x00000006, 0x00000217, 0x00000216, 0x00050085,
|
||||
0x00000006, 0x00000219, 0x00000217, 0x00000403, 0x00050085, 0x00000006, 0x0000021b, 0x00000219,
|
||||
0x00000214, 0x00050085, 0x00000006, 0x0000021d, 0x0000021b, 0x00000194, 0x00050085, 0x00000006,
|
||||
0x0000021f, 0x0000021d, 0x000003fb, 0x00050083, 0x00000006, 0x00000220, 0x00000029, 0x0000021f,
|
||||
0x000500ba, 0x000000b1, 0x00000223, 0x0000016b, 0x0000004e, 0x000300f7, 0x00000225, 0x00000000,
|
||||
0x000400fa, 0x00000223, 0x00000224, 0x00000225, 0x000200f8, 0x00000224, 0x0004003d, 0x00000170,
|
||||
0x00000226, 0x00000172, 0x00070050, 0x00000032, 0x00000229, 0x00000220, 0x00000220, 0x00000220,
|
||||
0x00000029, 0x00040063, 0x00000226, 0x00000123, 0x00000229, 0x000200f9, 0x00000243, 0x000200f8,
|
||||
0x00000225, 0x000500be, 0x000000b1, 0x0000022c, 0x00000220, 0x00000140, 0x000300f7, 0x0000022e,
|
||||
0x00000000, 0x000400fa, 0x0000022c, 0x0000022d, 0x0000022e, 0x000200f8, 0x0000022d, 0x000200f9,
|
||||
0x00000243, 0x000200f8, 0x0000022e, 0x0004003d, 0x00000170, 0x00000232, 0x00000172, 0x00050062,
|
||||
0x00000032, 0x00000234, 0x00000232, 0x00000123, 0x0004003d, 0x00000170, 0x00000235, 0x00000172,
|
||||
0x0008004f, 0x0000000a, 0x00000238, 0x00000234, 0x00000234, 0x00000000, 0x00000001, 0x00000002,
|
||||
0x0005008e, 0x0000000a, 0x0000023a, 0x00000238, 0x00000220, 0x00050051, 0x00000006, 0x0000023c,
|
||||
0x00000234, 0x00000003, 0x00050051, 0x00000006, 0x0000023d, 0x0000023a, 0x00000000, 0x00050051,
|
||||
0x00000006, 0x0000023e, 0x0000023a, 0x00000001, 0x00050051, 0x00000006, 0x0000023f, 0x0000023a,
|
||||
0x00000002, 0x00070050, 0x00000032, 0x00000240, 0x0000023d, 0x0000023e, 0x0000023f, 0x0000023c,
|
||||
0x00040063, 0x00000235, 0x00000123, 0x00000240, 0x000200f9, 0x00000243, 0x000200f8, 0x00000243,
|
||||
0x000100fd, 0x00010038,
|
||||
};
|
||||
@@ -214,6 +214,21 @@ void rt_dispatch(Cpu *c) {
|
||||
__attribute__((musttail)) return f(c);
|
||||
}
|
||||
|
||||
// The plugin trace (plugin_init.c, TOTK_PLUGIN_TRACE): the slot of the function start a runs fn from now on. Once per
|
||||
// traced function, before the game's code runs; the hot path stays as it is. 0 when a is no function start of the
|
||||
// table or fn lies out of the reach of a slot's 32-bit offset.
|
||||
int rt_dispatch_reroute(uint64_t a, GuestFn fn) {
|
||||
uint64_t i = (a - D.lo) >> 2;
|
||||
if (!g_ready || (a & 3) || a < D.lo || i >= D.slots || !D.slot[i]) return 0;
|
||||
uintptr_t f = (uintptr_t)fn;
|
||||
if (f <= D.anchor || f - D.anchor > UINT32_MAX) return 0;
|
||||
uint64_t page = (uint64_t)(uintptr_t)&D.slot[i] & ~0xFFFull;
|
||||
if (!plat_mem_protect(page, 0x1000, PLAT_PROT_RW)) return 0;
|
||||
((uint32_t *)D.slot)[i] = (uint32_t)(f - D.anchor); // the table is sealed read-only, unsealed above
|
||||
plat_mem_protect(page, 0x1000, PLAT_PROT_READ);
|
||||
return 1;
|
||||
}
|
||||
|
||||
RtDispatchStats rt_dispatch_stats(void) {
|
||||
return (RtDispatchStats){D.lo, D.lo + D.slots * 4, D.slots, g_table_bytes, g_functions, g_nhost};
|
||||
}
|
||||
+5
-2
@@ -19,8 +19,10 @@ typedef struct RtModule {
|
||||
} RtModule;
|
||||
|
||||
// The module glue that tools/build_game.py writes for each build (build/<version>/modules.c), from layout.json and
|
||||
// layout.h: every module of the layout, and the modules linked into this executable.
|
||||
typedef struct RtLayoutEntry { const char *name; uint64_t base, size; } RtLayoutEntry;
|
||||
// layout.h: every module of the layout, and the modules linked into this executable. A mod's code module
|
||||
// (recomp/layout.py plugin<N>, after sdk) also names its NSO file and that file's SHA-256; a game module has NULL there
|
||||
// and is read from the ExeFS directory.
|
||||
typedef struct RtLayoutEntry { const char *name; uint64_t base, size; const char *file, *sha256; } RtLayoutEntry;
|
||||
extern const RtLayoutEntry rt_layout[];
|
||||
extern const int rt_layout_count;
|
||||
int rt_linked_modules(RtModule *out, int max);
|
||||
@@ -36,6 +38,7 @@ void rt_dispatch_init(const RtModule *mods, int count);
|
||||
|
||||
// The host function for a guest address, or NULL when nothing is there. Does not run guest code.
|
||||
GuestFn rt_dispatch_lookup(uint64_t pc);
|
||||
int rt_dispatch_reroute(uint64_t a, GuestFn fn); // plugin trace only (dispatch.c); 0 when it cannot
|
||||
|
||||
// "0x7000001234 (main+0x1234)" for a guest address inside a module, else the bare address. Returns buf.
|
||||
const char *rt_guest_name(uint64_t pc, char *buf, int size);
|
||||
|
||||
@@ -185,14 +185,16 @@ static uint64_t read_ptr(uint64_t a) {
|
||||
uint64_t p = 0;
|
||||
return read_guest(a, &p, 8) ? p : 0;
|
||||
}
|
||||
// 1.2.1: [main+0x4728538] (1.1.0: [main+0x4630a68], 1.4.3: [main+0x3add238]) +0x1e8 scene, its component 13 lists the
|
||||
// 1.2.1: [main+0x4728538] (1.1.0: [[main+0x4630a68]], 1.4.3: [main+0x3add238]) +0x1e8 scene, its component 13 lists the
|
||||
// resident actors; the one named "Player" has its position at +0x2b4 (MacNativeGames world_survey.c, game_version.h
|
||||
// TOTK_GAME_V121/V143). The 1.1.0 slot was measured from its own dereference chain: 181 scene accesses in that build
|
||||
// read it, and one of them reproduces this walk (the 14-component check, component 13, the 0x70 stride and the name
|
||||
// compare) instruction for instruction.
|
||||
// compare) instruction for instruction. Its slot is a GOT entry pointing to the singleton's storage, so it needs
|
||||
// one more dereference than the direct singleton slots of 1.2.1 and 1.4.3.
|
||||
static int player_pos(float xyz[3]) {
|
||||
uint64_t module = read_ptr(MOD_MAIN_BASE + (RT_V143 ? 0x3add238 : RT_V110 ? 0x4630a68 : 0x4728538)),
|
||||
scene = module ? read_ptr(module + 0x1e8) : 0;
|
||||
uint64_t module = read_ptr(MOD_MAIN_BASE + (RT_V143 ? 0x3add238 : RT_V110 ? 0x4630a68 : 0x4728538));
|
||||
if (RT_V110) module = read_ptr(module);
|
||||
uint64_t scene = module ? read_ptr(module + 0x1e8) : 0;
|
||||
int32_t count = 0;
|
||||
if (!scene || !read_guest(scene + 0x50, &count, 4) || count < 14 || count > 256) return 0;
|
||||
uint64_t comps = read_ptr(scene + 0x58), resident = comps ? read_ptr(comps + 13 * 8) : 0;
|
||||
|
||||
+18
-7
@@ -47,14 +47,19 @@ enum { ROMFS_PROMPTS_OK, ROMFS_PROMPTS_MISSING, ROMFS_PROMPTS_FAILED, ROMFS_PROM
|
||||
ROMFS_PROMPTS_PATCHES };
|
||||
const char *romfs_prompts(void);
|
||||
int romfs_prompts_ready(const char *folder);
|
||||
// 1 when the game resolution w x h is of another shape whose folders are missing: the UI layout, or that of
|
||||
// prompts_folder (a prompts' folder that is there at 16:9; NULL for the game's own prompts). romfs.c shaped_name.
|
||||
int romfs_shape_missing(unsigned w, unsigned h, const char *prompts_folder);
|
||||
// The folders a start at game resolution w x h with prompts_folder (input_prompts_folder; NULL for the game's own
|
||||
// prompts) and the selected HUD width needs and that have no manifest: ROMFS_NEED_PROMPTS, prompts_folder itself (16:9);
|
||||
// at another shape (res_wants_wide_overlay) ROMFS_NEED_LAYOUT, its romfs-patches-<w>x<h>[-hud..], and
|
||||
// ROMFS_NEED_SHAPED_PROMPTS, <prompts_folder>-<w>x<h>[-hud..]. A full-layout fallback does not satisfy a requested HUD
|
||||
// cap. 0 with TOTK_ROMFS_PATCHES set.
|
||||
enum { ROMFS_NEED_LAYOUT = 1, ROMFS_NEED_PROMPTS = 2, ROMFS_NEED_SHAPED_PROMPTS = 4 };
|
||||
int romfs_folders_missing(unsigned w, unsigned h, const char *prompts_folder);
|
||||
// 1 when build-cache/rebuild.txt names the setup's Python and tools/make_romfs_patches.py and both exist, with romfs/.
|
||||
int romfs_shape_can_prepare(void);
|
||||
// Starts the generator for w x h's shape (its layout, and prompts_folder's when that is there at 16:9 and lacks it) as
|
||||
// child processes the game does not wait for; the next start loads the result. 1 when every one started.
|
||||
int romfs_shape_prepare(unsigned w, unsigned h, const char *prompts_folder);
|
||||
int romfs_folders_can_prepare(void);
|
||||
// Starts the generator for each folder romfs_folders_missing names, once per folder in this process, as child
|
||||
// processes the game does not wait for; the next start loads the result. 1 when every one runs, 0 when none was
|
||||
// missing, the tools are not there or one could not start.
|
||||
int romfs_folders_prepare(unsigned w, unsigned h, const char *prompts_folder);
|
||||
int romfs_prompts_off(const char *folder);
|
||||
const char *romfs_overlay(size_t k, const char **file, uint64_t *size, int *is_added); // RomFS path of overlay k
|
||||
void fs_trace(const char *what, const char *path); // TOTK_TRACE=fs: one line per open
|
||||
@@ -66,3 +71,9 @@ int fs_save_busy(void); // a save is being wr
|
||||
// or save data changed in the last 3 s and not committed
|
||||
void fs_save_flush(void); // wait for a save Commit still running in the background;
|
||||
// every exit path calls it before the process ends
|
||||
uint32_t fs_save_commits(char *slot, size_t cap); // commits that changed save files; slot: the save folder
|
||||
// (slot_00 ...) the last one wrote first
|
||||
int fs_save_copy_slot(const char *slot, const char *dst); // a folder of the newest save copied to dst (replaced)
|
||||
void fs_save_read_from(const char *dir); // quick load: reads of save:/slot_NN/<file> open dir/<file>
|
||||
// while dir is set; NULL ends it
|
||||
int fs_save_read_from_hits(void); // opens redirected since the last fs_save_read_from(dir)
|
||||
+73
-1
@@ -281,6 +281,18 @@ static int same_file(const char *a, const char *b) {
|
||||
return same;
|
||||
}
|
||||
|
||||
// The folder of the save (slot_00 ...) whose file the running commit wrote first, for quick save (fs_save_commits):
|
||||
// note_changed takes the first path component under new_root of each file copy_tree copies instead of linking.
|
||||
static char changed_slot[64], last_slot[64];
|
||||
static uint32_t commits; // commits that changed a file, under tx_lock
|
||||
static void note_changed(const char *dst) {
|
||||
size_t n = strlen(new_root);
|
||||
if (changed_slot[0] || !n || strncmp(dst, new_root, n) || dst[n] != '/') return;
|
||||
const char *rel = dst + n + 1, *sl = strchr(rel, '/');
|
||||
size_t len = sl ? (size_t)(sl - rel) : sizeof changed_slot;
|
||||
if (len < sizeof changed_slot) memcpy(changed_slot, rel, len), changed_slot[len] = 0;
|
||||
}
|
||||
|
||||
// Copy the tree src to dst, which must not exist; links are skipped. durable: every file is flushed, and every
|
||||
// directory as far as the file system allows. base (or NULL): the committed save; a file whose bytes equal base's file
|
||||
// at the same path becomes a hard link to it instead of a copy (*nlinked), as committed files are never written in
|
||||
@@ -300,7 +312,7 @@ static int copy_tree(const char *src, const char *dst, const char *base, int dur
|
||||
if (l.e[i].kind == PLAT_FS_DIR) bad = copy_tree(s, d, b, durable, nfiles, nlinked, bytes);
|
||||
else {
|
||||
if (b && same_file(s, b) && !plat_fs_link(b, d)) bad = 0, ++*nlinked;
|
||||
else bad = copy_file(s, d, durable, bytes);
|
||||
else bad = copy_file(s, d, durable, bytes), note_changed(d);
|
||||
*nfiles += !bad;
|
||||
if (!bad && durable && crashed()) bad = -1;
|
||||
}
|
||||
@@ -509,6 +521,7 @@ static uint32_t save_commit_locked(void) {
|
||||
int nfiles = 0, linked = 0;
|
||||
tx_step = tx_dead = 0;
|
||||
const char *base = exists(newest_save()) ? newest_save() : NULL;
|
||||
changed_slot[0] = 0;
|
||||
if (remove_tree(new_root) || copy_tree(work_root, new_root, base, 1, &nfiles, &linked, &bytes)) {
|
||||
if (tx_dead) return FS_R_INVALID_ARGUMENT;
|
||||
rt_log("fs: save commit: copying the working copy failed; the newest save is unchanged");
|
||||
@@ -535,6 +548,8 @@ static uint32_t save_commit_locked(void) {
|
||||
ready_seq++;
|
||||
if (*ready_root) remove_tree(ready_root); // superseded: the working copy it was made from held all of it
|
||||
snprintf(ready_root, sizeof ready_root, "%s", ready);
|
||||
commits++;
|
||||
memcpy(last_slot, changed_slot, sizeof last_slot);
|
||||
plat_xchg32(&save_dirty, 0);
|
||||
if (crashed()) return FS_R_INVALID_ARGUMENT;
|
||||
int waits = swap_in();
|
||||
@@ -558,6 +573,34 @@ static void save_wait_commit(void) {
|
||||
|
||||
void fs_save_flush(void) { save_wait_commit(); }
|
||||
|
||||
// ---- quick save (quicksave.c): the save folder the last commit wrote, copied out of the newest save
|
||||
uint32_t fs_save_commits(char *slot, size_t cap) {
|
||||
plat_mutex_lock(&tx_lock);
|
||||
uint32_t n = commits;
|
||||
snprintf(slot, cap, "%s", last_slot);
|
||||
plat_mutex_unlock(&tx_lock);
|
||||
return n;
|
||||
}
|
||||
|
||||
// The folder slot of the newest save to dst (replaced). 0 on success.
|
||||
static int slot_name_ok(const char *slot) {
|
||||
return slot[0] && slot[0] != '.' && !strchr(slot, '/') && !strchr(slot, '\\') && !strchr(slot, ':');
|
||||
}
|
||||
|
||||
int fs_save_copy_slot(const char *slot, const char *dst) {
|
||||
if (!*save_root || !slot_name_ok(slot)) return -1;
|
||||
save_wait_commit();
|
||||
plat_mutex_lock(&tx_lock);
|
||||
char *src = join(newest_save(), slot);
|
||||
int n = 0, linked = 0;
|
||||
uint64_t bytes = 0;
|
||||
int bad = plat_fs_kind(src) != PLAT_FS_DIR || remove_tree(dst) || copy_tree(src, dst, NULL, 1, &n, &linked, &bytes);
|
||||
plat_mutex_unlock(&tx_lock);
|
||||
free(src);
|
||||
return bad ? -1 : 0;
|
||||
}
|
||||
|
||||
|
||||
static uint32_t commit_run(void) {
|
||||
plat_mutex_lock(&tx_lock);
|
||||
uint32_t r = save_commit_locked();
|
||||
@@ -877,6 +920,33 @@ static int64_t host_read_at(PlatFile *f, void *buf, uint32_t n, uint64_t off) {
|
||||
return got < 0 ? -1 : got;
|
||||
}
|
||||
|
||||
// Quick load (quicksave.c, fs_save_read_from): while set, a read-only open of a file of any slot folder of the save
|
||||
// mount (save:/slot_NN/<file>) opens <file> of this folder instead, so the game loads the quick save whichever slot it
|
||||
// was asked to load, and no slot of the save is written for it.
|
||||
static char read_from[PATH_CAP];
|
||||
static volatile int32_t read_from_on, read_from_hits;
|
||||
|
||||
void fs_save_read_from(const char *dir) {
|
||||
if (dir) snprintf(read_from, sizeof read_from, "%s", dir), plat_xchg32(&read_from_hits, 0);
|
||||
plat_xchg32(&read_from_on, dir != NULL);
|
||||
}
|
||||
|
||||
int fs_save_read_from_hits(void) { return plat_cas32(&read_from_hits, 0, 0); }
|
||||
|
||||
static void redirect_slot_read(const char *path, char *p, size_t cap) {
|
||||
const char *rest = strstr(path, ":/slot_");
|
||||
if (!rest) return;
|
||||
const char *d = rest + 7, *file;
|
||||
while (*d >= '0' && *d <= '9') d++;
|
||||
if (d == rest + 7 || *d != '/' || !d[1] || strchr(d + 1, '/')) return;
|
||||
file = d + 1;
|
||||
char q[PATH_CAP];
|
||||
if (snprintf(q, sizeof q, "%s/%s", read_from, file) >= (int)sizeof q || plat_fs_kind(q) != PLAT_FS_FILE) return;
|
||||
rt_log("fs: quick load: %s read from %s", path, q);
|
||||
snprintf(p, cap, "%s", q);
|
||||
plat_inc32(&read_from_hits);
|
||||
}
|
||||
|
||||
static uint32_t open_file(uint64_t *out, const char *path, int mode) {
|
||||
if (romfs_owns(path)) return romfs_open(out, path, mode);
|
||||
fs_trace(mode & FS_OPEN_WRITE ? "write" : "read", path);
|
||||
@@ -885,6 +955,8 @@ static uint32_t open_file(uint64_t *out, const char *path, int mode) {
|
||||
int kind = M_FREE;
|
||||
uint32_t r = host_path_kind(path, p, sizeof p, &kind);
|
||||
if (r) return r;
|
||||
if (kind == M_SAVE && !(mode & FS_OPEN_WRITE) && plat_cas32(&read_from_on, 0, 0))
|
||||
redirect_slot_read(path, p, sizeof p);
|
||||
if (plat_fs_kind(p) != PLAT_FS_FILE) return FS_R_PATH_NOT_FOUND;
|
||||
if (kind == M_SAVE_RO && (mode & FS_OPEN_WRITE)) return FS_R_UNSUPPORTED_OPEN;
|
||||
int save_writer = kind == M_SAVE && (mode & FS_OPEN_WRITE);
|
||||
|
||||
@@ -24,6 +24,7 @@ uint64_t gfx_vsync_time_ns(uint64_t tick); // kern_now_ns() time
|
||||
double gfx_window_refresh_hz(void); // refresh rate of the window's monitor; 0 unknown
|
||||
int gfx_window_focused(void);
|
||||
int gfx_picture_rect(float out[4]); // where the last present put the picture, fractions of the swapchain (x, y, w, h); 0 before one
|
||||
void gfx_present_hold(int on); // 1: the window keeps its last picture, nothing new is presented (quick load)
|
||||
// NVIDIA Reflex (gfx_present.c, VK_NV_low_latency2): the NVN front end and the input service mark a frame's stages.
|
||||
// The markers and the sleep return at once with Reflex off or unsupported.
|
||||
void vk_reflex_marker(int marker, uint64_t present_id); // present_id: the frame's (vk_reflex_frame_begin)
|
||||
|
||||
+15
-2
@@ -22,6 +22,7 @@
|
||||
#include "fs.h"
|
||||
#include "gfx.h"
|
||||
#include "gfx_wsys.h"
|
||||
#include "host.h"
|
||||
#include "nvn_api.h"
|
||||
#include "platform/platform.h"
|
||||
#include "ui/menu.h"
|
||||
@@ -246,6 +247,9 @@ static void window_settings_live(void) {
|
||||
static int started;
|
||||
static char present[16]; // the TOTK_VK_PRESENT the swapchain was made with
|
||||
unsigned v = cfg_version();
|
||||
// Every present: Reflex follows the frame limit, and with fps_limit = display the window measures the monitor's
|
||||
// rate after the swapchain is made, with no settings change to announce it. Unchanged, it returns at once.
|
||||
if (started) reflex_apply_locked();
|
||||
if (started && v == seen) return;
|
||||
seen = v;
|
||||
res_fov_live();
|
||||
@@ -306,8 +310,11 @@ static void reflex_apply_locked(void) {
|
||||
}
|
||||
int mode = reflex_mode_from_cfg();
|
||||
uint32_t min_us = 0;
|
||||
int limit = cfg_int("TOTK_FPS_LIMIT");
|
||||
if (limit > 0) min_us = (uint32_t)(1000000 / limit);
|
||||
// The driver's sleep holds frames to the same rate as the pacer (frame_rate.c frame_step_limit_hz): the setting,
|
||||
// the monitor's rate for fps_limit = display, 60 without the real-time step. cfg_int would read "display" as the
|
||||
// setting's default, 60, and Reflex would hold a 144 Hz monitor to 60 fps.
|
||||
double hz = frame_step_limit_hz();
|
||||
if (hz > 0) min_us = (uint32_t)(1e6 / hz);
|
||||
if (mode == g_reflex_mode && min_us == g_reflex_min_us) return;
|
||||
g_reflex_mode = mode;
|
||||
g_reflex_min_us = min_us;
|
||||
@@ -788,12 +795,18 @@ void gfx_fit_rect(int cw, int ch, int dw, int dh, int out[4]) {
|
||||
out[0] = (dw - out[2]) / 2, out[1] = (dh - out[3]) / 2;
|
||||
}
|
||||
|
||||
// Quick load (quicksave.c) holds the window on its last picture while it drives the game's load menu underneath:
|
||||
// no new frame is presented until gfx_present_hold(0), as while the window is minimized.
|
||||
static volatile int32_t g_hold;
|
||||
void gfx_present_hold(int on) { plat_xchg32(&g_hold, on != 0); }
|
||||
|
||||
static void present_image(VkImage src, VkImageLayout layout, VkFormat fmt, int w, int h, const int crop[4], int defer) {
|
||||
int general = layout == VK_IMAGE_LAYOUT_GENERAL;
|
||||
gfx_window_start();
|
||||
VkCtx *c = vk_ctx();
|
||||
plat_rmutex_lock(&g_pl);
|
||||
flip_locked();
|
||||
if (plat_cas32(&g_hold, 0, 0)) goto out;
|
||||
if (!g_sc || plat_cas32(&g_dirty, 0, 0)) {
|
||||
if (!wsys_minimized() && !create_swapchain() && !g_sc) goto out;
|
||||
}
|
||||
|
||||
+50
-2
@@ -25,7 +25,9 @@ void rt_log_raw(const char *p, size_t n);
|
||||
const char *rt_log_path(void); // the log file, NULL when this run writes none
|
||||
enum { RT_TRACE_SVC = 1, RT_TRACE_HOSTCALL = 2, RT_TRACE_IPC = 4, RT_TRACE_FS = 8, RT_TRACE_GFX = 16, RT_TRACE_PERF = 32,
|
||||
RT_TRACE_SCHED = 64, RT_TRACE_AUDIO = 128, RT_TRACE_PRESENT = 256,
|
||||
RT_TRACE_HOSTCOUNT = 512 }; // no TOTK_TRACE name of its own: hostfn_count switches it (host.h)
|
||||
RT_TRACE_HOSTCOUNT = 512, // no TOTK_TRACE name of its own: hostfn_count switches it (host.h)
|
||||
RT_TRACE_PLUGIN = 1024 }; // no name either: the plugin service run (plugin_init.c) sees every SVC through
|
||||
// rt_plugin_svc while it runs a plugin's init
|
||||
extern unsigned rt_trace; // from TOTK_TRACE=svc,host,ipc,fs,gfx,perf,sched,audio,present (or all)
|
||||
// prof_win.c: TOTK_PROFILE=<path> sampling profiler; TOTK_TRACE=perf frame timing (waits of the render thread)
|
||||
// PERF_TEX: texture uploads on the render thread (deswizzle, decode, staging), PERF_ASTC included
|
||||
@@ -150,6 +152,7 @@ uint32_t mem_set_attribute(uint64_t a, uint64_t n, uint32_t mask, uint32_t at);
|
||||
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
|
||||
uint32_t mem_query(uint64_t a, RtMemoryInfo *out); // 0x06
|
||||
extern void (*mem_query_hook)(uint64_t a, RtMemoryInfo *r); // plugin service run only: adjusts mem_query's answer
|
||||
uint32_t mem_map_physical(uint64_t a, uint64_t n); // 0x2C
|
||||
uint32_t mem_unmap_physical(uint64_t a, uint64_t n); // 0x2D
|
||||
int mem_info(uint32_t id, uint64_t *out); // GetInfo memory ids 2-7, 12-17, 21, 22, 28; 0 if not a memory id
|
||||
@@ -199,13 +202,24 @@ int rt_oom_forced_left(int site); // forced failures st
|
||||
typedef struct {
|
||||
const char *name; uint64_t base, size, text_end, data_off; // text_end, data_off: offsets from base
|
||||
uint64_t init, init_array, init_array_size, ctor_flag; // absolute guest addresses; init_array_size in bytes
|
||||
int plugin; // a mod's code module (layout plugin<N>), not a game module
|
||||
} RtLoaded;
|
||||
void ldr_load(const char *exefs_dir); // load, relocate (overrides applied), seal; once
|
||||
extern GuestFn ldr_plugin_import; // set before ldr_load (plugin_init.c): every JUMP_SLOT
|
||||
// import of a plugin binds to this observer
|
||||
// The module tables of the runtime library: it is built once per release (tools/build_game.py --make-runtime-lib),
|
||||
// before an install's layout (recomp/layout.py) adds its mod plugins after sdk, so they do not use that MOD_COUNT.
|
||||
#define RT_MAX_MODULES 32
|
||||
int ldr_count(void);
|
||||
int ldr_plugins_gone(uint32_t *key); // layout plugins whose file is gone; mixes their paths into key
|
||||
const RtLoaded *ldr_module(int i); // order: main, subsdk0, sdk
|
||||
uint64_t ldr_symbol(const char *name); // exported definition, 0 if none
|
||||
uint64_t ldr_plt_stub(const char *module, const char *name); // PLT stub whose GOT slot holds name, 0 if none
|
||||
const char *ldr_describe(uint64_t a, char *buf, int n); // "main+0x1234 (symbol+0x10)", "host <name>", or the address
|
||||
uint64_t ldr_nso_size(const char *dir, const char *file); // image size of an ExeFS NSO (SHA-256 checked)
|
||||
void ldr_map_image(const char *dir, const char *file, uint64_t base, uint64_t *text_end, uint64_t *data_off);
|
||||
// its segments at base (reserved by the caller), not
|
||||
// linked: the plugin service run's rtld (plugin_init.c)
|
||||
uint8_t *ldr_read_verified(const char *dir, const char *file, size_t *len); // whole file, SHA-256 checked against
|
||||
// modules.c (fatal on mismatch); free() it
|
||||
|
||||
@@ -309,6 +323,7 @@ int romfs_shaped_ready(unsigned w, unsigned h); // romfs-patches-<w>x
|
||||
int romfs_shaped_prompts_ready(const char *folder, unsigned w, unsigned h); // the same for <folder>-<w>x<h>, a
|
||||
// prompts' folder (romfs-patches-xbox, -xbox-label, -pc)
|
||||
void res_wanted(unsigned out[2]); // the output size TOTK_OUTPUT_RES asks for
|
||||
void res_asked(unsigned out[2]); // the same before a missing shaped layout made it 16:9
|
||||
void res_fov_live(void); // TOTK_FOV to the camera (set fov); on a settings change
|
||||
void res_dynres_live(void); // TOTK_DYNAMIC_RES to the game (set fixres); on a settings change
|
||||
// ---- code patches (patches.c) and the frame step (frame_rate.c)
|
||||
@@ -320,6 +335,25 @@ void rt_patch_disable(int set); // before the guest s
|
||||
void rt_patch_switch(int set, int on); // at run time (live settings): each site takes the new code
|
||||
// the next time it runs
|
||||
void *rt_patch_page(void); // the page the patched code reads (NULL without the table)
|
||||
// Contested sites (recomp/patches.py `ordered`): a site two or more ordered sets patch runs the one that is on with the
|
||||
// lowest rank (a tie: the one later in the patch file); rt_patch_pick[] holds its place, 1 up, 0 for none.
|
||||
typedef struct {
|
||||
const char *module; // "main"
|
||||
uint32_t offset; // the site's module offset
|
||||
const int16_t *sets; // its ordered sets, in the order its C tests them
|
||||
int nsets;
|
||||
} RtPatchPick;
|
||||
void rt_patch_rank(int set, int rank); // an ordered set's rank (0 first: the Mods tab's position);
|
||||
// unranked sets come after every ranked one
|
||||
void rt_patch_picks(void); // every contested site's pick from the sets on and their
|
||||
// ranks; rt_patch_switch of an ordered set redoes its sites
|
||||
int rt_patch_pick_count(void);
|
||||
const RtPatchPick *rt_patch_pick_at(int i); // NULL out of range
|
||||
int rt_patch_pick_winner(int i); // the place in its sets of the set that runs there, -1 none
|
||||
const char *rt_patch_name(int set); // NULL out of range
|
||||
// --probe-mods: a set table of its own (names, n sets, its contested sites), every set off and unranked; names NULL
|
||||
// returns to the generated table.
|
||||
void rt_patch_probe_table(const char *const *names, int n, const RtPatchPick *picks, int npicks);
|
||||
void frame_step_init(void); // after rt_patches_init: the real-time step's first value
|
||||
int frame_step_realtime(void); // the real-time step is on: presents ignore the interval
|
||||
uint64_t frame_step_cap_ns(void); // with the real-time step: the shortest frame in ns
|
||||
@@ -339,13 +373,27 @@ int rt_knob(const char *name, const char *def);
|
||||
void frame_step_present(uint64_t display_ns, int interval); // nvnQueuePresentTexture: the frame's display time and
|
||||
// present interval (60 Hz ticks)
|
||||
// ---- boot (boot.c, main.c)
|
||||
typedef struct { const char *exefs, *romfs, *profile; int boot; double seconds; const char *shot, *gpu; } RtConfig;
|
||||
typedef struct {
|
||||
const char *exefs, *romfs, *profile;
|
||||
int boot;
|
||||
double seconds;
|
||||
const char *shot, *gpu;
|
||||
const char *plugin_init; // --plugin-init DIR: the plugin service run writes its record there (plugin_init.c)
|
||||
} RtConfig;
|
||||
// romfs: directory with romfs.bin and index.json;
|
||||
// frames: --frames N (0 = no limit); shot: --shot
|
||||
// PATH; gpu: TOTK_GPU
|
||||
const RtConfig *rt_config(void);
|
||||
void rt_boot_event(const char *what, Cpu *c, const char *detail); // checkpoint log; "nvn" ends --boot
|
||||
void rt_boot(void); // boot.c
|
||||
void rt_boot_plugin_init(void); // boot.c: --plugin-init, the plugin service run
|
||||
void plugin_init_setup(void); // plugin_init.c: before ldr_load
|
||||
void plugin_init_run(Cpu *c, const RtLoaded *sdk); // plugin_init.c: from the module-init callback; exits
|
||||
void plugins_setup(void); // plugin_init.c: rt_boot, before ldr_load; nothing
|
||||
// without a plugin in the build
|
||||
int plugins_start(Cpu *c, const RtLoaded *sdk); // plugin_init.c: from the module-init callback, before
|
||||
// the game's constructors; 1 when it ran sdk's DT_INIT
|
||||
// (a plugin's init ran after it)
|
||||
// Modes of totk.exe. main.c has run mem_init and parsed the paths; each mode calls ldr_load itself if it needs the
|
||||
// modules, registers its host functions, then seals (hostfn_seal, or implicitly at the first rt_call). Return the
|
||||
// process exit code.
|
||||
|
||||
+319
-43
@@ -4,7 +4,7 @@
|
||||
// system's back end (input_wsys.h: input_win.c with Win32, input_sdl.c with SDL), which also owns the cursor capture.
|
||||
// Keys and their map: docs/controls.md.
|
||||
// The gamepad also rumbles (input_rumble) and, when it has a gyro and an accelerometer, feeds the six-axis sensor from a
|
||||
// thread of its own (input_motion_start). Every SDL call on the gamepad is made under `lock`.
|
||||
// thread of its own (input_motion_start). Every SDL call on the gamepad is made under `lock`, except the rumble writes (rumble_main).
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
@@ -37,12 +37,25 @@ int input_kbm_last(void) { return __atomic_load_n(&g_kbm_last, __ATOMIC_RELAXED)
|
||||
int input_gameplay_active(void) { return !g_menu && !g_block && ikb_foreground() && ikb_captured(); }
|
||||
static SDL_Gamepad *pad;
|
||||
static uint64_t next_scan;
|
||||
static volatile int32_t rumble_ready; // the open gamepad has rumble motors (what input_rumble returns)
|
||||
static void rumble_cancel(void);
|
||||
static int pad_rumble; // the open gamepad has rumble motors
|
||||
static volatile int32_t pad_labels[4]; // ... and the labels of its south, east, west, north buttons (PAD_LABEL_*), any thread
|
||||
static int pad_east_a; // ... and labels its east face button A (Nintendo layout under TOTK_PAD_LAYOUT=auto)
|
||||
static int pad_layout = -1; // PAD_LAYOUT_* in effect for the open gamepad, -1 to pick again; live (cfg_version)
|
||||
static unsigned pad_layout_seen;
|
||||
static volatile int32_t pad_layout_shown = -1; // pad_layout for the menu (any thread), -1 without a gamepad
|
||||
// Steam Input: a game Steam starts gets SDL_GAMECONTROLLER_IGNORE_DEVICES, the vendor/product pairs of the controllers
|
||||
// Steam reads itself, and sees Steam's virtual gamepad in their place. That pad has no motion sensors, so a Steam
|
||||
// Controller, a Steam Deck or a DualSense under Steam Input gives no gyro. steam_reveal keeps the list here and clears
|
||||
// the hint: the buttons and sticks still come from the virtual pad (scan_pads skips the listed devices, so Steam's
|
||||
// remapping holds and nothing is read twice), and only the sensors come from the real controller (motion_source).
|
||||
enum { STEAM_HIDDEN_MAX = 64 };
|
||||
static uint16_t steam_hidden[STEAM_HIDDEN_MAX][2]; // vendor, product
|
||||
static int steam_hidden_n;
|
||||
static SDL_Gamepad *motion_extra; // the hidden controller opened for its sensors only, NULL none
|
||||
static int pad_hidden; // the open gamepad is a controller Steam hid (scan_pads' fallback)
|
||||
static uint64_t next_motion_scan;
|
||||
static SDL_JoystickID sensor_pad; // the gamepad whose sensors the motion thread set up, 0 none
|
||||
static int sensor_ok; // ... and it has both sensors, enabled
|
||||
static int motion_thread; // 0 not started, 1 running, -1 off (TOTK_MOTION=0, no SDL)
|
||||
@@ -102,7 +115,10 @@ static void script_load(void) {
|
||||
ScriptEv e = {.at = (uint64_t)(at * unit + 0.5), .hold = timed ? 66667 : 4, .bit = -1, .timed = timed};
|
||||
long a, b;
|
||||
double c;
|
||||
if (!strcmp(name, "WHEEL")) {
|
||||
if (!strcmp(name, "QUICKSAVE") || !strcmp(name, "QUICKLOAD")) {
|
||||
e.stick = name[5] == 'S' ? 5 : 6, e.hold = 1; // once, as quicksave's keys
|
||||
snprintf(e.text, sizeof e.text, "%s", name);
|
||||
} else if (!strcmp(name, "WHEEL")) {
|
||||
if (sscanf(line + off, "%ld", &a) != 1) { rt_log("input: script line %d: WHEEL needs notches", ln); continue; }
|
||||
e.stick = 4, e.x = (int32_t)a, e.hold = 1; // one turn, never held
|
||||
snprintf(e.text, sizeof e.text, "WHEEL %d", e.x);
|
||||
@@ -150,7 +166,8 @@ static void script_apply(uint64_t *b, int32_t sl[2], int32_t sr[2]) {
|
||||
if (e->timed) rt_log("input: script frame %llu at %.1f ms: %s", (unsigned long long)fr, w / 1000.0, e->text);
|
||||
else rt_log("input: script frame %llu tick %llu: %s", (unsigned long long)fr, (unsigned long long)tick, e->text);
|
||||
}
|
||||
if (e->stick == 4) script_wheel += e->x;
|
||||
if (e->stick >= 5) quicksave_request(e->stick == 6);
|
||||
else if (e->stick == 4) script_wheel += e->x;
|
||||
else if (e->stick == 3) {
|
||||
int64_t x = (int64_t)script_mouse[0] + e->x, y = (int64_t)script_mouse[1] + e->y;
|
||||
script_mouse[0] = (int32_t)(x < INT32_MIN ? INT32_MIN : x > INT32_MAX ? INT32_MAX : x);
|
||||
@@ -347,6 +364,14 @@ static void walk_get(void) {
|
||||
static int mouse_selector;
|
||||
int input_direct_mouse_selector_active(void) { return __atomic_load_n(&mouse_selector, __ATOMIC_RELAXED) != 0; }
|
||||
|
||||
// A script's MOUSE line within the last 100 ms (under `lock`): mouse_camera then makes a stick of it
|
||||
static uint64_t script_mouse_at;
|
||||
static int input_script_mouse_recent(void) {
|
||||
uint64_t now = plat_now_ns();
|
||||
if (script_mouse[0] || script_mouse[1]) script_mouse_at = now;
|
||||
return script_mouse_at && now - script_mouse_at < 100000000ull;
|
||||
}
|
||||
|
||||
// Selector 1 is a radial wheel, 2..4 are distinct horizontal quick lists; only a wheel retains a virtual cursor.
|
||||
// Under `lock`.
|
||||
static void mouse_camera(int32_t out[2], int selector) {
|
||||
@@ -379,7 +404,10 @@ static void mouse_camera(int32_t out[2], int selector) {
|
||||
frame = ~0ull;
|
||||
return; // the camera update takes the raw counts itself, once, outside the HID stick path
|
||||
}
|
||||
if (!ikb_captured()) {
|
||||
// A script's MOUSE lines move the stick as the mouse does, captured or not (in direct mode the camera hook takes
|
||||
// them, input_direct_mouse_sample): for 100 ms after one the stick is the mouse's, as while captured
|
||||
int scripted = input_script_mouse_recent();
|
||||
if (!ikb_captured() && !scripted) {
|
||||
ikb_mouse_take(&dx, &dy);
|
||||
held[0] = held[1] = 0;
|
||||
frame = ~0ull;
|
||||
@@ -389,6 +417,9 @@ static void mouse_camera(int32_t out[2], int selector) {
|
||||
if (fr != frame) {
|
||||
double dt = age < 0.004 ? 0.004 : age > 0.1 ? 0.1 : age;
|
||||
ikb_mouse_take(&dx, &dy);
|
||||
if (!ikb_captured()) dx = dy = 0;
|
||||
dx += script_mouse[0], dy += script_mouse[1];
|
||||
script_mouse[0] = script_mouse[1] = 0;
|
||||
input_mouse_stick(dx, dy, dt, mouse_sens_get(), held);
|
||||
frame = fr;
|
||||
t0 = now;
|
||||
@@ -420,10 +451,86 @@ static void stick(SDL_GamepadAxis ax, SDL_GamepadAxis ay, float dead, int32_t ou
|
||||
input_pad_stick(SDL_GetGamepadAxis(pad, ax), -(int32_t)SDL_GetGamepadAxis(pad, ay), dead, out);
|
||||
}
|
||||
|
||||
// Open the first gamepad when none is open or the open one went away; logs once per change.
|
||||
// Before SDL_Init: keep the controllers Steam hid (steam_hidden) and let SDL open them. The list is
|
||||
// "0xVVVV/0xPPPP,..." (SDL's own format). With motion off (TOTK_MOTION=0 at start) Steam's list stays in force.
|
||||
static void steam_reveal(void) {
|
||||
const char *e = getenv("SDL_GAMECONTROLLER_IGNORE_DEVICES");
|
||||
if (!e || !*e || !cfg_bool("TOTK_MOTION")) return;
|
||||
for (const char *s = e; *s && steam_hidden_n < STEAM_HIDDEN_MAX;) {
|
||||
unsigned v, p;
|
||||
int used = 0;
|
||||
if (sscanf(s, " %x/%x%n", &v, &p, &used) == 2 && used > 0) {
|
||||
steam_hidden[steam_hidden_n][0] = (uint16_t)v;
|
||||
steam_hidden[steam_hidden_n][1] = (uint16_t)p;
|
||||
steam_hidden_n++;
|
||||
s += used;
|
||||
}
|
||||
const char *c = strchr(s, ',');
|
||||
if (!c) break;
|
||||
s = c + 1;
|
||||
}
|
||||
if (!steam_hidden_n) return;
|
||||
// The environment outranks a hint of normal priority, so this one overrides it
|
||||
SDL_SetHintWithPriority(SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES, "", SDL_HINT_OVERRIDE);
|
||||
rt_log("input: Steam Input hides %d controller type(s); buttons stay on Steam's virtual gamepad, motion is read "
|
||||
"from the controller itself", steam_hidden_n);
|
||||
}
|
||||
|
||||
// The ids the device itself reports. SDL_GetGamepadVendorForID and ...ProductForID give a Steam virtual pad the ids of
|
||||
// the controller behind it, which would make it look like a controller Steam hid; the GUID keeps the device's own.
|
||||
static void raw_ids(SDL_JoystickID id, uint16_t *v, uint16_t *p) {
|
||||
SDL_GetJoystickGUIDInfo(SDL_GetGamepadGUIDForID(id), v, p, NULL, NULL);
|
||||
}
|
||||
|
||||
static int steam_hidden_id(SDL_JoystickID id) {
|
||||
uint16_t v, p;
|
||||
raw_ids(id, &v, &p);
|
||||
for (int i = 0; i < steam_hidden_n; i++)
|
||||
if (steam_hidden[i][0] == v && steam_hidden[i][1] == p) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
// Steam's virtual gamepad: Valve's vendor id with product 0x11ff in the device's own ids (raw_ids; SDL's
|
||||
// SDL_IsJoystickSteamVirtualGamepad is not public)
|
||||
static int steam_virtual(SDL_Gamepad *g) {
|
||||
uint16_t v, p;
|
||||
raw_ids(SDL_GetGamepadID(g), &v, &p);
|
||||
return v == 0x28de && p == 0x11ff;
|
||||
}
|
||||
|
||||
static int has_motion(SDL_Gamepad *g) {
|
||||
return SDL_GamepadHasSensor(g, SDL_SENSOR_GYRO) && SDL_GamepadHasSensor(g, SDL_SENSOR_ACCEL);
|
||||
}
|
||||
|
||||
// A gamepad Steam did not hide is connected (Steam's virtual pad, or another controller).
|
||||
static int unhidden_pad_present(void) {
|
||||
int n = 0, found = 0;
|
||||
SDL_JoystickID *ids = SDL_GetGamepads(&n);
|
||||
for (int i = 0; ids && i < n && !found; i++) found = !steam_hidden_id(ids[i]);
|
||||
SDL_free(ids);
|
||||
return found;
|
||||
}
|
||||
|
||||
// Open the first gamepad when none is open or the open one went away; logs once per change. A controller Steam hid
|
||||
// (steam_hidden) is taken only when no other gamepad is there, e.g. while Steam's virtual pad is not up yet, and gives
|
||||
// way to the virtual pad once it is (pad_physical looks again every RESCAN_MS while pad_hidden): otherwise Steam's
|
||||
// remapping would be lost for the session. The hidden controller then stays open for its sensors (motion_extra), so
|
||||
// its bias and orientation go on.
|
||||
static void scan_pads(void) {
|
||||
if (pad && SDL_GamepadConnected(pad)) return;
|
||||
if (pad && SDL_GamepadConnected(pad)) {
|
||||
if (!pad_hidden || !unhidden_pad_present()) return;
|
||||
rt_log("input: Steam Input's virtual gamepad is up: buttons move to it from \"%s\"", SDL_GetGamepadName(pad));
|
||||
if (!motion_extra && has_motion(pad)) motion_extra = pad;
|
||||
else SDL_CloseGamepad(pad);
|
||||
pad = NULL;
|
||||
pad_hidden = 0;
|
||||
plat_xchg32(&rumble_ready, 0);
|
||||
rumble_cancel();
|
||||
}
|
||||
if (pad) {
|
||||
plat_xchg32(&rumble_ready, 0);
|
||||
rumble_cancel();
|
||||
SDL_CloseGamepad(pad); pad = NULL; sensor_pad = 0; sensor_ok = 0;
|
||||
// Its bias and an attempt collecting from it go with it; the next pad gets its own in pad_bias_select.
|
||||
motion_bias_reset(motion_global());
|
||||
@@ -434,10 +541,18 @@ static void scan_pads(void) {
|
||||
}
|
||||
int n = 0;
|
||||
SDL_JoystickID *ids = SDL_GetGamepads(&n);
|
||||
for (int i = 0; ids && i < n && !pad; i++) pad = SDL_OpenGamepad(ids[i]);
|
||||
for (int pass = 0; pass < 2 && !pad; pass++)
|
||||
for (int i = 0; ids && i < n && !pad; i++)
|
||||
if (steam_hidden_id(ids[i]) == pass) {
|
||||
// The controller motion_source holds for its sensors serves as the pad too: one open handle
|
||||
if (motion_extra && SDL_GetGamepadID(motion_extra) == ids[i]) { pad = motion_extra; motion_extra = NULL; }
|
||||
else pad = SDL_OpenGamepad(ids[i]);
|
||||
}
|
||||
SDL_free(ids);
|
||||
if (!pad) return;
|
||||
pad_hidden = steam_hidden_n && steam_hidden_id(SDL_GetGamepadID(pad));
|
||||
pad_rumble = SDL_GetBooleanProperty(SDL_GetGamepadProperties(pad), SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false);
|
||||
plat_xchg32(&rumble_ready, pad_rumble);
|
||||
pad_east_a = SDL_GetGamepadButtonLabel(pad, SDL_GAMEPAD_BUTTON_EAST) == SDL_GAMEPAD_BUTTON_LABEL_A;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
SDL_GamepadButtonLabel lb = SDL_GetGamepadButtonLabel(pad, pad_sdl[PAD_SOUTH + i]);
|
||||
@@ -453,7 +568,10 @@ static void scan_pads(void) {
|
||||
}
|
||||
pad_layout = -1;
|
||||
int motion = SDL_GamepadHasSensor(pad, SDL_SENSOR_GYRO) && SDL_GamepadHasSensor(pad, SDL_SENSOR_ACCEL);
|
||||
rt_log("input: gamepad \"%s\" (%s, %s, east button %s)", SDL_GetGamepadName(pad), pad_rumble ? "rumble" : "no rumble",
|
||||
uint16_t rv, rp;
|
||||
raw_ids(SDL_GetGamepadID(pad), &rv, &rp);
|
||||
rt_log("input: gamepad \"%s\" %04x:%04x%s (%s, %s, east button %s)", SDL_GetGamepadName(pad), rv, rp,
|
||||
steam_virtual(pad) ? " Steam Input" : "", pad_rumble ? "rumble" : "no rumble",
|
||||
motion ? "gyro and accelerometer" : "no motion sensors", pad_east_a ? "labelled A" : "not labelled A");
|
||||
}
|
||||
|
||||
@@ -496,6 +614,20 @@ static void binds_refresh(void) {
|
||||
// TOTK_TEST_PAD=<lx>,<ly>,<rx>,<ry> (test runs): an SDL virtual gamepad whose sticks rest at these raw SDL axis values
|
||||
// (-32768..32767, down is +y), attached before the first scan so it is the gamepad the game reads: drift and full
|
||||
// deflection go through the same mapping and dead zone as a real pad.
|
||||
// TOTK_TEST_PAD_RUMBLE_MS=<n>: the test gamepad has rumble and each write to it takes n ms (a slow Bluetooth HID write),
|
||||
// to show that input_rumble does not wait for it. Read with cfg_get, as TOTK_TEST_PAD is: a test variable has no row in
|
||||
// the settings table, and cfg_int stops the game on a name without one.
|
||||
static int test_pad_rumble_ms(void) {
|
||||
const char *e = cfg_get("TOTK_TEST_PAD_RUMBLE_MS");
|
||||
return e ? atoi(e) : 0;
|
||||
}
|
||||
|
||||
static bool test_pad_rumble(void *userdata, Uint16 low, Uint16 high) {
|
||||
(void)userdata; (void)low; (void)high;
|
||||
plat_wait_ns((uint64_t)test_pad_rumble_ms() * 1000000ull);
|
||||
return true;
|
||||
}
|
||||
|
||||
static void test_pad_attach(void) {
|
||||
static SDL_Joystick *joy; // kept open: a virtual joystick's axes are set through an open handle
|
||||
const char *e = cfg_get("TOTK_TEST_PAD");
|
||||
@@ -511,6 +643,7 @@ static void test_pad_attach(void) {
|
||||
d.naxes = SDL_GAMEPAD_AXIS_COUNT;
|
||||
d.nbuttons = SDL_GAMEPAD_BUTTON_COUNT;
|
||||
d.name = "TotK test gamepad";
|
||||
if (test_pad_rumble_ms() > 0) d.Rumble = test_pad_rumble;
|
||||
SDL_JoystickID id = SDL_AttachVirtualJoystick(&d);
|
||||
joy = id ? SDL_OpenJoystick(id) : NULL;
|
||||
if (!joy) {
|
||||
@@ -528,6 +661,14 @@ static void start(void) {
|
||||
binds_refresh();
|
||||
const char *e = cfg_get("TOTK_INPUT");
|
||||
if (e && !strcmp(e, "none")) { state = -1; rt_log("input: disabled (TOTK_INPUT=none)"); return; }
|
||||
steam_reveal();
|
||||
// SDL drops gamepad button presses and stick movements (and leaves the polled state unchanged) while its own
|
||||
// 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");
|
||||
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();
|
||||
@@ -650,7 +791,7 @@ static void wheel_route(uint64_t *bp, int32_t sl[2], int32_t sr[2]) {
|
||||
|
||||
// Under lock, state 1: the open gamepad's inputs by position (pd[PAD_*] != 0 held); 0 without a connected gamepad.
|
||||
static int pad_physical(uint8_t pd[PAD_COUNT]) {
|
||||
if ((!pad || !SDL_GamepadConnected(pad)) && plat_now_ns() / 1000000u >= next_scan) { next_scan = plat_now_ns() / 1000000u + RESCAN_MS; scan_pads(); }
|
||||
if ((!pad || !SDL_GamepadConnected(pad) || pad_hidden) && plat_now_ns() / 1000000u >= next_scan) { next_scan = plat_now_ns() / 1000000u + RESCAN_MS; scan_pads(); }
|
||||
SDL_UpdateGamepads();
|
||||
if (!pad || !SDL_GamepadConnected(pad)) return 0;
|
||||
for (int p = PAD_SOUTH; p < PAD_ZL; p++) pd[p] = SDL_GetGamepadButton(pad, pad_sdl[p]);
|
||||
@@ -741,6 +882,9 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
|
||||
else if (!click_held[i]) click_held[i] = 1, click_talk[i] = menu_cursor_dialogue();
|
||||
if (click_talk[i]) down[key] = 0, b |= 1ull << click_btn[i];
|
||||
}
|
||||
// The quick save and quick load keys are quicksave's while it is on (quicksave.c): they reach no binding
|
||||
// then, and do nothing while the settings menu or a text entry is open
|
||||
if (quicksave_on()) quicksave_keys(down, !g_menu && !g_block);
|
||||
if (cap && !g_menu && !g_block) gameplay_tweaks_prepare_keys(down, b);
|
||||
else gameplay_tweaks_reset();
|
||||
b |= input_map_buttons(down);
|
||||
@@ -777,6 +921,13 @@ static void poll_merged(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx
|
||||
if (pad_used) __atomic_store_n(&g_kbm_last, 0, __ATOMIC_RELAXED);
|
||||
else if (kbm_used) __atomic_store_n(&g_kbm_last, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
// Without the keyboard and mouse poll above (TOTK_INPUT=none in scripted runs, or the window in the background), a
|
||||
// script's MOUSE lines still move the right stick wherever the mouse would (mouse_camera)
|
||||
if (!(state > 0 && ikb_foreground()) && input_script_mouse_recent() && !input_direct_mouse_active()) {
|
||||
int32_t k[2];
|
||||
mouse_camera(k, 0);
|
||||
pick(&sr[0], &sr[1], k[0], k[1]);
|
||||
}
|
||||
script_apply(&b, sl, sr);
|
||||
wheel_route(&b, sl, sr);
|
||||
gameplay_tweaks_apply(__atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED), input_gameplay_active(), &b, &sl[0], &sl[1], &sr[0], &sr[1]);
|
||||
@@ -852,7 +1003,10 @@ static int blocked(volatile int32_t *flag, volatile uint64_t *closed, const char
|
||||
|
||||
void input_poll(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) {
|
||||
poll_merged(buttons, lx, ly, rx, ry);
|
||||
if (!g_block && !g_menu) menu_cursor_poll(buttons);
|
||||
// While quick load drives the game's load menu the pointer leaves it alone and the game gets only its presses
|
||||
if (!g_block && !g_menu && !quicksave_busy()) menu_cursor_poll(buttons);
|
||||
// A quick load under way goes on while the settings menu or a text entry opens: the held picture ends with it
|
||||
if ((quicksave_busy() || (!g_block && !g_menu)) && quicksave_poll(buttons, lx, ly, rx, ry)) return;
|
||||
const int32_t axes[4] = {*lx, *ly, *rx, *ry};
|
||||
int text = blocked(&g_block, &g_block_closed, "text entry", *buttons, axes),
|
||||
menu = blocked(&g_menu, &g_menu_closed, "menu", *buttons, axes);
|
||||
@@ -930,17 +1084,83 @@ int input_rumble_triggers_enabled(void) {
|
||||
return cfg_bool("TOTK_RUMBLE_TRIGGERS");
|
||||
}
|
||||
|
||||
int input_rumble(uint16_t low, uint16_t high, uint32_t ms) {
|
||||
int ok = 0;
|
||||
static int triggers = -1;
|
||||
static unsigned seen;
|
||||
if (triggers < 0 || seen != cfg_version()) seen = cfg_version(), triggers = input_rumble_triggers_enabled();
|
||||
// The rumble worker. input_rumble only stores the newest request (rq) and wakes the worker; the worker sends it to the
|
||||
// gamepad. A Bluetooth HID write can block for tens of milliseconds, and the callers are the guest thread that runs
|
||||
// SendVibrationValue and every path that takes `lock`, so no SDL rumble call is made on them. Requests that pile up
|
||||
// while the worker is in a write are dropped except the newest (Savage Wind Recomp, commit a8ad674, does the same for
|
||||
// issue #730).
|
||||
//
|
||||
// The worker takes its own handle on the open gamepad under `lock` (SDL_OpenGamepad of an open pad's id returns the same
|
||||
// object with its reference count raised) and releases `lock` before the write, so a scan_pads close of `pad` meanwhile
|
||||
// only drops one reference and the object lives until the worker's SDL_CloseGamepad. SDL itself serialises the write
|
||||
// with its other joystick calls (SDL_RumbleJoystick runs under the joystick lock), so a poll or motion_main's
|
||||
// SDL_UpdateGamepads that lands inside a slow write still waits for it; the thread that sends rumble and the other
|
||||
// `lock` users that make no SDL gamepad call do not.
|
||||
typedef struct { uint16_t low, high; uint32_t ms; int pending; } RumbleReq;
|
||||
static PlatMutex rq_lock = PLAT_MUTEX_INIT; // guards rq, rumble_stop and rumble_thread; taken after `lock`, never before it
|
||||
static PlatCond rq_cond = PLAT_COND_INIT;
|
||||
static RumbleReq rq;
|
||||
static int rumble_stop;
|
||||
static PlatThread *rumble_thread;
|
||||
|
||||
static void rumble_write(uint16_t low, uint16_t high, uint32_t ms) {
|
||||
SDL_Gamepad *g = NULL;
|
||||
int triggers = input_rumble_triggers_enabled();
|
||||
plat_mutex_lock(&lock);
|
||||
if (state == 1 && pad && pad_rumble) {
|
||||
ok = SDL_RumbleGamepad(pad, low, high, ms);
|
||||
if (triggers) SDL_RumbleGamepadTriggers(pad, high, high, ms); // unsupported pads return false: ignored
|
||||
}
|
||||
if (state == 1 && pad && pad_rumble) g = SDL_OpenGamepad(SDL_GetGamepadID(pad));
|
||||
plat_mutex_unlock(&lock);
|
||||
if (!g) return;
|
||||
SDL_RumbleGamepad(g, low, high, ms);
|
||||
if (triggers) SDL_RumbleGamepadTriggers(g, high, high, ms); // unsupported pads return false: ignored
|
||||
SDL_CloseGamepad(g);
|
||||
}
|
||||
|
||||
static void rumble_main(void *arg) {
|
||||
(void)arg;
|
||||
plat_mutex_lock(&rq_lock);
|
||||
for (;;) {
|
||||
while (!rq.pending && !rumble_stop) plat_cond_wait(&rq_cond, &rq_lock);
|
||||
if (!rq.pending) break;
|
||||
RumbleReq r = rq;
|
||||
rq.pending = 0;
|
||||
plat_mutex_unlock(&rq_lock);
|
||||
rumble_write(r.low, r.high, r.ms);
|
||||
plat_mutex_lock(&rq_lock);
|
||||
}
|
||||
plat_mutex_unlock(&rq_lock);
|
||||
}
|
||||
|
||||
// Stops the motors and the worker at exit: a pad keeps its last request running for its duration otherwise.
|
||||
static void rumble_exit(void) {
|
||||
plat_mutex_lock(&rq_lock);
|
||||
PlatThread *t = rumble_thread;
|
||||
rq = (RumbleReq){0, 0, 0, 1};
|
||||
rumble_stop = 1;
|
||||
plat_cond_signal(&rq_cond);
|
||||
plat_mutex_unlock(&rq_lock);
|
||||
if (t) plat_thread_join_ns(t, 300000000ull); // a write stuck past this is left to the exit
|
||||
}
|
||||
|
||||
// Drops the request that has not been sent yet (the gamepad it was for went away). A request in flight holds its own
|
||||
// handle and ends by itself. Under lock.
|
||||
static void rumble_cancel(void) {
|
||||
plat_mutex_lock(&rq_lock);
|
||||
rq.pending = 0;
|
||||
plat_mutex_unlock(&rq_lock);
|
||||
}
|
||||
|
||||
int input_rumble(uint16_t low, uint16_t high, uint32_t ms) {
|
||||
int ok = __atomic_load_n(&rumble_ready, __ATOMIC_ACQUIRE);
|
||||
if (!ok) return 0;
|
||||
plat_mutex_lock(&rq_lock);
|
||||
if (!rumble_thread && !rumble_stop) {
|
||||
rumble_thread = plat_thread_new(rumble_main, NULL, "rumble");
|
||||
if (!rumble_thread) rt_fatal("input: cannot start the rumble thread");
|
||||
atexit(rumble_exit);
|
||||
}
|
||||
rq = (RumbleReq){low, high, ms, 1};
|
||||
plat_cond_signal(&rq_cond);
|
||||
plat_mutex_unlock(&rq_lock);
|
||||
return ok;
|
||||
}
|
||||
|
||||
@@ -973,17 +1193,24 @@ static void copy_name(char *dst, size_t cap, const char *src) {
|
||||
dst[n] = 0;
|
||||
}
|
||||
|
||||
// Under lock: the open gamepad's identity for the saved bias. Its name, plus a hash of SDL's serial when the pad
|
||||
// Under lock: the identity of src (motion_source) for the saved bias. Its name, plus a hash of SDL's serial when the pad
|
||||
// reports one (Switch and PlayStation pads report their Bluetooth address), so two controllers of one model keep their
|
||||
// own bias; the hash keeps the address out of totk.ini and the log, which players post with bug reports.
|
||||
static void pad_identity(char *dst, size_t cap) {
|
||||
const char *name = SDL_GetGamepadName(pad), *serial = SDL_GetGamepadSerial(pad);
|
||||
static void pad_identity(SDL_Gamepad *src, char *dst, size_t cap) {
|
||||
const char *name = SDL_GetGamepadName(src), *serial = SDL_GetGamepadSerial(src);
|
||||
char id[160];
|
||||
if (serial && *serial) {
|
||||
uint32_t h = 2166136261u; // FNV-1a
|
||||
for (const char *c = serial; *c; c++) h = (h ^ (uint8_t)*c) * 16777619u;
|
||||
snprintf(id, sizeof id, "%s #%08x", name ? name : "", h);
|
||||
} else snprintf(id, sizeof id, "%s", name ? name : "");
|
||||
// Steam's virtual pad takes the name of the controller behind it but sends Steam's corrected motion: its bias
|
||||
// is its own (pad_bias_select would otherwise load the raw controller's)
|
||||
// A controller read past Steam Input sends what Steam set it to: on the Steam Controller that is motion the
|
||||
// controller already corrected, so the bias of the same controller read with Steam closed does not apply either
|
||||
if (steam_virtual(src)) strncat(id, " (Steam Input)", sizeof id - strlen(id) - 1);
|
||||
else if (steam_hidden_n && steam_hidden_id(SDL_GetGamepadID(src)))
|
||||
strncat(id, " (under Steam)", sizeof id - strlen(id) - 1);
|
||||
copy_name(dst, cap, id);
|
||||
}
|
||||
|
||||
@@ -991,35 +1218,82 @@ static void pad_identity(char *dst, size_t cap) {
|
||||
// previous controller's bias and any attempt still collecting from it are dropped, then the bias saved in totk.ini is
|
||||
// taken when gyro_bias_pad names this controller. It is taken with gyro_calibration off too: the switch only decides
|
||||
// whether motion_feed subtracts it, so turning the switch on mid-run applies the saved bias.
|
||||
static void pad_bias_select(void) {
|
||||
static void pad_bias_select(SDL_Gamepad *src) {
|
||||
char id[128];
|
||||
pad_identity(id, sizeof id);
|
||||
pad_identity(src, id, sizeof id);
|
||||
motion_bias_reset(motion_global());
|
||||
calib_pad_name[0] = 0;
|
||||
const char *saved = cfg_get("TOTK_GYRO_BIAS_PAD");
|
||||
if (saved && !strcmp(saved, id)) {
|
||||
motion_bias_load(motion_global());
|
||||
copy_name(calib_pad_name, sizeof calib_pad_name, SDL_GetGamepadName(pad));
|
||||
copy_name(calib_pad_name, sizeof calib_pad_name, SDL_GetGamepadName(src));
|
||||
rt_log("input: gyro bias loaded from totk.ini for %s", calib_pad_name);
|
||||
}
|
||||
}
|
||||
|
||||
// Under lock: (re)enable the sensors when the open gamepad changed; 1 if it has both and they are on.
|
||||
static int sensors_ready(void) {
|
||||
SDL_JoystickID id = SDL_GetGamepadID(pad);
|
||||
// Under lock: the gamepad the sensors are read from, NULL without one. The open pad when it has a gyro and an
|
||||
// accelerometer, or when Steam hid nothing. Otherwise (Steam's virtual pad, which has neither) the first controller
|
||||
// Steam hid that has both, looked for once a RESCAN_MS; one without them is not opened again until it reconnects.
|
||||
static SDL_Gamepad *motion_source(void) {
|
||||
static SDL_JoystickID rejected[8];
|
||||
if (motion_extra && !SDL_GamepadConnected(motion_extra)) {
|
||||
rt_log("input: \"%s\" (motion only) disconnected", SDL_GetGamepadName(motion_extra));
|
||||
SDL_CloseGamepad(motion_extra);
|
||||
motion_extra = NULL;
|
||||
}
|
||||
int pad_on = pad && SDL_GamepadConnected(pad);
|
||||
// Newer Steam clients give the virtual pad motion too, but already corrected by Steam (and gated by the layout's
|
||||
// gyro settings), so the bias calibrated on the raw controller would count twice and the camera drift. Under
|
||||
// Steam Input the real controller's raw sensors come first; the virtual pad's are the fallback.
|
||||
if (pad_on && has_motion(pad) && !(steam_hidden_n && steam_virtual(pad))) {
|
||||
if (motion_extra) { SDL_CloseGamepad(motion_extra); motion_extra = NULL; }
|
||||
return pad;
|
||||
}
|
||||
if (!motion_extra && steam_hidden_n && plat_now_ns() / 1000000u >= next_motion_scan) {
|
||||
next_motion_scan = plat_now_ns() / 1000000u + RESCAN_MS;
|
||||
int n = 0;
|
||||
SDL_JoystickID *ids = SDL_GetGamepads(&n), skip = pad_on ? SDL_GetGamepadID(pad) : 0;
|
||||
for (int i = 0; ids && i < n && !motion_extra; i++) {
|
||||
int seen = 0;
|
||||
for (int r = 0; r < 8; r++) seen |= rejected[r] == ids[i];
|
||||
if (ids[i] == skip || seen || !steam_hidden_id(ids[i])) continue;
|
||||
SDL_Gamepad *g = SDL_OpenGamepad(ids[i]);
|
||||
if (g && has_motion(g)) {
|
||||
motion_extra = g;
|
||||
rt_log("input: motion from \"%s\" (%04x:%04x), the controller behind Steam Input's virtual gamepad",
|
||||
SDL_GetGamepadName(g), SDL_GetGamepadVendor(g), SDL_GetGamepadProduct(g));
|
||||
} else {
|
||||
if (g) SDL_CloseGamepad(g);
|
||||
memmove(rejected + 1, rejected, sizeof rejected - sizeof rejected[0]);
|
||||
rejected[0] = ids[i];
|
||||
}
|
||||
}
|
||||
SDL_free(ids);
|
||||
}
|
||||
return motion_extra ? motion_extra : pad_on ? pad : NULL;
|
||||
}
|
||||
|
||||
// Under lock: (re)enable the sensors when the motion source changed; 1 if it has both and they are on.
|
||||
static int sensors_ready(SDL_Gamepad *src) {
|
||||
SDL_JoystickID id = SDL_GetGamepadID(src);
|
||||
if (id == sensor_pad) return sensor_ok;
|
||||
sensor_pad = id;
|
||||
pad_bias_select();
|
||||
pad_bias_select(src);
|
||||
// Nothing drains the SDL event queue: no event per sample (the data still updates, SDL_SendJoystickSensor)
|
||||
SDL_SetEventEnabled(SDL_EVENT_GAMEPAD_SENSOR_UPDATE, false);
|
||||
sensor_ok =SDL_GamepadHasSensor(pad, SDL_SENSOR_GYRO) && SDL_GamepadHasSensor(pad, SDL_SENSOR_ACCEL) &&
|
||||
SDL_SetGamepadSensorEnabled(pad, SDL_SENSOR_GYRO, true) &&
|
||||
SDL_SetGamepadSensorEnabled(pad, SDL_SENSOR_ACCEL, true);
|
||||
if (sensor_ok) rt_log("input: motion sensors on (gyro %.0f Hz, accelerometer %.0f Hz)",
|
||||
(double)SDL_GetGamepadSensorDataRate(pad, SDL_SENSOR_GYRO),
|
||||
(double)SDL_GetGamepadSensorDataRate(pad, SDL_SENSOR_ACCEL));
|
||||
sensor_ok = has_motion(src) &&
|
||||
SDL_SetGamepadSensorEnabled(src, SDL_SENSOR_GYRO, true) &&
|
||||
SDL_SetGamepadSensorEnabled(src, SDL_SENSOR_ACCEL, true);
|
||||
if (sensor_ok) {
|
||||
rt_log("input: motion sensors on (gyro %.0f Hz, accelerometer %.0f Hz)",
|
||||
(double)SDL_GetGamepadSensorDataRate(src, SDL_SENSOR_GYRO),
|
||||
(double)SDL_GetGamepadSensorDataRate(src, SDL_SENSOR_ACCEL));
|
||||
motion_restart(motion_global()); // another controller: its own orientation, from its first reading
|
||||
} else if (has_motion(src)) // after PR #1024: the SDL error, not "no sensors", when enabling them failed
|
||||
rt_log("input: \"%s\" has a gyro and an accelerometer but SDL could not turn them on (%s): the six-axis sensor "
|
||||
"reads a controller at rest", SDL_GetGamepadName(src), SDL_GetError());
|
||||
else rt_log("input: \"%s\" has no gyro and accelerometer: the six-axis sensor reads a controller at rest",
|
||||
SDL_GetGamepadName(pad));
|
||||
SDL_GetGamepadName(src));
|
||||
return sensor_ok;
|
||||
}
|
||||
|
||||
@@ -1044,10 +1318,11 @@ static void motion_main(void *arg) {
|
||||
float a[3], g[3];
|
||||
int have = 0;
|
||||
plat_mutex_lock(&lock);
|
||||
if (pad && SDL_GamepadConnected(pad)) {
|
||||
SDL_Gamepad *src = motion_source();
|
||||
if (src) {
|
||||
SDL_UpdateGamepads();
|
||||
have = sensors_ready() && SDL_GetGamepadSensorData(pad, SDL_SENSOR_ACCEL, a, 3) &&
|
||||
SDL_GetGamepadSensorData(pad, SDL_SENSOR_GYRO, g, 3);
|
||||
have = sensors_ready(src) && SDL_GetGamepadSensorData(src, SDL_SENSOR_ACCEL, a, 3) &&
|
||||
SDL_GetGamepadSensorData(src, SDL_SENSOR_GYRO, g, 3);
|
||||
}
|
||||
plat_mutex_unlock(&lock);
|
||||
if (!have || !input_motion_enabled()) continue;
|
||||
@@ -1080,18 +1355,19 @@ void input_motion_calibrate(void) {
|
||||
// The menu can run before the game starts the six-axis sensor (the title screen): the thread starts here then.
|
||||
if (input_gyro_calibration_enabled() && input_motion_enabled()) motion_thread_start();
|
||||
const char *why = NULL;
|
||||
SDL_Gamepad *src = motion_thread == 1 ? motion_source() : NULL;
|
||||
if (!input_gyro_calibration_enabled()) why = "gyro_calibration is off";
|
||||
else if (!input_motion_enabled()) why = "motion is off (TOTK_MOTION=0)";
|
||||
else if (motion_thread != 1) why = "no SDL gamepad support";
|
||||
else if (!pad || !SDL_GamepadConnected(pad)) why = "no gamepad";
|
||||
else if (!src) why = "no gamepad";
|
||||
// sensors_ready here, not at the sensor thread's next look at a new pad: that look selects the pad's bias and
|
||||
// would cancel the attempt that starts below.
|
||||
else if (!sensors_ready()) why = "the gamepad has no gyro and accelerometer";
|
||||
else if (!sensors_ready(src)) why = "the gamepad has no gyro and accelerometer";
|
||||
if (why) rt_log("input: calibrate gyro ignored: %s", why);
|
||||
else {
|
||||
char id[128];
|
||||
pad_identity(id, sizeof id);
|
||||
copy_name(calib_pad_name, sizeof calib_pad_name, SDL_GetGamepadName(pad));
|
||||
pad_identity(src, id, sizeof id);
|
||||
copy_name(calib_pad_name, sizeof calib_pad_name, SDL_GetGamepadName(src));
|
||||
motion_calibrate_start(motion_global(), id, kern_now_ns());
|
||||
rt_log("input: gyro calibration started on %s", calib_pad_name);
|
||||
}
|
||||
|
||||
@@ -58,6 +58,27 @@ int menu_cursor_menu(void);
|
||||
int menu_cursor_strip(void);
|
||||
// The Purah Pad's camera is open: its frame and pointer without the map the Scope has. 0 with the menu cursor off.
|
||||
int menu_cursor_camera(void);
|
||||
// menu_cursor.c, the game's menus by name for quicksave.c (game thread, 1.4.3): a screen of that layout is open; the
|
||||
// screen with the focus box (its layout name) and the focused node, 0 with none; the focused screen's shown button of
|
||||
// parts layout parts with root pane root (usable_out: it can be pressed), 0 none; the load list's first entry with a
|
||||
// save; the focus to node (1 once it is there)
|
||||
int menu_ui_open(const char *layout);
|
||||
int menu_ui_focus(char *screen, size_t n, uint64_t *node);
|
||||
uint64_t menu_ui_button(const char *parts, const char *root, int *usable_out);
|
||||
uint64_t menu_ui_first_save(void);
|
||||
int menu_ui_focus_to(uint64_t node);
|
||||
// quicksave.c (TOTK_QUICKSAVE): keys: the keys held now, its two keys (TOTK_QUICKSAVE_KEY, TOTK_QUICKLOAD_KEY) start
|
||||
// it when pressed and act is set, and are cleared from down either way; request: save (0) or load (1), as the keys
|
||||
// and the script lines QUICKSAVE / QUICKLOAD do; guest: once per game pad read on the game thread, where quick save
|
||||
// calls into the game; poll: once per game pad read, 1 while quick load drives the game's load menu with its own
|
||||
// presses in place of the input; busy: quick load runs
|
||||
struct Cpu;
|
||||
int quicksave_on(void); // TOTK_QUICKSAVE is on and the game is 1.4.3
|
||||
void quicksave_keys(uint8_t *down, int act);
|
||||
void quicksave_request(int load);
|
||||
void quicksave_guest(struct Cpu *c);
|
||||
int quicksave_poll(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry);
|
||||
int quicksave_busy(void);
|
||||
// The same for host UI (the text entry): never blocked. input_block(1) while a text entry is open: input_poll then
|
||||
// reports nothing; input_block(0) when it closes: nothing until all buttons and stick directions are released.
|
||||
void input_poll_ui(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry);
|
||||
@@ -128,6 +149,9 @@ int input_motion_calib_state(char *pad, size_t cap);
|
||||
int input_gyro_calibration_enabled(void);
|
||||
// The fusion's own read of the same switch (motion_fusion.c); input.c reaches it for the row's state.
|
||||
int motion_calibration_enabled(void);
|
||||
// The drift tracker's switch (gyro_auto_bias, live): the drift left after calibration, learned while the controller
|
||||
// lies still, is subtracted too.
|
||||
int motion_auto_bias_enabled(void);
|
||||
// SDL sensor values (accelerometer m/s^2, gyro rad/s, SDL gamepad axes) to the Switch controller frame motion_feed
|
||||
// takes (acceleration in G as gravity reads, rotation rad/s). The mapping is documented in input_win.c.
|
||||
void input_motion_axes(const float sdl_acc[3], const float sdl_gyro[3], double acc_g[3], double gyro[3]);
|
||||
|
||||
+6
-1
@@ -307,12 +307,17 @@ int input_pad_layout_pick(const char *setting, int east_labelled_a) {
|
||||
|
||||
int input_prompts_pick(const char *prompts, const char *pad_layout) {
|
||||
if (prompts && *prompts)
|
||||
return !strcasecmp(prompts, "xbox") ? PROMPTS_XBOX : !strcasecmp(prompts, "pc") ? PROMPTS_PC : PROMPTS_NINTENDO;
|
||||
return !strcasecmp(prompts, "xbox") ? PROMPTS_XBOX
|
||||
: !strcasecmp(prompts, "playstation") || !strcasecmp(prompts, "ps") ? PROMPTS_PLAYSTATION
|
||||
: !strcasecmp(prompts, "pc") ? PROMPTS_PC : PROMPTS_NINTENDO;
|
||||
return pad_layout && !strcasecmp(pad_layout, "xbox_prompts") ? PROMPTS_XBOX : PROMPTS_NINTENDO;
|
||||
}
|
||||
|
||||
const char *input_prompts_folder(int prompts, const char *pad_layout) {
|
||||
if (prompts == PROMPTS_PC) return "romfs-patches-pc";
|
||||
if (prompts == PROMPTS_PLAYSTATION)
|
||||
return input_pad_layout_pick(pad_layout, 0) == PAD_LAYOUT_NINTENDO ? "romfs-patches-playstation"
|
||||
: "romfs-patches-playstation-xbox";
|
||||
if (prompts != PROMPTS_XBOX) return NULL;
|
||||
// The folders are read at start, before a pad is open: auto counts as Xbox, as for a pad without Nintendo labels.
|
||||
// A Nintendo-labelled pad under auto plays by label too (its A is on the button labelled A), so it matches as well.
|
||||
|
||||
+10
-7
@@ -91,18 +91,21 @@ int input_pad_layout_pick(const char *setting, int east_labelled_a);
|
||||
|
||||
// Button prompts (TOTK_PROMPTS): the controller whose buttons the game's prompts show. Nintendo: the game's own. Xbox:
|
||||
// LB RB LT RT, Menu, View and a d-pad cross for the other buttons, and the face buttons named by the label of the
|
||||
// button the pad layout presses (runtime/romfs.c overlay_init, tools/make_romfs_patches.py --prompts). PC: the key or
|
||||
// button the pad layout presses (runtime/romfs.c overlay_init, tools/make_romfs_patches.py --prompts). PlayStation: the
|
||||
// face buttons as ○ × △ □, L1 R1 L2 R2, Options and Share, likewise on the button the pad layout presses. PC: the key or
|
||||
// mouse button the keyboard defaults press each button with, the mouse for the right stick.
|
||||
enum { PROMPTS_NINTENDO, PROMPTS_XBOX, PROMPTS_PC };
|
||||
// The prompts for a TOTK_PROMPTS value ("nintendo", "xbox" or "pc", any case). Unset or empty: Xbox while the pad
|
||||
// layout setting is "xbox_prompts", else Nintendo.
|
||||
enum { PROMPTS_NINTENDO, PROMPTS_XBOX, PROMPTS_PLAYSTATION, PROMPTS_PC };
|
||||
// The prompts for a TOTK_PROMPTS value ("nintendo", "xbox", "playstation" or "pc", any case). Unset or empty: Xbox
|
||||
// while the pad layout setting is "xbox_prompts", else Nintendo.
|
||||
int input_prompts_pick(const char *prompts, const char *pad_layout);
|
||||
// The folder next to romfs-index.bin that holds those prompts for a TOTK_PAD_LAYOUT value, NULL for the game's own. The
|
||||
// Nintendo layout plays an Xbox pad by position, so its folder names the face buttons the other way round
|
||||
// (romfs-patches-xbox: the right button does A and is labelled B); xbox and auto put every Switch button on the button
|
||||
// labelled with its letter (auto picks the layout per pad by its labels), so they share romfs-patches-xbox-label. The PC
|
||||
// prompts follow no pad: romfs-patches-pc whatever the layout (romfs.c overlay_init serves romfs-patches-pc-<w>x<h>
|
||||
// under that name at a game resolution of another shape).
|
||||
// labelled with its letter (auto picks the layout per pad by its labels), so they share romfs-patches-xbox-label. The
|
||||
// PlayStation prompts have the same two folders: romfs-patches-playstation (Nintendo layout, A on the right button is
|
||||
// circle) and romfs-patches-playstation-xbox (xbox and auto, A on the bottom button is cross). The PC prompts follow no
|
||||
// pad: romfs-patches-pc whatever the layout (romfs.c overlay_init serves romfs-patches-pc-<w>x<h> under that name at a
|
||||
// game resolution of another shape).
|
||||
const char *input_prompts_folder(int prompts, const char *pad_layout);
|
||||
// down[pad] != 0 for the gamepad inputs held. Returns the Switch button bits (0..15) the layout's pad table presses.
|
||||
uint64_t input_map_pad_buttons(const uint8_t down[PAD_COUNT], int layout);
|
||||
|
||||
@@ -38,3 +38,10 @@ extern volatile int kern_test_cv_old_order; // WaitProcessWideKeyAtomi
|
||||
// the key (MNG's pre-fix order, the negative control)
|
||||
extern void (*volatile kern_test_cv_hook)(void); // called right after the lock release, holding the kernel lock
|
||||
extern void (*volatile svc_test_exit_hook)(unsigned code); // svc 0x07 calls it instead of ExitProcess (probes)
|
||||
|
||||
// ---- mod plugin service run (plugin_init.c sets these; the game calls none of the SVCs they serve)
|
||||
extern uint64_t rt_svc_tick_offset; // added to GetSystemTick (0x1E): the service run's second run picks other ticks
|
||||
extern int (*rt_plugin_svc)(Cpu *c, uint32_t imm, uint64_t pc); // with RT_TRACE_PLUGIN: sees each SVC
|
||||
// first; 1: refused, the result is in x0 and the SVC does not run
|
||||
extern uint32_t (*rt_process_memory)(int unmap, uint64_t dst, uint32_t process, uint64_t src, uint64_t size);
|
||||
// Map/UnmapProcessMemory (0x74/0x75); NULL outside the service run: fatal
|
||||
+95
-16
@@ -47,11 +47,12 @@ typedef struct {
|
||||
uint64_t *plt_slot, *plt_stub, nplt; // PLT stubs sorted by GOT slot (ldr_plt_stub), built on first use
|
||||
// statistics
|
||||
uint64_t kinds[K_COUNT], sym_import, sym_own;
|
||||
uint32_t imports, import_to[MOD_COUNT], weak_unresolved, strong_unresolved;
|
||||
uint32_t imports, import_to[RT_MAX_MODULES], weak_unresolved, strong_unresolved;
|
||||
uint32_t init_off;
|
||||
} Mod;
|
||||
|
||||
static Mod mods[MOD_COUNT];
|
||||
static Mod mods[RT_MAX_MODULES];
|
||||
GuestFn ldr_plugin_import;
|
||||
static int nmods;
|
||||
static uint64_t identity_refs, stubs;
|
||||
static int *ovr_used, *obs_used; // per linked table entry, plus probe overrides counted separately
|
||||
@@ -74,6 +75,51 @@ static void hex32(const uint8_t d[32], char out[65]) {
|
||||
for (int i = 0; i < 32; i++) snprintf(out + 2 * i, 3, "%02x", d[i]);
|
||||
}
|
||||
|
||||
static uint8_t *read_path_verified(const char *path, const char *want, size_t *len, const char *hint) {
|
||||
uint8_t *p = read_file(path, len);
|
||||
if (!p) rt_fatal("loader: cannot read %s (%s)", path, hint);
|
||||
uint8_t d[32];
|
||||
char hex[65];
|
||||
rt_sha256(p, *len, d);
|
||||
hex32(d, hex);
|
||||
if (strcmp(hex, want)) rt_fatal("loader: %s has SHA-256 %s, expected %s", path, hex, want);
|
||||
return p;
|
||||
}
|
||||
|
||||
// Mod plugins of the layout whose file is gone (their mod was removed): a rebuild without them is due (cheats.c
|
||||
// rebuild_if_needed), keyed by their paths.
|
||||
static int plugins_gone;
|
||||
static uint32_t plugins_gone_key = 0x811C9DC5u;
|
||||
|
||||
int ldr_plugins_gone(uint32_t *key) {
|
||||
if (plugins_gone) *key = (*key ^ plugins_gone_key) * 0x01000193u;
|
||||
return plugins_gone;
|
||||
}
|
||||
|
||||
// 1 when the plugin file of lay is the one the build lifted; logged when not.
|
||||
static int plugin_file_ok(const RtLayoutEntry *lay) {
|
||||
size_t len;
|
||||
uint8_t *p = read_file(lay->file, &len);
|
||||
if (!p) {
|
||||
rt_log("loader: %s: cannot read %s; the plugin is left out", lay->name, lay->file);
|
||||
if (!plat_file_exists(lay->file)) {
|
||||
plugins_gone++;
|
||||
for (const char *c = lay->file; *c; c++) plugins_gone_key = (plugins_gone_key ^ (uint8_t)*c) * 0x01000193u;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
uint8_t d[32];
|
||||
char hex[65];
|
||||
rt_sha256(p, len, d);
|
||||
free(p);
|
||||
hex32(d, hex);
|
||||
if (strcmp(hex, lay->sha256)) {
|
||||
rt_log("loader: %s: %s changed since the build lifted it; the plugin is left out", lay->name, lay->file);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
uint8_t *ldr_read_verified(const char *dir, const char *file, size_t *len) {
|
||||
const char *want = NULL;
|
||||
for (int i = 0; i < rt_exefs_sha256_count; i++)
|
||||
@@ -81,14 +127,7 @@ uint8_t *ldr_read_verified(const char *dir, const char *file, size_t *len) {
|
||||
if (!want) rt_fatal("loader: no expected SHA-256 for %s in modules.c", file);
|
||||
char path[1024];
|
||||
snprintf(path, sizeof path, "%s/%s", dir, file);
|
||||
uint8_t *p = read_file(path, len);
|
||||
if (!p) rt_fatal("loader: cannot read %s (extract the game first: tools/extract.py)", path);
|
||||
uint8_t d[32];
|
||||
char hex[65];
|
||||
rt_sha256(p, *len, d);
|
||||
hex32(d, hex);
|
||||
if (strcmp(hex, want)) rt_fatal("loader: %s has SHA-256 %s, expected %s", path, hex, want);
|
||||
return p;
|
||||
return read_path_verified(path, want, len, "extract the game first: tools/extract.py");
|
||||
}
|
||||
|
||||
// ---- NSO
|
||||
@@ -141,6 +180,32 @@ static void nso_segment(const uint8_t *raw, const Seg *s, uint8_t *dst, const ch
|
||||
}
|
||||
}
|
||||
|
||||
// The plugin service run's stand-in for rtld (plugin_init.c): an ExeFS NSO's image, read and checked like a module but
|
||||
// neither relocated, linked nor sealed. Nothing runs it; exlaunch only reads it while it walks the address space.
|
||||
uint64_t ldr_nso_size(const char *dir, const char *file) {
|
||||
size_t len;
|
||||
uint8_t *raw = ldr_read_verified(dir, file, &len);
|
||||
Seg seg[3];
|
||||
uint64_t size = nso_segments(raw, len, file, seg);
|
||||
free(raw);
|
||||
return size;
|
||||
}
|
||||
|
||||
void ldr_map_image(const char *dir, const char *file, uint64_t base, uint64_t *text_end, uint64_t *data_off) {
|
||||
size_t len;
|
||||
uint8_t *raw = ldr_read_verified(dir, file, &len);
|
||||
Seg seg[3];
|
||||
uint64_t size = nso_segments(raw, len, file, seg);
|
||||
if (!plat_mem_commit(base, size)) rt_fatal("loader: cannot commit %s at %#llx", file, (unsigned long long)base);
|
||||
for (int i = 0; i < 3; i++) {
|
||||
if ((uint64_t)seg[i].mem_off + seg[i].size > size) rt_fatal("loader: %s segment %d exceeds the image", file, i);
|
||||
nso_segment(raw, &seg[i], (uint8_t *)(uintptr_t)(base + seg[i].mem_off), file, i);
|
||||
}
|
||||
free(raw);
|
||||
*text_end = seg[0].mem_off + seg[0].size;
|
||||
*data_off = seg[2].mem_off;
|
||||
}
|
||||
|
||||
// ---- symbols
|
||||
static const char *sym_name(const Mod *m, uint32_t i) { return m->strtab + m->syms[i].name; }
|
||||
static int sym_defined(const Mod *m, uint32_t i) { return m->syms[i].shndx != 0; }
|
||||
@@ -273,9 +338,12 @@ static uint64_t decode_ctor_flag(const Mod *m) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// A plugin (lay->file set) comes from its mod folder, checked against the hash the build took when it lifted it.
|
||||
static void load_module(Mod *m, const char *dir, const RtLayoutEntry *lay) {
|
||||
size_t len;
|
||||
uint8_t *raw = ldr_read_verified(dir, lay->name, &len);
|
||||
uint8_t *raw = lay->file ? read_path_verified(lay->file, lay->sha256, &len, "the mod's code module the build "
|
||||
"lifted; rebuild after changing mods")
|
||||
: ldr_read_verified(dir, lay->name, &len);
|
||||
Seg seg[3];
|
||||
uint64_t size = nso_segments(raw, len, lay->name, seg);
|
||||
if (size != lay->size)
|
||||
@@ -291,6 +359,7 @@ static void load_module(Mod *m, const char *dir, const RtLayoutEntry *lay) {
|
||||
}
|
||||
free(raw);
|
||||
m->pub.name = lay->name;
|
||||
m->pub.plugin = lay->file != NULL;
|
||||
m->pub.base = lay->base;
|
||||
m->pub.size = size;
|
||||
m->pub.text_end = seg[0].mem_off + seg[0].size;
|
||||
@@ -328,7 +397,11 @@ 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 && (f = hostfn_observer(name))) {
|
||||
if (jump && m->pub.plugin && ldr_plugin_import) { // the plugin service run counts the plugin's calls by name
|
||||
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};
|
||||
} else if (jump && (f = hostfn_observer(name))) {
|
||||
r = (Res){hostfn_register_observer(name, f, guest), RES_OBSERVER};
|
||||
mark_used(1, name);
|
||||
} else if ((f = hostfn_override(name))) {
|
||||
@@ -444,9 +517,15 @@ static void seal(Mod *m) {
|
||||
void ldr_load(const char *exefs_dir) {
|
||||
if (nmods) rt_fatal("ldr_load called twice");
|
||||
if (!mem_layout()->pool) rt_fatal("ldr_load before mem_init");
|
||||
if (rt_layout_count > MOD_COUNT) rt_fatal("loader: %d modules in the layout", rt_layout_count);
|
||||
for (int i = 0; i < rt_layout_count; i++) load_module(&mods[i], exefs_dir, &rt_layout[i]);
|
||||
nmods = rt_layout_count;
|
||||
if (rt_layout_count > RT_MAX_MODULES) rt_fatal("loader: %d modules in the layout", rt_layout_count);
|
||||
int n = 0;
|
||||
for (int i = 0; i < rt_layout_count; i++) {
|
||||
// A mod plugin's file that is gone or changed since the build is left out at play time: its patch set cannot
|
||||
// run (plugin_init.c plugins_start keeps it off); the plugin service run needs it and stops.
|
||||
if (rt_layout[i].file && !rt_config()->plugin_init && !plugin_file_ok(&rt_layout[i])) continue;
|
||||
load_module(&mods[n++], exefs_dir, &rt_layout[i]);
|
||||
}
|
||||
nmods = n;
|
||||
ovr_used = calloc(hostfn_table_size(0) + 1, sizeof(int));
|
||||
obs_used = calloc(hostfn_table_size(1) + 1, sizeof(int));
|
||||
for (int i = 0; i < nmods; i++) {
|
||||
@@ -557,7 +636,7 @@ uint64_t ldr_plt_stub(const char *module, const char *name) {
|
||||
typedef struct {
|
||||
const char *name;
|
||||
uint64_t kinds[K_COUNT], total, sym_import, sym_own;
|
||||
uint32_t imports, to[MOD_COUNT], weak, init_off, init_array;
|
||||
uint32_t imports, to[RT_MAX_MODULES], weak, init_off, init_array;
|
||||
} Expect;
|
||||
static const Expect expect_121[] = {
|
||||
{"main", {508816, 1415, 32, 641}, 510904, 2088, 0, 675, {0, 16, 647}, 12, 0x30, 10673},
|
||||
|
||||
+6
-1
@@ -611,7 +611,7 @@ static int usage(const char *argv0) {
|
||||
"--probe-cfg | --probe-dpi | --probe-mods | --probe-playtime | --probe-kernel | --probe-ipc | --probe-services | --probe-fs | --probe-gfx-abi | "
|
||||
"--probe-nvn | --probe-nvn-tex | --probe-window | --probe-shader | --probe-vkmem | "
|
||||
"--probe-vkexec | --probe-astc | --probe-movie | --probe-crash-call | --probe-crash-null | --probe-discord | "
|
||||
"--prepare-shaders | --warm-shaders | --boot |--seconds S [--shot PNG]]\n", argv0);
|
||||
"--prepare-shaders | --warm-shaders | --boot | --plugin-init DIR | --seconds S [--shot PNG]]\n", argv0);
|
||||
return 2;
|
||||
}
|
||||
|
||||
@@ -700,6 +700,10 @@ int main(int argc, char **argv) {
|
||||
} else if (!strcmp(argv[i], "--shot")) {
|
||||
if (++i == argc) return usage(argv[0]);
|
||||
cfg.shot = argv[i];
|
||||
} else if (!mode && !strcmp(argv[i], "--plugin-init")) { // the plugin service run (plugin_init.c)
|
||||
if (++i == argc) return usage(argv[0]);
|
||||
mode = argv[i - 1];
|
||||
cfg.plugin_init = argv[i];
|
||||
} else if (!mode && !strncmp(argv[i], "--", 2)) {
|
||||
mode = argv[i];
|
||||
} else {
|
||||
@@ -744,5 +748,6 @@ int main(int argc, char **argv) {
|
||||
if (!strcmp(mode, "--prepare-shaders")) return vk_pipeline_prepare_shaders();
|
||||
if (!strcmp(mode, "--warm-shaders")) return vk_pipeline_warm_shaders();
|
||||
if (!strcmp(mode, "--boot")) { cfg.boot = 1; rt_boot(); return 0; }
|
||||
if (!strcmp(mode, "--plugin-init")) { rt_boot_plugin_init(); return 0; }
|
||||
return usage(argv[0]);
|
||||
}
|
||||
+6
-2
@@ -57,7 +57,7 @@ static uint8_t *alias_pages; // 1 per mapped 4 KiB page of the alias regi
|
||||
typedef struct { uint64_t dst, src, size; } StackMap;
|
||||
static StackMap stack_maps[MAX_STACK_MAPS];
|
||||
static unsigned nstack_maps;
|
||||
static uint8_t *module_perm[MOD_COUNT]; // per data page of each module: perm | ATTR_PERMISSION_LOCKED
|
||||
static uint8_t *module_perm[RT_MAX_MODULES]; // per data page of each module: perm | ATTR_PERMISSION_LOCKED
|
||||
|
||||
static uint64_t align_up(uint64_t v, uint64_t a) { return (v + a - 1) & ~(a - 1); }
|
||||
|
||||
@@ -530,7 +530,7 @@ uint32_t mem_unmap_physical(uint64_t a, uint64_t n) { return alias_map(1, a, n);
|
||||
// as taken (Code, RX), so the SDK never picks it.
|
||||
static void taken_gap(uint64_t a, uint64_t *base, uint64_t *size) {
|
||||
uint64_t lo = 0, hi = RT_ADDRESS_LIMIT;
|
||||
RtRange known[3 + MOD_COUNT + 2];
|
||||
RtRange known[3 + RT_MAX_MODULES + 2];
|
||||
int n = 0;
|
||||
known[n++] = (RtRange){L.aslr.base, low_size};
|
||||
known[n++] = L.alias;
|
||||
@@ -562,6 +562,9 @@ static uint64_t run_start(const uint8_t *p, uint64_t i, uint8_t v) { // first
|
||||
return i;
|
||||
}
|
||||
|
||||
// The plugin service run (plugin_init.c) shows rtld, its process-memory aliases and its free pool here.
|
||||
void (*mem_query_hook)(uint64_t a, RtMemoryInfo *r);
|
||||
|
||||
uint32_t mem_query(uint64_t a, RtMemoryInfo *out) {
|
||||
RtMemoryInfo r = {.base = a & ~(PAGE - 1), .size = PAGE};
|
||||
uint64_t low = L.aslr.base;
|
||||
@@ -632,6 +635,7 @@ uint32_t mem_query(uint64_t a, RtMemoryInfo *out) {
|
||||
r.size = hi - lo;
|
||||
}
|
||||
plat_mutex_unlock_shared(&lock);
|
||||
if (mem_query_hook) mem_query_hook(a, &r);
|
||||
if (out) *out = r;
|
||||
return R_OK;
|
||||
}
|
||||
|
||||
@@ -499,3 +499,103 @@ int menu_cursor_shortcut(void) {
|
||||
if (f.screen) layout_name(f.screen, nm, sizeof nm);
|
||||
return f.screen && (!strcmp(nm, "ShortCutMainItem_00") || !strcmp(nm, "ShortCut_00"));
|
||||
}
|
||||
|
||||
// ---- The game's menus for quicksave.c, on the game thread: the same reads and focus writes as above, by name
|
||||
static void main_range(void) {
|
||||
if (!main_lo) main_lo = MOD_MAIN_BASE, main_hi = MOD_MAIN_BASE + MAIN_SIZE;
|
||||
}
|
||||
// nn::ui2d::Pane: its name (+0xb0, 24 characters) and its children, an intrusive list whose links (+0x8 in each
|
||||
// child) start at +0x20
|
||||
enum { PANE_CHILDREN = 0x20, PANE_LINK = 0x8, PANE_NAME = 0xb0, PANE_NAME_MAX = 24 };
|
||||
static int pane_named(uint64_t pane, const char *name) {
|
||||
if (!ok_at(pane, PANE_NAME + PANE_NAME_MAX)) return 0;
|
||||
char nm[PANE_NAME_MAX + 1];
|
||||
memcpy(nm, (const void *)(uintptr_t)(pane + PANE_NAME), PANE_NAME_MAX);
|
||||
nm[PANE_NAME_MAX] = 0;
|
||||
return !strcmp(nm, name);
|
||||
}
|
||||
// The pane called name in the tree under pane, depth first, 0: none
|
||||
static uint64_t pane_find(uint64_t pane, const char *name, int depth) {
|
||||
if (pane_named(pane, name)) return pane;
|
||||
if (depth >= 6 || !ok_at(pane, PANE_NAME + PANE_NAME_MAX)) return 0;
|
||||
uint64_t head = pane + PANE_CHILDREN;
|
||||
int n = 0;
|
||||
for (uint64_t link = rd64(head); link != head && n < 64; link = rd64(link), n++) {
|
||||
if (!ok_at(link, 16)) return 0;
|
||||
uint64_t child = link - PANE_LINK;
|
||||
if (!ok_at(child, PANE_NAME + PANE_NAME_MAX) || rd64(child + PANE_PARENT) != pane) return 0;
|
||||
uint64_t hit = pane_find(child, name, depth + 1);
|
||||
if (hit) return hit;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int menu_ui_open(const char *layout) {
|
||||
main_range();
|
||||
uint64_t sm = screen_mgr();
|
||||
if (!sm) return 0;
|
||||
int32_t n = (int32_t)rd32(sm + SM_COUNT);
|
||||
uint64_t arr = rd64(sm + SM_SCREENS);
|
||||
if (n <= 0 || n > 1024 || !ok_at(arr, 8ull * (uint64_t)n)) return 0;
|
||||
for (int32_t i = 0; i < n; i++) {
|
||||
uint64_t scr = rd64(arr + 8ull * (uint64_t)i);
|
||||
if (!game_object(scr, SCR_REQUEST + 1) || rd8(scr + SCR_STATE) != SCR_OPENED) continue;
|
||||
char nm[48];
|
||||
layout_name(scr, nm, sizeof nm);
|
||||
if (!strcmp(nm, layout)) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int menu_ui_focus(char *screen, size_t n, uint64_t *node) {
|
||||
main_range();
|
||||
Focus f = focus_now();
|
||||
screen[0] = 0, *node = f.node;
|
||||
if (f.screen) layout_name(f.screen, screen, n);
|
||||
return f.screen != 0;
|
||||
}
|
||||
|
||||
uint64_t menu_ui_button(const char *parts, const char *root, int *usable_out) {
|
||||
main_range();
|
||||
Focus f = focus_now();
|
||||
if (!f.screen) return 0;
|
||||
static uint64_t node[MAX_NODES], btn[MAX_NODES];
|
||||
int n = nodes_of(f.screen, node, btn);
|
||||
for (int i = 0; i < n; i++) {
|
||||
uint64_t pane = root_pane(btn[i]);
|
||||
char nm[48];
|
||||
layout_name(btn[i] - SCR_LAYOUT + BTN_LAYOUT, nm, sizeof nm); // the button's parts layout
|
||||
if (strcmp(nm, parts) || !pane_named(pane, root) || !pane_shown(pane)) continue;
|
||||
if (usable_out) *usable_out = usable(btn[i]);
|
||||
return node[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// SystemLoadList_00 lists the saves as PaDataFileBtn_00 entries, newest first; an entry without a save fades
|
||||
// N_Disable_00 out (and is not shown when the list is shorter). The first entry that holds a save, 0 none.
|
||||
uint64_t menu_ui_first_save(void) {
|
||||
main_range();
|
||||
Focus f = focus_now();
|
||||
if (!f.screen) return 0;
|
||||
static uint64_t node[MAX_NODES], btn[MAX_NODES];
|
||||
int n = nodes_of(f.screen, node, btn);
|
||||
for (int i = 0; i < n; i++) {
|
||||
uint64_t pane = root_pane(btn[i]);
|
||||
char nm[48];
|
||||
layout_name(btn[i] - SCR_LAYOUT + BTN_LAYOUT, nm, sizeof nm);
|
||||
if (strcmp(nm, "PaDataFileBtn_00") || !usable(btn[i]) || !pane_shown(pane)) continue;
|
||||
uint64_t filled = pane_find(pane, "N_Disable_00", 0);
|
||||
if (filled && rd8(filled + PANE_ALPHA) >= 128) return node[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int menu_ui_focus_to(uint64_t node) {
|
||||
main_range();
|
||||
Focus f = focus_now();
|
||||
if (!f.screen || !node) return 0;
|
||||
if (f.node == node) return 1;
|
||||
move_focus(&f, node);
|
||||
return 0;
|
||||
}
|
||||
+359
-34
@@ -9,7 +9,14 @@
|
||||
// The order and the switches are totk.ini keys (cfg.c): TOTK_MODS_ORDER lists names top first, separated by '|' (a
|
||||
// Windows file name cannot hold '|'; a folder whose name does on Linux is listed as unusable); a folder it does not name
|
||||
// goes below the named ones, by name. TOTK_MODS_DISABLED lists the switched-off names. The menu changes the list in
|
||||
// place and writes both keys; the scan's state is kept to tell the menu a restart is due.
|
||||
// place and writes both keys; the scan's state is kept to tell the menu a restart is due. TOTK_MODS_NO_CODE lists the
|
||||
// mods used without their code part (their switch "use without its code"; TOTK_MODS_WITHOUT_CODE = 1 is that switch on
|
||||
// for every mod).
|
||||
//
|
||||
// The order decides every conflict, top mod winning: romfs.c serves the top mod's file, mods_exefs_apply stores the
|
||||
// top mod's data bytes last and ranks each mod's patch sets by its position (rt_patch_rank), so at a code site several
|
||||
// mods patch the top one's code runs (patches.c rt_patch_picks). What a mod won or lost goes into one conflict table
|
||||
// (mods_conflict), which the menu and the log read.
|
||||
//
|
||||
// ExeFS patch files: an .ips or .pchtxt file in the exefs folder or in atmosphere/exefs_patches/<name>/ is for the game
|
||||
// when its build id is main's (an IPS file's name, a pchtxt file's @nsobid line); others are another version's and
|
||||
@@ -18,6 +25,15 @@
|
||||
// rebuild at start (cheats.c), and its mod stays off until then. A file's writes into main's data (.rodata, .data,
|
||||
// .bss) are lines of build-cache/exefs.data, stored into the loaded main before the game runs (mods_exefs_data), as
|
||||
// emulators apply a patch file to the module before its dynamic linker runs.
|
||||
//
|
||||
// Code modules: an exefs/subsdk* file is a plugin that patches main from its own start-up on the Switch (exlaunch).
|
||||
// The setup builds it in (tools/exefs_plugins.py, after the design in #845 by itaskaev2) and writes its line into
|
||||
// build-cache/plugins.status (the format of exefs.status): `plugin`, its patch set mod_<hash> holds its hook sites and
|
||||
// its init runs at every start (plugin_init.c); `unsupported`, the note says why the build refused it. A plugin without
|
||||
// a line waits for the rebuild like an ExeFS patch file; one whose start differed from the build is listed in
|
||||
// build-cache/plugins.stale (mods_plugin_off) and waits for it too. A replaced exefs/main is another game code the port
|
||||
// cannot load. A code module the port cannot run (ModInfo.code names them) keeps its mod off unless it is used without
|
||||
// its code, which also leaves out the ExeFS patch files the port cannot apply.
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -36,7 +52,10 @@ static ModInfo *mods;
|
||||
static int nmods;
|
||||
static char dir[2048];
|
||||
static char start_order[MAX_MODS][256]; // names in the scan's order and their switches, for mods_changed
|
||||
static int start_enabled[MAX_MODS];
|
||||
static int start_enabled[MAX_MODS], start_no_code[MAX_MODS];
|
||||
#define MAX_CONFLICTS 1024
|
||||
static ModConflict conflicts[MAX_CONFLICTS];
|
||||
static int nconflicts;
|
||||
|
||||
// 1 when a file lies anywhere under path.
|
||||
static int has_file_cb(const char *name, int kind, uint64_t size, void *ctx);
|
||||
@@ -72,14 +91,29 @@ static int ends_with_ci(const char *s, const char *tail) {
|
||||
return n >= t && !strcasecmp(s + n - t, tail);
|
||||
}
|
||||
|
||||
// A code module of m the port cannot run, named in m->code.
|
||||
static void code_unrun(ModInfo *m, const char *name) {
|
||||
size_t k = strlen(m->code);
|
||||
snprintf(m->code + k, sizeof m->code - k, "%s%s", k ? ", " : "", name);
|
||||
}
|
||||
|
||||
static void plugin_file(ModInfo *m, const char *leaf);
|
||||
|
||||
// What the ExeFS folder holds: MOD_EXEFS for patches (.ips, .pchtxt), MOD_SUBSDK for code modules (subsdk* plugins, a
|
||||
// replaced main). main.npdm alone is the process's metadata, not code: it counts as neither.
|
||||
static int exefs_cb(const char *name, int kind, uint64_t size, void *ctx) {
|
||||
(void)size;
|
||||
int *k = ctx;
|
||||
ModInfo *m = ctx;
|
||||
if (kind != PLAT_FS_FILE) return 1;
|
||||
if (ends_with_ci(name, ".ips") || ends_with_ci(name, ".pchtxt")) *k |= MOD_EXEFS;
|
||||
else if (!strncasecmp(name, "subsdk", 6) || !strcasecmp(name, "main")) *k |= MOD_SUBSDK;
|
||||
if (ends_with_ci(name, ".ips") || ends_with_ci(name, ".pchtxt")) {
|
||||
m->kind |= MOD_EXEFS;
|
||||
} else if (!strncasecmp(name, "subsdk", 6)) {
|
||||
m->kind |= MOD_SUBSDK;
|
||||
plugin_file(m, name);
|
||||
} else if (!strcasecmp(name, "main")) {
|
||||
m->kind |= MOD_SUBSDK;
|
||||
code_unrun(m, name);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -127,9 +161,13 @@ static int by_order(const void *a, const void *b) {
|
||||
static const char *problem_name(ModProblem p) {
|
||||
switch (p) {
|
||||
case MOD_EMPTY: return "empty";
|
||||
case MOD_PLUGIN: return "has a code module (subsdk or main), not supported; the whole mod stays off";
|
||||
case MOD_PLUGIN:
|
||||
return "has a code module (subsdk or main), not supported; the whole mod stays off (its switch \"use without "
|
||||
"its code\" uses the rest of it)";
|
||||
case MOD_EXEFS_LATER: return "ExeFS patches wait for a rebuild of the game code; the whole mod stays off";
|
||||
case MOD_EXEFS_UNSUPPORTED: return "an ExeFS patch file cannot be applied; the whole mod stays off";
|
||||
case MOD_EXEFS_UNSUPPORTED:
|
||||
return "an ExeFS patch file cannot be applied; the whole mod stays off (its switch \"use without its code\" "
|
||||
"uses the rest of it)";
|
||||
case MOD_EXEFS_OTHER: return "its ExeFS patches are for another game version";
|
||||
case MOD_BAD_NAME: return "its folder name holds '|', which the order list uses; rename the folder";
|
||||
default: return "ok";
|
||||
@@ -174,6 +212,7 @@ static int same_build(const char *hex, size_t n) {
|
||||
|
||||
// build-cache/<name> next to totk.exe, read once into *text; "" when there is none (mods_probe_cache sets the text).
|
||||
static char *status_text, *data_text;
|
||||
static int no_stale_file; // --probe-mods: plugins.stale stays in memory
|
||||
static const char *build_cache(const char *name, char **text) {
|
||||
if (*text) return *text;
|
||||
char path[2100];
|
||||
@@ -189,14 +228,17 @@ static const char *build_cache(const char *name, char **text) {
|
||||
return *text;
|
||||
}
|
||||
|
||||
static char *plugin_status_text, *plugin_stale_text;
|
||||
static const char *exefs_status(void) { return build_cache("exefs.status", &status_text); }
|
||||
static const char *exefs_data(void) { return build_cache("exefs.data", &data_text); }
|
||||
static const char *plugin_status(void) { return build_cache("plugins.status", &plugin_status_text); }
|
||||
static const char *plugin_stale(void) { return build_cache("plugins.stale", &plugin_stale_text); }
|
||||
|
||||
// The status line of key: its kind, built-in sets and note, NUL-terminated copies; 0 when none.
|
||||
static int status_line(const char *key, const char *content, char *kind, char *over, char *note) {
|
||||
// The line of key in a status text: its kind, built-in sets and note, NUL-terminated copies; 0 when none.
|
||||
static int status_in(const char *text, const char *key, const char *content, char *kind, char *over, char *note) {
|
||||
char want[20];
|
||||
snprintf(want, sizeof want, "%s\t%s\t", key, content);
|
||||
for (const char *line = exefs_status(); *line;) {
|
||||
for (const char *line = text; *line;) {
|
||||
const char *end = strchr(line, '\n');
|
||||
size_t len = end ? (size_t)(end - line) : strlen(line);
|
||||
if (len > 18 && !memcmp(line, want, 18)) {
|
||||
@@ -218,6 +260,69 @@ static int status_line(const char *key, const char *content, char *kind, char *o
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int status_line(const char *key, const char *content, char *kind, char *over, char *note) {
|
||||
return status_in(exefs_status(), key, content, kind, over, note);
|
||||
}
|
||||
|
||||
// The reason plugins.stale gives for key and content, or NULL.
|
||||
static const char *stale_reason(const char *key, const char *content, char *out, size_t cap) {
|
||||
char want[20];
|
||||
snprintf(want, sizeof want, "%s\t%s\t", key, content);
|
||||
for (const char *line = plugin_stale(); *line;) {
|
||||
const char *end = strchr(line, '\n');
|
||||
size_t len = end ? (size_t)(end - line) : strlen(line);
|
||||
if (len > 18 && !memcmp(line, want, 18)) {
|
||||
size_t n = len - 18;
|
||||
if (n && line[len - 1] == '\r') n--;
|
||||
snprintf(out, cap, "%.*s", (int)(n < cap ? n : cap - 1), line + 18);
|
||||
return out;
|
||||
}
|
||||
line = end ? end + 1 : line + len;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// One exefs/subsdk* file of m: a built plugin joins its patch sets, a refused one is code it cannot run, one the build
|
||||
// lacks (or whose start differed from the build) waits for the rebuild.
|
||||
static void plugin_file(ModInfo *m, const char *leaf) {
|
||||
char path[4300], rel[600];
|
||||
snprintf(path, sizeof path, "%s/%s", m->exefs, leaf);
|
||||
size_t root = strlen(dir) + 1 + strlen(m->name) + 1; // m->exefs is <dir>/<mod>/<exefs place>
|
||||
snprintf(rel, sizeof rel, "%s/%s/%s", m->name, strlen(m->exefs) > root ? m->exefs + root : "exefs", leaf);
|
||||
uint64_t n = 0;
|
||||
char *data = (char *)plat_file_read(path, &n);
|
||||
if (!data) {
|
||||
rt_log("mods: %s: cannot read %s", m->name, path);
|
||||
code_unrun(m, leaf);
|
||||
return;
|
||||
}
|
||||
char key[9], content[9], kind[16], over[256], note[256], stale[256];
|
||||
snprintf(key, sizeof key, "%08X", fnv(rel, strlen(rel)));
|
||||
snprintf(content, sizeof content, "%08X", fnv(data, (size_t)n));
|
||||
free(data);
|
||||
if (!status_in(plugin_status(), key, content, kind, over, note) || stale_reason(key, content, stale, sizeof stale)) {
|
||||
m->pending++;
|
||||
m->pending_key = (m->pending_key ^ fnv(key, 8)) * 0x01000193u;
|
||||
m->pending_key = (m->pending_key ^ fnv(content, 8)) * 0x01000193u;
|
||||
return;
|
||||
}
|
||||
if (!strcmp(kind, "plugin") && m->nsets < (int)(sizeof m->sets / sizeof *m->sets) &&
|
||||
m->nplugins < (int)(sizeof m->plugin_keys / sizeof *m->plugin_keys)) {
|
||||
uint32_t k = (uint32_t)strtoul(key, NULL, 16);
|
||||
m->sets[m->nsets++] = k;
|
||||
m->plugin_keys[m->nplugins] = k;
|
||||
m->plugin_contents[m->nplugins++] = (uint32_t)strtoul(content, NULL, 16);
|
||||
const char *hooks = strstr(note, ", ");
|
||||
m->plugin_hooks += hooks ? atoi(hooks + 2) : 0;
|
||||
size_t at = strlen(m->overrides);
|
||||
if (*over) snprintf(m->overrides + at, sizeof m->overrides - at, "%s%s", at ? "," : "", over);
|
||||
} else {
|
||||
code_unrun(m, leaf);
|
||||
if (!m->plugin_note[0]) snprintf(m->plugin_note, sizeof m->plugin_note, "%s", note);
|
||||
}
|
||||
if (!m->plugin_file[0]) snprintf(m->plugin_file, sizeof m->plugin_file, "%s", leaf);
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
ModInfo *m;
|
||||
const char *folder, *rel; // the folder listed and its path in the mod
|
||||
@@ -270,7 +375,8 @@ static int exefs_file_cb(const char *leaf, int kind, uint64_t size, void *ctx) {
|
||||
return 1;
|
||||
}
|
||||
if (!strcmp(kind_s, "unsupported")) {
|
||||
if (!w->unsupported) snprintf(m->note, sizeof m->note, "%s: %s", leaf, note);
|
||||
if (!m->unsupported) snprintf(m->note, sizeof m->note, "%s: %s", leaf, note);
|
||||
m->unsupported++;
|
||||
w->unsupported = 1;
|
||||
} else if (!strcmp(kind_s, "code") && m->nsets < (int)(sizeof m->sets / sizeof *m->sets)) {
|
||||
m->sets[m->nsets++] = (uint32_t)strtoul(key, NULL, 16);
|
||||
@@ -323,6 +429,7 @@ static int scan_cb(const char *name, int kind, uint64_t size, void *ctx) {
|
||||
}
|
||||
ModInfo *m = &mods[nmods];
|
||||
memset(m, 0, sizeof *m);
|
||||
m->id = nmods;
|
||||
char path[2100];
|
||||
if (snprintf(m->name, sizeof m->name, "%s", name) >= (int)sizeof m->name ||
|
||||
snprintf(path, sizeof path, "%s/%s", dir, name) >= (int)sizeof path) {
|
||||
@@ -334,17 +441,24 @@ static int scan_cb(const char *name, int kind, uint64_t size, void *ctx) {
|
||||
find_root(path, "exefs", m->exefs, sizeof m->exefs);
|
||||
find_root(path, "cheats", m->cheats, sizeof m->cheats);
|
||||
if (m->romfs[0] && has_file(m->romfs)) m->kind |= MOD_ROMFS;
|
||||
if (m->exefs[0]) plat_fs_list(m->exefs, exefs_cb, &m->kind);
|
||||
if (m->exefs[0]) plat_fs_list(m->exefs, exefs_cb, m);
|
||||
if (m->cheats[0]) plat_fs_list(m->cheats, cheats_cb, &m->kind);
|
||||
int unsupported = exefs_check(m, path);
|
||||
// a mod whose code part the port cannot use is off as a whole: its RomFS files may expect that code
|
||||
m->problem = strchr(m->name, '|') ? MOD_BAD_NAME
|
||||
: m->kind & MOD_SUBSDK ? MOD_PLUGIN
|
||||
: unsupported ? MOD_EXEFS_UNSUPPORTED
|
||||
: m->pending ? MOD_EXEFS_LATER
|
||||
: m->nsets || m->ndata || m->kind & (MOD_ROMFS | MOD_CHEATS) ? MOD_OK
|
||||
: m->kind & MOD_EXEFS ? MOD_EXEFS_OTHER
|
||||
: MOD_EMPTY;
|
||||
// A mod whose code part the port cannot use is off as a whole: its RomFS files may expect that code. Used without
|
||||
// its code (its switch, or mods_without_code = 1 for every mod), the code modules (m->code) and the ExeFS patch
|
||||
// files the port cannot apply are left out and the rest of the mod is used, when it has a rest. Each plugin of a
|
||||
// mod is built or refused on its own (tools/exefs_plugins.py), so a built plugin is such a rest too.
|
||||
m->no_code = listed(cfg_get("TOTK_MODS_NO_CODE"), m->name);
|
||||
m->without_code = m->no_code || cfg_bool("TOTK_MODS_WITHOUT_CODE");
|
||||
int usable = m->nsets || m->ndata || m->kind & (MOD_ROMFS | MOD_CHEATS);
|
||||
int code_off = m->code[0] && (!m->without_code || !(m->kind & (MOD_ROMFS | MOD_EXEFS | MOD_CHEATS) || m->nplugins));
|
||||
m->problem = strchr(m->name, '|') ? MOD_BAD_NAME
|
||||
: code_off ? MOD_PLUGIN
|
||||
: unsupported && (!m->without_code || !usable) ? MOD_EXEFS_UNSUPPORTED
|
||||
: m->pending ? MOD_EXEFS_LATER
|
||||
: usable ? MOD_OK
|
||||
: m->kind & MOD_EXEFS ? MOD_EXEFS_OTHER
|
||||
: MOD_EMPTY;
|
||||
m->enabled = !listed(disabled, m->name);
|
||||
nmods++;
|
||||
return 1;
|
||||
@@ -407,11 +521,18 @@ void mods_scan(void) {
|
||||
for (int i = 0; i < nmods; i++) {
|
||||
snprintf(start_order[i], sizeof start_order[i], "%s", mods[i].name);
|
||||
start_enabled[i] = mods[i].enabled;
|
||||
start_no_code[i] = mods[i].no_code;
|
||||
const ModInfo *m = &mods[i];
|
||||
rt_log("mods: %s: %s,%s%s%s%s%s, %s%s%s", m->name, m->enabled ? "on" : "off", m->kind & MOD_ROMFS ? " romfs" : "",
|
||||
m->kind & MOD_EXEFS ? " exefs" : "", m->kind & MOD_SUBSDK ? " subsdk" : "",
|
||||
m->kind & MOD_CHEATS ? " cheats" : "", m->kind ? "" : " no files", problem_name(m->problem),
|
||||
m->note[0] ? ": " : "", m->note);
|
||||
if (m->code[0] && m->problem != MOD_PLUGIN)
|
||||
rt_log("mods: %s: used without its code: its code module (%s) does not load; the rest of the mod is used",
|
||||
m->name, m->code);
|
||||
if (m->unsupported && m->problem != MOD_EXEFS_UNSUPPORTED)
|
||||
rt_log("mods: %s: used without its code: %u ExeFS patch files the port cannot apply are left out (%s); the "
|
||||
"rest of the mod is used", m->name, m->unsupported, m->note);
|
||||
}
|
||||
rt_log("mods: %d folders in %s", nmods, dir);
|
||||
}
|
||||
@@ -549,38 +670,176 @@ void mods_probe_cache(const char *status, const char *data) {
|
||||
data_text = dup_text(data);
|
||||
}
|
||||
|
||||
void mods_probe_plugins(const char *status, const char *stale) {
|
||||
free(plugin_status_text);
|
||||
free(plugin_stale_text);
|
||||
plugin_status_text = dup_text(status);
|
||||
plugin_stale_text = dup_text(stale);
|
||||
no_stale_file = status != NULL;
|
||||
}
|
||||
|
||||
void mods_rescan(void) {
|
||||
free(mods);
|
||||
mods = NULL;
|
||||
nmods = 0;
|
||||
nconflicts = 0;
|
||||
scanned = 0;
|
||||
}
|
||||
|
||||
// Switches the patch set mod_<key> on; 0 when this build lacks it (logged).
|
||||
static int set_on(const ModInfo *m, uint32_t key) {
|
||||
// ---- the conflict table
|
||||
|
||||
void mods_conflict(int winner, int loser, ModPart part, uint32_t count) {
|
||||
for (int i = 0; i < nconflicts; i++) {
|
||||
ModConflict *c = &conflicts[i];
|
||||
if (c->winner == winner && c->loser == loser && c->part == part) {
|
||||
c->count += count;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (nconflicts == MAX_CONFLICTS) return; // a mod list with more pairs than that: the rest goes unshown
|
||||
conflicts[nconflicts++] = (ModConflict){winner, loser, part, count};
|
||||
}
|
||||
|
||||
int mods_conflict_count(void) { return nconflicts; }
|
||||
const ModConflict *mods_conflict_at(int i) { return i >= 0 && i < nconflicts ? &conflicts[i] : NULL; }
|
||||
|
||||
const ModInfo *mods_by_id(int id) {
|
||||
for (int i = 0; i < nmods; i++)
|
||||
if (mods[i].id == id) return &mods[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void mods_conflicts_log(ModPart part) {
|
||||
static const char *const unit[MOD_PARTS] = {"files", "bytes of main's data", "code sites"};
|
||||
for (int i = 0; i < nconflicts; i++) {
|
||||
const ModConflict *c = &conflicts[i];
|
||||
const ModInfo *w = mods_by_id(c->winner), *l = mods_by_id(c->loser);
|
||||
if (c->part != part || !w || !l) continue;
|
||||
rt_log("mods: %s: overrides %s at %u %s", w->name, l->name, c->count, unit[part]);
|
||||
rt_log("mods: %s: %u %s overridden by %s", l->name, c->count, unit[part], w->name);
|
||||
}
|
||||
}
|
||||
|
||||
// Switches the patch set mod_<key> on and gives it rank; -1 when this build lacks it (logged).
|
||||
static int set_on(const ModInfo *m, uint32_t key, int rank) {
|
||||
char name[32];
|
||||
snprintf(name, sizeof name, "mod_%08x", key);
|
||||
int set = rt_patch_set(name);
|
||||
if (set >= 0) rt_patch_switch(set, 1);
|
||||
else rt_log("mods: %s: patch set %s is not in this build", m->name, name);
|
||||
return set >= 0;
|
||||
if (set >= 0) {
|
||||
rt_patch_rank(set, rank);
|
||||
rt_patch_switch(set, 1);
|
||||
} else {
|
||||
rt_log("mods: %s: patch set %s is not in this build", m->name, name);
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
// The mod in use whose ExeFS patch file has the patch set, NULL for a set of no mod.
|
||||
static const ModInfo *set_owner(int set) {
|
||||
const char *name = rt_patch_name(set);
|
||||
if (!name || strncmp(name, "mod_", 4)) return NULL;
|
||||
uint32_t key = (uint32_t)strtoul(name + 4, NULL, 16);
|
||||
for (int i = 0; i < nmods; i++)
|
||||
for (int k = 0; start_enabled[i] && mods[i].problem == MOD_OK && k < mods[i].nsets; k++)
|
||||
if (mods[i].sets[k] == key) return &mods[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// The contested code sites (patches.c): which mod's code runs at each, logged, and one site per losing mod in the
|
||||
// conflict table. Two files of one mod on one site are no conflict: the later file in the mod runs (the tie rule of
|
||||
// rt_patch_picks, as emulators apply a mod's files in name order, each over the one before).
|
||||
static void code_conflicts(void) {
|
||||
int logged = 0, contested = 0;
|
||||
for (int i = 0; i < rt_patch_pick_count(); i++) {
|
||||
const RtPatchPick *p = rt_patch_pick_at(i);
|
||||
int w = rt_patch_pick_winner(i);
|
||||
const ModInfo *wm = w >= 0 ? set_owner(p->sets[w]) : NULL;
|
||||
if (!wm) continue;
|
||||
char lost[512] = "";
|
||||
const ModInfo *seen[16];
|
||||
int nseen = 0;
|
||||
for (int j = 0; j < p->nsets; j++) {
|
||||
const ModInfo *lm = j != w && rt_patch_enabled(p->sets[j]) ? set_owner(p->sets[j]) : NULL;
|
||||
int dup = !lm || lm == wm;
|
||||
for (int k = 0; !dup && k < nseen; k++) dup = seen[k] == lm;
|
||||
if (dup) continue;
|
||||
if (nseen < 16) seen[nseen++] = lm;
|
||||
mods_conflict(wm->id, lm->id, MOD_PART_CODE, 1);
|
||||
size_t at = strlen(lost);
|
||||
snprintf(lost + at, sizeof lost - at, "%s%s", at ? ", " : "", lm->name);
|
||||
}
|
||||
if (!*lost) continue;
|
||||
contested++;
|
||||
if (logged++ < 32)
|
||||
rt_log("mods: code site %s+%#x: %s's patch runs; %s's stays off (higher in the list wins)", p->module,
|
||||
p->offset, wm->name, lost);
|
||||
}
|
||||
if (logged > 32) rt_log("mods: %d more contested code sites", logged - 32);
|
||||
if (contested) mods_conflicts_log(MOD_PART_CODE);
|
||||
}
|
||||
|
||||
// The data bytes stored at start, by mod: the overlaps are data conflicts.
|
||||
typedef struct { uint64_t addr; int n, id, pos; } DataSpan;
|
||||
static DataSpan *spans;
|
||||
static int nspans, cap_spans, span_id, span_pos;
|
||||
static int (*span_store)(uint64_t addr, const uint8_t *bytes, int n);
|
||||
|
||||
static int record_store(uint64_t addr, const uint8_t *bytes, int n) {
|
||||
if (!(span_store ? span_store : store_main)(addr, bytes, n)) return 0;
|
||||
if (nspans == cap_spans) {
|
||||
int cap = cap_spans ? 2 * cap_spans : 256;
|
||||
DataSpan *grown = realloc(spans, (size_t)cap * sizeof *spans);
|
||||
if (!grown) return 1; // stored; only its conflict goes unseen
|
||||
spans = grown, cap_spans = cap;
|
||||
}
|
||||
spans[nspans++] = (DataSpan){addr, n, span_id, span_pos};
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int by_addr(const void *a, const void *b) {
|
||||
uint64_t x = ((const DataSpan *)a)->addr, y = ((const DataSpan *)b)->addr;
|
||||
return (x > y) - (x < y);
|
||||
}
|
||||
|
||||
// Bytes two mods both wrote: the higher one's stayed (mods_exefs_apply stores bottom first).
|
||||
static void data_conflicts(void) {
|
||||
qsort(spans, (size_t)nspans, sizeof *spans, by_addr);
|
||||
int any = 0;
|
||||
for (int i = 0; i < nspans; i++) {
|
||||
uint64_t end = spans[i].addr + (uint64_t)spans[i].n;
|
||||
for (int j = i + 1; j < nspans && spans[j].addr < end; j++) {
|
||||
if (spans[j].id == spans[i].id) continue;
|
||||
uint64_t jend = spans[j].addr + (uint64_t)spans[j].n;
|
||||
uint32_t n = (uint32_t)((jend < end ? jend : end) - spans[j].addr);
|
||||
const DataSpan *hi = spans[i].pos < spans[j].pos ? &spans[i] : &spans[j];
|
||||
mods_conflict(hi->id, hi == &spans[i] ? spans[j].id : spans[i].id, MOD_PART_DATA, n);
|
||||
any = 1;
|
||||
}
|
||||
}
|
||||
free(spans);
|
||||
spans = NULL;
|
||||
nspans = cap_spans = 0;
|
||||
if (any) mods_conflicts_log(MOD_PART_DATA);
|
||||
}
|
||||
|
||||
void mods_exefs_apply(uint64_t base, uint64_t size, uint64_t code_end,
|
||||
int (*store)(uint64_t addr, const uint8_t *bytes, int n)) {
|
||||
// bottom first: the top mod's data writes land last and win, as its RomFS files do. Patch sets are only switches
|
||||
// (rt_patch_switch), so their order does not matter.
|
||||
// bottom first: the top mod's data writes land last and win, as its RomFS files do. Patch sets are switches
|
||||
// (rt_patch_switch); the mod's position ranks them, so where two mods patch one code site the higher one's runs
|
||||
// (rt_patch_picks after the loop).
|
||||
span_store = store;
|
||||
for (int i = nmods - 1; i >= 0; i--) {
|
||||
const ModInfo *m = &mods[i];
|
||||
if (!start_enabled[i] || m->problem != MOD_OK || !(m->nsets || m->ndata)) continue;
|
||||
// the data first: a mod whose data writes cannot all be stored keeps its code patches off too, as half of a
|
||||
// patch file is worse than none
|
||||
long stored = size ? mods_exefs_data(m, base, size, code_end, store) : 0;
|
||||
span_id = m->id, span_pos = i;
|
||||
long stored = size ? mods_exefs_data(m, base, size, code_end, record_store) : 0;
|
||||
if (stored < 0) {
|
||||
rt_log("mods: %s: its ExeFS patch files stay off: their data writes could not all be stored", m->name);
|
||||
continue;
|
||||
}
|
||||
for (int k = 0; k < m->nsets; k++) set_on(m, m->sets[k]);
|
||||
for (int k = 0; k < m->nsets; k++) set_on(m, m->sets[k], i);
|
||||
char over[256];
|
||||
snprintf(over, sizeof over, "%s", m->overrides);
|
||||
for (char *s = strtok(over, ","); s; s = strtok(NULL, ",")) {
|
||||
@@ -591,6 +850,57 @@ void mods_exefs_apply(uint64_t base, uint64_t size, uint64_t code_end,
|
||||
rt_log("mods: %s: %d ExeFS patch files on, %ld bytes of main's data stored", m->name, m->nsets + m->ndata,
|
||||
stored);
|
||||
}
|
||||
span_store = NULL;
|
||||
data_conflicts();
|
||||
rt_patch_picks();
|
||||
code_conflicts();
|
||||
}
|
||||
|
||||
// build-cache/plugins.stale next to totk.exe: one more line (--probe-mods keeps it in memory).
|
||||
static void stale_append(const char *line) {
|
||||
size_t had = plugin_stale_text ? strlen(plugin_stale_text) : 0, n = strlen(line);
|
||||
char *grown = realloc(plugin_stale_text, had + n + 1);
|
||||
if (grown) {
|
||||
if (!plugin_stale_text) grown[0] = 0;
|
||||
memcpy(grown + had, line, n + 1);
|
||||
plugin_stale_text = grown;
|
||||
}
|
||||
char path[2100];
|
||||
if (no_stale_file || !plat_exe_path(path, sizeof path)) return;
|
||||
char *cut = strrchr(path, '/'), *back = strrchr(path, '\\');
|
||||
if (back > cut) cut = back;
|
||||
if (!cut || snprintf(cut + 1, sizeof path - (size_t)(cut + 1 - path), "build-cache/plugins.stale") >=
|
||||
(int)(sizeof path - (size_t)(cut + 1 - path)))
|
||||
return;
|
||||
FILE *f = fopen(path, "ab");
|
||||
if (!f) {
|
||||
rt_log("mods: cannot write %s", path);
|
||||
return;
|
||||
}
|
||||
fputs(line, f);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
void mods_plugin_off(int set, const char *why) {
|
||||
const ModInfo *owner = set_owner(set);
|
||||
rt_patch_switch(set, 0);
|
||||
if (!owner) return;
|
||||
ModInfo *m = (ModInfo *)owner;
|
||||
snprintf(m->plugin_off, sizeof m->plugin_off, "%s", why);
|
||||
const char *name = rt_patch_name(set);
|
||||
uint32_t key = name ? (uint32_t)strtoul(name + 4, NULL, 16) : 0;
|
||||
for (int k = 0; k < m->nplugins; k++) {
|
||||
if (m->plugin_keys[k] != key) continue;
|
||||
char line[400];
|
||||
snprintf(line, sizeof line, "%08X\t%08X\t%s\n", key, m->plugin_contents[k], why);
|
||||
stale_append(line);
|
||||
}
|
||||
rt_log("mods: %s: its plugin stays off this run (%s); it waits for the rebuild at the next start", m->name, why);
|
||||
int kept = 0; // the code conflicts counted anew without the set
|
||||
for (int i = 0; i < nconflicts; i++)
|
||||
if (conflicts[i].part != MOD_PART_CODE) conflicts[kept++] = conflicts[i];
|
||||
nconflicts = kept;
|
||||
code_conflicts();
|
||||
}
|
||||
|
||||
void mods_exefs_switch(void) {
|
||||
@@ -616,12 +926,13 @@ const char *mods_dir(void) { return dir; }
|
||||
int mods_count(void) { return nmods; }
|
||||
ModInfo *mods_at(int i) { return i >= 0 && i < nmods ? &mods[i] : NULL; }
|
||||
|
||||
// TOTK_MODS_ORDER as every listed name top first; TOTK_MODS_DISABLED as the switched-off names. A name holding '|'
|
||||
// would split into two; it is left out of both (its mod is unusable anyway).
|
||||
// TOTK_MODS_ORDER as every listed name top first; TOTK_MODS_DISABLED as the switched-off names; TOTK_MODS_NO_CODE as
|
||||
// the names used without their code. A name holding '|' would split into two; it is left out of all (its mod is
|
||||
// unusable anyway).
|
||||
static void write_keys(void) {
|
||||
size_t cap = (size_t)nmods * 257 + 1;
|
||||
char *order = calloc(cap, 1), *off = calloc(cap, 1);
|
||||
if (order && off) {
|
||||
char *order = calloc(cap, 1), *off = calloc(cap, 1), *no_code = calloc(cap, 1);
|
||||
if (order && off && no_code) {
|
||||
for (int i = 0; i < nmods; i++) {
|
||||
if (mods[i].problem == MOD_BAD_NAME) continue;
|
||||
if (*order) strcat(order, "|");
|
||||
@@ -630,12 +941,18 @@ static void write_keys(void) {
|
||||
if (*off) strcat(off, "|");
|
||||
strcat(off, mods[i].name);
|
||||
}
|
||||
if (mods[i].no_code) {
|
||||
if (*no_code) strcat(no_code, "|");
|
||||
strcat(no_code, mods[i].name);
|
||||
}
|
||||
}
|
||||
cfg_set("TOTK_MODS_ORDER", order);
|
||||
cfg_set("TOTK_MODS_DISABLED", off);
|
||||
cfg_set("TOTK_MODS_NO_CODE", no_code);
|
||||
}
|
||||
free(order);
|
||||
free(off);
|
||||
free(no_code);
|
||||
}
|
||||
|
||||
void mods_set_enabled(int i, int on) {
|
||||
@@ -644,6 +961,12 @@ void mods_set_enabled(int i, int on) {
|
||||
write_keys();
|
||||
}
|
||||
|
||||
void mods_set_no_code(int i, int on) {
|
||||
if (i < 0 || i >= nmods) return;
|
||||
mods[i].no_code = on != 0;
|
||||
write_keys();
|
||||
}
|
||||
|
||||
void mods_move(int i, int delta) {
|
||||
int j = i + delta;
|
||||
if (i < 0 || i >= nmods || j < 0 || j >= nmods || i == j) return;
|
||||
@@ -655,6 +978,8 @@ void mods_move(int i, int delta) {
|
||||
|
||||
int mods_changed(void) {
|
||||
for (int i = 0; i < nmods; i++)
|
||||
if (strcmp(mods[i].name, start_order[i]) || mods[i].enabled != start_enabled[i]) return 1;
|
||||
if (strcmp(mods[i].name, start_order[i]) || mods[i].enabled != start_enabled[i] ||
|
||||
mods[i].no_code != start_no_code[i])
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
+47
-8
@@ -5,7 +5,9 @@
|
||||
// switched with their mod (mods_exefs_switch), and data writes stored into main before the game runs (mods_exefs_data).
|
||||
// The list is scanned once at start (romfs.c overlay_init);
|
||||
// its order and switches live in totk.ini [mods] (TOTK_MODS_ORDER: names top first, separated by '|';
|
||||
// TOTK_MODS_DISABLED: names switched off). The top mod wins a file two mods replace.
|
||||
// TOTK_MODS_DISABLED: names switched off; TOTK_MODS_NO_CODE: names used without their code part). The top mod wins
|
||||
// whatever two mods change: a file, bytes of main's data, a code site (patches.c rt_patch_picks); the conflict table
|
||||
// (mods_conflict_at) records who won over whom, for the menu and the log.
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
@@ -14,10 +16,13 @@ typedef enum {
|
||||
MOD_OK,
|
||||
MOD_EMPTY, // no RomFS file, no ExeFS patch, no cheat file
|
||||
MOD_PLUGIN, // has code modules (exefs/subsdk*, a replaced exefs/main): the port has no module loader, so the
|
||||
// whole mod stays off (its RomFS files may expect that code)
|
||||
// whole mod stays off (its RomFS files may expect that code); used without its code
|
||||
// (ModInfo.without_code) the rest of such a mod is used, without those code modules
|
||||
// (ModInfo.code names them)
|
||||
MOD_EXEFS_LATER, // has ExeFS patches for this game's main that the game was built without: the rebuild at the
|
||||
// next start builds them in; the whole mod stays off until then
|
||||
MOD_EXEFS_UNSUPPORTED, // an ExeFS patch file the port cannot apply (note says why): the whole mod stays off
|
||||
MOD_EXEFS_UNSUPPORTED, // an ExeFS patch file the port cannot apply (note says why): the whole mod stays off,
|
||||
// unless it is used without its code (ModInfo.without_code) and has a usable rest
|
||||
MOD_EXEFS_OTHER, // only ExeFS patches, all for another game version
|
||||
MOD_BAD_NAME, // its folder name holds '|', the separator of the order keys
|
||||
} ModProblem;
|
||||
@@ -27,14 +32,19 @@ typedef struct {
|
||||
char romfs[2048]; // UTF-8 path of its RomFS root; "" none
|
||||
char exefs[2048]; // UTF-8 path of its ExeFS folder; "" none
|
||||
char cheats[2048]; // UTF-8 path of its cheats folder; "" none
|
||||
int kind, enabled;
|
||||
int kind, enabled; // kind: MOD_SUBSDK for any code module
|
||||
int id; // its place in the scan: names it in the conflict table, whatever the menu moves
|
||||
int no_code; // its switch "use without its code" (TOTK_MODS_NO_CODE)
|
||||
int without_code; // the scan's: no_code or TOTK_MODS_WITHOUT_CODE (every mod); the code parts it cannot run
|
||||
// (code modules, unsupported ExeFS patch files) are left out and the rest is used
|
||||
char code[64]; // its code modules in exefs ("subsdk9", "main, subsdk9"): never loaded
|
||||
uint32_t unsupported; // its ExeFS patch files the port cannot apply (the first one's reason in note)
|
||||
ModProblem problem;
|
||||
uint32_t replaced, added, overridden; // romfs.c: files served (replacing / added), files a higher mod serves
|
||||
uint32_t other_version; // files named for another game version: RomFS *.Product.<n>.* the RomFS
|
||||
// lacks (served under their own names; another version's size table is
|
||||
// not) and ExeFS patches for another build (not used)
|
||||
char overridden_by[256]; // the first higher mod that took one of its files
|
||||
char note[256]; // MOD_EXEFS_UNSUPPORTED: why
|
||||
char note[256]; // an unsupported ExeFS patch file: which and why
|
||||
uint32_t pending, pending_key; // ExeFS patch files the build lacks; FNV-1a of their names and contents
|
||||
int nsets;
|
||||
uint32_t sets[16]; // the built patch sets mod_<hash> of its ExeFS patch files
|
||||
@@ -43,8 +53,29 @@ typedef struct {
|
||||
uint32_t data_bytes; // the bytes its usable ExeFS patch files write into main's data, as their
|
||||
// status lines count them ("data <bytes>")
|
||||
char overrides[256]; // the port's own patch sets its patches replace, comma separated
|
||||
// Its exefs/subsdk* plugins (build-cache/plugins.status, tools/exefs_plugins.py): the built ones are patch sets in
|
||||
// sets[] whose init runs at start (plugin_init.c); a refused one is a code module it cannot run (code).
|
||||
int nplugins, plugin_hooks; // built plugins and their hooks
|
||||
uint32_t plugin_keys[4], plugin_contents[4]; // their file and content hashes, for plugins.stale
|
||||
char plugin_file[64]; // the first plugin's file name
|
||||
char plugin_note[256]; // why the build refused a plugin ("" none)
|
||||
char plugin_off[256]; // why its plugin stays off this run: its start differed from the build
|
||||
} ModInfo;
|
||||
|
||||
// What two mods both change, the higher one winning: files (romfs.c), bytes of main's data and code sites
|
||||
// (mods_exefs_apply). One entry per winner, loser and part, as at start.
|
||||
typedef enum { MOD_PART_FILES, MOD_PART_DATA, MOD_PART_CODE, MOD_PARTS } ModPart;
|
||||
typedef struct {
|
||||
int winner, loser; // ModInfo.id
|
||||
ModPart part;
|
||||
uint32_t count; // files, bytes, code sites
|
||||
} ModConflict;
|
||||
void mods_conflict(int winner, int loser, ModPart part, uint32_t count); // adds count to the pair's entry
|
||||
int mods_conflict_count(void);
|
||||
const ModConflict *mods_conflict_at(int i);
|
||||
void mods_conflicts_log(ModPart part); // one line each way per entry of that part
|
||||
const ModInfo *mods_by_id(int id);
|
||||
|
||||
void mods_scan(void); // once; later calls return at once
|
||||
// Every switched-on mod folder's RomFS root, without the rest of the scan (no ExeFS checks, no order): for mem_init,
|
||||
// which runs before the paths mods_scan needs are set (resolution.c mod_tex_heap_kib). cb gets the name and root.
|
||||
@@ -55,10 +86,12 @@ ModInfo *mods_at(int i); // 0 = top of the order; NULL out of range
|
||||
// Menu edits (present path). They change the list mods_at shows and write TOTK_MODS_ORDER / TOTK_MODS_DISABLED with
|
||||
// cfg_set; romfs.c used the start state, so they apply at the next start.
|
||||
void mods_set_enabled(int i, int on);
|
||||
void mods_set_no_code(int i, int on); // "use without its code" (TOTK_MODS_NO_CODE)
|
||||
void mods_move(int i, int delta); // -1 up, +1 down; nothing at the ends
|
||||
int mods_changed(void); // 1 when the order or a switch differs from the start
|
||||
// After ldr_load and rt_patches_init, before any game code: the patch sets of the enabled mods' ExeFS patches on, the
|
||||
// port's own sets they replace off, and their data writes stored into main (mods_exefs_data).
|
||||
// After ldr_load and rt_patches_init, before any game code: the patch sets of the enabled mods' ExeFS patches on and
|
||||
// ranked by the order (rt_patch_rank: the top mod's code runs where several patch one site), the port's own sets they
|
||||
// replace off, and their data writes stored into main (mods_exefs_data); the data and code conflicts recorded.
|
||||
void mods_exefs_switch(void);
|
||||
// What mods_exefs_switch does with main's image at base (size bytes, code below code_end; size 0: no data stored), for
|
||||
// every enabled mod from the bottom one up, so that the top mod's data writes win where two mods write the same bytes.
|
||||
@@ -79,5 +112,11 @@ void mods_rescan(void);
|
||||
// The ExeFS patch files of the enabled mods that the build lacks, their FNV-1a mixed into *key (cheats.c starts the
|
||||
// rebuild for them).
|
||||
int mods_exefs_pending(uint32_t *key);
|
||||
// From plugin_init.c plugins_start: the plugin patch set `set` stays off this run (why), its mod's row says so,
|
||||
// build-cache/plugins.stale marks its file for the rebuild at the next start, and the code conflicts are counted anew.
|
||||
void mods_plugin_off(int set, const char *why);
|
||||
// --probe-mods: the texts of build-cache/plugins.status and plugins.stale instead of the files; the stale lines
|
||||
// mods_plugin_off adds stay in memory.
|
||||
void mods_probe_plugins(const char *status, const char *stale);
|
||||
// The hex of the game main's build id (64 digits), "" when exefs/main cannot be read.
|
||||
const char *mods_main_build_id(void);
|
||||
@@ -121,11 +121,262 @@ static void probe_data(const char *root) {
|
||||
mods_exefs_apply(base, sizeof img, 8, store_buffer);
|
||||
CHECK(img[0x28] == 0xAA, "two mods write the same byte: the top mod's byte stays");
|
||||
CHECK(!memcmp(img + 0x10, "ABC", 3) && !img[0x30], "the other mods' data as each one stores it alone");
|
||||
const ModInfo *xm = by_name("X"), *ym = by_name("Y");
|
||||
CHECK(mods_conflict_count() == 1 && xm && ym && mods_conflict_at(0)->winner == ym->id &&
|
||||
mods_conflict_at(0)->loser == xm->id && mods_conflict_at(0)->part == MOD_PART_DATA &&
|
||||
mods_conflict_at(0)->count == 1,
|
||||
"the conflict table: Y overrides X at one byte of data");
|
||||
}
|
||||
mods_probe_cache(NULL, NULL);
|
||||
remove_tree(root);
|
||||
}
|
||||
|
||||
// "mod_<key>": the name tools/exefs_patches.py gives the patch set of the file at rel (mod folder name / path in it).
|
||||
static void set_name(char *out, size_t cap, const char *rel) { snprintf(out, cap, "mod_%08x", fnv(rel, strlen(rel))); }
|
||||
|
||||
// Code sites several mods patch (patches.c rt_patch_picks): a set table of the probe's own, with the sets of the ExeFS
|
||||
// patch files of A (one file), B (two files) and C (one, switched off) and three contested sites:
|
||||
// 0: A and B's first file the higher mod's set runs; a conflict of B over A or A over B
|
||||
// 1: B's two files the later file in the mod runs; no conflict
|
||||
// 2: C and A C is off, so A's runs; no conflict
|
||||
static void probe_code(const char *root) {
|
||||
remove_tree(root);
|
||||
plat_file_mkdir_p(root);
|
||||
const char *bid = *mods_main_build_id() ? mods_main_build_id() : "0";
|
||||
char a[160], b1[160], b2[160], c[160];
|
||||
snprintf(a, sizeof a, "A/exefs/%s.ips", bid);
|
||||
snprintf(b1, sizeof b1, "B/atmosphere/exefs_patches/one/%s.ips", bid);
|
||||
snprintf(b2, sizeof b2, "B/atmosphere/exefs_patches/two/%s.ips", bid);
|
||||
snprintf(c, sizeof c, "C/exefs/%s.ips", bid);
|
||||
const char *files[] = {a, b1, b2, c};
|
||||
static char names[5][16];
|
||||
static const char *const table[] = {"fps60", names[1], names[2], names[3], names[4]};
|
||||
char status[512] = "";
|
||||
for (int i = 0; i < 4; i++) {
|
||||
put(root, files[i]);
|
||||
set_name(names[i + 1], sizeof names[i + 1], files[i]);
|
||||
size_t at = strlen(status);
|
||||
snprintf(status + at, sizeof status - at, "%08X\t%08X\tcode\t-\t\n", fnv(files[i], strlen(files[i])),
|
||||
fnv("probe", 5));
|
||||
}
|
||||
static const int16_t s0[] = {1, 2}, s1[] = {2, 3}, s2[] = {4, 1};
|
||||
static const RtPatchPick picks[] = {{"main", 0x100, s0, 2}, {"main", 0x200, s1, 2}, {"main", 0x300, s2, 2}};
|
||||
mods_probe_cache(status, "");
|
||||
cfg_set("TOTK_MODS_DIR", root);
|
||||
cfg_set("TOTK_MODS_DISABLED", "C");
|
||||
for (int round = 0; round < 2; round++) {
|
||||
cfg_set("TOTK_MODS_ORDER", round ? "A|B" : "B|A");
|
||||
mods_rescan();
|
||||
mods_scan();
|
||||
rt_patch_probe_table(table, 5, picks, 3);
|
||||
mods_exefs_apply(0, 0, 0, NULL);
|
||||
const ModInfo *am = by_name("A"), *bm = by_name("B");
|
||||
CHECK(am && bm && am->nsets == 1 && bm->nsets == 2 && am->problem == MOD_OK, "code scan: A one set, B two");
|
||||
if (!am || !bm) break;
|
||||
const ModInfo *hi = round ? am : bm, *lo = round ? bm : am;
|
||||
CHECK(rt_patch_pick_winner(0) == (round ? 0 : 1), round ? "A above B: A's code runs at their site"
|
||||
: "B above A: B's code runs at their site");
|
||||
CHECK(rt_patch_pick_winner(1) == 1, "two files of one mod on a site: the later file's code runs");
|
||||
CHECK(rt_patch_pick_winner(2) == 1 && !rt_patch_enabled(4), "a switched-off mod's set stays off");
|
||||
CHECK(mods_conflict_count() == 1 && mods_conflict_at(0)->winner == hi->id &&
|
||||
mods_conflict_at(0)->loser == lo->id && mods_conflict_at(0)->part == MOD_PART_CODE &&
|
||||
mods_conflict_at(0)->count == 1,
|
||||
"the conflict table: the higher mod overrides the lower one at one code site, and only there");
|
||||
// the winner switched off at run time: the site takes the other mod's set
|
||||
rt_patch_switch(round ? 1 : 2, 0);
|
||||
CHECK(rt_patch_pick_winner(0) == (round ? 1 : 0), "a contested site follows a switch of its winner");
|
||||
}
|
||||
// the table itself: one entry per pair and part, counts adding up
|
||||
mods_conflict(7, 8, MOD_PART_FILES, 2);
|
||||
mods_conflict(7, 8, MOD_PART_FILES, 3);
|
||||
const ModConflict *last = mods_conflict_at(mods_conflict_count() - 1);
|
||||
CHECK(last && last->winner == 7 && last->count == 5, "mods_conflict adds to the pair's entry");
|
||||
rt_patch_probe_table(NULL, 0, NULL, 0);
|
||||
cfg_set("TOTK_MODS_DISABLED", "");
|
||||
mods_probe_cache(NULL, NULL);
|
||||
remove_tree(root);
|
||||
}
|
||||
|
||||
// build-cache/plugins.status lines (tools/exefs_plugins.py) that refuse the probe's subsdk9 files of E and H: they stay
|
||||
// code the port cannot run.
|
||||
static const char *refused_plugins(void) {
|
||||
static char text[256];
|
||||
snprintf(text, sizeof text, "%08X\t%08X\tunsupported\t-\tthe init called svc 0x40\n"
|
||||
"%08X\t%08X\tunsupported\t-\tthe init called svc 0x40\n", fnv("E/exefs/subsdk9", 15), fnv("probe", 5),
|
||||
fnv("H/exefs/subsdk9", 15), fnv("probe", 5));
|
||||
return text;
|
||||
}
|
||||
|
||||
// Mod plugins (build-cache/plugins.status, plugins.stale; mods.c plugin_file, mods_plugin_off) in a folder of their own:
|
||||
// P RomFS + a built plugin (7 hooks) its set on, ranked by the order; a contested site with Q's patch file
|
||||
// Q an ExeFS patch file on P's site
|
||||
// R a plugin the build has no line for waits for the rebuild
|
||||
// S RomFS + a refused plugin off, the reason kept; used without its code, the rest runs
|
||||
// T a built plugin + a refused one each judged alone: off for the refused one, its reason kept; used
|
||||
// without its code, the built one's set runs
|
||||
// Then P's start differs from the build (mods_plugin_off): its set goes off, Q's code runs at the site, the conflict
|
||||
// goes, a stale line marks P's file, and the next scan has P wait for the rebuild.
|
||||
static void probe_plugins(const char *root) {
|
||||
remove_tree(root);
|
||||
plat_file_mkdir_p(root);
|
||||
const char *bid = *mods_main_build_id() ? mods_main_build_id() : "0";
|
||||
char q[160];
|
||||
snprintf(q, sizeof q, "Q/exefs/%s.ips", bid);
|
||||
static const char *const files[] = {"P/romfs/p.bin", "P/exefs/subsdk9", "R/exefs/subsdk9", "S/romfs/s.bin",
|
||||
"S/exefs/subsdk9", "T/exefs/subsdk8", "T/exefs/subsdk9"};
|
||||
for (size_t i = 0; i < sizeof files / sizeof *files; i++) put(root, files[i]);
|
||||
put(root, q);
|
||||
static char names[4][16];
|
||||
static const char *const table[] = {"fps60", names[1], names[2], names[3]};
|
||||
set_name(names[1], sizeof names[1], "P/exefs/subsdk9");
|
||||
set_name(names[2], sizeof names[2], q);
|
||||
set_name(names[3], sizeof names[3], "T/exefs/subsdk9");
|
||||
char status[256], plugins[512];
|
||||
snprintf(status, sizeof status, "%08X\t%08X\tcode\t-\t\n", fnv(q, strlen(q)), fnv("probe", 5));
|
||||
snprintf(plugins, sizeof plugins, "%08X\t%08X\tplugin\tfps60\tplugin0, 7 hooks\n"
|
||||
"%08X\t%08X\tunsupported\t-\tthe code its hooks reach has svc 0x40\n"
|
||||
"%08X\t%08X\tplugin\t-\tplugin1, 2 hooks\n"
|
||||
"%08X\t%08X\tunsupported\t-\tthe run was refused: svc 0x1 at plugin2+0x50a0\n", fnv("P/exefs/subsdk9", 15),
|
||||
fnv("probe", 5), fnv("S/exefs/subsdk9", 15), fnv("probe", 5), fnv("T/exefs/subsdk9", 15), fnv("probe", 5),
|
||||
fnv("T/exefs/subsdk8", 15), fnv("probe", 5));
|
||||
static const int16_t s0[] = {1, 2};
|
||||
static const RtPatchPick picks[] = {{"main", 0x100, s0, 2}};
|
||||
mods_probe_cache(status, "");
|
||||
mods_probe_plugins(plugins, "");
|
||||
cfg_set("TOTK_MODS_DIR", root);
|
||||
cfg_set("TOTK_MODS_DISABLED", "");
|
||||
cfg_set("TOTK_MODS_NO_CODE", "");
|
||||
for (int round = 0; round < 2; round++) {
|
||||
cfg_set("TOTK_MODS_ORDER", round ? "Q|P" : "P|Q");
|
||||
mods_rescan();
|
||||
mods_scan();
|
||||
rt_patch_probe_table(table, 4, picks, 1);
|
||||
rt_patch_switch(0, 1);
|
||||
mods_exefs_apply(0, 0, 0, NULL);
|
||||
const ModInfo *pm = by_name("P"), *qm = by_name("Q"), *rm = by_name("R"), *sm = by_name("S"),
|
||||
*tm = by_name("T");
|
||||
CHECK(pm && qm && rm && sm && tm, "plugin scan: five mods");
|
||||
if (!pm || !qm || !rm || !sm || !tm) break;
|
||||
CHECK(pm->problem == MOD_OK && pm->nsets == 1 && pm->nplugins == 1 && pm->plugin_hooks == 7 && !pm->code[0] &&
|
||||
EQ(pm->overrides, "fps60"), "a built plugin: its set, its hooks, the built-in set it replaces");
|
||||
CHECK(rt_patch_enabled(1) && !rt_patch_enabled(0), "the plugin's set on, the built-in set it replaces off");
|
||||
CHECK(rt_patch_pick_winner(0) == (round ? 1 : 0), round ? "Q above P: Q's patch runs at their site"
|
||||
: "P above Q: P's plugin hook runs at their site");
|
||||
CHECK(mods_conflict_count() == 1 && mods_conflict_at(0)->part == MOD_PART_CODE &&
|
||||
mods_conflict_at(0)->winner == (round ? qm : pm)->id,
|
||||
"the conflict table: a plugin site against a patch file goes by the order");
|
||||
CHECK(rm->problem == MOD_EXEFS_LATER && rm->pending == 1, "a plugin the build lacks waits for the rebuild");
|
||||
CHECK(sm->problem == MOD_PLUGIN && EQ(sm->code, "subsdk9") && strstr(sm->plugin_note, "svc 0x40"),
|
||||
"a refused plugin keeps its mod off and says why");
|
||||
CHECK(tm->problem == MOD_PLUGIN && tm->nplugins == 1 && tm->plugin_hooks == 2 && EQ(tm->code, "subsdk8") &&
|
||||
strstr(tm->plugin_note, "svc 0x1") && !rt_patch_enabled(3),
|
||||
"a built plugin beside a refused one: the mod off, the refused one's reason on its row");
|
||||
}
|
||||
// P above Q, then P's start differs from the build
|
||||
cfg_set("TOTK_MODS_ORDER", "P|Q");
|
||||
mods_rescan();
|
||||
mods_scan();
|
||||
rt_patch_probe_table(table, 4, picks, 1);
|
||||
mods_exefs_apply(0, 0, 0, NULL);
|
||||
mods_plugin_off(1, "probe: 1 of the words the build recorded were not written");
|
||||
const ModInfo *pm = by_name("P");
|
||||
CHECK(!rt_patch_enabled(1) && rt_patch_pick_winner(0) == 1, "a plugin off at start: the other mod's patch runs");
|
||||
CHECK(pm && strstr(pm->plugin_off, "were not written"), "its row says why");
|
||||
CHECK(mods_conflict_count() == 0, "its conflict goes with it");
|
||||
cfg_set("TOTK_MODS_NO_CODE", "S|T");
|
||||
mods_rescan();
|
||||
mods_scan();
|
||||
rt_patch_probe_table(table, 4, picks, 1);
|
||||
mods_exefs_apply(0, 0, 0, NULL);
|
||||
pm = by_name("P");
|
||||
const ModInfo *sm = by_name("S"), *tm = by_name("T");
|
||||
CHECK(pm && pm->problem == MOD_EXEFS_LATER && pm->pending == 1, "the next start: its file waits for the rebuild");
|
||||
CHECK(sm && sm->problem == MOD_OK && sm->plugin_note[0], "a refused plugin used without its code: the rest runs");
|
||||
CHECK(tm && tm->problem == MOD_OK && tm->plugin_note[0] && rt_patch_enabled(3),
|
||||
"a built plugin beside a refused one, used without its code: the built one's set runs");
|
||||
rt_patch_probe_table(NULL, 0, NULL, 0);
|
||||
cfg_set("TOTK_MODS_NO_CODE", "");
|
||||
cfg_set("TOTK_MODS_ORDER", "");
|
||||
mods_probe_cache(NULL, NULL);
|
||||
mods_probe_plugins(refused_plugins(), "");
|
||||
remove_tree(root);
|
||||
}
|
||||
|
||||
// Mods with code the port cannot run (a code module, an ExeFS patch file it cannot apply): used without that code
|
||||
// by their own switch (mods_no_code) or by mods_without_code for every mod.
|
||||
static void probe_without_code(const char *root) {
|
||||
remove_tree(root);
|
||||
plat_file_mkdir_p(root);
|
||||
const char *bid = *mods_main_build_id() ? mods_main_build_id() : "0";
|
||||
char u[160], v[160];
|
||||
snprintf(u, sizeof u, "U/exefs/%s.ips", bid); // with RomFS files: the rest is usable
|
||||
snprintf(v, sizeof v, "V/exefs/%s.ips", bid); // nothing else
|
||||
static const char *const files[] = {"E/exefs/subsdk9", "H/romfs/h.bin", "H/exefs/subsdk9", "I/romfs/i.bin",
|
||||
"I/exefs/main", "U/romfs/u.bin"};
|
||||
for (size_t i = 0; i < sizeof files / sizeof *files; i++) put(root, files[i]);
|
||||
put(root, u);
|
||||
put(root, v);
|
||||
char status[256];
|
||||
snprintf(status, sizeof status, "%08X\t%08X\tunsupported\t-\tit writes outside main\n"
|
||||
"%08X\t%08X\tunsupported\t-\tit writes outside main\n", fnv(u, strlen(u)), fnv("probe", 5),
|
||||
fnv(v, strlen(v)), fnv("probe", 5));
|
||||
mods_probe_cache(status, "");
|
||||
cfg_set("TOTK_MODS_NO_CODE", "H|U|V");
|
||||
cfg_set("TOTK_MODS_DIR", root);
|
||||
cfg_set("TOTK_MODS_ORDER", "");
|
||||
cfg_set("TOTK_MODS_DISABLED", "");
|
||||
mods_rescan();
|
||||
mods_scan();
|
||||
{
|
||||
ModInfo *h = by_name("H"), *im = by_name("I"), *um = by_name("U"), *vm = by_name("V");
|
||||
CHECK(h && im && um && vm, "per-mod scan: four mods");
|
||||
if (h && im && um && vm) {
|
||||
CHECK(h->problem == MOD_OK && h->no_code && EQ(h->code, "subsdk9"),
|
||||
"its own switch: RomFS + subsdk9 is used without the code module");
|
||||
CHECK(im->problem == MOD_PLUGIN && !im->no_code, "a mod without the switch stays off");
|
||||
CHECK(um->problem == MOD_OK && um->unsupported == 1 && um->note[0],
|
||||
"its own switch: RomFS + an unsupported patch file is used without that file");
|
||||
CHECK(vm->problem == MOD_EXEFS_UNSUPPORTED, "an unsupported patch file and nothing else stays off");
|
||||
int ii = 0;
|
||||
while (mods_at(ii) != im) ii++;
|
||||
mods_set_no_code(ii, 1);
|
||||
CHECK(EQ(cfg_get("TOTK_MODS_NO_CODE"), "H|I|U|V") && mods_changed(), "the switch writes mods_no_code");
|
||||
}
|
||||
}
|
||||
cfg_set("TOTK_MODS_NO_CODE", "");
|
||||
cfg_set("TOTK_MODS_WITHOUT_CODE", "0");
|
||||
mods_rescan();
|
||||
mods_scan();
|
||||
CHECK(by_name("U") && by_name("U")->problem == MOD_EXEFS_UNSUPPORTED, "without the switch an unsupported file "
|
||||
"keeps the whole mod off");
|
||||
remove_tree(root);
|
||||
plat_file_mkdir_p(root);
|
||||
for (size_t i = 0; i < 5; i++) put(root, files[i]);
|
||||
mods_probe_cache("", "");
|
||||
cfg_set("TOTK_MODS_DIR", root);
|
||||
cfg_set("TOTK_MODS_ORDER", "");
|
||||
cfg_set("TOTK_MODS_DISABLED", "");
|
||||
cfg_set("TOTK_MODS_WITHOUT_CODE", "1");
|
||||
mods_rescan();
|
||||
mods_scan();
|
||||
ModInfo *e = by_name("E"), *h = by_name("H"), *im = by_name("I");
|
||||
CHECK(e && h && im, "without-code scan: three mods");
|
||||
if (e && h && im) {
|
||||
CHECK(e->problem == MOD_PLUGIN, "mods_without_code: a mod with only a code module stays off");
|
||||
CHECK(h->problem == MOD_OK && EQ(h->code, "subsdk9"), "mods_without_code: RomFS + subsdk9 is used without it");
|
||||
CHECK(im->problem == MOD_OK && EQ(im->code, "main"), "mods_without_code: RomFS + replaced main is used");
|
||||
}
|
||||
cfg_set("TOTK_MODS_WITHOUT_CODE", "0");
|
||||
mods_rescan();
|
||||
mods_scan();
|
||||
h = by_name("H");
|
||||
CHECK(h && h->problem == MOD_PLUGIN && !h->without_code, "without mods_without_code a mod with a code module stays "
|
||||
"off");
|
||||
cfg_set("TOTK_MODS_WITHOUT_CODE", "");
|
||||
mods_probe_cache(NULL, NULL);
|
||||
remove_tree(root);
|
||||
}
|
||||
|
||||
// s ends in tail, either path separator matching either.
|
||||
static int ends_with(const char *s, const char *tail) {
|
||||
size_t n = strlen(s), t = strlen(tail);
|
||||
@@ -146,6 +397,7 @@ int probe_mods(void) {
|
||||
if (back > cut) cut = back;
|
||||
if (!cut) return 1;
|
||||
strcpy(cut + 1, "mods-probe");
|
||||
mods_probe_plugins(refused_plugins(), ""); // not the build's own plugins.status
|
||||
remove_tree(root);
|
||||
plat_file_mkdir_p(root);
|
||||
static const char *const files[] = {
|
||||
@@ -214,6 +466,10 @@ int probe_mods(void) {
|
||||
CHECK(mods_changed(), "changes seen");
|
||||
}
|
||||
probe_data(root);
|
||||
probe_without_code(root);
|
||||
probe_code(root);
|
||||
probe_plugins(root);
|
||||
mods_probe_plugins(NULL, NULL);
|
||||
printf("mods: %s\n", fails ? "FAIL" : "ok");
|
||||
int table = restbl_probe();
|
||||
return fails || table ? 1 : 0;
|
||||
|
||||
+148
-15
@@ -6,12 +6,17 @@
|
||||
// reports it: acceleration in G, angular velocity in revolutions per second, angle = the integrated revolutions per
|
||||
// axis, direction = the controller's three axes in a reference frame whose z is up. The orientation is integrated from
|
||||
// the gyro and, while the controller is not being accelerated (|a| within 15 % of 1 G), pulled toward the measured
|
||||
// gravity (Mahony, gain 0.5/s: about 2 s), as the Switch's sensor fusion does; yaw has no reference and drifts with the
|
||||
// gyro's bias, so a bias measured with the controller at rest (the Calibrate gyro row, motion_calibrate_start) is
|
||||
// subtracted from every sample while gyro_calibration is on. The newest MOTION_RING samples are kept; reads are newest
|
||||
// first. A restart (StartSixAxisSensor) drops the samples before it: reads return nothing until the next sample, which
|
||||
// starts a fresh frame and angle; sampling numbers go on. The feeding thread writes, guest threads read, both under the
|
||||
// instance's SRW lock.
|
||||
// gravity (Mahony, gain 0.5/s: about 2 s), as the Switch's sensor fusion does; held still (|a| within 5 % of 1 G,
|
||||
// turning slower than STILL_RATE) the pull is STILL_GAIN, so a down the gyro got wrong while the controller moved is
|
||||
// right again before the next aim. The game splits the aim into pitch and yaw by the reported down: a wrong one turns a
|
||||
// tilt up or down into a turn to the side as well. Yaw has no reference and drifts with the gyro's bias, so a bias
|
||||
// measured with the controller at rest (the Calibrate gyro row, motion_calibrate_start) is subtracted from every sample
|
||||
// while gyro_calibration is on, and the drift left after it is learned while the controller lies still and subtracted
|
||||
// too while gyro_auto_bias is on (drift_track). The newest MOTION_RING samples are kept; reads are newest first. A
|
||||
// restart (StartSixAxisSensor) drops the samples before it: reads return nothing until the first sample with a reading
|
||||
// (|a| over 0.5 G: a sensor just switched on reads zero until its first report), which starts a fresh frame, levelled
|
||||
// by that reading, and a fresh angle; sampling numbers go on. The feeding thread writes, guest threads read, both under
|
||||
// the instance's SRW lock.
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -31,6 +36,29 @@ enum { MOTION_RING = 64, CALIB_SETTLE = 125, CALIB_SAMPLES = 250 };
|
||||
// near 0.01-0.02 rad/s. A jolt that stays under the limit moves the mean by at most the limit times the square root of
|
||||
// the share of the second it lasts.
|
||||
#define CALIB_MAX_SPREAD 0.04
|
||||
#define STILL_GAIN 4.0 // 1/s: a wrong down is 2 % of itself after a second held still
|
||||
#define STILL_RATE 0.5 // rad/s, about 30 deg/s: a slow aim still counts as held still
|
||||
// The drift tracker (drift_track), after PR #380's estimator: a window of REST_WIN samples (256 ms) is still when every
|
||||
// axis of the gyro stays within REST_GYRO_PTP peak to peak and of the acceleration within REST_ACC_PTP, |a| is within
|
||||
// REST_GRAVITY of 1 G, and the window's mean rate is within DRIFT_FIRST_MAX (before the estimate settled) or
|
||||
// DRIFT_TRACK_MAX (after) of the estimate in use. A Pro Controller on a table reads 0.004-0.006 rad/s of noise and
|
||||
// passes; held in a hand, even steadily, it reads 0.013-0.025 rad/s and mostly does not, so the tracker learns from a
|
||||
// controller put down rather than from an aim held still. After REST_HOLD_S still the estimate moves toward the
|
||||
// window's mean with a time constant of DRIFT_TAU_FIRST until it has settled, then DRIFT_TAU: a bias changes only
|
||||
// slowly as the controller warms up, and a hand that slips past the gate shifts it little. No dead zone: a slow aim
|
||||
// keeps every bit of its rate.
|
||||
enum { REST_WIN = 64 };
|
||||
#define REST_GYRO_PTP 0.04 // rad/s, per axis over the window
|
||||
#define REST_ACC_PTP 0.03 // G, per axis over the window
|
||||
#define REST_GRAVITY 0.25 // G: controllers' accelerometers read 1 G only roughly
|
||||
#define REST_HOLD_S 0.5
|
||||
#define DRIFT_FIRST_MAX 0.1 // rad/s, 5.7 deg/s; a larger factory bias (one Pro: 0.14 on z) needs the calibration
|
||||
#define DRIFT_TRACK_MAX 0.05 // rad/s
|
||||
#define DRIFT_TAU_FIRST 0.25 // s
|
||||
#define DRIFT_TAU 30.0 // s
|
||||
#define DRIFT_SETTLE_S 1.5 // learning this long with the estimate within DRIFT_SETTLED of the window: settled
|
||||
#define DRIFT_SETTLED 0.01 // rad/s
|
||||
#define DRIFT_LIMIT 0.3 // rad/s per axis
|
||||
|
||||
struct MotionFusion {
|
||||
PlatMutex lock;
|
||||
@@ -49,6 +77,16 @@ struct MotionFusion {
|
||||
char calib_pad[128]; // the controller the attempt measures (input.c pad_identity), written with the bias
|
||||
int calib_result; // MOTION_CALIB_NONE, _DONE, _FAILED or _MOVED: the outcome the row shows between attempts
|
||||
int persist; // the gamepad's instance: a finished calibration is written to totk.ini
|
||||
// The drift tracker: the estimate (rad/s, on top of gyro_bias when gyro_calibration is on), whether it settled,
|
||||
// and the rest window it is learned from. The estimate belongs to the controller and to the bias it was learned
|
||||
// against: kept through restarts, cleared with a new controller, a new calibration or a change of
|
||||
// gyro_calibration (drift_clear).
|
||||
double drift[3];
|
||||
int drift_settled;
|
||||
int drift_base; // gyro_calibration the estimate was learned with, -1 none
|
||||
double rest_s, learn_s;
|
||||
double win_g[REST_WIN][3], win_a[REST_WIN][3];
|
||||
int win_n, win_i;
|
||||
};
|
||||
|
||||
MotionFusion *motion_new(void) {
|
||||
@@ -56,6 +94,7 @@ MotionFusion *motion_new(void) {
|
||||
if (!m) rt_fatal("motion: out of memory");
|
||||
plat_mutex_init(&m->lock);
|
||||
m->restart = 1;
|
||||
m->drift_base = -1;
|
||||
return m;
|
||||
}
|
||||
|
||||
@@ -89,11 +128,11 @@ static void orthonormalize(double R[3][3]) {
|
||||
for (int j = 0; j < 3; j++) R[0][j] /= n;
|
||||
cross3(R[2], R[0], R[1]);
|
||||
}
|
||||
// A fresh orientation: z up against the measured gravity, x as close to the controller's x as that allows.
|
||||
// A fresh orientation: z up against the measured gravity (|acc| over 0.5 G), x as close to the controller's x as that
|
||||
// allows.
|
||||
static void align_to(double R[3][3], const double acc[3]) {
|
||||
double n = norm3(acc), up[3] = {0, 0, 1}, x[3] = {1, 0, 0};
|
||||
if (n > 0.5)
|
||||
for (int j = 0; j < 3; j++) up[j] = -acc[j] / n;
|
||||
double n = norm3(acc), up[3], x[3] = {1, 0, 0};
|
||||
for (int j = 0; j < 3; j++) up[j] = -acc[j] / n;
|
||||
if (fabs(up[0]) > 0.9) { x[0] = 0; x[1] = 1; }
|
||||
memcpy(R[2], up, sizeof up);
|
||||
memcpy(R[0], x, sizeof x);
|
||||
@@ -103,7 +142,7 @@ static void align_to(double R[3][3], const double acc[3]) {
|
||||
static void integrate(double R[3][3], const double gyro[3], const double acc[3], double dt) {
|
||||
double w[3] = {gyro[0], gyro[1], gyro[2]}, n = norm3(acc);
|
||||
if (fabs(n - 1) < 0.15) { // not being accelerated: turn the estimated down toward the measured one
|
||||
const double kp = 0.5;
|
||||
double kp = fabs(n - 1) < 0.05 && norm3(gyro) < STILL_RATE ? STILL_GAIN : 0.5;
|
||||
double measured[3] = {acc[0] / n, acc[1] / n, acc[2] / n}, estimated[3] = {-R[2][0], -R[2][1], -R[2][2]}, e[3];
|
||||
cross3(measured, estimated, e);
|
||||
for (int j = 0; j < 3; j++) w[j] += kp * e[j];
|
||||
@@ -128,6 +167,80 @@ static void integrate(double R[3][3], const double gyro[3], const double acc[3],
|
||||
orthonormalize(R);
|
||||
}
|
||||
|
||||
// The tracker's own switch (gyro_auto_bias, live, default 0: subtracting a learned bias made aiming feel worse in
|
||||
// play, cause unknown). Off, nothing is learned or subtracted.
|
||||
int motion_auto_bias_enabled(void) {
|
||||
static int on = -1;
|
||||
static unsigned seen;
|
||||
unsigned v = cfg_version();
|
||||
if (on < 0 || v != seen) {
|
||||
seen = v;
|
||||
on = cfg_bool("TOTK_GYRO_AUTO_BIAS");
|
||||
}
|
||||
return on;
|
||||
}
|
||||
|
||||
// m->lock held: forget the estimate and the rest window.
|
||||
static void drift_clear(MotionFusion *m) {
|
||||
memset(m->drift, 0, sizeof m->drift);
|
||||
m->drift_settled = 0;
|
||||
m->drift_base = -1;
|
||||
m->rest_s = m->learn_s = 0;
|
||||
m->win_n = m->win_i = 0;
|
||||
}
|
||||
|
||||
// Largest per-axis peak-to-peak of a full window.
|
||||
static double win_ptp(const double w[REST_WIN][3]) {
|
||||
double worst = 0;
|
||||
for (int i = 0; i < 3; i++) {
|
||||
double lo = w[0][i], hi = w[0][i];
|
||||
for (int j = 1; j < REST_WIN; j++) {
|
||||
if (w[j][i] < lo) lo = w[j][i];
|
||||
if (w[j][i] > hi) hi = w[j][i];
|
||||
}
|
||||
if (hi - lo > worst) worst = hi - lo;
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
|
||||
// m->lock held, one sample with a reading: gyro is the rate with the calibrated bias taken off when base is 1. Moves
|
||||
// m->drift toward the rate of a controller lying still. Returns 1 when the estimate settled with this sample.
|
||||
static int drift_track(MotionFusion *m, const double acc[3], const double gyro[3], int base, double dt) {
|
||||
if (m->drift_base != base) { // nothing learned yet, or learned against the other baseline: start over
|
||||
drift_clear(m);
|
||||
m->drift_base = base;
|
||||
}
|
||||
memcpy(m->win_g[m->win_i], gyro, sizeof m->win_g[0]);
|
||||
memcpy(m->win_a[m->win_i], acc, sizeof m->win_a[0]);
|
||||
m->win_i = (m->win_i + 1) % REST_WIN;
|
||||
if (m->win_n < REST_WIN) m->win_n++;
|
||||
if (m->win_n < REST_WIN) return 0;
|
||||
double mean[3] = {0, 0, 0}, a[3] = {0, 0, 0}, dev = 0;
|
||||
for (int j = 0; j < REST_WIN; j++)
|
||||
for (int i = 0; i < 3; i++) mean[i] += m->win_g[j][i] / REST_WIN, a[i] += m->win_a[j][i] / REST_WIN;
|
||||
for (int i = 0; i < 3; i++)
|
||||
if (fabs(mean[i] - m->drift[i]) > dev) dev = fabs(mean[i] - m->drift[i]);
|
||||
int still = fabs(norm3(a) - 1) < REST_GRAVITY && win_ptp(m->win_g) < REST_GYRO_PTP &&
|
||||
win_ptp(m->win_a) < REST_ACC_PTP && dev < (m->drift_settled ? DRIFT_TRACK_MAX : DRIFT_FIRST_MAX);
|
||||
if (!still) {
|
||||
m->rest_s = 0;
|
||||
if (!m->drift_settled) m->learn_s = 0;
|
||||
return 0;
|
||||
}
|
||||
m->rest_s += dt;
|
||||
if (m->rest_s < REST_HOLD_S) return 0;
|
||||
double k = dt / (m->drift_settled ? DRIFT_TAU : DRIFT_TAU_FIRST);
|
||||
for (int i = 0; i < 3; i++) {
|
||||
m->drift[i] += k * (mean[i] - m->drift[i]);
|
||||
if (m->drift[i] > DRIFT_LIMIT) m->drift[i] = DRIFT_LIMIT;
|
||||
if (m->drift[i] < -DRIFT_LIMIT) m->drift[i] = -DRIFT_LIMIT;
|
||||
}
|
||||
m->learn_s += dt;
|
||||
if (m->drift_settled || m->learn_s < DRIFT_SETTLE_S || dev >= DRIFT_SETTLED) return 0;
|
||||
m->drift_settled = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Write the calibrated bias to totk.ini. Called with m->lock released: cfg_set takes cfg.c's own lock and cfg_save
|
||||
// rewrites the file, and neither belongs inside the sensor thread's critical section.
|
||||
static void save_bias(const double bias[3], const char *pad, double spread) {
|
||||
@@ -203,18 +316,24 @@ static int calib_sample(MotionFusion *m, const double g[3], double *spread) {
|
||||
m->bias_valid = 1;
|
||||
m->calib_result = MOTION_CALIB_DONE;
|
||||
m->restart = 1; // the angle and direction start over from the new bias
|
||||
drift_clear(m); // what it learned was the old bias's remainder
|
||||
return 1;
|
||||
}
|
||||
|
||||
void motion_feed(MotionFusion *m, const double acc[3], const double gyro_raw[3], uint64_t now) {
|
||||
const int calib_on = motion_calibration_enabled(); // read before the lock: a settings change takes cfg.c's lock
|
||||
double saved[3] = {0, 0, 0}, spread = 0;
|
||||
// Read before the lock: a settings change takes cfg.c's lock.
|
||||
const int calib_on = motion_calibration_enabled(), auto_on = motion_auto_bias_enabled();
|
||||
double saved[3] = {0, 0, 0}, spread = 0, drift[3] = {0, 0, 0};
|
||||
char saved_pad[sizeof m->calib_pad] = "";
|
||||
int ended = 0, timed_out = 0, samples = 0;
|
||||
int ended = 0, timed_out = 0, samples = 0, settled = 0;
|
||||
uint64_t started = 0;
|
||||
plat_mutex_lock(&m->lock);
|
||||
double dt = m->last_ns && now > m->last_ns ? (double)(now - m->last_ns) / 1e9 : 0.004;
|
||||
if (dt > 0.05) dt = 0.004; // a gap (no controller, sensors were off): no integration across it
|
||||
if (dt > 0.05) { // a gap (no controller, sensors were off): no integration and no rest across it
|
||||
dt = 0.004;
|
||||
m->rest_s = 0;
|
||||
m->win_n = m->win_i = 0;
|
||||
}
|
||||
// Calibration: the player holds the controller still, so the raw gyro reads the bias. With the switch off an
|
||||
// attempt in progress is dropped.
|
||||
if (m->calibrating && !calib_on) {
|
||||
@@ -237,6 +356,14 @@ void motion_feed(MotionFusion *m, const double acc[3], const double gyro_raw[3],
|
||||
// The bias applies only while the switch is on; with no bias measured it is zero and the gyro passes unchanged.
|
||||
double gyro[3];
|
||||
for (int i = 0; i < 3; i++) gyro[i] = gyro_raw[i] - (calib_on ? m->gyro_bias[i] : 0);
|
||||
// A sample without a reading (a sensor just switched on reads zero) neither starts a frame nor counts as rest.
|
||||
const int reading = norm3(acc) >= 0.5;
|
||||
if (!auto_on) {
|
||||
if (m->drift_base >= 0) drift_clear(m);
|
||||
} else if (reading && (settled = drift_track(m, acc, gyro, calib_on, dt)))
|
||||
memcpy(drift, m->drift, sizeof drift);
|
||||
for (int i = 0; i < 3; i++) gyro[i] -= m->drift[i]; // zero while the switch is off
|
||||
if (m->restart && !reading) goto unlock; // no state yet; the logs below still run
|
||||
if (m->restart) {
|
||||
align_to(m->R, acc);
|
||||
memset(m->angle, 0, sizeof m->angle);
|
||||
@@ -253,9 +380,13 @@ void motion_feed(MotionFusion *m, const double acc[3], const double gyro_raw[3],
|
||||
for (int j = 0; j < 3; j++) s->dir[i * 3 + j] = (float)m->R[j][i]; // direction i = controller axis i in the reference frame
|
||||
}
|
||||
m->produced++;
|
||||
unlock:
|
||||
// The logs run with the lock released: the log back end can be slow, and the menu thread holds this lock in
|
||||
// motion_calib_poll.
|
||||
plat_mutex_unlock(&m->lock);
|
||||
if (settled)
|
||||
rt_log("motion: gyro drift at rest learned: %.5f %.5f %.5f rad/s, taken off %s", drift[0], drift[1], drift[2],
|
||||
calib_on ? "on top of the calibrated bias" : "the raw gyro");
|
||||
if (timed_out)
|
||||
rt_log("motion: gyro calibration timed out after %.1f s (%d samples): sensor data not arriving",
|
||||
(now - started) / 1e9, samples);
|
||||
@@ -322,6 +453,7 @@ void motion_bias_load(MotionFusion *m) {
|
||||
memcpy(m->gyro_bias, bias, sizeof bias);
|
||||
m->bias_valid = 1;
|
||||
m->calib_result = MOTION_CALIB_DONE;
|
||||
drift_clear(m);
|
||||
plat_mutex_unlock(&m->lock);
|
||||
}
|
||||
|
||||
@@ -335,6 +467,7 @@ void motion_bias_reset(MotionFusion *m) {
|
||||
m->calib_pad[0] = 0;
|
||||
m->calib_result = MOTION_CALIB_NONE;
|
||||
m->bias_valid = 0;
|
||||
drift_clear(m); // the drift belonged to that controller too
|
||||
plat_mutex_unlock(&m->lock);
|
||||
}
|
||||
|
||||
|
||||
+32
-2
@@ -7,6 +7,7 @@
|
||||
// raw-count angular deltas at its spherical-angle output instead. The aiming, scope, ability, horse and Purah Pad
|
||||
// cameras do the same at the angle each integrates from (camera_load). Ultrahand has a separate post-curve hook.
|
||||
// The other camera modes still take the mouse as stick, linear on both axes (mouse_stick_add).
|
||||
// A camera that runs none of these hooks gets the mouse as the right stick instead, through input.c (camera_unhooked).
|
||||
// The ordinary stick's result stays, so a controller still uses the game's own response.
|
||||
//
|
||||
// This is deliberately not a render-camera override: the game remains responsible for aiming, camera collision,
|
||||
@@ -64,10 +65,20 @@ static int hand_active(uint64_t now) {
|
||||
return last && now - last < 150000000ull;
|
||||
}
|
||||
|
||||
// Cameras no direct hook reaches. The hooks below (the free orbit's orbit_begin, every camera_load site, Ultrahand's
|
||||
// hand_input) mark each camera step they run in (step_hooked). A camera that runs none of them, such as Autobuild's
|
||||
// placement camera on games 1.4.3 and 1.2.1, reads its turn from input the hooks never see. After UNHOOKED_STEPS such
|
||||
// steps in a row the mouse leaves the direct path and acts as the right stick (input.c mouse_camera), as with
|
||||
// mouse_mode = stick, until a step runs a hook again.
|
||||
#define UNHOOKED_STEPS 2
|
||||
static volatile int32_t step_hooked, unhooked_steps;
|
||||
static void step_mark_hooked(void) { __atomic_store_n(&step_hooked, 1, __ATOMIC_RELAXED); }
|
||||
static int camera_unhooked(void) { return __atomic_load_n(&unhooked_steps, __ATOMIC_RELAXED) >= UNHOOKED_STEPS; }
|
||||
|
||||
int input_direct_mouse_active(void) {
|
||||
uint64_t last = __atomic_load_n(&last_update, __ATOMIC_ACQUIRE);
|
||||
return direct_mode() && (__atomic_load_n(&accepts_mouse, __ATOMIC_RELAXED) || hand_active(plat_now_ns())) && last &&
|
||||
plat_now_ns() - last < 150000000ull;
|
||||
plat_now_ns() - last < 150000000ull && !camera_unhooked();
|
||||
}
|
||||
|
||||
int input_direct_mouse_enabled(void) { return direct_mode(); }
|
||||
@@ -373,7 +384,19 @@ static void camera_input(Cpu *c) {
|
||||
memcpy(&next.pad[1], &c->v[10], sizeof(float));
|
||||
if (flags & 2) next.pad[0] = -next.pad[0];
|
||||
if (flags & 4) next.pad[1] = -next.pad[1];
|
||||
if (direct_mode()) {
|
||||
// The step before this one ran no direct hook: count it (camera_unhooked)
|
||||
int hooked = __atomic_exchange_n(&step_hooked, 0, __ATOMIC_RELAXED);
|
||||
int unhooked = hooked ? 0 : __atomic_load_n(&unhooked_steps, __ATOMIC_RELAXED) + (camera_unhooked() ? 0 : 1);
|
||||
if (direct_mode() && (unhooked >= UNHOOKED_STEPS) != camera_unhooked()) {
|
||||
static int lines;
|
||||
if (lines < 6) {
|
||||
lines++;
|
||||
rt_log(unhooked >= UNHOOKED_STEPS ? "mouse: the camera runs no direct hook; the mouse acts as the right stick"
|
||||
: "mouse: the camera runs a direct hook again; the mouse turns it directly");
|
||||
}
|
||||
}
|
||||
__atomic_store_n(&unhooked_steps, unhooked, __ATOMIC_RELAXED);
|
||||
if (direct_mode() && !camera_unhooked()) {
|
||||
int32_t dx, dy;
|
||||
input_direct_mouse_sample(!input_direct_mouse_selector_active() && (accept || hand_active(plat_now_ns())), &dx, &dy);
|
||||
float sensitivity = (float)cfg_double("TOTK_MOUSE_SENS");
|
||||
@@ -432,6 +455,10 @@ static void camera_input(Cpu *c) {
|
||||
rt_log("mouse: direct camera input after the stick dead zone, clamp and exponent");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Off the direct path (another mouse_mode, or a camera without a direct hook) no step follows a shake: a side
|
||||
// left set would hold input.c's right stick at full tilt
|
||||
__atomic_store_n(&shake_side, 0, __ATOMIC_RELAXED);
|
||||
}
|
||||
plat_mutex_lock(&sample_lock);
|
||||
MouseSample last = sample;
|
||||
@@ -463,6 +490,7 @@ static void orbit_begin(Cpu *c) {
|
||||
__atomic_store_n(&cam_kind_at, plat_now_ns(), __ATOMIC_RELEASE);
|
||||
orbit.object = 0;
|
||||
uint64_t object = c->x[0];
|
||||
step_mark_hooked();
|
||||
if (direct_mode()) {
|
||||
MouseSample m = sample_read();
|
||||
uint64_t input = guest_pointer(object + 0x20);
|
||||
@@ -587,6 +615,7 @@ static void orbit_angles(Cpu *c) {
|
||||
static void hand_input(Cpu *c) {
|
||||
const MouseLayout *ml = mouse_layout();
|
||||
__atomic_store_n(&hand_update, plat_now_ns(), __ATOMIC_RELEASE);
|
||||
step_mark_hooked();
|
||||
static _Thread_local uint64_t object, generation;
|
||||
if (direct_mode()) {
|
||||
MouseSample m = sample_read();
|
||||
@@ -1039,6 +1068,7 @@ static void camera_load(Cpu *c) {
|
||||
rt_log("mouse: load hook called from main+%#llx, no such site", (unsigned long long)offset);
|
||||
abort();
|
||||
}
|
||||
step_mark_hooked();
|
||||
int mapped = INPUT_CAM_UNCLASSIFIED;
|
||||
switch (s->mode) {
|
||||
case MODE_AIM:
|
||||
|
||||
@@ -49,8 +49,12 @@ uint64_t nvn_new_serial(void); // next tex_t / prog_
|
||||
// that assumption too early.
|
||||
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 on and not refused (no shadow storage, no known wait site)
|
||||
int vk_mem_shadow_on(void); // vk_memory.c: 1 with shadow storage on (valid once the Vulkan back end is up)
|
||||
void vk_mem_shadow_fence(void); // vk_memory.c: returns once every shadow sync that read the old guard is done
|
||||
// vk_memory.c: the game is about to read [addr, addr+size) of pool storage; waits for a GPU write into it that the game
|
||||
// was told is done, unless the range still holds the result of the write before
|
||||
void vk_mem_shadow_read(uint64_t addr, uint64_t size);
|
||||
void gfx_replay_wait_value(uint64_t v); // vk_backend.c: the replay thread submitted value v
|
||||
uint64_t nvn_fence_last(void); // fence value of the newest submit (0 before the first)
|
||||
int nvn_depth_minus_w(void); // 1 after DeviceSetDepthMode(NEAR_IS_MINUS_W), else 0
|
||||
|
||||
+30
-10
@@ -30,6 +30,7 @@
|
||||
#define MIN_COMMAND_SIZE 512 // NVN_DEVICE_INFO_COMMAND_BUFFER_MIN_COMMAND_SIZE (nvn_api_core.c devinfo)
|
||||
#define MIN_CONTROL_SIZE 256 // NVN_DEVICE_INFO_COMMAND_BUFFER_MIN_CONTROL_SIZE
|
||||
#define CTL_PER_RECORDING 64 // control memory one recording is reported to use
|
||||
#define CTL_PER_CALL 24 // control memory one called handle is reported to use (CallCommands)
|
||||
#define COPY_PAGE_SHIFT 16 // recording copy index granularity (release_copies)
|
||||
|
||||
static cmd_t *cmd_of(const Cpu *c) { return arg_p(c, 0); }
|
||||
@@ -412,8 +413,9 @@ void nvn_pins_stats(uint64_t *live, uint64_t *freed) {
|
||||
// copies per page), and the recording threads waited on it.
|
||||
// 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
|
||||
typedef struct { uint64_t magic, bytes, made_at, used_at, deferred, pins, cap; const tex_t **pin_v; } copy_prefix;
|
||||
// (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;
|
||||
_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;
|
||||
@@ -573,11 +575,12 @@ uint64_t nvn_handle_bytes(uint64_t handle) {
|
||||
}
|
||||
|
||||
// Marks a live copy used by submission now; its size from OP_BEGIN to OP_END inclusive.
|
||||
static uint64_t copy_touch(uint64_t handle, uint64_t now, const char *what) {
|
||||
static uint64_t copy_touch(uint64_t handle, uint64_t now, const char *what, uint64_t *hw) {
|
||||
plat_mutex_lock_shared(©_lock);
|
||||
copy_prefix *pf = copy_find(handle);
|
||||
uint64_t bytes = 0;
|
||||
if (pf) __atomic_store_n(&pf->used_at, now, __ATOMIC_RELAXED), bytes = pf->bytes;
|
||||
if (hw) *hw = pf ? pf->hw : 0;
|
||||
plat_mutex_unlock_shared(©_lock);
|
||||
if (!pf) rt_fatal("nvn: %s: command handle %#llx is not a live recording (released or never recorded)", what,
|
||||
(unsigned long long)handle);
|
||||
@@ -731,6 +734,9 @@ NVN_API(nvnCommandBufferAddCommandMemory) {
|
||||
const pool_t *p = arg_p(c, 1);
|
||||
o->cmd_base = (uintptr_t)(p ? p->mem : NULL) + (uintptr_t)arg_x(c, 2);
|
||||
o->game_size = arg_x(c, 3);
|
||||
// Memory added while recording (the out-of-memory callback): hw_start moves with hw_used, so hw_used - hw_start
|
||||
// stays the whole recording's size at EndRecording (unsigned wrap-around cancels out).
|
||||
if (o->recording) o->hw_start -= o->hw_used;
|
||||
o->cmd_used = 0;
|
||||
o->hw_used = 0;
|
||||
}
|
||||
@@ -781,6 +787,7 @@ NVN_API(nvnCommandBufferEndRecording) {
|
||||
uintptr_t lo = (uintptr_t)o->ctl + (o->ctl_used < o->ctl_size ? o->ctl_used : 0);
|
||||
uintptr_t hi = o->ctl ? lo + 1 : 0;
|
||||
o->ctl_used += CTL_PER_RECORDING;
|
||||
((copy_prefix *)copy - 1)->hw = o->hw_used - o->hw_start; // BEGIN and END excluded; what a copy of it adds
|
||||
copy_add(lo, hi, copy);
|
||||
ret_x(c, (uintptr_t)copy);
|
||||
}
|
||||
@@ -789,32 +796,45 @@ NVN_API(nvnCommandBufferIsRecording) { ret_x(c, cmd_of(c)->recording != 0); }
|
||||
|
||||
// The called recording is copied into the caller at the call position: the game recycles command memory in small steps,
|
||||
// so a handle may be gone by the time the caller is submitted. Deferred binds stay deferred. A copy is OP_BEGIN, its
|
||||
// records and OP_END (flatten_recording checked them), so the records go over as one block; usage grows by the same
|
||||
// records and OP_END (flatten_recording checked them), so the records go over as one block; cmd_used grows by the same
|
||||
// bytes as record by record.
|
||||
static void inline_recording(cmd_t *o, uint64_t handle, const char *what) {
|
||||
// nvnCommandBufferGetCommandMemoryUsed grows as on the real driver: a call by nothing (the driver puts a call in
|
||||
// control memory, nvnCommandBufferCallCommands) and a copy by the copied recording's hardware size (copy_prefix.hw), not by our record bytes. The
|
||||
// game measures small command sets it records and sizes renderer memory pools from them: MacNativeGames commit 6909dbb7
|
||||
// measured one recording with two uniform buffer binds and one CallCommands at 40 bytes on the original driver
|
||||
// (Ryujinx, 1.0.0) and 88 in their port, whose larger sizes doubled a renderer's pool and ran its private heap dry
|
||||
// (NULL write crash near Zora's Domain). 1.4.3 calls in recordings it queries every frame (copies were not seen).
|
||||
static void inline_recording(cmd_t *o, uint64_t handle, int call) {
|
||||
const char *what = call ? "CallCommands" : "CopyCommands";
|
||||
if (!handle) rt_fatal("nvn: %s with a null handle", what);
|
||||
uint64_t bytes = copy_touch(handle, __atomic_load_n(&nsubmits, __ATOMIC_RELAXED), what);
|
||||
uint64_t hw = 0;
|
||||
uint64_t bytes = copy_touch(handle, __atomic_load_n(&nsubmits, __ATOMIC_RELAXED), what, &hw);
|
||||
if (bytes <= 16) return;
|
||||
size_t body = (size_t)bytes - 16;
|
||||
cmd_reserve(o, body);
|
||||
memcpy(o->cur, (const uint8_t *)(uintptr_t)handle + 8, body);
|
||||
o->cur += body;
|
||||
o->cmd_used += body;
|
||||
o->hw_used += body;
|
||||
if (!call) o->hw_used += hw;
|
||||
o->last_rec = 0;
|
||||
}
|
||||
// void nvnCommandBuffer{Call,Copy}Commands(NVNcommandBuffer *cmd, int n, const NVNcommandHandle *handles)
|
||||
// A call takes control memory instead: the game's inline copy of the driver's call (1.4.3 main+0x2d33a4, in the
|
||||
// function that measures a renderer's command set) writes one 24-byte control entry per segment of the called handle,
|
||||
// after an 8-byte block header. The game reads a buffer whose command and control usage are both 0 as empty
|
||||
// (main+0x83f8c clears bit 0 of its flags), so a buffer that only called recordings must show control usage.
|
||||
NVN_API(nvnCommandBufferCallCommands) {
|
||||
cmd_t *o = cmd_of(c);
|
||||
int n = (int)arg_x(c, 1);
|
||||
const uint64_t *h = arg_p(c, 2);
|
||||
for (int i = 0; i < n; i++) inline_recording(o, h[i], "CallCommands");
|
||||
for (int i = 0; i < n; i++) inline_recording(o, h[i], 1);
|
||||
if (n > 0) o->ctl_used += CTL_PER_CALL * (size_t)n;
|
||||
}
|
||||
NVN_API(nvnCommandBufferCopyCommands) {
|
||||
cmd_t *o = cmd_of(c);
|
||||
int n = (int)arg_x(c, 1);
|
||||
const uint64_t *h = arg_p(c, 2);
|
||||
for (int i = 0; i < n; i++) inline_recording(o, h[i], "CopyCommands");
|
||||
for (int i = 0; i < n; i++) inline_recording(o, h[i], 0);
|
||||
}
|
||||
|
||||
// ---------- CommandBuffer: commands with CPU-visible results (performed by the back end in GPU order)
|
||||
@@ -1285,7 +1305,7 @@ static int resolve_deferred(const uint8_t *p, int depth) { // returns the numb
|
||||
|
||||
void nvn_submit_prepare(const uint64_t *handles, int n) {
|
||||
uint64_t now = __atomic_add_fetch(&nsubmits, 1, __ATOMIC_RELAXED);
|
||||
for (int i = 0; i < n; i++) copy_touch(handles[i], now, "QueueSubmitCommands");
|
||||
for (int i = 0; i < n; i++) copy_touch(handles[i], now, "QueueSubmitCommands", NULL);
|
||||
for (int i = 0; i < n; i++) resolve_deferred((const uint8_t *)(uintptr_t)handles[i], 0);
|
||||
}
|
||||
|
||||
|
||||
+17
-5
@@ -53,13 +53,19 @@ void nvn_guest_written(uint64_t addr, uint64_t size) {
|
||||
if (size) gfx_backend()->guest_written(addr, size);
|
||||
}
|
||||
|
||||
// The camera jitter of 1.4.3 (vk_dlaa.c); a weak default like the hooks below.
|
||||
void vk_dlaa_camera_copied(uint64_t lr, uint64_t dst, uint64_t off);
|
||||
__attribute__((weak)) void vk_dlaa_camera_copied(uint64_t lr, uint64_t dst, uint64_t off) { (void)lr, (void)dst, (void)off; }
|
||||
|
||||
// memcpy of pool storage the GPU rendered into must copy what the GPU wrote: TotK moves its generated grass maps
|
||||
// between pools with memcpy. Copies below 1 KiB skip the check; the copy itself is memmove, as overlapping
|
||||
// arguments are undefined for memcpy anyway.
|
||||
// arguments are undefined for memcpy anyway. TotK 1.4.3 copies its camera matrices with 64-byte memcpys
|
||||
// (f_70000e31d4); x8 holds the member's offset in the block there (vk_dlaa.c vk_dlaa_camera_copied).
|
||||
static void ov_memcpy(Cpu *c) {
|
||||
uint64_t dst = arg_x(c, 0), src = arg_x(c, 1), n = arg_x(c, 2);
|
||||
if (n >= 1024) gfx_backend()->guest_read(src, n);
|
||||
memmove((void *)(uintptr_t)dst, (const void *)(uintptr_t)src, n);
|
||||
if (n == 64) vk_dlaa_camera_copied(c->x[30], dst, c->x[8]);
|
||||
ret_x(c, dst);
|
||||
}
|
||||
HOST_OVERRIDE("memcpy", ov_memcpy);
|
||||
@@ -475,15 +481,17 @@ NVN_API(nvnQueueFenceSync) {
|
||||
// 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
|
||||
// one, waits for the frame before it instead. What the game reads back of GPU results after the wait can then be a
|
||||
// frame old. The game's CPU writes to memory the GPU still reads reach the GPU only through shadow copies, which are
|
||||
// frame old; a buffer that holds no older result is waited for when the game invalidates it (vk_memory.c
|
||||
// vk_mem_shadow_read). The game's CPU writes to memory the GPU still reads reach the GPU only through shadow copies, which are
|
||||
// queued for the GPU or wait (nvn_sync_ahead_guard). The wait still lasts until the replay thread submitted the asked
|
||||
// value, so no copy of that value itself picks up those writes. pa_fence: the newest fence at the latest present and
|
||||
// the one before, present thread only for writes. pa_guard: the newest value the game was told is done early.
|
||||
static uint64_t pa_fence[2], pa_guard;
|
||||
// The return address of that wait. 1.2.1: 0x7000b23dfc. 1.4.3: 0x70002db99c, the second of the two nvnSyncWait calls
|
||||
// in f_70002db8ac; like on 1.2.1 its sync comes from a two-entry ring indexed per frame, and the first call waits on
|
||||
// one object's sync behind a mode check. 0: no site known, the switch stays off.
|
||||
// The return address of that wait. 1.1.0: 0x7000b39aa4, 1.2.1: 0x7000b23dfc, 1.4.3: 0x70002db99c. The second
|
||||
// nvnSyncWait in 1.1.0 f_7000b39a00 and 1.4.3 f_70002db8ac uses the per-frame sync, like on 1.2.1; the first
|
||||
// call waits on one object's sync behind a mode check. 0: no site known, the switch stays off.
|
||||
static uint64_t frame_wait_lr(void) {
|
||||
if (rt_game_version == 110) return 0x7000b39aa4ull;
|
||||
return rt_game_version == 121 ? 0x7000b23dfcull : rt_game_version == 143 ? 0x70002db99cull : 0;
|
||||
}
|
||||
static int sync_ahead(void) {
|
||||
@@ -503,6 +511,9 @@ static int sync_ahead(void) {
|
||||
"GPU as before");
|
||||
on = 0;
|
||||
}
|
||||
// The depth query patch (set qstamp, patches-v143.txt) is switched by TOTK_SYNC_AHEAD too: a refused switch
|
||||
// leaves the game's own frame number check, as with the switch off.
|
||||
if (!on) rt_patch_switch(rt_patch_set("qstamp"), 0);
|
||||
if (on) rt_log("nvn: TOTK_SYNC_AHEAD: a wait for the frame presented last waits for the frame before it");
|
||||
}
|
||||
return on;
|
||||
@@ -513,6 +524,7 @@ void nvn_sync_ahead_present(void) {
|
||||
__atomic_store_n(&pa_fence[0], nvn_fence_last(), __ATOMIC_RELEASE);
|
||||
}
|
||||
uint64_t nvn_sync_ahead_guard(void) { return __atomic_load_n(&pa_guard, __ATOMIC_ACQUIRE); }
|
||||
int nvn_sync_ahead_on(void) { return sync_ahead(); }
|
||||
|
||||
// NVNsyncWaitResult nvnSyncWait(const NVNsync *s, uint64_t timeout_ns): a sync never fenced reports a timeout at once;
|
||||
// a fenced one is released only after the back end completed that fence value
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
void nvn_pool_invalidate(const pool_t *p, uint64_t off, uint64_t size) {
|
||||
if (!p->mem || nvn_gpu_only((uintptr_t)p->mem) || off >= p->size || !size) return;
|
||||
if (size > p->size - off) size = p->size - off;
|
||||
vk_mem_shadow_read((uintptr_t)p->mem + off, size);
|
||||
gfx_backend()->guest_read((uintptr_t)p->mem + off, size);
|
||||
}
|
||||
|
||||
|
||||
@@ -770,6 +770,16 @@ static void probe_commands(void) {
|
||||
// adding the control memory again retires the recordings made in it
|
||||
CALL(nvnCommandBufferAddControlMemory, U(&cmd2), U(ctlmem2), 0x1000);
|
||||
CHECK(!nvn_handle_live(h2) && nvn_handle_live(h), "reusing control memory retires only the handles recorded in it");
|
||||
|
||||
// a buffer that only called a recording is not empty: the call takes control memory and no command memory
|
||||
CALL(nvnCommandBufferAddCommandMemory, U(&cmd2), U(&pool), 0x34000, 0x4000);
|
||||
CALL(nvnCommandBufferBeginRecording, U(&cmd2));
|
||||
CALL(nvnCommandBufferCallCommands, U(&cmd2), 1, U(&h));
|
||||
uint64_t used = CALL(nvnCommandBufferGetCommandMemoryUsed, U(&cmd2));
|
||||
uint64_t ctl_used = CALL(nvnCommandBufferGetControlMemoryUsed, U(&cmd2));
|
||||
CHECK(used == 0 && ctl_used > 0, "a call takes control memory only: command %llu, control %llu bytes",
|
||||
(unsigned long long)used, (unsigned long long)ctl_used);
|
||||
CALL(nvnCommandBufferEndRecording, U(&cmd2));
|
||||
CALL(nvnCommandBufferFinalize, U(&cmd2));
|
||||
probe_pins();
|
||||
n_objects += 5;
|
||||
|
||||
@@ -94,6 +94,7 @@ static void npad_states(Cpu *c, uint32_t want) {
|
||||
if (live) {
|
||||
s.attributes = ATTR_CONNECTED;
|
||||
input_poll(&s.buttons, &s.lx, &s.ly, &s.rx, &s.ry);
|
||||
quicksave_guest(c); // quick save and load call into the game here, between two of its own calls
|
||||
vk_reflex_marker(6, vk_reflex_frame()); // VK_LATENCY_MARKER_INPUT_SAMPLE_NV
|
||||
}
|
||||
*out = s;
|
||||
|
||||
+114
-4
@@ -244,6 +244,12 @@ static char *lang(void) {
|
||||
}
|
||||
|
||||
static void set_env(const char *name, const char *value) { plat_setenv(name, value); } // NULL removes it
|
||||
// A live setting read through a cfg_version cache: the environment wins, and the cfg_set (empty = the default) moves
|
||||
// the version so the cache reads it again.
|
||||
static void set_live(const char *name, const char *value) {
|
||||
set_env(name, value);
|
||||
cfg_set(name, value ? value : "");
|
||||
}
|
||||
|
||||
static void probe_oe(void) {
|
||||
char *keep_lang = cfg_get("TOTK_LANG") ? strdup(cfg_get("TOTK_LANG")) : NULL;
|
||||
@@ -523,6 +529,26 @@ static void probe_time(void) {
|
||||
static int near3(const float *v, double x, double y, double z, double tol) {
|
||||
return fabs(v[0] - x) <= tol && fabs(v[1] - y) <= tol && fabs(v[2] - z) <= tol;
|
||||
}
|
||||
// A gyro sample: rate plus noise. Uniform noise of half-width amp from a fixed LCG, so every run reads the same.
|
||||
static void noisy(const double rate[3], double amp, uint32_t *seed, double out[3]) {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
*seed = *seed * 1664525u + 1013904223u;
|
||||
out[i] = rate[i] + amp * ((double)(*seed >> 8) / (1 << 24) * 2 - 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Feed secs of samples at the sensor thread's 4 ms; returns the yaw (angle z, revolutions) the last state reads.
|
||||
static double feed_for(MotionFusion *m, const double acc[3], const double rate[3], double amp, uint32_t *seed,
|
||||
double secs, uint64_t *t) {
|
||||
MotionState s;
|
||||
double g[3];
|
||||
for (int i = 0; i < (int)(secs * 250 + 0.5); i++) {
|
||||
noisy(rate, amp, seed, g);
|
||||
motion_feed(m, acc, g, *t += 4000000);
|
||||
}
|
||||
return motion_read(m, &s, 1, *t + 1000000) == 1 ? s.angle[2] : NAN;
|
||||
}
|
||||
|
||||
static int at_rest(const MotionState *s) {
|
||||
return !s->attributes && !s->sampling && near3(s->acc, 0, 0, -1, 0) && near3(s->gyro, 0, 0, 0, 0) &&
|
||||
near3(s->dir, 1, 0, 0, 0) && near3(s->dir + 3, 0, 1, 0, 0) && near3(s->dir + 6, 0, 0, 1, 0);
|
||||
@@ -655,6 +681,87 @@ static void probe_feedback(uint32_t pid, uint32_t style) {
|
||||
fabs(ms[0].gyro[2] - bias[2] / (2 * M_PI)) < 1e-6,
|
||||
"calibration without samples: state %d after 1 s, %d after 6 s; after a reset the raw gyro passes", waiting,
|
||||
failed);
|
||||
// A sensor just switched on reads zero: the frame starts at the first reading, here standing on the bottom edge
|
||||
// (controller y up). Then the down is wrong by a quarter turn (laid flat without turning): a second held still
|
||||
// levels it to within 8 degrees.
|
||||
MotionFusion *u = motion_new();
|
||||
const double standing[3] = {0, -1, 0};
|
||||
motion_feed(u, still, still, t);
|
||||
int before = motion_read(u, ms, 16, t + 1000000);
|
||||
motion_feed(u, standing, still, t += 4000000);
|
||||
int first = motion_read(u, ms, 16, t + 1000000);
|
||||
int upright_y = first == 1 && near3(ms[0].dir + 3, 0, 0, 1, 0.01);
|
||||
for (int i = 0; i < 250; i++) motion_feed(u, down, still, t += 4000000);
|
||||
motion_read(u, ms, 16, t + 1000000);
|
||||
CHECK(before == 0 && upright_y && ms[0].dir[8] > 0.99,
|
||||
"fusion start and levelling: %d states before a reading, %d after (y up %d), z up %.3f after 1 s still",
|
||||
before, first, upright_y, (double)ms[0].dir[8]);
|
||||
|
||||
// Drift at rest (gyro_auto_bias). Table noise is +-0.006 rad/s, a hand's +-0.03; drift is the yaw rate a
|
||||
// controller lying still reads, in rad/s, over the 10 s after the tracker had 10 s to learn.
|
||||
char *keep_auto = cfg_get("TOTK_GYRO_AUTO_BIAS") ? strdup(cfg_get("TOTK_GYRO_AUTO_BIAS")) : NULL;
|
||||
char *keep_cal = cfg_get("TOTK_GYRO_CALIBRATION") ? strdup(cfg_get("TOTK_GYRO_CALIBRATION")) : NULL;
|
||||
set_live("TOTK_GYRO_CALIBRATION", "1");
|
||||
const double drift_b[3] = {0.02, -0.03, 0.05}, rev = 2 * M_PI;
|
||||
uint32_t seed = 1;
|
||||
double drift_rate[2];
|
||||
for (int on = 0; on < 2; on++) {
|
||||
set_live("TOTK_GYRO_AUTO_BIAS", on ? "1" : "0");
|
||||
MotionFusion *d = motion_new();
|
||||
uint64_t td = t;
|
||||
feed_for(d, down, drift_b, 0.006, &seed, 10, &td);
|
||||
double y0 = feed_for(d, down, drift_b, 0.006, &seed, 0.004, &td);
|
||||
drift_rate[on] = (feed_for(d, down, drift_b, 0.006, &seed, 10, &td) - y0) * rev / 10;
|
||||
}
|
||||
CHECK(fabs(drift_rate[0] - drift_b[2]) < 0.002 && fabs(drift_rate[1]) < 0.001,
|
||||
"drift at rest: yaw %.5f rad/s with gyro_auto_bias off, %.5f on (bias %.3f)", drift_rate[0], drift_rate[1],
|
||||
drift_b[2]);
|
||||
// The #1267 case: calibrated, then the bias moved by 0.01 rad/s (the controller warmed up). The tracker takes the
|
||||
// remainder on top of the calibrated bias, and a new calibration starts it over.
|
||||
MotionFusion *c = motion_new();
|
||||
uint64_t tc = t;
|
||||
motion_calibrate_start(c, "probe pad", tc);
|
||||
feed_for(c, down, drift_b, 0.006, &seed, 1.6, &tc);
|
||||
int cal = motion_calib_poll(c, tc);
|
||||
const double warm[3] = {drift_b[0], drift_b[1], drift_b[2] - 0.01};
|
||||
double c0 = feed_for(c, down, warm, 0.006, &seed, 0.004, &tc);
|
||||
double c_early = (feed_for(c, down, warm, 0.006, &seed, 0.5, &tc) - c0) * rev / 0.5;
|
||||
feed_for(c, down, warm, 0.006, &seed, 10, &tc);
|
||||
c0 = feed_for(c, down, warm, 0.006, &seed, 0.004, &tc);
|
||||
double c_late = (feed_for(c, down, warm, 0.006, &seed, 10, &tc) - c0) * rev / 10;
|
||||
CHECK(cal == MOTION_CALIB_DONE && fabs(c_early + 0.01) < 0.002 && fabs(c_late) < 0.001,
|
||||
"drift after calibration: state %d, yaw %.5f rad/s right after, %.5f once learned", cal, c_early, c_late);
|
||||
// In the hand: a slow aim, 0.05 rad/s (3 deg/s) of yaw with a hand's noise, for 10 s. Nothing is learned from it,
|
||||
// so the full turn reaches the game.
|
||||
MotionFusion *h = motion_new();
|
||||
uint64_t th = t;
|
||||
const double pan[3] = {0, 0, 0.05};
|
||||
double h0 = feed_for(h, down, pan, 0.03, &seed, 0.004, &th);
|
||||
double turned = (feed_for(h, down, pan, 0.03, &seed, 10, &th) - h0) * rev;
|
||||
CHECK(fabs(turned - 0.5) < 0.01, "slow aim in the hand: %.4f rad of the 0.5 turned", turned);
|
||||
// Levelling and drift together: the frame starts standing on the bottom edge, then the controller lies flat with
|
||||
// a bias on every axis. The bias tilts the fused down by bias / gain (0.05 / 4 rad, 0.7 degrees) until it is
|
||||
// learned; then the down is level, and yaw holds.
|
||||
MotionFusion *l = motion_new();
|
||||
uint64_t tl = t;
|
||||
feed_for(l, standing, drift_b, 0.006, &seed, 0.004, &tl);
|
||||
feed_for(l, down, drift_b, 0.006, &seed, 1, &tl);
|
||||
motion_read(l, ms, 1, tl + 1000000);
|
||||
double up_1s = ms[0].dir[8];
|
||||
feed_for(l, down, drift_b, 0.006, &seed, 10, &tl);
|
||||
double l0 = feed_for(l, down, drift_b, 0.006, &seed, 0.004, &tl);
|
||||
double l_rate = (feed_for(l, down, drift_b, 0.006, &seed, 10, &tl) - l0) * rev / 10;
|
||||
motion_read(l, ms, 1, tl + 1000000);
|
||||
CHECK(up_1s > 0.99 && ms[0].dir[8] > 0.99999 && fabs(l_rate) < 0.001,
|
||||
"levelling with drift: z up %.5f after 1 s, %.6f after 21 s, yaw %.5f rad/s", up_1s, (double)ms[0].dir[8],
|
||||
l_rate);
|
||||
printf("hid drift at rest: yaw %.5f rad/s off, %.5f on; after calibration %.5f, then %.5f; slow aim %.4f of 0.5 "
|
||||
"rad; levelled z %.5f, yaw %.5f rad/s\n",
|
||||
drift_rate[0], drift_rate[1], c_early, c_late, turned, up_1s, l_rate);
|
||||
set_live("TOTK_GYRO_AUTO_BIAS", keep_auto);
|
||||
set_live("TOTK_GYRO_CALIBRATION", keep_cal);
|
||||
free(keep_auto);
|
||||
free(keep_cal);
|
||||
printf("hid feedback: vibration handles %#x %#x, six-axis %#x, at rest when stopped; fusion quarter turn %.4f rev\n",
|
||||
vh[0], vh[1], sh[0], quarter);
|
||||
}
|
||||
@@ -895,11 +1002,14 @@ static void probe_fonts(void) {
|
||||
CHECK(got == sizeof head && size && size + 8 == (uint64_t)len, "shared font 0: size %llu, file %lld bytes",
|
||||
(unsigned long long)size, (long long)len);
|
||||
const uint8_t *p = (const uint8_t *)(uintptr_t)addr;
|
||||
CHECK(addr && !memcmp(p - 8, head, sizeof head) && ov_bfttf_size(p - 8, size + 8) == size,
|
||||
"shared font 0: the address is not 8 bytes into the BFTTF file");
|
||||
// The pl shared memory layout: the file's BFTTF header unchanged at Address - 8, the decoded sfnt font at Address.
|
||||
CHECK(addr && !memcmp(p - 8, head, 8) && ov_bfttf_size(head, size + 8) == size,
|
||||
"shared font 0: the address is not 8 bytes past the file's BFTTF header");
|
||||
CHECK(!memcmp(p, "\0\1\0\0", 4) || !memcmp(p, "OTTO", 4),
|
||||
"shared font 0: the data at the address is not plain sfnt: %02x %02x %02x %02x", p[0], p[1], p[2], p[3]);
|
||||
CHECK(CALL("pl.GetSharedFontAddress", 0) == addr, "shared font 0: the address changed");
|
||||
printf("pl: shared font 0 (Standard) at %#llx, %llu bytes, BFTTF header checked (%s)\n", (unsigned long long)addr,
|
||||
(unsigned long long)size, path);
|
||||
printf("pl: shared font 0 (Standard) at %#llx, %llu bytes, BFTTF header and decoded sfnt checked (%s)\n",
|
||||
(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
|
||||
|
||||
+14
-4
@@ -775,10 +775,15 @@ static void ov_user_difference(Cpu *c) {
|
||||
|
||||
// ==== nn::pl shared fonts (shared_font.c). TotK asks for them only from its font loader, only with Simplified Chinese,
|
||||
// Korean or Traditional Chinese text, and only for type 0; tools/extract_fonts.py writes
|
||||
// them from the user's firmware. Each type is read on first use into guest-visible memory as the BFTTF file the pl
|
||||
// shared memory holds; Address is 8 bytes past the file start (after the BFTTF header) and Size the decoded font size,
|
||||
// as in MNG. The load state is always Loaded: the game spins until it is, so missing files stop with a named fatal at
|
||||
// Address/Size instead of a hang. TOTK_SHARED_FONTS=<dir> overrides <romfs>/../../firmware/shared-fonts.
|
||||
// them from the user's firmware. Each type is read on first use into guest-visible memory laid out as the pl shared
|
||||
// memory holds it: the file's 8-byte BFTTF header as it is, then the font decoded to plain sfnt data. Address is 8
|
||||
// bytes past the file start (after the header) and Size the decoded font size, as in MNG. The firmware file keeps the
|
||||
// font XOR-encoded, and the game cannot read it that way: its font loader takes the data at Address as a font when the
|
||||
// first word is an sfnt tag and otherwise hands it to nn::fontll::ScalableFontEngineHelper::Decode, which knows only
|
||||
// a BFTTF header at the start and returns NULL for an encoded payload. The face then gets no name, SetFont fails, and
|
||||
// the text draws the previous face's glyphs with the failed face's metrics (the CJK ellipsis above the line; MNG
|
||||
// shared_font.c load decodes the same way since its pull request #2145). The load state is always Loaded: the game
|
||||
// spins until it is, so missing files stop with a named fatal at Address/Size instead of a hang. TOTK_SHARED_FONTS=<dir> overrides <romfs>/../../firmware/shared-fonts.
|
||||
#define SHARED_FONT_TYPES 6
|
||||
#define BFTTF_MAGIC 0x7f9a0218u
|
||||
static const char *const font_files[SHARED_FONT_TYPES] = {
|
||||
@@ -840,6 +845,11 @@ static const uint8_t *font_data(Cpu *c, const char *fn, int64_t t) {
|
||||
fclose(f);
|
||||
uint64_t size = got == (size_t)len ? ov_bfttf_size(p, (uint64_t)len) : 0;
|
||||
if (!size) rt_fatal("nn::pl: shared font %s is not a BFTTF font", path);
|
||||
// Decode the font in place; the words are big-endian, so byte i of each word takes key byte i.
|
||||
uint32_t key = be32(p) ^ BFTTF_MAGIC;
|
||||
for (int64_t i = 8; i < len; i++) p[i] ^= (uint8_t)(key >> (24 - 8 * (i & 3)));
|
||||
if (memcmp(p + 8, "\0\1\0\0", 4) && memcmp(p + 8, "OTTO", 4))
|
||||
rt_fatal("nn::pl: shared font %s is not an sfnt font after decoding", path);
|
||||
fonts.size[t] = size;
|
||||
__atomic_store_n(&fonts.file[t], p, __ATOMIC_RELEASE);
|
||||
rt_log("pl: shared font %lld (%s): %llu bytes from %s", (long long)t, font_type_name(t),
|
||||
|
||||
+96
-10
@@ -8,6 +8,12 @@
|
||||
// code reaches it with one adrp, as MacNativeGames' data page after main (games/totk/runtime/game_patches.c). Its
|
||||
// layout belongs to the sets that use it (frame_rate.c: +0 the 30 Hz ratio, +4 the frame step in seconds, +8 the
|
||||
// step in 60 Hz ticks).
|
||||
//
|
||||
// Contested sites: a site that two or more ordered sets patch (the mods' ExeFS patch files, tools/exefs_patches.py)
|
||||
// tests one byte, rt_patch_pick[site], instead of each set's switch. rt_patch_picks fills it from the sets that are on
|
||||
// and the ranks their owner gave them (mods.c: the Mods tab's position), so the load order decides which mod's code
|
||||
// runs there, as it decides RomFS files and data writes. Generic over what owns a set: a part kind that patches code
|
||||
// (stage 2's plugin hooks) ranks its sets the same way.
|
||||
// Probe modes never call rt_patches_init: every set stays off.
|
||||
#include "cfg.h"
|
||||
#include "platform/platform.h"
|
||||
@@ -24,8 +30,12 @@
|
||||
#ifndef RT_PATCH_COUNT
|
||||
#define RT_PATCH_COUNT 0
|
||||
#endif
|
||||
#ifndef RT_PATCH_PICK_COUNT
|
||||
#define RT_PATCH_PICK_COUNT 0
|
||||
#endif
|
||||
|
||||
uint8_t rt_patch_on[RT_PATCH_COUNT > 0 ? RT_PATCH_COUNT : 1]; // read by the generated C at every patched site
|
||||
uint8_t rt_patch_pick[RT_PATCH_PICK_COUNT > 0 ? RT_PATCH_PICK_COUNT : 1]; // read at every contested site
|
||||
|
||||
#if RT_PATCH_COUNT
|
||||
static const struct { const char *name, *env; int on; } sets[] = {
|
||||
@@ -35,6 +45,26 @@ static const struct { const char *name, *env; int on; } sets[] = {
|
||||
};
|
||||
static void *page;
|
||||
#endif
|
||||
#if RT_PATCH_PICK_COUNT
|
||||
#define X(i, m, o, ...) static const int16_t pick_sets_##i[] = {__VA_ARGS__};
|
||||
RT_PATCH_PICKS(X)
|
||||
#undef X
|
||||
static const RtPatchPick gen_picks[] = {
|
||||
#define X(i, m, o, ...) {m, o, pick_sets_##i, (int)(sizeof pick_sets_##i / sizeof *pick_sets_##i)},
|
||||
RT_PATCH_PICKS(X)
|
||||
#undef X
|
||||
};
|
||||
#else
|
||||
static const RtPatchPick *const gen_picks = NULL;
|
||||
#endif
|
||||
static uint16_t gen_rank[RT_PATCH_COUNT > 0 ? RT_PATCH_COUNT : 1]; // rank + 1; 0 unranked
|
||||
|
||||
// The table in use: the generated one, or --probe-mods' own (rt_patch_probe_table).
|
||||
static int nset = RT_PATCH_COUNT, npick = RT_PATCH_PICK_COUNT;
|
||||
static uint8_t *on = rt_patch_on, *pick = rt_patch_pick;
|
||||
static uint16_t *rank = gen_rank;
|
||||
static const RtPatchPick *picks = gen_picks;
|
||||
static const char *const *probe_names;
|
||||
|
||||
void rt_patches_init(void) {
|
||||
#if RT_PATCH_COUNT
|
||||
@@ -53,26 +83,82 @@ void rt_patches_init(void) {
|
||||
if (n >= sizeof list) n = sizeof list - 1;
|
||||
}
|
||||
rt_log("patches: %s (page %#llx)", list, RT_PATCH_PAGE);
|
||||
rt_patch_picks(); // a set the environment switched on runs at its sites, unranked
|
||||
#endif
|
||||
}
|
||||
|
||||
const char *rt_patch_name(int set) {
|
||||
if (set < 0 || set >= nset) return NULL;
|
||||
if (probe_names) return probe_names[set];
|
||||
#if RT_PATCH_COUNT
|
||||
return sets[set].name;
|
||||
#else
|
||||
return NULL;
|
||||
#endif
|
||||
}
|
||||
|
||||
int rt_patch_set(const char *name) {
|
||||
#if RT_PATCH_COUNT
|
||||
for (int i = 0; i < RT_PATCH_COUNT; i++)
|
||||
if (!strcmp(sets[i].name, name)) return i;
|
||||
#endif
|
||||
(void)name;
|
||||
for (int i = 0; i < nset; i++)
|
||||
if (!strcmp(rt_patch_name(i), name)) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
int rt_patch_enabled(int set) { return set >= 0 && set < RT_PATCH_COUNT && rt_patch_on[set]; }
|
||||
int rt_patch_enabled(int set) { return set >= 0 && set < nset && on[set]; }
|
||||
|
||||
void rt_patch_disable(int set) {
|
||||
if (set >= 0 && set < RT_PATCH_COUNT) rt_patch_on[set] = 0;
|
||||
// The place in p's sets of the one that runs: on, the lowest rank, a tie to the later one; -1 when none is on.
|
||||
static int winner(const RtPatchPick *p) {
|
||||
int best = -1;
|
||||
unsigned best_key = 0;
|
||||
for (int j = 0; j < p->nsets; j++) {
|
||||
int s = p->sets[j];
|
||||
if (s < 0 || s >= nset || !on[s]) continue;
|
||||
unsigned key = rank[s] ? rank[s] : 0x10000u;
|
||||
if (best < 0 || key <= best_key) best = j, best_key = key;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
void rt_patch_switch(int set, int on) {
|
||||
if (set >= 0 && set < RT_PATCH_COUNT) __atomic_store_n(&rt_patch_on[set], (uint8_t)(on != 0), __ATOMIC_RELAXED);
|
||||
// The picks of the contested sites set touches (every site for -1).
|
||||
static void repick(int set) {
|
||||
for (int i = 0; i < npick; i++) {
|
||||
int has = set < 0;
|
||||
for (int j = 0; !has && j < picks[i].nsets; j++) has = picks[i].sets[j] == set;
|
||||
if (has) __atomic_store_n(&pick[i], (uint8_t)(winner(&picks[i]) + 1), __ATOMIC_RELAXED);
|
||||
}
|
||||
}
|
||||
|
||||
void rt_patch_disable(int set) {
|
||||
if (set >= 0 && set < nset) on[set] = 0;
|
||||
repick(set);
|
||||
}
|
||||
|
||||
void rt_patch_switch(int set, int value) {
|
||||
if (set < 0 || set >= nset) return;
|
||||
__atomic_store_n(&on[set], (uint8_t)(value != 0), __ATOMIC_RELAXED);
|
||||
repick(set);
|
||||
}
|
||||
|
||||
void rt_patch_rank(int set, int r) {
|
||||
if (set >= 0 && set < nset) rank[set] = (uint16_t)(r < 0 ? 1 : r > 0xFFFE ? 0xFFFF : r + 1);
|
||||
}
|
||||
|
||||
void rt_patch_picks(void) { repick(-1); }
|
||||
int rt_patch_pick_count(void) { return npick; }
|
||||
const RtPatchPick *rt_patch_pick_at(int i) { return i >= 0 && i < npick ? &picks[i] : NULL; }
|
||||
int rt_patch_pick_winner(int i) { return i >= 0 && i < npick ? (int)__atomic_load_n(&pick[i], __ATOMIC_RELAXED) - 1 : -1; }
|
||||
|
||||
void rt_patch_probe_table(const char *const *names, int n, const RtPatchPick *p, int np) {
|
||||
if (probe_names) {
|
||||
free(on);
|
||||
free(pick);
|
||||
free(rank);
|
||||
}
|
||||
probe_names = NULL;
|
||||
nset = RT_PATCH_COUNT, npick = RT_PATCH_PICK_COUNT;
|
||||
on = rt_patch_on, pick = rt_patch_pick, rank = gen_rank, picks = gen_picks;
|
||||
if (!names) return;
|
||||
on = calloc((size_t)n + 1, 1), pick = calloc((size_t)np + 1, 1), rank = calloc((size_t)n + 1, sizeof *rank);
|
||||
probe_names = names, nset = n, npick = np, picks = p;
|
||||
}
|
||||
|
||||
void *rt_patch_page(void) {
|
||||
|
||||
@@ -379,6 +379,17 @@ static inline char *plat_last_sep(const char *path) {
|
||||
if (*p == '/' || *p == '\\') last = (char *)p;
|
||||
return last;
|
||||
}
|
||||
// 1 when path does not depend on the working directory: it starts with a separator (a root or UNC path) or, on
|
||||
// Windows, with a drive letter and a separator.
|
||||
static inline int plat_path_absolute(const char *path) {
|
||||
if (path[0] == '/' || path[0] == '\\') return 1;
|
||||
#ifdef _WIN32
|
||||
char c = path[0];
|
||||
return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) && path[1] == ':' && (path[2] == '/' || path[2] == '\\');
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
// Environment variable as UTF-8 into out; its length, or 0 when unset, empty or too long for cap.
|
||||
size_t plat_getenv(const char *name, char *out, size_t cap);
|
||||
// The user's UI language as a BCP-47 tag ("ru-RU", "en-US"); "" when the system gives none. Valid for the process.
|
||||
|
||||
@@ -0,0 +1,703 @@
|
||||
// Mod plugins' inits (recomp/layout.py plugin<N>, an exlaunch plugin such as a mod's exefs/subsdk9), run natively on
|
||||
// this runtime's own kernel and sdk. The design follows #845 by itaskaev2, with the init run natively instead of under
|
||||
// Unicorn, and run again at every start instead of an image taken after one run at build time.
|
||||
//
|
||||
// The service run: totk.exe --plugin-init DIR runs the plugins' DT_INITs, records what the inits did and exits before
|
||||
// any game module's constructor, nnMain, graphics or audio. TOTK_PLUGIN_ONLY names the one plugin module whose init
|
||||
// runs ("-": none); the others stay loaded, as they are at play. tools/exefs_plugins.py runs each plugin on its own,
|
||||
// so a plugin that is refused, crashes or hangs costs only itself; it checks each record and writes the plugin's patch
|
||||
// set (its hook sites, recomp/patches.py `plugin` lines).
|
||||
//
|
||||
// At every start (plugins_start, from the module-init callback in boot.c): when the build has a plugin whose patch set
|
||||
// its mod switched on, sdk's DT_INIT runs first, then the plugin's, in the same environment as in the service run, and
|
||||
// then the game's constructors. That is the order of the Switch's rtld, which runs the modules' DT_INITs from the last
|
||||
// loaded to the first (oss-rtld, librtld/source/ld.cpp __rtld_modules_init walks g_pAutoLoadList backwards; the list is
|
||||
// filled in address order by __rtld_relocate_modules in librtld/source/relocation.cpp: main, subsdk*, sdk), so sdk
|
||||
// runs before a subsdk plugin and the plugin before the game's main. The plugin keeps what its init made: heap blocks,
|
||||
// its GOT, its alias addresses. What the init wrote into the game modules (its hook branches) and the plugin's .text
|
||||
// after it (its stubs and trampolines) are compared with the record the build used (patches.h RT_PLUGIN_WRITES and
|
||||
// RT_PLUGINS): equal, the plugin's set stays on and the generated hook sites call into it; different, the set goes off
|
||||
// for this run, the reason is logged and the mod waits for a rebuild (mods.c mods_plugin_off). Each plugin is compared
|
||||
// right after its own init, and the branches it wrote into main's .text are taken back before the next init: the next
|
||||
// plugin sees the game's own bytes, as in its own service run (two plugins hooking one site each relocate the game's
|
||||
// instruction; the generated site runs the one the Mods tab order picks). The lifted code is the code that runs, and
|
||||
// main keeps the game's bytes.
|
||||
// Without a plugin in the build none of this runs (RT_PLUGIN_COUNT 0).
|
||||
//
|
||||
// What exlaunch's init needs from the process, and how this run gives it:
|
||||
// - Its module walk (exl::util::FindModules) reads QueryMemory from 0 up and takes every Code RX, Code R, CodeData
|
||||
// RW run as a module, the first being rtld and the second main. Our layout has no rtld and reports the host's
|
||||
// ranges as Code RX (memory.c taken_gap), which would make it take a gap for a module. mem_query_hook shows the
|
||||
// game's own rtld NSO (exefs/rtld, read, never run) right below main, and the host's ranges as Inaccessible.
|
||||
// - It picks a random free range in the ASLR region (GetSystemTick seeds it) for its process-memory aliases. Our
|
||||
// ASLR region is almost all host ranges, so a free pool of POOL_SIZE is reserved after the alias region.
|
||||
// - GetInfo 65001 (svc.c) gives it the current process handle; MapProcessMemory maps main's .text and its own pages
|
||||
// at the picked address. Guest addresses are host addresses and the modules are not file-backed, so an alias is a
|
||||
// copy: its pages hold the source's bytes when mapped, and the words written through it are written into the
|
||||
// source when it is unmapped and when the init returns. That is how the stubs reach the plugin's image and the
|
||||
// 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.
|
||||
//
|
||||
// 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,
|
||||
// all segments) and plugin<N>.pre.img (the same after loading and relocation, before the init).
|
||||
// TOTK_PLUGIN_TICK_OFFSET adds to every GetSystemTick, so two runs pick different aliases.
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "cfg.h"
|
||||
#include "dispatch.h"
|
||||
#include "host.h"
|
||||
#include "kernel.h"
|
||||
#include "mods.h"
|
||||
#include "platform/platform.h"
|
||||
|
||||
#if __has_include("patches.h")
|
||||
#include "patches.h"
|
||||
#endif
|
||||
#ifndef RT_PLUGIN_COUNT
|
||||
#define RT_PLUGIN_COUNT 0
|
||||
#endif
|
||||
|
||||
#define PAGE 0x1000ull
|
||||
#define GiB (1ull << 30)
|
||||
#define POOL_SIZE (64 * GiB)
|
||||
#define POOL_ALIGN (4 * GiB)
|
||||
#define RTLD_ALIGN 0x200000ull
|
||||
#define MAX_ALIASES 256
|
||||
#define MAX_IMPORTS 64
|
||||
#define CUR_PROCESS 0xFFFF8001u
|
||||
// Horizon memory states and permissions of QueryMemory, and results.
|
||||
enum { ST_FREE = 0, ST_CODE = 3, ST_CODEDATA = 4, ST_SHARED_CODE = 0xF, ST_INACCESSIBLE = 0x10 };
|
||||
enum { PERM_R = 1, PERM_RW = 3, PERM_RX = 5 };
|
||||
#define R_OK 0u
|
||||
#define R_INVALID_ADDRESS 0xcc01u
|
||||
#define R_INVALID_STATE 0xd401u
|
||||
#define R_INVALID_HANDLE 0xe401u
|
||||
#define R_LIMIT_REACHED 0x10801u
|
||||
#define SYM_DISPLAY_VERSION "_ZN2nn2oe17GetDisplayVersionEPNS0_14DisplayVersionE"
|
||||
|
||||
typedef struct {
|
||||
uint64_t dst, src, size;
|
||||
uint8_t *snap; // the source's bytes when mapped: the words that differ from it were written through the alias
|
||||
int live, unmapped;
|
||||
} Alias;
|
||||
static Alias aliases[MAX_ALIASES];
|
||||
static int naliases;
|
||||
static uint64_t rtld_base, rtld_size, rtld_text_end, rtld_data_off;
|
||||
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 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
|
||||
static uint8_t *ran; // service run, per loaded module: its init ran
|
||||
|
||||
static uint64_t align_up(uint64_t v, uint64_t a) { return (v + a - 1) & ~(a - 1); }
|
||||
|
||||
static void clip(uint64_t a, uint64_t *lo, uint64_t *hi, uint64_t b, uint64_t n) {
|
||||
if (!n) return;
|
||||
uint64_t e = b + n;
|
||||
if (e <= a && e > *lo) *lo = e;
|
||||
if (b > a && b < *hi) *hi = b;
|
||||
}
|
||||
|
||||
static void clip_aliases(uint64_t a, uint64_t *lo, uint64_t *hi) {
|
||||
for (int i = 0; i < naliases; i++)
|
||||
if (aliases[i].live) clip(a, lo, hi, aliases[i].dst, aliases[i].size);
|
||||
}
|
||||
|
||||
static int in_module(uint64_t a) {
|
||||
for (int i = 0; i < ldr_count(); i++)
|
||||
if (a - ldr_module(i)->base < ldr_module(i)->size) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- QueryMemory as exlaunch expects it (memory.c mem_query_hook)
|
||||
static void query_hook(uint64_t a, RtMemoryInfo *r) {
|
||||
for (int i = 0; i < naliases; i++) {
|
||||
const Alias *al = &aliases[i];
|
||||
if (al->live && a - al->dst < al->size) {
|
||||
*r = (RtMemoryInfo){.base = al->dst, .size = al->size, .state = ST_SHARED_CODE, .perm = PERM_RW};
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (a - rtld_base < rtld_size) {
|
||||
uint64_t off = a - rtld_base, text = align_up(rtld_text_end, PAGE);
|
||||
if (off < text) *r = (RtMemoryInfo){.base = rtld_base, .size = text, .state = ST_CODE, .perm = PERM_RX};
|
||||
else if (off < rtld_data_off)
|
||||
*r = (RtMemoryInfo){.base = rtld_base + text, .size = rtld_data_off - text, .state = ST_CODE, .perm = PERM_R};
|
||||
else
|
||||
*r = (RtMemoryInfo){.base = rtld_base + rtld_data_off, .size = rtld_size - rtld_data_off,
|
||||
.state = ST_CODEDATA, .perm = PERM_RW};
|
||||
return;
|
||||
}
|
||||
uint64_t lo = r->base, hi = r->base + r->size;
|
||||
if (a - pool_base < POOL_SIZE) {
|
||||
lo = pool_base, hi = pool_base + POOL_SIZE;
|
||||
*r = (RtMemoryInfo){.state = ST_FREE};
|
||||
} else if (r->state == ST_CODE && !in_module(a)) { // a host range (memory.c taken_gap)
|
||||
clip(a, &lo, &hi, rtld_base, rtld_size);
|
||||
clip(a, &lo, &hi, pool_base, POOL_SIZE);
|
||||
*r = (RtMemoryInfo){.state = ST_INACCESSIBLE};
|
||||
} else if (r->state != ST_FREE) {
|
||||
return;
|
||||
}
|
||||
clip_aliases(a, &lo, &hi);
|
||||
r->base = lo;
|
||||
r->size = hi - lo;
|
||||
}
|
||||
|
||||
// ---- Map/UnmapProcessMemory (svc.c rt_process_memory)
|
||||
static const RtLoaded *module_holding(uint64_t a, uint64_t n) {
|
||||
for (int i = 0; i < ldr_count(); i++) {
|
||||
const RtLoaded *m = ldr_module(i);
|
||||
if (a >= m->base && n <= m->size && a - m->base <= m->size - n) return m;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Writes the words changed through an alias into its source. The source's read-only pages (sealed .text and .rodata)
|
||||
// are made writable for the copy and sealed again.
|
||||
static void flush(Alias *al) {
|
||||
const RtLoaded *m = module_holding(al->src, al->size);
|
||||
const uint8_t *now = (const uint8_t *)(uintptr_t)al->dst;
|
||||
for (uint64_t off = 0; off < al->size; off += PAGE) {
|
||||
if (!memcmp(now + off, al->snap + off, PAGE)) continue;
|
||||
uint64_t page = al->src + off;
|
||||
int sealed = page - m->base < m->data_off;
|
||||
if (sealed && !plat_mem_protect(page, PAGE, PLAT_PROT_RW)) rt_fatal("plugin-init: cannot unseal %#llx", (unsigned long long)page);
|
||||
for (uint64_t w = 0; w < PAGE; w += 4)
|
||||
if (memcmp(now + off + w, al->snap + off + w, 4)) memcpy((void *)(uintptr_t)(page + w), now + off + w, 4);
|
||||
if (sealed && !plat_mem_protect(page, PAGE, PLAT_PROT_READ)) rt_fatal("plugin-init: cannot seal %#llx", (unsigned long long)page);
|
||||
}
|
||||
memcpy(al->snap, now, al->size); // flushed: a later flush writes only what changes after this one
|
||||
}
|
||||
|
||||
static uint32_t process_memory(int unmap, uint64_t dst, uint32_t process, uint64_t src, uint64_t size) {
|
||||
if (process != CUR_PROCESS) return R_INVALID_HANDLE;
|
||||
if (!size || ((dst | src | size) & (PAGE - 1))) return R_INVALID_ADDRESS;
|
||||
if (unmap) {
|
||||
for (int i = 0; i < naliases; i++) {
|
||||
Alias *al = &aliases[i];
|
||||
if (!al->live || al->dst != dst || al->src != src || al->size != size) continue;
|
||||
flush(al);
|
||||
if (!plat_mem_decommit(dst, size)) rt_fatal("plugin-init: cannot unmap the alias at %#llx", (unsigned long long)dst);
|
||||
free(al->snap);
|
||||
al->snap = NULL;
|
||||
al->live = 0;
|
||||
al->unmapped = 1;
|
||||
return R_OK;
|
||||
}
|
||||
return R_INVALID_STATE;
|
||||
}
|
||||
if (!module_holding(src, size)) return R_INVALID_STATE; // only the modules' own memory
|
||||
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 (!plat_mem_commit(dst, size)) return R_INVALID_STATE; // not inside one of our reservations
|
||||
Alias *al = &aliases[naliases];
|
||||
al->snap = malloc(size);
|
||||
if (!al->snap) rt_fatal("plugin-init: out of memory for a %#llx byte alias", (unsigned long long)size);
|
||||
memcpy((void *)(uintptr_t)dst, (const void *)(uintptr_t)src, size);
|
||||
memcpy(al->snap, (const void *)(uintptr_t)src, size);
|
||||
*al = (Alias){dst, src, size, al->snap, 1, 0};
|
||||
naliases++;
|
||||
return R_OK;
|
||||
}
|
||||
|
||||
// ---- svcs and imports
|
||||
static void write_record(const char *refused);
|
||||
|
||||
static void refuse(const char *why) {
|
||||
rt_log("plugin-init: refused: %s", why);
|
||||
if (play) { // the init goes on with an error result; the plugin stays off (plugins_start)
|
||||
if (!failed[0]) snprintf(failed, sizeof failed, "%s", why);
|
||||
return;
|
||||
}
|
||||
write_record(why);
|
||||
fflush(NULL);
|
||||
plat_exit(3);
|
||||
}
|
||||
|
||||
#define R_NOT_IMPLEMENTED 0xF601u
|
||||
|
||||
static int plugin_svc(Cpu *c, uint32_t imm, uint64_t pc) {
|
||||
if (!running) return 0;
|
||||
svc_count[imm & 0x7F]++;
|
||||
char why[256], at[128];
|
||||
switch (imm) {
|
||||
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)) {
|
||||
info_count[id]++;
|
||||
return 0;
|
||||
}
|
||||
if (id == 65001) {
|
||||
info_65001++;
|
||||
return 0;
|
||||
}
|
||||
snprintf(why, sizeof why, "GetInfo id %u at %s", id, ldr_describe(pc, at, sizeof at));
|
||||
refuse(why);
|
||||
c->x[0] = R_NOT_IMPLEMENTED;
|
||||
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));
|
||||
refuse(why);
|
||||
c->x[0] = R_NOT_IMPLEMENTED;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Every JUMP_SLOT import of a plugin binds here (loader.c resolve): counted by name, then the guest definition runs,
|
||||
// except nn::oe::GetDisplayVersion, which gets this build's game version.
|
||||
static void plugin_import(Cpu *c) {
|
||||
const char *name = hostfn_name(c->pc);
|
||||
int i = 0;
|
||||
while (i < nimports && strcmp(imports[i].name, name)) i++;
|
||||
if (i == nimports && nimports < MAX_IMPORTS) imports[nimports++].name = name;
|
||||
if (i < MAX_IMPORTS && running) imports[i].calls++;
|
||||
if (!strcmp(name, SYM_DISPLAY_VERSION)) { // DisplayVersion { char value[16]; }
|
||||
char v[16] = {0};
|
||||
snprintf(v, sizeof v, "%d.%d.%d", rt_game_version / 100, rt_game_version / 10 % 10, rt_game_version % 10);
|
||||
memcpy((void *)(uintptr_t)c->x[0], v, sizeof v);
|
||||
return;
|
||||
}
|
||||
rt_original(c);
|
||||
}
|
||||
|
||||
// ---- the record
|
||||
static FILE *open_out(const char *file, const char *mode) {
|
||||
char path[PLAT_PATH_MAX];
|
||||
snprintf(path, sizeof path, "%s/%s", rt_config()->plugin_init, file);
|
||||
FILE *f = fopen(path, mode);
|
||||
if (!f) rt_fatal("plugin-init: cannot write %s", path);
|
||||
return f;
|
||||
}
|
||||
|
||||
static void write_image(const char *file, const void *p, uint64_t n) {
|
||||
FILE *f = open_out(file, "wb");
|
||||
if (fwrite(p, 1, n, f) != n || fclose(f)) rt_fatal("plugin-init: cannot write %s", file);
|
||||
}
|
||||
|
||||
static void sha256_hex(const void *p, uint64_t n, char out[65]) {
|
||||
uint8_t d[32];
|
||||
rt_sha256(p, n, d);
|
||||
for (int i = 0; i < 32; i++) snprintf(out + 2 * i, 3, "%02x", d[i]);
|
||||
}
|
||||
|
||||
static void json_str(FILE *f, const char *s) {
|
||||
fputc('"', f);
|
||||
for (; *s; s++) {
|
||||
if (*s == '"' || *s == '\\') fputc('\\', f);
|
||||
if ((unsigned char)*s < 0x20) fprintf(f, "\\u%04x", *s);
|
||||
else fputc(*s, f);
|
||||
}
|
||||
fputc('"', f);
|
||||
}
|
||||
|
||||
// The words of each game module that differ from its image before the plugins' inits: (module, offset, old, new).
|
||||
static void write_writes(FILE *f) {
|
||||
int first = 1;
|
||||
for (int i = 0; i < ldr_count(); i++) {
|
||||
const RtLoaded *m = ldr_module(i);
|
||||
if (m->plugin || !pre || !pre[i]) continue;
|
||||
const uint8_t *now = (const uint8_t *)(uintptr_t)m->base;
|
||||
for (uint64_t off = 0; off < m->size; off += PAGE) {
|
||||
if (!memcmp(now + off, pre[i] + off, PAGE)) continue;
|
||||
for (uint64_t w = off; w < off + PAGE; w += 4) {
|
||||
uint32_t a, b;
|
||||
memcpy(&a, pre[i] + w, 4);
|
||||
memcpy(&b, now + w, 4);
|
||||
if (a == b) continue;
|
||||
// fn_start: a lifted function starts at the word (a b there replaces the function)
|
||||
fprintf(f, "%s\n {\"module\": \"%s\", \"offset\": \"%#llx\", \"old\": \"%#010x\", \"new\": \"%#010x\", "
|
||||
"\"fn_start\": %s}", first ? "" : ",", m->name, (unsigned long long)w, a, b,
|
||||
rt_dispatch_lookup(m->base + w) ? "true" : "false");
|
||||
first = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void write_record(const char *refused) {
|
||||
for (int i = 0; i < naliases; i++)
|
||||
if (aliases[i].live) flush(&aliases[i]);
|
||||
FILE *f = open_out("record.json", "w");
|
||||
// The marker of generated game-derived files (tools/check_content.py): the record never goes into the repository.
|
||||
fprintf(f, "{\n\"marker\": \"%s%s\",\n\"game_version\": %d,\n\"tick_offset\": \"%#llx\",\n\"refused\": ",
|
||||
"TOTK_RECOMP_", "GENERATED_FROM_GAME_CODE", rt_game_version, (unsigned long long)rt_svc_tick_offset);
|
||||
if (refused) json_str(f, refused);
|
||||
else fputs("null", f);
|
||||
fprintf(f, ",\n\"rtld\": {\"base\": \"%#llx\", \"size\": \"%#llx\"},\n\"pool\": {\"base\": \"%#llx\", \"size\": \"%#llx\"},",
|
||||
(unsigned long long)rtld_base, (unsigned long long)rtld_size, (unsigned long long)pool_base,
|
||||
(unsigned long long)POOL_SIZE);
|
||||
fputs("\n\"modules\": [", f);
|
||||
for (int i = 0; i < ldr_count(); i++) {
|
||||
const RtLoaded *m = ldr_module(i);
|
||||
fprintf(f, "%s\n {\"name\": \"%s\", \"base\": \"%#llx\", \"size\": \"%#llx\", \"text_end\": \"%#llx\", "
|
||||
"\"data_off\": \"%#llx\", \"init\": \"%#llx\", \"plugin\": %s",
|
||||
i ? "," : "", m->name, (unsigned long long)m->base, (unsigned long long)m->size,
|
||||
(unsigned long long)m->text_end, (unsigned long long)m->data_off, (unsigned long long)m->init,
|
||||
m->plugin ? "true" : "false");
|
||||
if (m->plugin) fprintf(f, ", \"ran\": %s", ran && ran[i] ? "true" : "false");
|
||||
if (m->plugin && !refused) {
|
||||
char img[64], pre_img[64], hex[65];
|
||||
snprintf(img, sizeof img, "%s.img", m->name);
|
||||
snprintf(pre_img, sizeof pre_img, "%s.pre.img", m->name);
|
||||
write_image(img, (const void *)(uintptr_t)m->base, m->size);
|
||||
if (pre && pre[i]) write_image(pre_img, pre[i], m->size);
|
||||
sha256_hex((const void *)(uintptr_t)m->base, m->size, hex);
|
||||
fprintf(f, ", \"image\": \"%s\", \"image_sha256\": \"%s\", \"pre_image\": \"%s\"", img, hex, pre_img);
|
||||
}
|
||||
if (m->plugin) { // the lifted function starts: a main write may branch straight to one (tools/exefs_plugins.py)
|
||||
RtModule lm[16];
|
||||
int n = rt_linked_modules(lm, 16);
|
||||
for (int k = 0; k < n; k++) {
|
||||
if (strcmp(lm[k].name, m->name)) continue;
|
||||
fputs(", \"functions\": [", f);
|
||||
for (uint64_t j = 0; j < lm[k].count; j++)
|
||||
fprintf(f, "%s\"%#llx\"", j ? ", " : "", (unsigned long long)(lm[k].addrs[j] - m->base));
|
||||
fputc(']', f);
|
||||
}
|
||||
}
|
||||
for (int k = 0; k < rt_layout_count; k++)
|
||||
if (rt_layout[k].file && !strcmp(rt_layout[k].name, m->name)) {
|
||||
fputs(", \"file\": ", f);
|
||||
json_str(f, rt_layout[k].file);
|
||||
fprintf(f, ", \"nso_sha256\": \"%s\"", rt_layout[k].sha256);
|
||||
}
|
||||
fputc('}', f);
|
||||
}
|
||||
fputs("\n],\n\"writes\": [", f);
|
||||
write_writes(f);
|
||||
fputs("\n],\n\"aliases\": [", f);
|
||||
for (int i = 0; i < naliases; i++)
|
||||
fprintf(f, "%s\n {\"dst\": \"%#llx\", \"src\": \"%#llx\", \"size\": \"%#llx\", \"unmapped\": %s}", i ? "," : "",
|
||||
(unsigned long long)aliases[i].dst, (unsigned long long)aliases[i].src,
|
||||
(unsigned long long)aliases[i].size, aliases[i].unmapped ? "true" : "false");
|
||||
fputs("\n],\n\"svcs\": {", f);
|
||||
int first = 1;
|
||||
for (int i = 0; i < 0x80; i++)
|
||||
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++)
|
||||
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);
|
||||
for (int i = 0; i < nimports; i++) {
|
||||
fputs(i ? ", " : "", f);
|
||||
json_str(f, imports[i].name);
|
||||
fprintf(f, ": %llu", (unsigned long long)imports[i].calls);
|
||||
}
|
||||
fputs("}\n}\n", f);
|
||||
if (fclose(f)) rt_fatal("plugin-init: cannot write record.json");
|
||||
}
|
||||
|
||||
// ---- setup and run
|
||||
static int layout_plugins(void) {
|
||||
int plugins = 0;
|
||||
for (int i = 0; i < rt_layout_count; i++) plugins += rt_layout[i].file != NULL;
|
||||
return plugins;
|
||||
}
|
||||
|
||||
static void environment(void);
|
||||
|
||||
// Before ldr_load: the import observer, the svc hooks, the pool and the stand-in for rtld.
|
||||
void plugin_init_setup(void) {
|
||||
if (!layout_plugins()) rt_fatal("plugin-init: this build's layout has no plugin module (recomp/gen.py --plugins)");
|
||||
plat_file_mkdir_p(rt_config()->plugin_init);
|
||||
const char *off = cfg_get("TOTK_PLUGIN_TICK_OFFSET");
|
||||
rt_svc_tick_offset = off ? strtoull(off, NULL, 0) : 0;
|
||||
environment();
|
||||
}
|
||||
|
||||
// The environment of a plugin's init, the same in the service run and at every start.
|
||||
static void environment(void) {
|
||||
ldr_plugin_import = plugin_import;
|
||||
rt_process_memory = process_memory;
|
||||
rt_plugin_svc = plugin_svc;
|
||||
|
||||
const RtGuestLayout *g = mem_layout();
|
||||
uint64_t main_base = rt_layout[0].base;
|
||||
rtld_size = ldr_nso_size(rt_config()->exefs, "rtld");
|
||||
rtld_base = main_base - align_up(rtld_size, RTLD_ALIGN);
|
||||
for (uint64_t at = align_up(g->alias.base + g->alias.size, POOL_ALIGN); at + POOL_SIZE <= rtld_base && !pool_base;
|
||||
at += POOL_ALIGN)
|
||||
if (plat_mem_reserve(at, POOL_SIZE, 0)) pool_base = at;
|
||||
if (!pool_base) rt_fatal("plugin-init: no free %llu GiB below main for the alias pool", POOL_SIZE / GiB);
|
||||
if (!plat_mem_reserve(rtld_base, align_up(rtld_size, PAGE), 0))
|
||||
rt_fatal("plugin-init: %#llx below main is taken; rtld goes there", (unsigned long long)rtld_base);
|
||||
ldr_map_image(rt_config()->exefs, "rtld", rtld_base, &rtld_text_end, &rtld_data_off);
|
||||
mem_query_hook = query_hook;
|
||||
rt_log("plugin-init: rtld at %#llx+%#llx, alias pool %#llx+%llu GiB, tick offset %#llx", (unsigned long long)rtld_base,
|
||||
(unsigned long long)rtld_size, (unsigned long long)pool_base, POOL_SIZE / GiB,
|
||||
(unsigned long long)rt_svc_tick_offset);
|
||||
}
|
||||
|
||||
// rt_boot, before ldr_load: the plugins' environment when the build has one (nothing otherwise).
|
||||
void plugins_setup(void) {
|
||||
if (!RT_PLUGIN_COUNT || !layout_plugins()) return;
|
||||
play = 1;
|
||||
environment();
|
||||
}
|
||||
|
||||
// From nn::init::Start's module-init callback (boot.c), in place of the game's constructors. rtld initialises the
|
||||
// modules from the last loaded to the first, so on the Switch sdk's DT_INIT runs before a subsdk plugin's; then each
|
||||
// plugin's, the last first. Exits with the record written.
|
||||
void plugin_init_run(Cpu *c, const RtLoaded *sdk) {
|
||||
rt_log("plugin-init: ENTER %s DT_INIT", sdk->name);
|
||||
rt_call(c, sdk->init, 0);
|
||||
pre = calloc((size_t)ldr_count(), sizeof *pre);
|
||||
if (!pre) rt_fatal("plugin-init: out of memory");
|
||||
for (int i = 0; i < ldr_count(); i++) { // the images before the plugins run
|
||||
const RtLoaded *m = ldr_module(i);
|
||||
pre[i] = malloc(m->size);
|
||||
if (!pre[i]) rt_fatal("plugin-init: out of memory for a copy of %s", m->name);
|
||||
memcpy(pre[i], (const void *)(uintptr_t)m->base, m->size);
|
||||
}
|
||||
const char *only = cfg_get("TOTK_PLUGIN_ONLY");
|
||||
ran = calloc((size_t)ldr_count(), 1);
|
||||
if (!ran) rt_fatal("plugin-init: out of memory");
|
||||
for (int i = ldr_count() - 1; i >= 0; i--) {
|
||||
const RtLoaded *m = ldr_module(i);
|
||||
if (!m->plugin) continue;
|
||||
if (only && *only && strcmp(only, m->name)) {
|
||||
rt_log("plugin-init: %s stays loaded, its init does not run (TOTK_PLUGIN_ONLY=%s)", m->name, only);
|
||||
continue;
|
||||
}
|
||||
ran[i] = 1;
|
||||
if (!m->init) refuse("a plugin without DT_INIT");
|
||||
rt_log("plugin-init: ENTER %s DT_INIT at %#llx (%llu init_array entries)", m->name, (unsigned long long)m->init,
|
||||
(unsigned long long)(m->init_array_size / 8));
|
||||
running = 1;
|
||||
rt_trace |= RT_TRACE_PLUGIN;
|
||||
rt_call(c, m->init, 0);
|
||||
rt_trace &= ~(unsigned)RT_TRACE_PLUGIN;
|
||||
running = 0;
|
||||
rt_log("plugin-init: %s DT_INIT returned", m->name);
|
||||
}
|
||||
write_record(NULL);
|
||||
int live = 0;
|
||||
for (int i = 0; i < naliases; i++) live += aliases[i].live;
|
||||
rt_log("plugin-init: record written to %s (%d process-memory maps, %d still mapped)", rt_config()->plugin_init,
|
||||
naliases, live);
|
||||
fflush(NULL);
|
||||
plat_exit(0);
|
||||
}
|
||||
|
||||
// ---- at every start
|
||||
#if RT_PLUGIN_COUNT
|
||||
static const struct { const char *module; int set; const char *sha256; } plugin_tab[] = {
|
||||
#define X(i, mod, set, sha) {mod, set, sha},
|
||||
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
|
||||
};
|
||||
#define NWRITES ((int)(sizeof write_tab / sizeof *write_tab))
|
||||
#ifdef RT_PLUGIN_ROOTS
|
||||
static const struct { const char *module; uint64_t off; } root_tab[] = {
|
||||
#define X(mod, off) {mod, off},
|
||||
RT_PLUGIN_ROOTS(X)
|
||||
#undef X
|
||||
};
|
||||
#define NROOTS ((int)(sizeof root_tab / sizeof *root_tab))
|
||||
#else
|
||||
#define NROOTS 0
|
||||
#endif
|
||||
|
||||
static const RtLoaded *loaded(const char *name) {
|
||||
for (int i = 0; i < ldr_count(); i++)
|
||||
if (!strcmp(ldr_module(i)->name, name)) return ldr_module(i);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// TOTK_PLUGIN_TRACE = 1: the first call of each hook entry (patches.h RT_PLUGIN_ROOTS: callbacks, replace and call
|
||||
// targets) is logged with its count so far; the entries run through count_entry, their dispatch slots rerouted once
|
||||
// at start (dispatch.c rt_dispatch_reroute). The calls inside the plugin are direct and not counted.
|
||||
static struct { uint64_t addr; GuestFn fn; uint64_t calls; } traced[64];
|
||||
static int ntraced;
|
||||
|
||||
static void count_entry(Cpu *c) {
|
||||
for (int i = 0; i < ntraced; i++) {
|
||||
if (traced[i].addr != c->pc) continue;
|
||||
if (__atomic_add_fetch(&traced[i].calls, 1, __ATOMIC_RELAXED) == 1) {
|
||||
char at[128];
|
||||
rt_log("plugins: hook entry %s reached (first call)", ldr_describe(c->pc, at, sizeof at));
|
||||
}
|
||||
__attribute__((musttail)) return traced[i].fn(c);
|
||||
}
|
||||
rt_fatal("plugins: traced entry %#llx without its function", (unsigned long long)c->pc);
|
||||
}
|
||||
|
||||
static void trace_entries(void) {
|
||||
#ifdef RT_PLUGIN_ROOTS
|
||||
for (int i = 0; i < NROOTS && ntraced < 64; i++) {
|
||||
const RtLoaded *m = loaded(root_tab[i].module);
|
||||
if (!m) continue;
|
||||
uint64_t a = m->base + root_tab[i].off;
|
||||
GuestFn f = rt_dispatch_lookup(a);
|
||||
if (!f) continue;
|
||||
traced[ntraced] = (typeof(traced[0])){a, f, 0};
|
||||
if (rt_dispatch_reroute(a, count_entry)) ntraced++;
|
||||
else rt_log("plugins: trace: cannot reroute %#llx", (unsigned long long)a);
|
||||
}
|
||||
#endif
|
||||
rt_log("plugins: trace: %d hook entries counted", ntraced);
|
||||
}
|
||||
|
||||
// Takes back a page an init changed in the sealed part (.text, .rodata) of a game module: main keeps the game's own
|
||||
// bytes, the lifted code being what runs.
|
||||
static void restore_page(const RtLoaded *m, uint64_t off, const uint8_t *was) {
|
||||
if (!plat_mem_protect(m->base + off, PAGE, PLAT_PROT_RW)) rt_fatal("plugins: cannot unseal %s+%#llx", m->name,
|
||||
(unsigned long long)off);
|
||||
memcpy((void *)(uintptr_t)(m->base + off), was, PAGE);
|
||||
plat_mem_protect(m->base + off, PAGE, PLAT_PROT_READ);
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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.
|
||||
static void check_writes(int plugin, int first_alias, char *why, size_t cap) {
|
||||
for (int i = first_alias; i < naliases; i++)
|
||||
if (aliases[i].live) flush(&aliases[i]);
|
||||
uint8_t seen[NWRITES > 0 ? NWRITES : 1];
|
||||
memset(seen, 0, sizeof seen);
|
||||
int unexpected = 0, missing = 0;
|
||||
char first[160] = "";
|
||||
for (int i = 0; i < ldr_count(); i++) {
|
||||
const RtLoaded *m = ldr_module(i);
|
||||
if (!pre[i]) continue;
|
||||
uint8_t *now = (uint8_t *)(uintptr_t)m->base;
|
||||
for (uint64_t off = 0; off < m->size; off += PAGE) {
|
||||
if (!memcmp(now + off, pre[i] + off, PAGE)) continue;
|
||||
for (uint64_t w = off; w < off + PAGE; w += 4) {
|
||||
uint32_t a, b;
|
||||
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) {
|
||||
seen[k] = 1;
|
||||
} else if (!unexpected++) {
|
||||
snprintf(first, sizeof first, "%s+%#llx %08x -> %08x", m->name, (unsigned long long)w, a, b);
|
||||
}
|
||||
}
|
||||
if (off < m->data_off) restore_page(m, off, pre[i] + off);
|
||||
else memcpy(pre[i] + off, now + off, PAGE);
|
||||
}
|
||||
}
|
||||
for (int k = 0; k < NWRITES; k++) missing += write_tab[k].plugin == plugin && !seen[k];
|
||||
if (why[0]) return;
|
||||
if (unexpected)
|
||||
snprintf(why, cap, "its init wrote %d words the build did not record (first %s)", unexpected, first);
|
||||
else if (missing)
|
||||
snprintf(why, cap, "%d of the words the build recorded were not written", missing);
|
||||
}
|
||||
#endif
|
||||
|
||||
int plugins_start(Cpu *c, const RtLoaded *sdk) {
|
||||
#if RT_PLUGIN_COUNT
|
||||
if (!play) return 0;
|
||||
int run[RT_PLUGIN_COUNT] = {0}, nrun = 0;
|
||||
char why[RT_PLUGIN_COUNT][256];
|
||||
for (int i = 0; i < RT_PLUGIN_COUNT; i++) {
|
||||
why[i][0] = 0;
|
||||
const RtLoaded *m = loaded(plugin_tab[i].module);
|
||||
if (!rt_patch_enabled(plugin_tab[i].set)) continue;
|
||||
if (!m) { // loader.c left it out (its file is gone or changed): its set cannot run
|
||||
mods_plugin_off(plugin_tab[i].set, "its file is not the one the build lifted");
|
||||
continue;
|
||||
}
|
||||
if (!m->init) {
|
||||
mods_plugin_off(plugin_tab[i].set, "it has no DT_INIT");
|
||||
continue;
|
||||
}
|
||||
run[i] = 1, nrun++;
|
||||
}
|
||||
if (!nrun) { // every plugin's mod off or gone: the game sees its address space as without plugins
|
||||
mem_query_hook = NULL;
|
||||
rt_process_memory = NULL;
|
||||
return 0;
|
||||
}
|
||||
uint64_t t0 = plat_now_ms();
|
||||
rt_log("boot: ENTER %s DT_INIT first: a mod plugin's init runs before the game's constructors", sdk->name);
|
||||
rt_call(c, sdk->init, 0);
|
||||
pre = calloc((size_t)ldr_count(), sizeof *pre);
|
||||
if (!pre) rt_fatal("plugins: out of memory");
|
||||
for (int i = 0; i < ldr_count(); i++) { // the game modules before the plugins run
|
||||
const RtLoaded *m = ldr_module(i);
|
||||
if (m->plugin) continue;
|
||||
pre[i] = malloc(m->size);
|
||||
if (!pre[i]) rt_fatal("plugins: out of memory for a copy of %s", m->name);
|
||||
memcpy(pre[i], (const void *)(uintptr_t)m->base, m->size);
|
||||
}
|
||||
for (int i = RT_PLUGIN_COUNT - 1; i >= 0; i--) {
|
||||
if (!run[i]) continue;
|
||||
const RtLoaded *m = loaded(plugin_tab[i].module);
|
||||
rt_log("plugins: ENTER %s DT_INIT at %#llx", m->name, (unsigned long long)m->init);
|
||||
failed[0] = 0;
|
||||
int first_alias = naliases;
|
||||
running = 1;
|
||||
rt_trace |= RT_TRACE_PLUGIN;
|
||||
rt_call(c, m->init, 0);
|
||||
rt_trace &= ~(unsigned)RT_TRACE_PLUGIN;
|
||||
running = 0;
|
||||
if (failed[0]) snprintf(why[i], sizeof why[i], "its init asked for what the port does not serve: %s", failed);
|
||||
check_writes(i, first_alias, why[i], sizeof why[i]);
|
||||
char hex[65];
|
||||
sha256_hex((const void *)(uintptr_t)m->base, m->text_end, hex);
|
||||
if (!why[i][0] && strcmp(hex, plugin_tab[i].sha256))
|
||||
snprintf(why[i], sizeof why[i], "its code after the init is not the one the build lifted");
|
||||
}
|
||||
for (int i = 0; i < ldr_count(); i++) free(pre[i]);
|
||||
free(pre);
|
||||
pre = NULL;
|
||||
mem_query_hook = NULL; // the game's own QueryMemory sees its address space as without plugins
|
||||
rt_process_memory = NULL; // a callback that maps process memory stops with a named fatal (svc.c)
|
||||
int on = 0;
|
||||
for (int i = 0; i < RT_PLUGIN_COUNT; i++) {
|
||||
if (!run[i]) continue;
|
||||
if (why[i][0]) {
|
||||
rt_log("plugins: %s stays off: %s", plugin_tab[i].module, why[i]);
|
||||
mods_plugin_off(plugin_tab[i].set, why[i]);
|
||||
continue;
|
||||
}
|
||||
int hooks = 0;
|
||||
for (int k = 0; k < NWRITES; k++) hooks += write_tab[k].plugin == i;
|
||||
rt_log("plugins: %s: init ran, %d hooks on (set %s)", plugin_tab[i].module, hooks,
|
||||
rt_patch_name(plugin_tab[i].set));
|
||||
on++;
|
||||
}
|
||||
int live = 0;
|
||||
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);
|
||||
if (on && cfg_bool("TOTK_PLUGIN_TRACE")) trace_entries();
|
||||
return 1;
|
||||
#else
|
||||
(void)c, (void)sdk;
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
// Quick save and quick load, 1.4.3 only (TOTK_QUICKSAVE, live, default 0): one key saves the game at once and another
|
||||
// loads that save, F6 and F7 by default as in Half-Life (TOTK_QUICKSAVE_KEY, TOTK_QUICKLOAD_KEY: a key name of
|
||||
// input_map.c, or none; live). Keyboard and mouse keys only: a gamepad has no quick save button. No menu shows: quick
|
||||
// save asks the game directly, quick load runs the game's load menu under a held picture.
|
||||
//
|
||||
// Quick save asks the game for an autosave the way its own event graphs do (the execute of the sequence node
|
||||
// OneShotAutoSaveMgrRequestAutoSave, 1.4.3 main+0x24fed3c): component 10 of the game's root is the AutoSaveMgr,
|
||||
// main+0x513ab8 says whether it would autosave now (a cutscene, an event, a fight or a recent autosave say no) and
|
||||
// main+0x1f8ed24 queues the request with kind 4, as that node does. The game then writes one of its autosave slots and
|
||||
// commits the save; fs_host.c reports the slot folder that commit wrote (fs_save_commits), and quicksave copies it to
|
||||
// <profile>/quicksave/slot, its name to <profile>/quicksave/slot.txt. A toast at the top of the picture says "Game
|
||||
// saved" (ui/menu.cpp menu_toast), or why nothing was saved.
|
||||
//
|
||||
// Quick load: the game starts a load only from its own load list (System tab) or its Game Over screen, and loads the
|
||||
// slot that screen names; nothing in play requests one. So quick load drives the load list as a player with a
|
||||
// controller would, under a held picture: the toast "Loading the quick save" shows, the window keeps that picture
|
||||
// (gfx_present_hold) while Plus, R to the System tab, Load, the list's first save and the confirmation's Load are
|
||||
// pressed, and the picture comes back with the game's loading fade. From the confirmation on, the game's reads of the
|
||||
// files of a slot open the quick save's files instead (fs_save_read_from), so it loads the quick save whichever slot
|
||||
// the list offered first, and no slot of the save is written for it (quicksave_poll); the redirect ends with the load
|
||||
// (reads_watch).
|
||||
//
|
||||
// Both start only in play: the world loaded, the HUD's PlayerStatus_00 open, no screen with the focus box, no dialogue
|
||||
// box and no loading fade. Script lines QUICKSAVE and QUICKLOAD (input.c) start them as the keys do.
|
||||
//
|
||||
// Threads. 1.4.3 has no one thread for the AutoSaveMgr: a trace of the hooked functions (function-entry hooks on a test
|
||||
// build) saw the game itself call AUTOSAVE_REQ from at least four guest threads, as events and sequence nodes run on the
|
||||
// game's job workers, and the manager check its pending request (main+0x50ed8c, +0x50f3e8, with AUTOSAVE_CAN) on two
|
||||
// others; the pad was read on six. So quick save calls AUTOSAVE_CAN and AUTOSAVE_REQ the way those events do: from a
|
||||
// game thread between two of the game's own calls, the pad read (quicksave_guest, from ov_input.c's npad_states).
|
||||
// AUTOSAVE_REQ only sets the manager's request flag, and the manager checks AUTOSAVE_CAN again before it saves. As
|
||||
// several threads read the pad at once, one of them at a time steps quick save and quick load (qs_lock); the others give
|
||||
// the game the same presses.
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
|
||||
#include "cfg.h"
|
||||
#include "fs.h"
|
||||
#include "host.h"
|
||||
#include "input.h"
|
||||
#include "input_map.h"
|
||||
#include "layout.h"
|
||||
#include "gfx.h"
|
||||
#include "platform/platform.h"
|
||||
#include "ui/menu.h"
|
||||
#include "ui_text.h"
|
||||
|
||||
// 1.4.3 main: offsets from MOD_MAIN_BASE
|
||||
#define GAME_ROOT 0x395dc70ull // ** the game's root object (the sequence nodes' first read)
|
||||
#define COMPONENT 0x89f9b0ull // (root, index): the root's component of that index, 0 when none
|
||||
#define AUTOSAVE_INDEX 10 // the AutoSaveMgr's component index
|
||||
#define AUTOSAVE_TYPE 0xc1e348ull // (): AutoSaveMgr's runtime type info, for its vtable's first method (the cast)
|
||||
#define AUTOSAVE_CAN 0x513ab8ull // (mgr, kind, 0): bit 0 when the game would autosave now
|
||||
#define AUTOSAVE_REQ 0x1f8ed24ull // (mgr, kind): queue an autosave
|
||||
#define AUTOSAVE_KIND 4 // the kind OneShotAutoSaveMgrRequestAutoSave asks for
|
||||
#define SAVE_MS 5000 // the most the game takes from the request to the commit of the save (0.5 s seen)
|
||||
#define REQ_FLAGS 0x128ull // mgr+0x128: the request flags; AUTOSAVE_REQ sets bit 0 of their byte 5
|
||||
|
||||
enum { REQ_NONE, REQ_SAVE, REQ_LOAD };
|
||||
static volatile int32_t g_request; // REQ_*, set by the keys or a script, taken by quicksave_guest
|
||||
static int saving; // 1 waiting for the commit of the requested autosave, 2 copying it
|
||||
static uint32_t commits_before;
|
||||
static uint64_t save_started;
|
||||
static uint64_t req_flags; // the request flags' byte AUTOSAVE_REQ set, 0 when the game had set it already
|
||||
|
||||
static int save_key = KEY_F6, load_key = KEY_F7; // KEY_NONE: that key is off
|
||||
static PlatMutex qs_lock = PLAT_MUTEX_INIT; // the pad-reading thread that steps quick save / quick load
|
||||
|
||||
static int key_id(const char *name) {
|
||||
for (int k = KEY_A; k < KEY_COUNT; k++)
|
||||
if (input_key_name(k) && !strcasecmp(name, input_key_name(k))) return k;
|
||||
return KEY_NONE;
|
||||
}
|
||||
|
||||
// A key setting as a KEY_*: a key name of input_map.c (any case) or "none"; anything else is logged and the default
|
||||
// from the settings table is used
|
||||
static int key_setting(const char *var, const char *ini) {
|
||||
const char *v = cfg_value(var), *def = cfg_meta(var)->def;
|
||||
if (!strcasecmp(v, "none")) return KEY_NONE;
|
||||
int k = key_id(v);
|
||||
if (k == KEY_NONE) rt_log("quicksave: %s: unknown key '%s', %s is used", ini, v, def), k = key_id(def);
|
||||
return k;
|
||||
}
|
||||
|
||||
// The keys are read with the switch, so with it off nothing is logged
|
||||
int quicksave_on(void) {
|
||||
static unsigned seen = ~0u;
|
||||
static int on;
|
||||
unsigned v = cfg_version();
|
||||
if (v == seen) return on;
|
||||
int was = on, want = cfg_bool("TOTK_QUICKSAVE");
|
||||
static int told;
|
||||
seen = v, on = RT_V143 && want;
|
||||
// The game's addresses below are 1.4.3's: on 1.1.0 and 1.2.1 the setting is refused once, and no call is made
|
||||
if (want && !RT_V143 && !told) told = 1, rt_log("quicksave: game 1.4.3 only; quick save and quick load stay off");
|
||||
if (!on) return 0;
|
||||
int s = key_setting("TOTK_QUICKSAVE_KEY", "quicksave_key"), l = key_setting("TOTK_QUICKLOAD_KEY", "quickload_key");
|
||||
if (l == s && l != KEY_NONE) {
|
||||
rt_log("quicksave: quickload_key is the quick save key %s: it saves, no key loads", input_key_name(l));
|
||||
l = KEY_NONE;
|
||||
}
|
||||
if (!was || s != save_key || l != load_key)
|
||||
rt_log("quicksave: %s saves, %s loads", s ? input_key_name(s) : "no key", l ? input_key_name(l) : "no key");
|
||||
save_key = s, load_key = l;
|
||||
return on;
|
||||
}
|
||||
|
||||
void quicksave_request(int load) {
|
||||
if (!quicksave_on()) return;
|
||||
plat_cas32(&g_request, load ? REQ_LOAD : REQ_SAVE, REQ_NONE);
|
||||
}
|
||||
|
||||
void quicksave_keys(uint8_t *down, int act) {
|
||||
static int held_s, held_l;
|
||||
int s = save_key && down[save_key], l = load_key && down[load_key];
|
||||
if (act && s && !held_s) quicksave_request(0);
|
||||
if (act && l && !held_l) quicksave_request(1);
|
||||
held_s = s, held_l = l;
|
||||
down[save_key] = down[load_key] = 0; // KEY_NONE is slot 0, never a key
|
||||
}
|
||||
|
||||
// Why play is not at a point where quick save or load may start, NULL when it is
|
||||
static const char *not_in_play(void) {
|
||||
char scr[48];
|
||||
uint64_t node;
|
||||
if (frame_step_world_us() < 0) return "no save is loaded";
|
||||
if (menu_ui_focus(scr, sizeof scr, &node)) return "a menu is open";
|
||||
if (menu_ui_open("LoadingFade_00") || menu_ui_open("EventFade_00")) return "the game is loading";
|
||||
if (menu_ui_open("MessageDialog_00")) return "a dialogue box is open";
|
||||
if (!menu_ui_open("PlayerStatus_00")) return "the HUD is hidden (a cutscene or an event)";
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void say(int text, const char *what, const char *why) {
|
||||
rt_log("%s: %s", what, why);
|
||||
menu_toast(text, 2500);
|
||||
}
|
||||
|
||||
static int readable(uint64_t p, uint64_t n) { return p >= 0x10000 && p < (1ull << 47) && mem_guest_readable(p, n); }
|
||||
|
||||
// The game's AutoSaveMgr, found and cast as OneShotAutoSaveMgrRequestAutoSave's execute does; 0 when it has none
|
||||
static uint64_t autosave_mgr(Cpu *c) {
|
||||
uint64_t g = MOD_MAIN_BASE + GAME_ROOT;
|
||||
if (!readable(g, 8) || !readable(LD64(g), 8)) return 0;
|
||||
uint64_t root = LD64(LD64(g));
|
||||
if (!readable(root, 8)) return 0;
|
||||
uint64_t mgr = rt_call(c, MOD_MAIN_BASE + COMPONENT, 2, root, (uint64_t)AUTOSAVE_INDEX);
|
||||
if (!readable(mgr, 0x1a8) || !readable(LD64(mgr), 8)) return 0;
|
||||
uint64_t type = rt_call(c, MOD_MAIN_BASE + AUTOSAVE_TYPE, 0);
|
||||
return rt_call(c, LD64(LD64(mgr)), 2, mgr, type) ? mgr : 0;
|
||||
}
|
||||
|
||||
static void path_of(char *out, size_t cap, const char *leaf) {
|
||||
snprintf(out, cap, "%s/quicksave%s%s", rt_config()->profile, leaf ? "/" : "", leaf ? leaf : "");
|
||||
}
|
||||
|
||||
static void save_start(Cpu *c) {
|
||||
const char *why = not_in_play();
|
||||
if (why) { say(UI_QS_NOT_NOW, "quicksave: not now", why); return; }
|
||||
uint64_t mgr = autosave_mgr(c);
|
||||
if (!mgr) { say(UI_QS_FAILED, "quicksave", "the game has no AutoSaveMgr"); return; }
|
||||
// The manager's timer (+0x150, seconds) holds autosaves back for some ten minutes after the game's last one; a
|
||||
// quick save is the player's own and skips it, as Save in the System tab does. The other checks of AUTOSAVE_CAN
|
||||
// stay: its flags, the game's flag that turns autosaves off (events, fights) and the player's state. AUTOSAVE_REQ
|
||||
// itself drops the request while flag +0x1a0 is set and the state +0x1a4 is 3 (but for kind 2).
|
||||
float timer;
|
||||
memcpy(&timer, (const void *)(uintptr_t)(mgr + 0x150), 4);
|
||||
ST32(mgr + 0x150, 0);
|
||||
int can = rt_call(c, MOD_MAIN_BASE + AUTOSAVE_CAN, 3, mgr, (uint64_t)AUTOSAVE_KIND, 0ull) & 1;
|
||||
if (can && LD8(mgr + 0x1a0) && LD32(mgr + 0x1a4) == 3) can = 0;
|
||||
if (!can) {
|
||||
memcpy((void *)(uintptr_t)(mgr + 0x150), &timer, 4); // the game's own wait goes on as it was
|
||||
say(UI_QS_NOT_NOW, "quicksave: not now", "the game would not autosave here");
|
||||
return;
|
||||
}
|
||||
if (timer > 0) rt_log("quicksave: the game's autosave wait (%.0f s left) skipped", timer);
|
||||
char slot[64];
|
||||
commits_before = fs_save_commits(slot, sizeof slot);
|
||||
uint64_t flags = LD64(mgr + REQ_FLAGS) + 5;
|
||||
if (!readable(flags, 1)) { say(UI_QS_FAILED, "quicksave", "the AutoSaveMgr has no request flags"); return; }
|
||||
int pending = LD8(flags) & 1; // the game's own request, which quick save then waits for
|
||||
rt_call(c, MOD_MAIN_BASE + AUTOSAVE_REQ, 2, mgr, (uint64_t)AUTOSAVE_KIND);
|
||||
if (!(LD8(flags) & 1)) { say(UI_QS_NOT_NOW, "quicksave: not now", "the game dropped the request"); return; }
|
||||
req_flags = pending ? 0 : flags;
|
||||
saving = 1, save_started = plat_now_ms();
|
||||
rt_log("quicksave: autosave requested");
|
||||
}
|
||||
|
||||
// The slot the autosave wrote, copied to <profile>/quicksave on a thread of its own; saving goes back to 0 at its end
|
||||
static char copy_slot[64];
|
||||
static void copy_main(void *arg) {
|
||||
(void)arg;
|
||||
char dir[1200], data[1200], note[1200];
|
||||
path_of(dir, sizeof dir, NULL), path_of(data, sizeof data, "slot"), path_of(note, sizeof note, "slot.txt");
|
||||
plat_fs_mkdir(dir);
|
||||
if (fs_save_copy_slot(copy_slot, data) || !plat_file_write_atomic(note, copy_slot, strlen(copy_slot))) {
|
||||
say(UI_QS_FAILED, "quicksave", "the autosave could not be copied to the quick save");
|
||||
} else {
|
||||
rt_log("quicksave: saved: the game's autosave in %s (%.1f s), kept in %s", copy_slot,
|
||||
(plat_now_ms() - save_started) / 1000.0, data);
|
||||
menu_toast(UI_QS_SAVED, 2500);
|
||||
}
|
||||
__atomic_store_n(&saving, 0, __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
// After the request: the first commit that wrote a slot folder is the autosave
|
||||
static void save_wait(void) {
|
||||
if (__atomic_load_n(&saving, __ATOMIC_ACQUIRE) != 1) return; // 2: the copy runs
|
||||
char slot[64];
|
||||
uint32_t n = fs_save_commits(slot, sizeof slot);
|
||||
if (n == commits_before || !slot[0]) {
|
||||
// The game can take the request and still hold the autosave back (a fight in the Depths did): quick save then
|
||||
// takes its request back, so the game does not save some time later on its own, and says so
|
||||
if (plat_now_ms() - save_started > SAVE_MS) {
|
||||
// Atomic: the game's job threads set and read other bits of this byte at the same time
|
||||
if (req_flags) __atomic_fetch_and((uint8_t *)(uintptr_t)req_flags, (uint8_t)~1u, __ATOMIC_SEQ_CST);
|
||||
saving = 0;
|
||||
say(UI_QS_NOT_NOW, "quicksave: not now",
|
||||
req_flags ? "the game held the autosave back; the request is withdrawn" : "the game held its autosave back");
|
||||
}
|
||||
return;
|
||||
}
|
||||
saving = 2; // the copy runs on its own thread: no file I/O on the game thread
|
||||
snprintf(copy_slot, sizeof copy_slot, "%s", slot);
|
||||
if (!plat_thread_spawn(copy_main, NULL, "quicksave", 0)) copy_main(NULL);
|
||||
}
|
||||
|
||||
// ---- quick load: the game's load menu, driven under a held picture
|
||||
enum { ST_IDLE, ST_TOAST, ST_OPEN, ST_TAB, ST_PICK, ST_LIST, ST_CONFIRM, ST_LOADING, ST_CLEANUP };
|
||||
#define PRESS_MS 100 // a press, held long enough for any of the game's reads
|
||||
#define GAP_MS 120 // released after each press before the next step looks again
|
||||
#define SETTLE_MS 200 // a screen that just took the focus box plays its opening: act after this
|
||||
#define TAB_MS 100 // a tab of the pause menu that just took the focus: act after this (R stops at the last)
|
||||
#define TOAST_MS 150 // the toast is presented before the picture is held
|
||||
#define STEP_MS 3000 // the most any step waits for its screen
|
||||
#define LOAD_MS 10000 // the most the game takes from the confirmation to its loading fade
|
||||
#define BACK_MS 500 // the load is over once the HUD has been back this long, the loading fade closed
|
||||
#define READ_MAX_MS 120000 // the redirect ends this long after the confirmation whatever happened
|
||||
#define MAX_TABS 12 // R presses to reach the System tab, the last one (R stops there)
|
||||
#define MAX_BACK 10 // B presses to leave the menus after a failure
|
||||
|
||||
static struct {
|
||||
int state, tries;
|
||||
uint64_t state_at, press_until, gap_until, press_bit, focus_since, started;
|
||||
uint64_t reading, back_since; // reading: when the redirect began, 0 none; back_since: the HUD back since then
|
||||
char focus[48];
|
||||
} m;
|
||||
|
||||
int quicksave_busy(void) { return m.state != ST_IDLE; }
|
||||
|
||||
static void enter(int state, uint64_t now) { m.state = state, m.state_at = now, m.tries = 0; }
|
||||
|
||||
static void press(int bit, uint64_t now) {
|
||||
m.press_bit = 1ull << bit, m.press_until = now + PRESS_MS, m.gap_until = now + PRESS_MS + GAP_MS;
|
||||
}
|
||||
|
||||
static void fail(const char *why, uint64_t now) {
|
||||
rt_log("quickload: %s; leaving the menus", why);
|
||||
fs_save_read_from(NULL);
|
||||
m.reading = m.back_since = 0;
|
||||
menu_toast(UI_QS_LOAD_FAILED, 2500);
|
||||
enter(ST_CLEANUP, now);
|
||||
}
|
||||
|
||||
static void end(uint64_t now) {
|
||||
gfx_present_hold(0);
|
||||
enter(ST_IDLE, now);
|
||||
}
|
||||
|
||||
// Once per pad read on the game thread, after menu_cursor_poll: 1 while quick load runs, with the game's input
|
||||
// replaced by its presses. Quick load shows "Loading the quick save", then holds the window on that picture
|
||||
// (gfx_present_hold) while it opens the pause menu, turns to the System tab, presses Load, picks the list's first save
|
||||
// and confirms; from the confirmation on, the game's reads of a slot's files open the quick save's (fs_save_read_from),
|
||||
// so whichever slot the list offered first, the game loads the quick save. The picture comes back with the game's
|
||||
// loading fade, or as soon as a step fails (B then closes the menus).
|
||||
// The redirect of the slot reads ends with the load: once the game read the quick save's files, its loading fade closed
|
||||
// and the HUD (PlayerStatus_00) has been back BACK_MS; at once when a menu with the focus box opens (the load list
|
||||
// must show and load the slots as they are); after READ_MAX_MS whatever happened.
|
||||
static void reads_end(const char *why) {
|
||||
fs_save_read_from(NULL);
|
||||
rt_log("quickload: slot reads go to the save again (%s, %d files read from the quick save)", why,
|
||||
fs_save_read_from_hits());
|
||||
m.reading = m.back_since = 0;
|
||||
}
|
||||
|
||||
static void reads_watch(uint64_t now) {
|
||||
char scr[48];
|
||||
uint64_t node;
|
||||
if (menu_ui_focus(scr, sizeof scr, &node)) { reads_end("a menu opened"); return; }
|
||||
if (now - m.reading > READ_MAX_MS) { reads_end("the load did not end in time"); return; }
|
||||
int back = fs_save_read_from_hits() > 0 && !menu_ui_open("LoadingFade_00") && menu_ui_open("PlayerStatus_00");
|
||||
if (!back) m.back_since = 0;
|
||||
else if (!m.back_since) m.back_since = now;
|
||||
else if (now - m.back_since >= BACK_MS) reads_end("the load is over");
|
||||
}
|
||||
|
||||
static int poll_locked(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) {
|
||||
if (m.reading && m.state == ST_IDLE) reads_watch(plat_now_ms());
|
||||
if (m.state == ST_IDLE && __atomic_load_n(&g_request, __ATOMIC_RELAXED) != REQ_LOAD) return 0; // a plain read
|
||||
uint64_t now = plat_now_ms();
|
||||
if (m.state == ST_IDLE) {
|
||||
if (plat_cas32(&g_request, REQ_NONE, REQ_LOAD) != REQ_LOAD || !quicksave_on()) return 0;
|
||||
char data[1200];
|
||||
path_of(data, sizeof data, "slot");
|
||||
if (plat_fs_kind(data) != PLAT_FS_DIR) { say(UI_QS_NONE, "quickload", "there is no quick save"); return 0; }
|
||||
const char *why = not_in_play();
|
||||
if (why) { say(UI_QS_NOT_NOW, "quickload: not now", why); return 0; }
|
||||
rt_log("quickload: through the game's load menu, under the held picture");
|
||||
menu_toast(UI_QS_LOADING, 4000);
|
||||
m.started = now;
|
||||
enter(ST_TOAST, now);
|
||||
}
|
||||
plat_cas32(&g_request, REQ_NONE, REQ_LOAD); // a key pressed while it runs is dropped, not queued
|
||||
*buttons = 0, *lx = *ly = *rx = *ry = 0;
|
||||
if (now < m.press_until) { *buttons = m.press_bit; return 1; }
|
||||
if (now < m.gap_until) return 1;
|
||||
char scr[48];
|
||||
uint64_t node;
|
||||
int focus = menu_ui_focus(scr, sizeof scr, &node);
|
||||
if (!focus || strcmp(scr, m.focus)) m.focus_since = now, snprintf(m.focus, sizeof m.focus, "%s", focus ? scr : "");
|
||||
int settled = focus && now - m.focus_since >= SETTLE_MS;
|
||||
uint64_t waited = now - m.state_at;
|
||||
if (m.state != ST_CLEANUP && m.state != ST_LOADING && now - m.started > 4 * STEP_MS) {
|
||||
fail("took too long", now);
|
||||
return 1;
|
||||
}
|
||||
switch (m.state) {
|
||||
case ST_TOAST: // the toast reaches the screen; then the picture is held and Plus opens the pause menu
|
||||
if (waited < TOAST_MS) break;
|
||||
gfx_present_hold(1);
|
||||
press(B_PLUS, now);
|
||||
enter(ST_OPEN, now);
|
||||
break;
|
||||
case ST_OPEN: // the pause menu (Pouch_00) takes the focus box
|
||||
if (focus && strcmp(scr, "Pouch_00")) { fail("another menu opened", now); break; }
|
||||
if (settled) enter(ST_TAB, now);
|
||||
else if (waited > STEP_MS) fail("the pause menu did not open", now);
|
||||
break;
|
||||
case ST_TAB: { // R until the System tab's buttons show
|
||||
int ok;
|
||||
if (focus && strcmp(scr, "Pouch_00")) { fail("another menu opened", now); break; }
|
||||
if (!focus || now - m.focus_since < TAB_MS) {
|
||||
if (waited > STEP_MS) fail("the pause menu lost the focus", now);
|
||||
break;
|
||||
}
|
||||
if (menu_ui_button("PaCommonBtnThin_00", "Pa_Button_01", &ok)) { enter(ST_PICK, now); break; }
|
||||
if (m.tries++ >= MAX_TABS) { fail("the System tab was not found", now); break; }
|
||||
press(B_R, now);
|
||||
m.state_at = now; // each tab gets its own wait
|
||||
break;
|
||||
}
|
||||
case ST_PICK: { // Load (Pa_Button_01) takes the focus, then A
|
||||
int ok = 0;
|
||||
uint64_t b = menu_ui_button("PaCommonBtnThin_00", "Pa_Button_01", &ok);
|
||||
if (!b) { fail("the System tab closed", now); break; }
|
||||
if (!ok) { fail("the game does not allow loading now", now); break; }
|
||||
if (menu_ui_focus_to(b)) { press(B_A, now); enter(ST_LIST, now); }
|
||||
else if (waited > STEP_MS) fail("the focus did not move to Load", now);
|
||||
break;
|
||||
}
|
||||
case ST_LIST: { // the load list (SystemLoadList_00): its first save takes the focus, then A
|
||||
if (!settled || strcmp(scr, "SystemLoadList_00")) {
|
||||
if (focus && settled && strcmp(scr, "Pouch_00")) fail("another menu opened", now);
|
||||
else if (waited > STEP_MS) fail("the list of saves did not open", now);
|
||||
break;
|
||||
}
|
||||
uint64_t b = menu_ui_first_save();
|
||||
if (!b) { fail("the list holds no save", now); break; }
|
||||
if (menu_ui_focus_to(b)) { press(B_A, now); enter(ST_CONFIRM, now); }
|
||||
else if (waited > STEP_MS) fail("the focus did not move to the save", now);
|
||||
break;
|
||||
}
|
||||
case ST_CONFIRM: { // "Load this save?" (SystemSaveLoad_00): its first button and A, the slot reads redirected
|
||||
if (!settled || strcmp(scr, "SystemSaveLoad_00")) {
|
||||
if (focus && settled && strcmp(scr, "SystemLoadList_00")) fail("another menu opened", now);
|
||||
else if (waited > STEP_MS) fail("the game did not ask to confirm", now);
|
||||
break;
|
||||
}
|
||||
uint64_t b = menu_ui_button("PaCommonBtnThin_00", "Pa_CheckButton_00", NULL);
|
||||
if (!b) { fail("the confirmation has no first button", now); break; }
|
||||
if (menu_ui_focus_to(b)) {
|
||||
char data[1200];
|
||||
path_of(data, sizeof data, "slot");
|
||||
fs_save_read_from(data);
|
||||
m.reading = now, m.back_since = 0;
|
||||
press(B_A, now);
|
||||
enter(ST_LOADING, now);
|
||||
} else if (waited > STEP_MS) fail("the focus did not move to the confirmation", now);
|
||||
break;
|
||||
}
|
||||
case ST_LOADING: // the game fades out and loads: the picture comes back with its fade
|
||||
if (menu_ui_open("LoadingFade_00")) {
|
||||
rt_log("quickload: loading the quick save (%.1f s)", (now - m.started) / 1000.0);
|
||||
end(now);
|
||||
} else if (focus && settled && strcmp(scr, "SystemSaveLoad_00")) {
|
||||
fail("another menu opened instead of loading", now);
|
||||
}
|
||||
else if (waited > LOAD_MS) fail("the load did not start", now);
|
||||
break;
|
||||
case ST_CLEANUP: // B until no menu has the focus box; then the picture comes back
|
||||
if (!focus) { end(now); break; }
|
||||
if (m.tries++ >= MAX_BACK) {
|
||||
rt_log("quickload: a menu stays open after %d presses of B", MAX_BACK);
|
||||
end(now);
|
||||
break;
|
||||
}
|
||||
press(B_B, now);
|
||||
m.gap_until = now + PRESS_MS + 2 * GAP_MS;
|
||||
break;
|
||||
}
|
||||
if (now < m.press_until) *buttons = m.press_bit;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int quicksave_poll(uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) {
|
||||
if (!m.reading && m.state == ST_IDLE && __atomic_load_n(&g_request, __ATOMIC_RELAXED) != REQ_LOAD) return 0;
|
||||
if (!plat_mutex_trylock(&qs_lock)) { // another pad read steps it: this one gets the same presses
|
||||
if (m.state == ST_IDLE) return 0;
|
||||
*buttons = plat_now_ms() < m.press_until ? m.press_bit : 0, *lx = *ly = *rx = *ry = 0;
|
||||
return 1;
|
||||
}
|
||||
int r = poll_locked(buttons, lx, ly, rx, ry);
|
||||
plat_mutex_unlock(&qs_lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void guest_locked(Cpu *c);
|
||||
|
||||
// Once per game pad read (ov_input.c), with the reading thread's Cpu: quick save
|
||||
void quicksave_guest(Cpu *c) {
|
||||
if (!saving && __atomic_load_n(&g_request, __ATOMIC_RELAXED) != REQ_SAVE) return; // a plain read when idle
|
||||
if (!plat_mutex_trylock(&qs_lock)) return;
|
||||
guest_locked(c);
|
||||
plat_mutex_unlock(&qs_lock);
|
||||
}
|
||||
|
||||
static void guest_locked(Cpu *c) {
|
||||
if (!saving && __atomic_load_n(&g_request, __ATOMIC_RELAXED) != REQ_SAVE) return; // a plain read when idle
|
||||
if (saving) {
|
||||
save_wait();
|
||||
plat_cas32(&g_request, REQ_NONE, REQ_SAVE); // a key pressed while it saves is dropped, not queued
|
||||
return;
|
||||
}
|
||||
if (plat_cas32(&g_request, REQ_NONE, REQ_SAVE) != REQ_SAVE || !quicksave_on()) return;
|
||||
if (m.state != ST_IDLE) return;
|
||||
save_start(c);
|
||||
}
|
||||
+19
-12
@@ -58,6 +58,7 @@
|
||||
static struct {
|
||||
int decided;
|
||||
unsigned ow, oh, sw, sh; // output and scene
|
||||
unsigned aw, ah; // the output TOTK_OUTPUT_RES asks for, before shape_fallback
|
||||
int scene_set; // the scene differs from the game's 5/6 of the output
|
||||
int heapdef_ok; // romfs.c serves the grown HeapDef
|
||||
int on; // res_init switched the patch sets on
|
||||
@@ -161,14 +162,14 @@ static void shape_fallback(void) {
|
||||
static void decide(void) {
|
||||
if (R.decided) return;
|
||||
R.decided = 1;
|
||||
R.ow = BASE_W;
|
||||
R.oh = BASE_H;
|
||||
R.ow = R.aw = BASE_W;
|
||||
R.oh = R.ah = BASE_H;
|
||||
const char *o = cfg_value("TOTK_OUTPUT_RES");
|
||||
unsigned w = 0, h = 0;
|
||||
char tail;
|
||||
if (sscanf(o, "%ux%u%c", &w, &h, &tail) == 2 && w >= 1280 && h >= 720 && w <= 7680 && h <= 4320) {
|
||||
R.ow = w & ~1u;
|
||||
R.oh = h & ~1u;
|
||||
R.ow = R.aw = w & ~1u;
|
||||
R.oh = R.ah = h & ~1u;
|
||||
shape_fallback();
|
||||
} else {
|
||||
rt_log("resolution: TOTK_OUTPUT_RES=%s is not <width>x<height> in 1280x720..7680x4320; 1920x1080", o);
|
||||
@@ -510,9 +511,10 @@ static void shadow_init(uint8_t *page) {
|
||||
// ---- start: the patch page and the sets
|
||||
static uint64_t pack(unsigned w, unsigned h) { return (uint64_t)h << 32 | w; }
|
||||
|
||||
// TOTK_SHADOW_RANGE (percent, 50 to 400; 100 = the game's): the sun's shadow cascades end at 20, 40, 80 and 160 m.
|
||||
// Other values multiply those distances through the cascade patch set (recomp/patches-v143.txt), so the sharp first
|
||||
// cascade reaches further and the visible steps between cascades move away from the player, at the cost of shadow
|
||||
// TOTK_SHADOW_RANGE (percent, 50 to 400; 100 = the game's): the sun's shadow cascades end at 20, 40, 80 and 160 m by
|
||||
// the depth shadow parameters' defaults; in the field the shadow controller computes the boundaries from the camera
|
||||
// each frame instead. Other values multiply the boundaries through the cascade patch set (recomp/patches-v143.txt and
|
||||
// patches-v121.txt; the controller's sites take page +64 over 20 as the factor), so the sharp first cascade reaches further and the visible steps between cascades move away from the player, at the cost of shadow
|
||||
// texels per metre (TOTK_SHADOW_SCALE pays that back).
|
||||
static void res_shadow_range(void) {
|
||||
int pct = cfg_int("TOTK_SHADOW_RANGE"), set = rt_patch_set("cascade");
|
||||
@@ -625,10 +627,10 @@ int res_wants_wide_overlay(const unsigned out[2]) {
|
||||
return !res_is_16x9(out[0], out[1]) && rt_patch_set("aspect") >= 0;
|
||||
}
|
||||
|
||||
// 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-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.
|
||||
// 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.
|
||||
#define FOV_MIN 70
|
||||
#define FOV_MAX 140
|
||||
void res_fov_live(void) {
|
||||
@@ -648,7 +650,7 @@ void res_fov_live(void) {
|
||||
rt_log("resolution: field of view %d%% of the game's", pct);
|
||||
}
|
||||
|
||||
// TOTK_DYNAMIC_RES = 0 holds the game's dynamic resolution at 100 % (recomp/patches-v121.txt and patches-v143.txt,
|
||||
// TOTK_DYNAMIC_RES = 0 holds the game's dynamic resolution at 100 % (patches-v110.txt, patches-v121.txt and patches-v143.txt,
|
||||
// set fixres), so the scene renders at the size render_scale chose. The game picks its tier (100, 90 or 80 %) mostly
|
||||
// from a fixed cost model made for the Switch: one term grows with the object counts, one with (scene width / 1600)
|
||||
// squared. The GPU time it also measures (two NVN report timestamps, a frame apart) only lowers that prediction when the
|
||||
@@ -676,6 +678,11 @@ void res_wanted(unsigned out[2]) {
|
||||
out[0] = R.ow, out[1] = R.oh;
|
||||
}
|
||||
|
||||
void res_asked(unsigned out[2]) {
|
||||
decide();
|
||||
out[0] = R.aw, out[1] = R.ah;
|
||||
}
|
||||
|
||||
// A TOTK_DLSS change while the game runs (vk_dlaa.c, at a present): the new scene size goes to the patch page, where
|
||||
// the game reads it when it sets its render size (main+0x585e48). 1.4.3 does that once, at start: its renderer setup
|
||||
// (main+0x7000e67028) calls main+0x585bd0(renderer, force), which picks the console mode's sizes and flags the render
|
||||
|
||||
+174
-85
@@ -467,7 +467,8 @@ static const char *owner_name(const Overlay *o) {
|
||||
return o->mod ? mods_at(o->mod - 1)->name : o->prio ? "romfs_mods" : "the port's patches";
|
||||
}
|
||||
|
||||
// One overlay per path: the highest prio serves it; the others are dropped and counted on their mod.
|
||||
// One overlay per path: the highest prio serves it; the others are dropped and counted on their mod, and a file one
|
||||
// mod takes from another goes into the conflict table (mods_conflict).
|
||||
static void overlay_contest(void) {
|
||||
if (!noverlay) return;
|
||||
qsort(overlays, noverlay, sizeof *overlays, contest_order);
|
||||
@@ -478,7 +479,7 @@ static void overlay_contest(void) {
|
||||
if (o->mod) {
|
||||
ModInfo *m = mods_at(o->mod - 1);
|
||||
m->overridden++;
|
||||
if (!m->overridden_by[0]) snprintf(m->overridden_by, sizeof m->overridden_by, "%s", owner_name(w));
|
||||
if (w->mod) mods_conflict(mods_at(w->mod - 1)->id, m->id, MOD_PART_FILES, 1);
|
||||
} else if (w->mod) {
|
||||
rt_log("RomFS overlay: %s from mod %s replaces the one of %s", o->name, owner_name(w), owner_name(o));
|
||||
}
|
||||
@@ -509,10 +510,10 @@ static void mods_overlay_log(void) {
|
||||
for (int k = 0; k < mods_count(); k++) {
|
||||
const ModInfo *m = mods_at(k);
|
||||
if (!m->enabled || !(m->kind & MOD_ROMFS) || m->problem != MOD_OK) continue;
|
||||
rt_log("mods: %s: %u files served (%u replaced, %u added), %u overridden%s%s, %u for another game version",
|
||||
m->name, m->replaced + m->added, m->replaced, m->added, m->overridden, m->overridden ? " by " : "",
|
||||
m->overridden_by, m->other_version);
|
||||
rt_log("mods: %s: %u files served (%u replaced, %u added), %u overridden, %u for another game version",
|
||||
m->name, m->replaced + m->added, m->replaced, m->added, m->overridden, m->other_version);
|
||||
}
|
||||
mods_conflicts_log(MOD_PART_FILES);
|
||||
}
|
||||
|
||||
static int overlay_order(const void *a, const void *b) {
|
||||
@@ -933,14 +934,15 @@ static void camera_overlay(void) {
|
||||
// did not load (ROMFS_PROMPTS_*). The menu compares them with the settings in effect (ui/menu.cpp prompts_note).
|
||||
// Each folder keeps its name, but at a game resolution of another shape than 16:9 its files come from dir,
|
||||
// <name>-<w>x<h> (overlay_init), and ready is that one's.
|
||||
static struct { const char *name; int ready; char dir[64]; } prompts_folders[3];
|
||||
#define PROMPTS_FOLDERS 5 // the two Xbox folders, the two PlayStation ones, the PC one (overlay_init)
|
||||
static struct { const char *name; int ready; char dir[64]; } prompts_folders[PROMPTS_FOLDERS];
|
||||
static const char *prompts_wanted, *prompts_loaded;
|
||||
static int prompts_off;
|
||||
|
||||
const char *romfs_prompts(void) { return prompts_loaded; }
|
||||
|
||||
int romfs_prompts_ready(const char *folder) {
|
||||
for (int i = 0; i < 3; i++)
|
||||
for (int i = 0; i < PROMPTS_FOLDERS; i++)
|
||||
if (folder && prompts_folders[i].name && !strcmp(prompts_folders[i].name, folder)) return prompts_folders[i].ready;
|
||||
return 0;
|
||||
}
|
||||
@@ -969,39 +971,60 @@ static void overlay_drop(size_t a, size_t b) {
|
||||
noverlay -= b - a;
|
||||
}
|
||||
|
||||
// The folder <prefix>-<w>x<h> the game resolution w x h takes in base: that exact size when it has a manifest (an
|
||||
// The HUD cap for the canonical shape. An inapplicable cap is full, as in installer/steps.py shape_hud. The generator
|
||||
// takes that same shape, so a resolution alias near the one-percent boundary cannot ask for an invalid variant.
|
||||
static const char *hud_suffix(unsigned w, unsigned h) {
|
||||
unsigned shape[2] = {w, h};
|
||||
cfg_shape_size(w, h, shape);
|
||||
const char *value = cfg_value("TOTK_HUD_WIDTH");
|
||||
double cap = !strcmp(value, "21:9") ? 21.0 / 9 : !strcmp(value, "16:9") ? 16.0 / 9 : 0;
|
||||
return cap && shape[1] && cap < (double)shape[0] / shape[1] * 0.99
|
||||
? (cap > 2 ? "-hud21x9" : "-hud16x9") : "";
|
||||
}
|
||||
|
||||
// The folder <prefix>-<w>x<h><suffix> the game resolution w x h takes in base: that exact size when it has a manifest (an
|
||||
// install by a setup that wrote every size, or make_romfs_patches.py --aspect <w>x<h> in a source build), else the
|
||||
// size of its shape (cfg.c cfg_shape_size), the one folder per shape installer/steps.py Shapes writes. name gets the
|
||||
// folder found, or the shape's one when neither has a manifest (for the log). 1 when found.
|
||||
static int shaped_name(const char *base, const char *prefix, unsigned w, unsigned h, char *name, size_t cap) {
|
||||
static int shaped_name(const char *base, const char *prefix, unsigned w, unsigned h, const char *suffix,
|
||||
char *name, size_t cap) {
|
||||
char path[2400];
|
||||
unsigned s[2] = {w, h};
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
if (pass && !cfg_shape_size(w, h, s)) break;
|
||||
if (pass && s[0] == w && s[1] == h) break;
|
||||
snprintf(name, cap, "%s-%ux%u", prefix, s[0], s[1]);
|
||||
if (snprintf(name, cap, "%s-%ux%u%s", prefix, s[0], s[1], suffix) >= (int)cap) return 0;
|
||||
if (snprintf(path, sizeof path, "%s/%s/manifest.tsv", base, name) < (int)sizeof path && plat_file_exists(path))
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Prefer the selected HUD at both exact and canonical sizes. Boot may fall back to the full HUD, but preparation
|
||||
// and the menu's missing-layout note use strict lookup so a full layout cannot hide a missing capped variant.
|
||||
static int selected_shape(const char *base, const char *prefix, unsigned w, unsigned h, char *name, size_t cap,
|
||||
int fallback) {
|
||||
const char *suffix = hud_suffix(w, h);
|
||||
if (shaped_name(base, prefix, w, h, suffix, name, cap)) return 1;
|
||||
return fallback && *suffix && shaped_name(base, prefix, w, h, "", name, cap);
|
||||
}
|
||||
|
||||
static void overlay_init(void) {
|
||||
// TOTK_ROMFS_PATCHES unset: romfs-patches next to romfs-index.bin if it has a manifest (tools/make_romfs_patches.py).
|
||||
// A game resolution that is not 16:9 takes romfs-patches-<w>x<h> instead when it is there (shaped_name: the exact
|
||||
// size, else the folder of its shape): the same overlay with the UI laid out for that shape
|
||||
// (make_romfs_patches.py --aspect), when the game version has the camera aspect patch the layout goes with
|
||||
// (res_wants_wide_overlay).
|
||||
// With prompts = xbox, the Xbox prompts' folder for the pad layout in its place (input_prompts_folder): the same
|
||||
// patches with Xbox button icons (make_romfs_patches.py --prompts); prompts = pc takes romfs-patches-pc whatever
|
||||
// the pad layout. The game reads the archives once at boot, so the prompts stay until restart even though the
|
||||
// layout itself changes live. Each folder replaces romfs-patches as a whole. At a game resolution of another shape
|
||||
// the prompts come from <folder>-<w>x<h> (make_romfs_patches.py --prompts <style> --aspect): it carries that
|
||||
// shape's UI layout too, so it replaces romfs-patches-<w>x<h> as the folder replaces romfs-patches. Without it the
|
||||
// Switch prompts stay with the shape's layout. So they do when a RomFS mod (the TOTK_ROMFS_MODS manifest or a
|
||||
// player mod) replaces one of the prompts' fonts: romfs-patches loads in their place, so the mod's file is not
|
||||
// served beside prompts files made for the game's own. A mod's resource size table is no clash: restbl_overlay
|
||||
// merges it with the prompts' one.
|
||||
// With prompts = xbox or playstation, that controller's prompts' folder for the pad layout in its place
|
||||
// (input_prompts_folder): the same patches with Xbox or PlayStation button icons (make_romfs_patches.py
|
||||
// --prompts); prompts = pc takes romfs-patches-pc whatever the pad layout. The game reads the archives once at
|
||||
// boot, so the prompts stay until restart even though the layout itself changes live. Each folder replaces
|
||||
// romfs-patches as a whole. At a game resolution of another shape the prompts come from <folder>-<w>x<h>
|
||||
// (make_romfs_patches.py --prompts <style> --aspect): it carries that shape's UI layout too, so it replaces
|
||||
// romfs-patches-<w>x<h> as the folder replaces romfs-patches. Without it the Switch prompts stay with the shape's
|
||||
// layout. So they do when a RomFS mod (the TOTK_ROMFS_MODS manifest or a player mod) replaces one of the prompts'
|
||||
// fonts: romfs-patches loads in their place, so the mod's file is not served beside prompts files made for the
|
||||
// game's own. A mod's resource size table is no clash: restbl_overlay merges it with the prompts' one.
|
||||
char def[2100], path[2100];
|
||||
const char *patches = cfg_get("TOTK_ROMFS_PATCHES"), *mods = cfg_get("TOTK_ROMFS_MODS");
|
||||
int wide = 0;
|
||||
@@ -1011,22 +1034,31 @@ static void overlay_init(void) {
|
||||
cfg_shape_size(out[0], out[1], shape);
|
||||
if (!patches && res_wants_wide_overlay(out)) {
|
||||
char name[128];
|
||||
if (shaped_name(index_dir, "romfs-patches", out[0], out[1], name, sizeof name) &&
|
||||
if (selected_shape(index_dir, "romfs-patches", out[0], out[1], name, sizeof name, 1) &&
|
||||
snprintf(def, sizeof def, "%s/%s", index_dir, name) < (int)sizeof def) {
|
||||
patches = def, wide = 1;
|
||||
rt_log("RomFS overlay: the UI layout for %ux%u from %s", out[0], out[1], name);
|
||||
const char *suffix = hud_suffix(out[0], out[1]);
|
||||
if (*suffix && !ends_with(name, suffix))
|
||||
rt_log("RomFS overlay: the selected HUD layout is missing; using the full HUD (an install makes it "
|
||||
"in the background below; a source build: tools/make_romfs_patches.py --aspect %ux%u --hud %s)",
|
||||
shape[0], shape[1], cfg_value("TOTK_HUD_WIDTH"));
|
||||
} else {
|
||||
rt_log("RomFS overlay: no %s for this game resolution, the UI keeps its 16:9 layout (run the setup again, "
|
||||
"or tools/make_romfs_patches.py --aspect %ux%u)", name, shape[0], shape[1]);
|
||||
}
|
||||
}
|
||||
static const char *const layouts[2] = {"nintendo", "xbox"}; // one of each Xbox folder, then the PC one
|
||||
for (int i = 0; i < 3; i++) {
|
||||
const char *name = i < 2 ? input_prompts_folder(PROMPTS_XBOX, layouts[i]) : input_prompts_folder(PROMPTS_PC, 0);
|
||||
// one of each Xbox and PlayStation folder, then the PC one
|
||||
static const char *const layouts[2] = {"nintendo", "xbox"};
|
||||
for (int i = 0; i < PROMPTS_FOLDERS; i++) {
|
||||
const char *name = i < 2 ? input_prompts_folder(PROMPTS_XBOX, layouts[i])
|
||||
: i < 4 ? input_prompts_folder(PROMPTS_PLAYSTATION, layouts[i - 2])
|
||||
: input_prompts_folder(PROMPTS_PC, 0);
|
||||
char *dir = prompts_folders[i].dir;
|
||||
prompts_folders[i].name = name;
|
||||
if (wide) {
|
||||
prompts_folders[i].ready = shaped_name(index_dir, name, out[0], out[1], dir, sizeof prompts_folders[i].dir);
|
||||
prompts_folders[i].ready = selected_shape(index_dir, name, out[0], out[1], dir,
|
||||
sizeof prompts_folders[i].dir, 1);
|
||||
continue;
|
||||
}
|
||||
snprintf(dir, sizeof prompts_folders[i].dir, "%s", name);
|
||||
@@ -1035,11 +1067,17 @@ static void overlay_init(void) {
|
||||
}
|
||||
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
|
||||
int pick = input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout);
|
||||
const char *style = pick == PROMPTS_PC ? "keyboard and mouse" : "Xbox";
|
||||
const char *style = pick == PROMPTS_PC ? "keyboard and mouse"
|
||||
: pick == PROMPTS_PLAYSTATION ? "PlayStation"
|
||||
: "Xbox";
|
||||
prompts_wanted = input_prompts_folder(pick, layout);
|
||||
const char *wanted_dir = prompts_wanted; // the folder its files come from
|
||||
for (int i = 0; i < 3; i++)
|
||||
for (int i = 0; i < PROMPTS_FOLDERS; i++)
|
||||
if (prompts_wanted && !strcmp(prompts_folders[i].name, prompts_wanted)) wanted_dir = prompts_folders[i].dir;
|
||||
const char *suffix = hud_suffix(out[0], out[1]);
|
||||
if (wide && prompts_wanted && romfs_prompts_ready(prompts_wanted) && *suffix && !ends_with(wanted_dir, suffix))
|
||||
rt_log("RomFS overlay: the %s prompts have no selected HUD layout; their full HUD loads instead (an "
|
||||
"install makes it in the background below)", style);
|
||||
prompts_off = !prompts_wanted ? ROMFS_PROMPTS_OK
|
||||
: patches && !wide ? ROMFS_PROMPTS_PATCHES
|
||||
: !romfs_prompts_ready(prompts_wanted) ? (wide ? ROMFS_PROMPTS_SHAPE : ROMFS_PROMPTS_MISSING)
|
||||
@@ -1066,8 +1104,18 @@ static void overlay_init(void) {
|
||||
snprintf(why, sizeof why, "%s", prompts_off == ROMFS_PROMPTS_PATCHES
|
||||
? "TOTK_ROMFS_PATCHES is set"
|
||||
: "their folder has no manifest.tsv (run the setup again)");
|
||||
rt_log("RomFS overlay: prompts = %s, but %s; Switch prompts stay", pick == PROMPTS_PC ? "pc" : "xbox", why);
|
||||
rt_log("RomFS overlay: prompts = %s, but %s; Switch prompts stay",
|
||||
pick == PROMPTS_PC ? "pc" : pick == PROMPTS_PLAYSTATION ? "playstation" : "xbox", why);
|
||||
}
|
||||
// A folder the settings in effect ask for and the install lacks (an older setup, a failed setup step, a display
|
||||
// of another shape): its generator starts in the background for the next start when the setup's tools are next to
|
||||
// the game (romfs_folders_prepare). The size is the one output_res asks for: without its shape's layout the game
|
||||
// draws 16:9 this time (resolution.c shape_fallback). Without an output_res it is the display's shape, which the
|
||||
// default keeps only while that shape has the prompts' folder (cfg.c cfg_screen_size). Nothing with
|
||||
// TOTK_ROMFS_PATCHES set; a source build has no build-cache/rebuild.txt and keeps the lines above.
|
||||
unsigned asked[2];
|
||||
if (!cfg_screen_size(asked)) res_asked(asked);
|
||||
romfs_folders_prepare(asked[0], asked[1], prompts_wanted);
|
||||
size_t prompts_end = noverlay;
|
||||
char plain[2100]; // romfs-patches, when it has a manifest
|
||||
int plain_ok = snprintf(plain, sizeof plain, "%s/romfs-patches/manifest.tsv", index_dir) < (int)sizeof plain &&
|
||||
@@ -1127,27 +1175,33 @@ static void index_folder(char *dir, size_t cap) {
|
||||
}
|
||||
|
||||
// 1 when the folder overlay_init takes for <prefix> at w x h (shaped_name) has a manifest next to romfs-index.bin.
|
||||
static int shaped_folder_ready(const char *prefix, unsigned w, unsigned h) {
|
||||
static int shaped_folder_ready(const char *prefix, unsigned w, unsigned h, int fallback) {
|
||||
char dir[2100], name[128];
|
||||
index_folder(dir, sizeof dir);
|
||||
return shaped_name(dir, prefix, w, h, name, sizeof name);
|
||||
return selected_shape(dir, prefix, w, h, name, sizeof name, fallback);
|
||||
}
|
||||
|
||||
// 1 when the game resolution w x h has the UI layout of its shape: romfs-patches-<w>x<h> of that size or of its shape,
|
||||
// the folder overlay_init looks for.
|
||||
int romfs_shaped_ready(unsigned w, unsigned h) { return shaped_folder_ready("romfs-patches", w, h); }
|
||||
int romfs_shaped_ready(unsigned w, unsigned h) { return shaped_folder_ready("romfs-patches", w, h, 1); }
|
||||
|
||||
// 1 when it has a prompts' folder (input_prompts_folder) with that layout too: <folder>-<w>x<h>, which overlay_init
|
||||
// loads in its place with those prompts.
|
||||
int romfs_shaped_prompts_ready(const char *folder, unsigned w, unsigned h) { return shaped_folder_ready(folder, w, h); }
|
||||
int romfs_shaped_prompts_ready(const char *folder, unsigned w, unsigned h) { return shaped_folder_ready(folder, w, h, 1); }
|
||||
|
||||
// ---- the layout for a new screen, from the settings menu (ui/menu.cpp row_output_res)
|
||||
// The setup writes the shaped folders for the displays connected when it ran (installer/steps.py Shapes). After a
|
||||
// monitor change the menu can start the same generator for the shape of the game resolution: the setup's Python and
|
||||
// tools/make_romfs_patches.py, which build-cache/rebuild.txt names (installer/steps.py write_rebuild_command: line 1 the
|
||||
// Python, pythonw on Windows, so no console opens; line 4 the setup's folder), on the install folder's romfs/. Child
|
||||
// processes the game does not wait for: the generator writes manifest.tsv last, so a folder it has not finished is not
|
||||
// taken, and the next start loads the finished one.
|
||||
// ---- missing folders, made in the background (the settings menu, ui/menu.cpp folders_tick, and the start,
|
||||
// overlay_init)
|
||||
// The setup writes the 16:9 prompts' folders on every install (installer/steps.py Prepare, PcPrompts) and the shaped
|
||||
// folders for the displays connected when it ran (Shapes). An install by an older setup, a failed setup step, a
|
||||
// monitor change or a change of resolution, HUD width, prompts or pad layout can ask for a folder it did not write.
|
||||
// The game then starts the same generator: the setup's Python and tools/make_romfs_patches.py, which
|
||||
// build-cache/rebuild.txt names (installer/steps.py write_rebuild_command: line 1 the Python, pythonw on Windows, so
|
||||
// no console opens; line 4 the setup's folder; both relative to the install folder for the build kit,
|
||||
// installer/layout.py), on the install folder's romfs/. Child processes the game does not wait for. With --background
|
||||
// the generator writes into a folder of its own beside the output and renames it into place at the end, unless a
|
||||
// folder with a manifest is there by then: a folder this game or another start loaded is never written into, and two
|
||||
// generators for one folder (the menu and the start, or a restart while the last one runs) do not mix their files.
|
||||
// The next start loads the finished folder.
|
||||
static int prepare_tools(char *python, size_t pcap, char *script, size_t scap, char *dir, size_t dcap) {
|
||||
char path[2400];
|
||||
index_folder(dir, dcap);
|
||||
@@ -1165,21 +1219,35 @@ static int prepare_tools(char *python, size_t pcap, char *script, size_t scap, c
|
||||
lines[k++] = p;
|
||||
p = e + 1;
|
||||
}
|
||||
int ok = k >= 4 && !strcmp(lines[1], "-c") && snprintf(python, pcap, "%s", lines[0]) < (int)pcap &&
|
||||
snprintf(script, scap, "%s/tools/make_romfs_patches.py", lines[3]) < (int)scap;
|
||||
int ok = k >= 4 && !strcmp(lines[1], "-c");
|
||||
if (ok) { // the build kit's lines are relative to the install folder
|
||||
const char *at0 = plat_path_absolute(lines[0]) ? "" : dir, *at3 = plat_path_absolute(lines[3]) ? "" : dir;
|
||||
ok = snprintf(python, pcap, "%s%s%s", at0, *at0 ? "/" : "", lines[0]) < (int)pcap &&
|
||||
snprintf(script, scap, "%s%s%s/tools/make_romfs_patches.py", at3, *at3 ? "/" : "", lines[3]) < (int)scap;
|
||||
}
|
||||
free(text);
|
||||
snprintf(path, sizeof path, "%s/romfs/romfs.bin", dir);
|
||||
return ok && plat_file_exists(python) && plat_file_exists(script) && plat_file_exists(path);
|
||||
}
|
||||
|
||||
int romfs_shape_missing(unsigned w, unsigned h, const char *prompts_folder) {
|
||||
unsigned out[2] = {w, h};
|
||||
if (!res_wants_wide_overlay(out)) return 0;
|
||||
return !shaped_folder_ready("romfs-patches", w, h) ||
|
||||
(prompts_folder && romfs_prompts_ready(prompts_folder) && !shaped_folder_ready(prompts_folder, w, h));
|
||||
// 1 when folder (a name next to romfs-index.bin) has a manifest.
|
||||
static int plain_folder_ready(const char *folder) {
|
||||
char dir[2100], path[2400];
|
||||
index_folder(dir, sizeof dir);
|
||||
return snprintf(path, sizeof path, "%s/%s/manifest.tsv", dir, folder) < (int)sizeof path && plat_file_exists(path);
|
||||
}
|
||||
|
||||
int romfs_shape_can_prepare(void) {
|
||||
int romfs_folders_missing(unsigned w, unsigned h, const char *prompts_folder) {
|
||||
unsigned out[2] = {w, h};
|
||||
if (cfg_get("TOTK_ROMFS_PATCHES")) return 0;
|
||||
int need = prompts_folder && !plain_folder_ready(prompts_folder) ? ROMFS_NEED_PROMPTS : 0;
|
||||
if (!res_wants_wide_overlay(out)) return need;
|
||||
if (!shaped_folder_ready("romfs-patches", w, h, 0)) need |= ROMFS_NEED_LAYOUT;
|
||||
if (prompts_folder && !shaped_folder_ready(prompts_folder, w, h, 0)) need |= ROMFS_NEED_SHAPED_PROMPTS;
|
||||
return need;
|
||||
}
|
||||
|
||||
int romfs_folders_can_prepare(void) {
|
||||
static int known = -1;
|
||||
if (known < 0) {
|
||||
char python[1024], script[1100], dir[2100];
|
||||
@@ -1188,11 +1256,12 @@ int romfs_shape_can_prepare(void) {
|
||||
return known;
|
||||
}
|
||||
|
||||
// The folders a generator was started for in this process. The menu thread alone calls romfs_shape_prepare, so no
|
||||
// lock. The game picks its overlay at start, so a folder is not started twice before the next start, even when its
|
||||
// generator has ended: a second click, or the same size chosen again, starts no second generator writing into it.
|
||||
static char shape_started[8][160];
|
||||
static int shape_started_n;
|
||||
// The folders a generator was started for in this process, under shape_lock: the start (overlay_init) and the menu
|
||||
// thread both start them. The game picks its overlay at start, so a folder is not started twice before the next start,
|
||||
// even when its generator has ended: the same setting chosen again starts no second generator for it.
|
||||
static PlatMutex shape_lock = PLAT_MUTEX_INIT;
|
||||
static char (*shape_started)[160];
|
||||
static int shape_started_n, shape_started_cap;
|
||||
|
||||
static int shape_was_started(const char *folder) {
|
||||
for (int i = 0; i < shape_started_n; i++)
|
||||
@@ -1201,51 +1270,71 @@ static int shape_was_started(const char *folder) {
|
||||
}
|
||||
|
||||
// Starts the generator for folder (a name in dir) unless one was started for it before. 1 when one runs for it, 0 when
|
||||
// it could not start. plat_spawn starts it detached and closes its handles without waiting, so a click costs the menu
|
||||
// thread one CreateProcess.
|
||||
// it could not start. plat_spawn starts it detached and closes its handles without waiting, so a start costs the
|
||||
// calling thread one CreateProcess.
|
||||
static int shape_spawn(const char *const *argv, const char *dir, const char *folder) {
|
||||
if (shape_was_started(folder)) return 1;
|
||||
if (!plat_spawn(argv, dir)) return 0;
|
||||
if (shape_started_n < (int)(sizeof shape_started / sizeof *shape_started))
|
||||
snprintf(shape_started[shape_started_n++], sizeof *shape_started, "%s", folder);
|
||||
return 1;
|
||||
plat_mutex_lock(&shape_lock);
|
||||
int ok = 1;
|
||||
if (!shape_was_started(folder)) {
|
||||
if (shape_started_n == shape_started_cap) {
|
||||
int cap = shape_started_cap ? shape_started_cap * 2 : 8;
|
||||
void *grown = realloc(shape_started, (size_t)cap * sizeof *shape_started);
|
||||
if (grown) shape_started = grown, shape_started_cap = cap;
|
||||
}
|
||||
// never start a writer whose folder cannot be remembered for deduplication
|
||||
ok = shape_started_n < shape_started_cap && plat_spawn(argv, dir);
|
||||
if (ok) snprintf(shape_started[shape_started_n++], sizeof *shape_started, "%s", folder);
|
||||
}
|
||||
plat_mutex_unlock(&shape_lock);
|
||||
return ok;
|
||||
}
|
||||
|
||||
int romfs_shape_prepare(unsigned w, unsigned h, const char *prompts_folder) {
|
||||
int romfs_folders_prepare(unsigned w, unsigned h, const char *prompts_folder) {
|
||||
char python[1024], script[1100], dir[2100], romfs[2200], out[2300], reuse[2300], binds[2300], size[32], version[8],
|
||||
name[128], folder[160];
|
||||
unsigned s[2];
|
||||
if (!cfg_shape_size(w, h, s) || !prepare_tools(python, sizeof python, script, sizeof script, dir, sizeof dir))
|
||||
return 0;
|
||||
folder[160];
|
||||
int need = romfs_folders_missing(w, h, prompts_folder);
|
||||
if (!need || !prepare_tools(python, sizeof python, script, sizeof script, dir, sizeof dir)) return 0;
|
||||
unsigned s[2] = {w, h};
|
||||
int shaped = cfg_shape_size(w, h, s);
|
||||
snprintf(size, sizeof size, "%ux%u", s[0], s[1]);
|
||||
snprintf(version, sizeof version, "v%d", rt_game_version);
|
||||
snprintf(romfs, sizeof romfs, "%s/romfs", dir);
|
||||
const char *suffix = shaped ? hud_suffix(w, h) : "", *hud = *suffix ? cfg_value("TOTK_HUD_WIDTH") : "full";
|
||||
const char *style = prompts_folder ? prompts_folder + strlen("romfs-patches-") : NULL;
|
||||
// The keyboard and mouse prompts are drawn from totk.ini's bind_ lines, as the setup's PcPrompts and Shapes steps
|
||||
// draw them (installer/steps.py pc_binds); a file without such lines gives the keyboard defaults.
|
||||
snprintf(binds, sizeof binds, "%s/totk.ini", dir);
|
||||
int pc = style && !strcmp(style, "pc") && plat_file_exists(binds);
|
||||
static const int order[3] = {ROMFS_NEED_PROMPTS, ROMFS_NEED_LAYOUT, ROMFS_NEED_SHAPED_PROMPTS};
|
||||
int started = 0, failed = 0;
|
||||
if (!shaped_name(dir, "romfs-patches", w, h, name, sizeof name)) {
|
||||
snprintf(folder, sizeof folder, "romfs-patches-%s", size);
|
||||
for (int k = 0; k < 3; k++) {
|
||||
int what = order[k];
|
||||
if (!(need & what) || (what != ROMFS_NEED_PROMPTS && !shaped)) continue;
|
||||
if (what == ROMFS_NEED_PROMPTS) snprintf(folder, sizeof folder, "%s", prompts_folder);
|
||||
else if (what == ROMFS_NEED_LAYOUT) snprintf(folder, sizeof folder, "romfs-patches-%s%s", size, suffix);
|
||||
else snprintf(folder, sizeof folder, "%s-%s%s", prompts_folder, size, suffix);
|
||||
snprintf(out, sizeof out, "%s/%s", dir, folder);
|
||||
const char *argv[] = {python, script, "--version", version, "--romfs", romfs, "--out", out, "--aspect", size,
|
||||
NULL};
|
||||
const char *argv[24] = {python, script, "--version", version, "--romfs", romfs, "--out", out, "--background"};
|
||||
int argc = 9;
|
||||
if (what != ROMFS_NEED_LAYOUT) argv[argc++] = "--prompts", argv[argc++] = style;
|
||||
if (what != ROMFS_NEED_PROMPTS) {
|
||||
argv[argc++] = "--aspect", argv[argc++] = size;
|
||||
argv[argc++] = "--hud", argv[argc++] = hud;
|
||||
}
|
||||
// The shaped prompts differ from their 16:9 folder in the UI archive alone, so its fonts are linked, not
|
||||
// compressed again; a 16:9 folder still being made has nothing to link yet.
|
||||
if (what == ROMFS_NEED_SHAPED_PROMPTS && !(need & ROMFS_NEED_PROMPTS)) {
|
||||
snprintf(reuse, sizeof reuse, "%s/%s", dir, prompts_folder);
|
||||
argv[argc++] = "--reuse", argv[argc++] = reuse;
|
||||
}
|
||||
if (pc && what != ROMFS_NEED_LAYOUT) argv[argc++] = "--binds", argv[argc++] = binds;
|
||||
argv[argc] = NULL;
|
||||
if (shape_spawn(argv, dir, folder)) started++;
|
||||
else failed++;
|
||||
}
|
||||
snprintf(reuse, sizeof reuse, "%s/%s/manifest.tsv", dir, prompts_folder ? prompts_folder : "");
|
||||
if (prompts_folder && plat_file_exists(reuse) && !shaped_name(dir, prompts_folder, w, h, name, sizeof name)) {
|
||||
const char *style = prompts_folder + strlen("romfs-patches-");
|
||||
snprintf(reuse, sizeof reuse, "%s/%s", dir, prompts_folder);
|
||||
snprintf(folder, sizeof folder, "%s-%s", prompts_folder, size);
|
||||
snprintf(out, sizeof out, "%s/%s", dir, folder);
|
||||
// The keyboard and mouse prompts are drawn from totk.ini's bind_ lines, as the setup's PcPrompts and Shapes
|
||||
// steps draw them (installer/steps.py pc_binds); a file without such lines gives the keyboard defaults.
|
||||
snprintf(binds, sizeof binds, "%s/totk.ini", dir);
|
||||
int pc = !strcmp(style, "pc") && plat_file_exists(binds);
|
||||
const char *argv[] = {python, script, "--version", version, "--romfs", romfs, "--out", out, "--prompts", style,
|
||||
"--aspect", size, "--reuse", reuse, pc ? "--binds" : NULL, binds, NULL};
|
||||
if (shape_spawn(argv, dir, folder)) started++;
|
||||
else failed++;
|
||||
}
|
||||
rt_log("RomFS overlay: making the layout for %s in the background (%d generators running, %d failed; %s)", size,
|
||||
started, failed, script);
|
||||
rt_log("RomFS overlay: making %d missing folder%s for %ux%u%s%s in the background (%d failed to start; %s)",
|
||||
started + failed, started + failed == 1 ? "" : "s", w, h, style ? ", prompts " : "", style ? style : "",
|
||||
failed, script);
|
||||
return started && !failed;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,12 +7,13 @@ layout(local_size_x = 8, local_size_y = 8) in;
|
||||
|
||||
layout(binding = 0) uniform sampler2D lin_depth; // the game's linear depth: view distance / far
|
||||
layout(binding = 1, r11f_g11f_b10f) uniform image2D scene; // the lit scene colour, darkened in place
|
||||
layout(binding = 2) uniform sampler2D sun_vis; // half-resolution lighting: alpha is sun visibility
|
||||
|
||||
layout(push_constant) uniform Params {
|
||||
vec4 proj; // projection x scale, y scale, far plane, strength (0..1)
|
||||
vec4 light; // view-space direction toward the sun (xyz), march length in metres at 10 m (w)
|
||||
vec4 size; // width, height, 1/width, 1/height
|
||||
vec4 opt; // x: debug (1: write the shadow factor as grey)
|
||||
vec4 opt; // x: debug (1: the shadow factor as grey, 2: the sun visibility), y: 1 with sun_vis bound
|
||||
} pc;
|
||||
|
||||
vec3 view_pos(vec2 uv, float z) { // z: distance in front of the camera
|
||||
@@ -58,6 +59,14 @@ void main() {
|
||||
float z = d * pc.proj.z;
|
||||
if (z > 80.0) return;
|
||||
vec2 uv = (vec2(px) + 0.5) * pc.size.zw;
|
||||
// Direct sunlight on this pixel as the game's lighting found it: 0 in the shadow maps' shadow and underground, where
|
||||
// darkening would take away ambient light and texture detail (flat caves). Without that pass every pixel counts as lit.
|
||||
float vis = pc.opt.y > 0.5 ? textureLod(sun_vis, uv, 0.0).a : 1.0;
|
||||
if (pc.opt.x > 1.5) {
|
||||
imageStore(scene, px, vec4(vis, vis, vis, 1.0));
|
||||
return;
|
||||
}
|
||||
if (vis <= 0.0 && pc.opt.x < 0.5) return;
|
||||
vec3 p = view_pos(uv, z);
|
||||
// A contact shadow can only take away direct sunlight, and a surface turned away from the sun gets none: its march
|
||||
// runs into the surface itself at once, and darkening it would darken the ambient light and the fog the composite
|
||||
@@ -84,7 +93,7 @@ void main() {
|
||||
}
|
||||
}
|
||||
float fade = 1.0 - smoothstep(40.0, 80.0, z);
|
||||
float k = 1.0 - pc.proj.w * occ * fade * lit;
|
||||
float k = 1.0 - pc.proj.w * occ * fade * lit * vis;
|
||||
if (pc.opt.x > 0.5) {
|
||||
imageStore(scene, px, vec4(k, k, k, 1.0));
|
||||
return;
|
||||
|
||||
+18
-4
@@ -3,6 +3,8 @@
|
||||
// The SVC entry of the lifted code: preemption checkpoint, trace, then the thread and
|
||||
// synchronization SVCs (kernel.c), IPC (ipc.c), memory (memory.c), Break, OutputDebugString, GetInfo and ExitProcess. The 21 SVCs
|
||||
// TotK has but never reaches on MNG's boot path stop with a named fatal, the caller and the guest backtrace.
|
||||
// GetSystemTick, GetInfo 65001 and Map/UnmapProcessMemory are for mod plugins (exlaunch): the game calls none of them,
|
||||
// and process memory is mapped only in the plugin service run (plugin_init.c).
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
@@ -17,9 +19,13 @@
|
||||
#define ST_STACK 0xBu
|
||||
#define PERM_RW 3u
|
||||
#define PROGRAM_ID 0x0100f2c0115b6000ull
|
||||
#define CUR_PROCESS 0xFFFF8001u // Horizon's pseudo handle of the current process
|
||||
|
||||
static uint64_t g_svcs;
|
||||
void (*volatile svc_test_exit_hook)(unsigned code);
|
||||
uint64_t rt_svc_tick_offset;
|
||||
int (*rt_plugin_svc)(Cpu *c, uint32_t imm, uint64_t pc);
|
||||
uint32_t (*rt_process_memory)(int unmap, uint64_t dst, uint32_t process, uint64_t src, uint64_t size);
|
||||
|
||||
RtStats rt_stats(void) {
|
||||
return (RtStats){__atomic_load_n(&g_svcs, __ATOMIC_RELAXED), kern_threads_created(), hostfn_calls()};
|
||||
@@ -121,6 +127,7 @@ static void get_info(Cpu *c, uint64_t pc) {
|
||||
case 18: v = PROGRAM_ID; break;
|
||||
case 20: v = user_exception_context(); break; // the SDK keeps e.g. the dying message at +0x1C0
|
||||
case 23: v = 1; break;
|
||||
case 65001: v = CUR_PROCESS; break; // Mesosphere's current process handle (exlaunch's way to its own memory)
|
||||
default: {
|
||||
char why[64];
|
||||
snprintf(why, sizeof why, "GetInfo id %u (handle %#x, sub id %#llx)", id, (uint32_t)c->x[2],
|
||||
@@ -151,11 +158,13 @@ void rt_svc(Cpu *c, uint32_t imm, uint64_t pc) {
|
||||
|
||||
static void svc_body(Cpu *c, uint32_t imm, uint64_t pc) {
|
||||
__atomic_fetch_add(&g_svcs, 1, __ATOMIC_RELAXED);
|
||||
if (rt_trace & RT_TRACE_SVC) {
|
||||
if (rt_trace & (RT_TRACE_SVC | RT_TRACE_PLUGIN)) {
|
||||
if ((rt_trace & RT_TRACE_PLUGIN) && rt_plugin_svc && rt_plugin_svc(c, imm, pc)) return; // refused, x0 set
|
||||
char at[160];
|
||||
rt_log("svc %#x at %s x0=%#llx x1=%#llx x2=%#llx x3=%#llx", imm, ldr_describe(pc, at, sizeof at),
|
||||
(unsigned long long)c->x[0], (unsigned long long)c->x[1], (unsigned long long)c->x[2],
|
||||
(unsigned long long)c->x[3]);
|
||||
if (rt_trace & RT_TRACE_SVC)
|
||||
rt_log("svc %#x at %s x0=%#llx x1=%#llx x2=%#llx x3=%#llx", imm, ldr_describe(pc, at, sizeof at),
|
||||
(unsigned long long)c->x[0], (unsigned long long)c->x[1], (unsigned long long)c->x[2],
|
||||
(unsigned long long)c->x[3]);
|
||||
}
|
||||
if (kern_svc(c, imm)) return;
|
||||
uint64_t *x = c->x;
|
||||
@@ -210,6 +219,11 @@ static void svc_body(Cpu *c, uint32_t imm, uint64_t pc) {
|
||||
return;
|
||||
}
|
||||
case 0x29: get_info(c, pc); return;
|
||||
case 0x1E: x[0] = rt_ticks() + rt_svc_tick_offset; return; // GetSystemTick (19.2 MHz)
|
||||
case 0x74: case 0x75: // MapProcessMemory / UnmapProcessMemory(x0 dst, w1 process, x2 src, x3 size)
|
||||
if (!rt_process_memory) svc_fatal(c, imm, pc, "process memory is mapped only in the plugin service run");
|
||||
x[0] = rt_process_memory(imm == 0x75, x[0], (uint32_t)x[1], x[2], x[3]);
|
||||
return;
|
||||
case 0x07: { // ExitProcess, as closing the window (gfx_window_closed): pipeline cache, shader records and
|
||||
// profile saved, logs flushed, exit code 0
|
||||
char at[160];
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// gamepad cells show and change the table of the button layout in use (TOTK_PAD_LAYOUT).
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
|
||||
#include "imgui.h"
|
||||
#include "ui/binds_page.h"
|
||||
@@ -34,16 +35,22 @@ static const int kButtons[] = {B_A, B_B, B_X, B_Y, B_L, B_R, B_ZL, B_ZR, B_STICK
|
||||
static const int kMove[] = {B_SL_UP, B_SL_DOWN, B_SL_LEFT, B_SL_RIGHT};
|
||||
static const int kCamera[] = {B_SR_UP, B_SR_DOWN, B_SR_LEFT, B_SR_RIGHT};
|
||||
|
||||
// A key setting's row (binds_key_row) waits as this action, with the setting and its label beside it
|
||||
enum { ACTION_SETTING = ACTION_COUNT };
|
||||
static struct {
|
||||
int action = -1, cell; // the cell waiting for a press (0, 1 keys, 2 the controller); action -1 none
|
||||
bool reset; // the next capture poll takes what is held as the start
|
||||
uint64_t start, done; // plat_now_ns of the start and of the press, timeout or Esc (0 still waiting)
|
||||
const char *setting; // ACTION_SETTING: the TOTK_ name the key goes to
|
||||
UiTextId label; // and its row's label
|
||||
} g_cap;
|
||||
static char g_note[160]; // what the last change took or swapped, after its row's description
|
||||
static int g_note_action = -1;
|
||||
static uint64_t g_note_until;
|
||||
|
||||
static const char *action_label(int a) { return menu_text((UiTextId)(UI_BIND_A + a)); }
|
||||
static const char *action_label(int a) {
|
||||
return a == ACTION_SETTING ? menu_text(g_cap.label) : menu_text((UiTextId)(UI_BIND_A + a));
|
||||
}
|
||||
|
||||
static UiTextId action_desc(int a) {
|
||||
if (a <= B_MINUS) return (UiTextId)(UI_BIND_DESC_A + a);
|
||||
@@ -85,9 +92,23 @@ static const char *key_label(int k, char *buf, size_t n) {
|
||||
return buf;
|
||||
}
|
||||
|
||||
// A gamepad button: the label the open pad has on a face button, else its place on the pad.
|
||||
// A gamepad button: the label the open pad has on a face button, else its place on the pad. A PlayStation pad (its
|
||||
// bottom button labelled Cross, DualSense and DualShock 4 alike) has its shoulder, stick and menu buttons named as
|
||||
// printed on it, the names the PlayStation prompts draw (tools/button_icons.py playstation_icons: Share for Minus).
|
||||
static const char *pad_label(int p) {
|
||||
if (p == PAD_NONE) return "";
|
||||
if (input_pad_label(PAD_SOUTH) == PAD_LABEL_CROSS) {
|
||||
switch (p) {
|
||||
case PAD_L: return "L1";
|
||||
case PAD_R: return "R1";
|
||||
case PAD_ZL: return "L2";
|
||||
case PAD_ZR: return "R2";
|
||||
case PAD_LSTICK: return "L3";
|
||||
case PAD_RSTICK: return "R3";
|
||||
case PAD_START: return "Options";
|
||||
case PAD_BACK: return "Share";
|
||||
}
|
||||
}
|
||||
switch (input_pad_label(p)) {
|
||||
case PAD_LABEL_A: return "A";
|
||||
case PAD_LABEL_B: return "B";
|
||||
@@ -196,7 +217,11 @@ static void capture_window(void) {
|
||||
if (!g_cap.done) {
|
||||
int id = 0, got = input_capture(g_cap.reset, &id);
|
||||
g_cap.reset = false;
|
||||
if (got == INPUT_CAPTURE_KEY && !pad_cell) change(g_cap.action, g_cap.cell, id);
|
||||
if (got == INPUT_CAPTURE_KEY && g_cap.action == ACTION_SETTING) {
|
||||
cfg_set(g_cap.setting, input_key_name(id));
|
||||
opt_save_soon();
|
||||
rt_log("menu: %s = %s", g_cap.setting + 5, input_key_name(id));
|
||||
} else if (got == INPUT_CAPTURE_KEY && !pad_cell) change(g_cap.action, g_cap.cell, id);
|
||||
if (got == INPUT_CAPTURE_PAD && pad_cell) change(g_cap.action, g_cap.cell, id);
|
||||
if (got != INPUT_CAPTURE_NONE && !(got == INPUT_CAPTURE_KEY && pad_cell)) g_cap.done = now;
|
||||
if (now - g_cap.start > CAPTURE_SECONDS * 1000000000ull) g_cap.done = now;
|
||||
@@ -213,7 +238,8 @@ static void capture_window(void) {
|
||||
if (g_cap.done && now - g_cap.done > kDoneNs) {
|
||||
ImGui::CloseCurrentPopup();
|
||||
char id[48];
|
||||
snprintf(id, sizeof id, "BIND_%s#%d", input_action_name(g_cap.action), g_cap.cell);
|
||||
if (g_cap.action == ACTION_SETTING) snprintf(id, sizeof id, "%s#0", g_cap.setting + 5);
|
||||
else snprintf(id, sizeof id, "BIND_%s#%d", input_action_name(g_cap.action), g_cap.cell);
|
||||
opt_focus_key(id); // back on the cell it came from
|
||||
g_cap.action = -1;
|
||||
}
|
||||
@@ -223,6 +249,29 @@ static void capture_window(void) {
|
||||
|
||||
bool binds_modal(void) { return g_cap.action >= 0; }
|
||||
|
||||
// A key setting (quick save's keys): its key in the first cell, taken by the same capture window as a binding's key;
|
||||
// Delete, Backspace or X sets it to none. The other two cells stay empty (no controller button for it). note: e.g. the
|
||||
// binding that also uses the key.
|
||||
void binds_key_row(const char *setting, UiTextId label, UiTextId desc, const char *note) {
|
||||
const char *cur = cfg_value(setting);
|
||||
int key = KEY_NONE;
|
||||
for (int k = KEY_A; k < KEY_COUNT && key == KEY_NONE; k++)
|
||||
if (input_key_name(k) && !strcasecmp(input_key_name(k), cur)) key = k;
|
||||
char b[48];
|
||||
const char *cells[3] = {key != KEY_NONE ? key_label(key, b, sizeof b) : strcasecmp(cur, "none") ? cur : "", "", ""};
|
||||
const bool enabled[3] = {true, false, false};
|
||||
int r = opt_bind_row(setting + 5, menu_text(label), desc, cells, enabled, note);
|
||||
if (g_cap.action >= 0 || r < 0) return;
|
||||
if (r == 0) {
|
||||
g_cap.action = ACTION_SETTING, g_cap.cell = 0, g_cap.setting = setting, g_cap.label = label;
|
||||
g_cap.reset = true, g_cap.start = plat_now_ns(), g_cap.done = 0;
|
||||
} else if (r == 10) {
|
||||
cfg_set(setting, "none");
|
||||
opt_save_soon();
|
||||
rt_log("menu: %s = none", setting + 5);
|
||||
}
|
||||
}
|
||||
|
||||
static bool g_reset_asked; // the reset row was chosen this frame (acted on after the page)
|
||||
|
||||
void binds_rows(float scale) {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
// The remapping rows of the menu's Controls tab (ui/binds_page.cpp). Present path only (ImGui).
|
||||
#pragma once
|
||||
|
||||
extern "C" {
|
||||
#include "ui_text.h"
|
||||
}
|
||||
|
||||
// Inside the page's opt_begin / opt_end: every action's two keys and its controller button, remapped by selecting a
|
||||
// cell and pressing the new one, and the reset of them all. binds_after_page, after opt_end: the window that waits for
|
||||
// the press.
|
||||
@@ -8,3 +12,6 @@ void binds_rows(float scale);
|
||||
void binds_after_page(void);
|
||||
// A cell waits for a press (or its press is still reaching the menu): B, Esc, L / R and the tab keys stay on the page.
|
||||
bool binds_modal(void);
|
||||
// A key setting (TOTK_ name) as a row of one key cell, set by pressing the key as a binding's cell is; Delete sets it
|
||||
// to none. note (NULL none) follows the description.
|
||||
void binds_key_row(const char *setting, UiTextId label, UiTextId desc, const char *note);
|
||||
+238
-59
@@ -499,6 +499,73 @@ static void row_window_size(void) {
|
||||
opt_choice_list("TOTK_WINDOW_SIZE", UI_MENU_WINDOW_SIZE, pv, pn, n, UI_MENU_WINDOW_SIZE_DESC);
|
||||
}
|
||||
|
||||
// ---- the folders the next start needs (romfs.c romfs_folders_missing): a game resolution of another shape needs its
|
||||
// layout's folder, and Xbox, PlayStation or PC prompts their folder, at that shape too. The setup writes them for the
|
||||
// displays it saw and the prompts totk.ini had then (installer/steps.py Prepare, PcPrompts, Shapes). When the
|
||||
// resolution, the HUD width, the prompts or the pad layout ask for one it lacks, the generator starts for the next
|
||||
// start (romfs_folders_prepare: child processes, the menu does not wait), once per request: a request stays the same
|
||||
// for SETTLE_NS first, so stepping through the sizes starts none for the ones passed. The notes under the resolution
|
||||
// and the prompts say so (row_output_res, prompts_note); when it could not start they say that and offer a retry. The
|
||||
// file checks run only when the request changes, after a settings change (cfg_version).
|
||||
enum { SETTLE_NS = 1500000000 };
|
||||
static struct {
|
||||
unsigned seen; // cfg_version of the last look at the settings
|
||||
char request[160]; // output_res|hud_width|prompts folder in the settings
|
||||
unsigned w, h;
|
||||
const char *want; // input_prompts_folder of the settings (a string literal), NULL for the game's own
|
||||
int missing; // ROMFS_NEED_* for request
|
||||
uint64_t at; // plat_now_ns from which request starts; 0 none waiting
|
||||
char asked[160]; // the request started last
|
||||
int started; // for asked: 1 running, -1 failed to start
|
||||
} g_folders = {~0u, "", 0, 0, nullptr, 0, 0, "", 0};
|
||||
|
||||
static void folders_start(void) {
|
||||
g_folders.at = 0;
|
||||
snprintf(g_folders.asked, sizeof g_folders.asked, "%s", g_folders.request);
|
||||
g_folders.started = romfs_folders_prepare(g_folders.w, g_folders.h, g_folders.want) ? 1 : -1;
|
||||
}
|
||||
|
||||
// On every frame the menu lays out (now: start a waiting request at once, as the menu closes). 1 while a request
|
||||
// waits.
|
||||
static int folders_tick(bool now) {
|
||||
unsigned v = cfg_version();
|
||||
if (v != g_folders.seen) {
|
||||
g_folders.seen = v;
|
||||
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
|
||||
const char *want = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
|
||||
// Without an output_res the display's shape: the default falls back to 1920x1080 while that shape lacks the
|
||||
// prompts' folder, and the folders made for it bring the shape back at the next start (cfg_screen_size).
|
||||
unsigned s[2] = {0, 0};
|
||||
if (!cfg_screen_size(s) && sscanf(cfg_value("TOTK_OUTPUT_RES"), "%ux%u", &s[0], &s[1]) != 2) s[0] = s[1] = 0;
|
||||
char request[sizeof g_folders.request];
|
||||
snprintf(request, sizeof request, "%ux%u|%s|%s", s[0], s[1], cfg_value("TOTK_HUD_WIDTH"), want ? want : "");
|
||||
if (strcmp(request, g_folders.request)) {
|
||||
snprintf(g_folders.request, sizeof g_folders.request, "%s", request);
|
||||
unsigned w = s[0], h = s[1];
|
||||
g_folders.w = w, g_folders.h = h, g_folders.want = want;
|
||||
g_folders.missing = w && h ? romfs_folders_missing(w, h, want) : 0;
|
||||
g_folders.at = g_folders.missing && strcmp(request, g_folders.asked) && romfs_folders_can_prepare()
|
||||
? plat_now_ns() + SETTLE_NS : 0;
|
||||
}
|
||||
}
|
||||
if (!g_folders.at || (!now && plat_now_ns() < g_folders.at)) return g_folders.at != 0;
|
||||
folders_start();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// What happens to the folders of the request in the settings that need (a mask of ROMFS_NEED_*): 0 none missing or
|
||||
// no tools to make them, 1 being made (or about to start), -1 the generator did not start.
|
||||
static int folders_state(int need) {
|
||||
if (!(g_folders.missing & need)) return 0;
|
||||
if (g_folders.at) return 1;
|
||||
return g_folders.started && !strcmp(g_folders.asked, g_folders.request) ? g_folders.started : 0;
|
||||
}
|
||||
|
||||
// The retry under a row whose folders did not start.
|
||||
static void folders_retry(const char *id, int need) {
|
||||
if (folders_state(need) < 0 && opt_button(id, UI_MENU_PREPARE_RETRY, UI_MENU_PREPARE_RETRY_DESC)) folders_start();
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -518,35 +585,33 @@ static void row_output_res(void) {
|
||||
snprintf(shown[i], sizeof shown[i], "%d × %d", w, h); // U+00D7, the multiplication sign
|
||||
names[i] = shown[i];
|
||||
}
|
||||
// A size of another shape needs that shape's folders (romfs.c overlay_init): the layout, and with Xbox or PC
|
||||
// prompts the prompts' one too. The setup writes them for the displays it saw (installer/steps.py Shapes); at a
|
||||
// shape without them the game draws 16:9 with bars or keeps the Switch prompts, so the row says so and offers to
|
||||
// start the generator for the next start (romfs_shape_prepare; a child process, the menu does not wait). The file
|
||||
// checks run again only when a setting or the started generation changes.
|
||||
static unsigned seen = ~0u;
|
||||
static int missing, started; // started: 0 not asked, 1 running, -1 failed to start
|
||||
static char asked[16];
|
||||
const char *now = cfg_value("TOTK_OUTPUT_RES");
|
||||
if (seen != cfg_version()) {
|
||||
seen = cfg_version();
|
||||
unsigned w = 0, h = 0;
|
||||
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
|
||||
const char *want = input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout);
|
||||
missing = sscanf(now, "%ux%u", &w, &h) == 2 && romfs_shape_missing(w, h, want);
|
||||
}
|
||||
int here = started && !strcmp(asked, now); // the generation started for the value shown
|
||||
const char *note = !missing ? nullptr
|
||||
: here ? menu_text(started > 0 ? UI_MENU_OUTPUT_RES_PREPARING : UI_MENU_SHAPE_PREPARE_FAILED)
|
||||
: menu_text(UI_MENU_OUTPUT_RES_NO_LAYOUT);
|
||||
// A size of another shape needs that shape's folders (romfs.c overlay_init): the layout, and with Xbox,
|
||||
// PlayStation or PC prompts the prompts' one too. Without them the game draws 16:9 with bars or keeps the Switch
|
||||
// prompts; folders_tick starts their generator, and the row says they are being made, or that the setup's tools
|
||||
// are missing or did not start.
|
||||
const int need = ROMFS_NEED_LAYOUT | ROMFS_NEED_SHAPED_PROMPTS;
|
||||
int state = folders_state(need);
|
||||
const char *note = !(g_folders.missing & need) ? nullptr
|
||||
: state > 0 ? menu_text(UI_MENU_OUTPUT_RES_PREPARING)
|
||||
: state < 0 ? menu_text(UI_MENU_SHAPE_PREPARE_FAILED)
|
||||
: menu_text(UI_MENU_OUTPUT_RES_NO_LAYOUT);
|
||||
opt_choice_list("TOTK_OUTPUT_RES", UI_MENU_OUTPUT_RES, vals, names, N, UI_MENU_OUTPUT_RES_DESC, -1, note);
|
||||
if (!missing || here || !romfs_shape_can_prepare()) return;
|
||||
if (!opt_button("##shape_prepare", UI_MENU_SHAPE_PREPARE, UI_MENU_SHAPE_PREPARE_DESC)) return;
|
||||
unsigned w = 0, h = 0;
|
||||
const char *layout = cfg_value("TOTK_PAD_LAYOUT");
|
||||
sscanf(now, "%ux%u", &w, &h);
|
||||
snprintf(asked, sizeof asked, "%s", now);
|
||||
started = romfs_shape_prepare(w, h, input_prompts_folder(input_prompts_pick(cfg_get("TOTK_PROMPTS"), layout), layout))
|
||||
? 1 : -1;
|
||||
folders_retry("##shape_prepare", need);
|
||||
}
|
||||
|
||||
// Offer only caps narrower than the canonical layout, using the same tolerance as romfs.c hud_suffix and Shapes.
|
||||
// This also keeps a selected 21:9 cap visible after changing to a slightly wider-than-21:9 game resolution.
|
||||
static void row_hud_width(void) {
|
||||
unsigned w = 0, h = 0, shape[2];
|
||||
if (sscanf(cfg_value("TOTK_OUTPUT_RES"), "%ux%u", &w, &h) != 2 || !h) return;
|
||||
shape[0] = w, shape[1] = h;
|
||||
cfg_shape_size(w, h, shape);
|
||||
double aspect = (double)shape[0] / shape[1];
|
||||
if (16.0 / 9 >= aspect * 0.99) return;
|
||||
const char *vals[3] = {"full", "21:9", "16:9"}, *names[3] = {menu_text(UI_MENU_HUD_WIDTH_FULL), "21:9", "16:9"};
|
||||
int n = 21.0 / 9 < aspect * 0.99 ? 3 : 2;
|
||||
if (n == 2) vals[1] = vals[2], names[1] = names[2];
|
||||
opt_choice_list("TOTK_HUD_WIDTH", UI_MENU_HUD_WIDTH, vals, names, n, UI_MENU_HUD_WIDTH_DESC);
|
||||
}
|
||||
|
||||
static void row_render_scale(void) {
|
||||
@@ -705,6 +770,7 @@ static void tab_screen(float scale) {
|
||||
opt_choice("TOTK_PERF_OVERLAY", UI_MENU_PERF_OVERLAY, perf, 3, UI_MENU_PERF_OVERLAY_DESC);
|
||||
opt_group(UI_MENU_GRAPHICS);
|
||||
row_output_res();
|
||||
row_hud_width();
|
||||
row_render_scale();
|
||||
opt_toggle("TOTK_DYNAMIC_RES", UI_MENU_DYNAMIC_RES, UI_MENU_DYNAMIC_RES_DESC);
|
||||
row_shadow_res();
|
||||
@@ -734,6 +800,8 @@ static void tab_screen(float scale) {
|
||||
static const UiTextId chars[] = {UI_MENU_DLSS_CHARS_OFF, UI_MENU_DLSS_CHARS_LIGHT, UI_MENU_DLSS_CHARS_MEDIUM,
|
||||
UI_MENU_DLSS_CHARS_FULL};
|
||||
opt_choice("TOTK_DLSS_CHAR_MASK", UI_MENU_DLSS_CHARS, chars, 4, UI_MENU_DLSS_CHARS_DESC);
|
||||
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);
|
||||
opt_toggle("TOTK_FXAA", UI_MENU_FXAA, UI_MENU_FXAA_DESC);
|
||||
@@ -838,6 +906,21 @@ static int key_action(const InputMap *m, int key) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// "also <action>" when the bindings also use the key the setting names, else NULL; note holds the text
|
||||
static const char *key_taken(const char *setting, char *note, size_t size) {
|
||||
const char *cur = cfg_value(setting);
|
||||
InputMap m;
|
||||
input_map_snapshot(&m);
|
||||
for (int k = KEY_A; k < KEY_COUNT; k++) {
|
||||
if (!input_key_name(k) || strcasecmp(input_key_name(k), cur)) continue;
|
||||
int a = key_action(&m, k);
|
||||
if (a < 0 || !input_action_name(a)) return nullptr;
|
||||
snprintf(note, size, menu_text(UI_MENU_WALK_KEY_TAKEN), input_action_name(a));
|
||||
return note;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// The walk key as the handful of keys a player is likely to pick. "none" rather than an empty value closes it: an
|
||||
// unset key falls back to the default in the settings table, the same as a fresh installation. totk.ini takes any name
|
||||
// input_map.c knows (walks of the keyboard sticks, not of the gamepad). A key the current bindings also use says which
|
||||
@@ -845,26 +928,29 @@ static int key_action(const InputMap *m, int key) {
|
||||
static void row_walk_key(void) {
|
||||
static const char *const keys[] = {"none", "lshift", "lalt", "lctrl", "tab", "capslock"};
|
||||
const char *names[sizeof keys / sizeof *keys] = {menu_text(UI_MENU_OFF), "Shift", "Alt", "Ctrl", "Tab", "Caps Lock"};
|
||||
const char *cur = cfg_value("TOTK_WALK_KEY");
|
||||
static char note[64];
|
||||
const char *n = nullptr;
|
||||
InputMap m;
|
||||
input_map_snapshot(&m);
|
||||
for (int k = KEY_A; k < KEY_COUNT && !n; k++) {
|
||||
if (!input_key_name(k) || strcasecmp(input_key_name(k), cur)) continue;
|
||||
int a = key_action(&m, k);
|
||||
if (a >= 0 && input_action_name(a)) snprintf(note, sizeof note, menu_text(UI_MENU_WALK_KEY_TAKEN), input_action_name(a)), n = note;
|
||||
}
|
||||
opt_choice_list("TOTK_WALK_KEY", UI_MENU_WALK_KEY, keys, names, sizeof keys / sizeof *keys, UI_MENU_WALK_KEY_DESC,
|
||||
-1, n);
|
||||
-1, key_taken("TOTK_WALK_KEY", note, sizeof note));
|
||||
}
|
||||
|
||||
// Quick save's two keys (quicksave.c), F6 and F7 by default as Half-Life has them: any key or mouse button, taken by
|
||||
// the bindings' capture window (binds_key_row); Delete leaves that one without a key. A key the bindings also use says
|
||||
// which action it presses: while quick save is on it no longer does.
|
||||
static void row_quicksave_keys(void) {
|
||||
static char note[2][64];
|
||||
binds_key_row("TOTK_QUICKSAVE_KEY", UI_MENU_QUICKSAVE_KEY, UI_MENU_QUICKSAVE_KEY_DESC,
|
||||
key_taken("TOTK_QUICKSAVE_KEY", note[0], sizeof note[0]));
|
||||
binds_key_row("TOTK_QUICKLOAD_KEY", UI_MENU_QUICKLOAD_KEY, UI_MENU_QUICKSAVE_KEY_DESC,
|
||||
key_taken("TOTK_QUICKLOAD_KEY", note[1], sizeof note[1]));
|
||||
}
|
||||
|
||||
// The note under the prompts. The settings name a folder of prompts (input_prompts_folder: the prompts and the pad
|
||||
// layout, as a layout that puts A on the right button needs the face buttons named the other way round), but the game
|
||||
// reads its fonts and UI archive once at start (romfs.c overlay_init). While the folder in use differs: "files
|
||||
// missing" when the setup did not write the one asked for, why it was left out at start (damaged, a game resolution
|
||||
// that is not 16:9, a RomFS mod with the same files, TOTK_ROMFS_PATCHES), else "prompts change after restart", and only then
|
||||
// *restart is set: a restart would bring the prompts asked for. NULL when they match.
|
||||
// reads its fonts and UI archive once at start (romfs.c overlay_init). While the folder in use differs: when the
|
||||
// install lacks the one asked for (folders_tick looked), that it is being made in the background, or that it is
|
||||
// missing (no setup's tools) or could not be made; else why it was left out at start (damaged, a RomFS mod with the
|
||||
// same files, TOTK_ROMFS_PATCHES), else "prompts change after restart", and only then *restart is set: a restart would
|
||||
// bring the prompts asked for. NULL when they match.
|
||||
static const char *prompts_note(bool *restart) {
|
||||
*restart = false;
|
||||
const char *layout = cfg_value("TOTK_PAD_LAYOUT"), *used = romfs_prompts();
|
||||
@@ -872,12 +958,15 @@ static const char *prompts_note(bool *restart) {
|
||||
if (want == used || (want && used && !strcmp(want, used))) return nullptr;
|
||||
// A game resolution of another shape needs a folder of its own for the prompts (<folder>-<w>x<h>, one per shape).
|
||||
// The setup writes it for the shapes of the displays it saw and the prompts totk.ini had then; at another shape
|
||||
// the shape is the reason (row_output_res offers to make it), not a damaged install.
|
||||
int off = romfs_prompts_off(want);
|
||||
if (want && !romfs_prompts_ready(want) && off != ROMFS_PROMPTS_SHAPE) return menu_text(UI_MENU_PROMPTS_MISSING);
|
||||
switch (off) {
|
||||
// the shape is the reason, not a damaged install.
|
||||
int need = g_folders.missing & (ROMFS_NEED_PROMPTS | ROMFS_NEED_SHAPED_PROMPTS), state = folders_state(need);
|
||||
if (state > 0) return menu_text(UI_MENU_PROMPTS_PREPARING);
|
||||
if (state < 0) return menu_text(UI_MENU_SHAPE_PREPARE_FAILED);
|
||||
if (need & ROMFS_NEED_PROMPTS) return menu_text(UI_MENU_PROMPTS_MISSING);
|
||||
if (need) return menu_text(UI_MENU_PROMPTS_OFF_SHAPE);
|
||||
// ROMFS_PROMPTS_MISSING and _SHAPE: the folder the start lacked is there now, or the resolution needs another one
|
||||
switch (romfs_prompts_off(want)) {
|
||||
case ROMFS_PROMPTS_FAILED: return menu_text(UI_MENU_PROMPTS_FAILED);
|
||||
case ROMFS_PROMPTS_SHAPE: return menu_text(UI_MENU_PROMPTS_OFF_SHAPE);
|
||||
case ROMFS_PROMPTS_MODS: return menu_text(UI_MENU_PROMPTS_OFF_MODS);
|
||||
case ROMFS_PROMPTS_PATCHES: return menu_text(UI_MENU_PROMPTS_OFF_PATCHES);
|
||||
default: *restart = true; return menu_text(UI_MENU_PROMPTS_RESTART);
|
||||
@@ -954,10 +1043,12 @@ static void tab_controls(float scale) {
|
||||
opt_begin("##controls", scale);
|
||||
static const UiTextId layout[] = {UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO, UI_MENU_PAD_LAYOUT_XBOX};
|
||||
opt_choice("TOTK_PAD_LAYOUT", UI_MENU_PAD_LAYOUT, layout, 3, UI_MENU_PAD_LAYOUT_DESC, pad_layout_note());
|
||||
static const UiTextId prompts[] = {UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, UI_MENU_PROMPTS_PC};
|
||||
static const UiTextId prompts[] = {UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, UI_MENU_PROMPTS_PLAYSTATION,
|
||||
UI_MENU_PROMPTS_PC};
|
||||
bool restart;
|
||||
const char *note = prompts_note(&restart);
|
||||
opt_choice("TOTK_PROMPTS", UI_MENU_PROMPTS, prompts, 3, UI_MENU_PROMPTS_DESC, note);
|
||||
opt_choice("TOTK_PROMPTS", UI_MENU_PROMPTS, prompts, 4, UI_MENU_PROMPTS_DESC, note);
|
||||
folders_retry("##prompts_prepare", ROMFS_NEED_PROMPTS | ROMFS_NEED_SHAPED_PROMPTS);
|
||||
bool ask = restart && opt_button("##restart", UI_MENU_RESTART, UI_MENU_RESTART_DESC);
|
||||
opt_toggle("TOTK_MOTION", UI_MENU_MOTION, UI_MENU_MOTION_DESC);
|
||||
opt_toggle("TOTK_GYRO_CALIBRATION", UI_MENU_GYRO_CALIBRATION, UI_MENU_GYRO_CALIBRATION_DESC);
|
||||
@@ -978,6 +1069,7 @@ static void tab_controls(float scale) {
|
||||
if (opt_button("##gyro_calib", UI_MENU_GYRO_CALIBRATE, UI_MENU_GYRO_CALIBRATE_DESC, status))
|
||||
input_motion_calibrate();
|
||||
}
|
||||
opt_toggle("TOTK_GYRO_AUTO_BIAS", UI_MENU_GYRO_AUTO_BIAS, UI_MENU_GYRO_AUTO_BIAS_DESC);
|
||||
opt_slider("TOTK_RUMBLE_STRENGTH", UI_MENU_RUMBLE_STRENGTH, 0, 300, UI_MENU_RUMBLE_STRENGTH_DESC, 10, "%.0f %%");
|
||||
opt_slider("TOTK_RUMBLE_CURVE", UI_MENU_RUMBLE_CURVE, 0.2f, 1.5f, UI_MENU_RUMBLE_CURVE_DESC, 0.05f, "%.2f");
|
||||
opt_toggle("TOTK_RUMBLE_TRIGGERS", UI_MENU_RUMBLE_TRIGGERS, UI_MENU_RUMBLE_TRIGGERS_DESC);
|
||||
@@ -988,6 +1080,8 @@ static void tab_controls(float scale) {
|
||||
opt_toggle("TOTK_MAP_CLICK", UI_MENU_MAP_CLICK, UI_MENU_MAP_CLICK_DESC);
|
||||
opt_toggle("TOTK_DIALOGUE_CLICK", UI_MENU_DIALOGUE_CLICK, UI_MENU_DIALOGUE_CLICK_DESC);
|
||||
opt_toggle("TOTK_POINTER_IMAGE", UI_MENU_POINTER_IMAGE, UI_MENU_POINTER_IMAGE_DESC);
|
||||
opt_toggle("TOTK_QUICKSAVE", UI_MENU_QUICKSAVE, UI_MENU_QUICKSAVE_DESC);
|
||||
row_quicksave_keys();
|
||||
row_walk_key();
|
||||
opt_slider("TOTK_WALK_SCALE", UI_MENU_WALK_SCALE, 0.2f, 0.9f, UI_MENU_WALK_SCALE_DESC, 0.01f, "%.2f");
|
||||
rows_gameplay_tweaks();
|
||||
@@ -1241,10 +1335,26 @@ static void tab_mods(float scale) {
|
||||
const char *after = mods_changed() ? menu_text(UI_MENU_AFTER_RESTART) : nullptr;
|
||||
for (int i = 0; i < n; i++) {
|
||||
const ModInfo *m = mods_at(i);
|
||||
char id[32], desc[1536];
|
||||
char id[32], desc[4096];
|
||||
snprintf(id, sizeof id, "##mod%d", i);
|
||||
char over[512] = "", other[512] = "";
|
||||
if (m->overridden) snprintf(over, sizeof over, menu_text(UI_MENU_MODS_OVERRIDDEN), m->overridden, m->overridden_by);
|
||||
char over[2048] = "", other[512] = "";
|
||||
// what it won or lost to another mod, files, data and code alike (the conflict table, as at start)
|
||||
static const UiTextId lost[MOD_PARTS] = {UI_MENU_MODS_OVERRIDDEN, UI_MENU_MODS_DATA_OVERRIDDEN,
|
||||
UI_MENU_MODS_CODE_OVERRIDDEN},
|
||||
won[MOD_PARTS] = {UI_MENU_MODS_OVERRIDES_FILES, UI_MENU_MODS_OVERRIDES_DATA,
|
||||
UI_MENU_MODS_OVERRIDES_CODE};
|
||||
for (int c = 0; c < mods_conflict_count(); c++) {
|
||||
const ModConflict *e = mods_conflict_at(c);
|
||||
bool lose = e->loser == m->id;
|
||||
if (!lose && e->winner != m->id) continue;
|
||||
const ModInfo *them = mods_by_id(lose ? e->winner : e->loser);
|
||||
if (!them) continue;
|
||||
size_t at = strlen(over);
|
||||
if (at) at += (size_t)snprintf(over + at, sizeof over - at, "\n\n");
|
||||
if (at < sizeof over)
|
||||
snprintf(over + at, sizeof over - at, menu_text(lose ? lost[e->part] : won[e->part]), e->count,
|
||||
them->name);
|
||||
}
|
||||
if (m->other_version) snprintf(other, sizeof other, menu_text(UI_MENU_MODS_OTHER_VERSION), m->other_version);
|
||||
char cheat[256] = "";
|
||||
if (m->kind & MOD_CHEATS) { // its cheats as read at start, or the file they come from
|
||||
@@ -1254,14 +1364,33 @@ static void tab_mods(float scale) {
|
||||
if (count) snprintf(cheat, sizeof cheat, menu_text(UI_MENU_MODS_CHEATS), count);
|
||||
else snprintf(cheat, sizeof cheat, menu_text(UI_MENU_MODS_CHEATS_FILE), cheats_file());
|
||||
}
|
||||
char code[512] = "", problem[512] = "";
|
||||
char code[512] = "", problem[768] = "", skipped[512] = "", left[512] = "", plugin[512] = "";
|
||||
if (m->plugin_off[0]) // its plugin's start differed from the build (plugin_init.c)
|
||||
snprintf(plugin, sizeof plugin, menu_text(UI_MENU_MODS_PLUGIN_OFF), m->plugin_off);
|
||||
else if (m->plugin_hooks && m->problem == MOD_OK)
|
||||
snprintf(plugin, sizeof plugin, menu_text(UI_MENU_MODS_PLUGIN_ON), m->plugin_hooks);
|
||||
else if (m->plugin_note[0] && m->problem != MOD_PLUGIN) // used without its code: the refusal stays visible
|
||||
snprintf(plugin, sizeof plugin, menu_text(UI_MENU_MODS_PLUGIN_REFUSED), m->plugin_file, m->plugin_note);
|
||||
if (m->code[0] && m->problem != MOD_PLUGIN) // used without its code
|
||||
snprintf(skipped, sizeof skipped, menu_text(UI_MENU_MODS_CODE_SKIPPED), m->code);
|
||||
if (m->unsupported && m->problem != MOD_EXEFS_UNSUPPORTED)
|
||||
snprintf(left, sizeof left, menu_text(UI_MENU_MODS_EXEFS_SKIPPED), m->unsupported, m->note);
|
||||
if (m->nsets && m->overrides[0])
|
||||
snprintf(code, sizeof code, menu_text(UI_MENU_MODS_REPLACES_BUILTIN), m->nsets, m->overrides);
|
||||
else if (m->nsets || m->ndata)
|
||||
snprintf(code, sizeof code, menu_text(UI_MENU_MODS_EXEFS_ON), m->nsets + m->ndata);
|
||||
switch (m->problem) {
|
||||
case MOD_EMPTY: snprintf(problem, sizeof problem, "%s", menu_text(UI_MENU_MODS_EMPTY)); break;
|
||||
case MOD_PLUGIN: snprintf(problem, sizeof problem, "%s", menu_text(UI_MENU_MODS_SUBSDK)); break;
|
||||
case MOD_PLUGIN:
|
||||
if (m->plugin_note[0]) { // the build refused its plugin, and says why
|
||||
int n = snprintf(problem, sizeof problem, menu_text(UI_MENU_MODS_PLUGIN_REFUSED), m->plugin_file,
|
||||
m->plugin_note);
|
||||
if (n >= 0 && n < (int)sizeof problem)
|
||||
snprintf(problem + n, sizeof problem - n, " %s", menu_text(UI_MENU_MODS_PLUGIN_STAYS_OFF));
|
||||
} else {
|
||||
snprintf(problem, sizeof problem, "%s", menu_text(UI_MENU_MODS_SUBSDK));
|
||||
}
|
||||
break;
|
||||
case MOD_EXEFS_LATER: snprintf(problem, sizeof problem, "%s", menu_text(UI_MENU_MODS_EXEFS_LATER)); break;
|
||||
case MOD_EXEFS_UNSUPPORTED:
|
||||
snprintf(problem, sizeof problem, menu_text(UI_MENU_MODS_EXEFS_UNSUPPORTED), m->note);
|
||||
@@ -1271,7 +1400,8 @@ static void tab_mods(float scale) {
|
||||
default: break;
|
||||
}
|
||||
int k = snprintf(desc, sizeof desc, menu_text(UI_MENU_MODS_ROW_DESC), m->replaced, m->added);
|
||||
const char *parts[] = {over, other, cheat, code, problem, menu_text(UI_MENU_MODS_MOVE_HINT)};
|
||||
const char *parts[] = {over, other, cheat, code, plugin, skipped, left, problem,
|
||||
menu_text(UI_MENU_MODS_MOVE_HINT)};
|
||||
for (const char *part : parts)
|
||||
if (*part && k >= 0 && k < (int)sizeof desc) k += snprintf(desc + k, sizeof desc - k, "\n\n%s", part);
|
||||
const char *note = m->enabled && m->problem != MOD_OK ? menu_text(UI_MENU_MODS_UNUSED) : after;
|
||||
@@ -1285,6 +1415,20 @@ static void tab_mods(float scale) {
|
||||
snprintf(id, sizeof id, "##mod%d", to);
|
||||
opt_focus_key(id); // the cursor follows the mod
|
||||
opt_save_soon();
|
||||
continue; // m is the moved mod's neighbour now; its switch row comes next frame
|
||||
}
|
||||
// under a mod with code the port cannot run (a code module, an ExeFS patch file it cannot apply): its switch
|
||||
// "use without its code"; mods_without_code = 1 holds it on for every mod
|
||||
if (m->code[0] || m->unsupported) {
|
||||
char nid[32], label[320];
|
||||
snprintf(nid, sizeof nid, "##modnc%d", i);
|
||||
snprintf(label, sizeof label, menu_text(UI_MENU_MODS_WITHOUT_CODE), m->name);
|
||||
bool all = cfg_bool("TOTK_MODS_WITHOUT_CODE") != 0;
|
||||
if (all) opt_disable_next(UI_MENU_MODS_WITHOUT_CODE_ALL);
|
||||
if (opt_toggle_text(nid, label, menu_text(UI_MENU_MODS_WITHOUT_CODE_DESC), all || m->no_code) && !all) {
|
||||
mods_set_no_code(i, !m->no_code);
|
||||
opt_save_soon();
|
||||
}
|
||||
}
|
||||
}
|
||||
bool rebuild =
|
||||
@@ -1389,7 +1533,8 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
static int g_save_pending; // a changed setting still waits for its write to totk.ini (opt_save_tick)
|
||||
// a changed setting still waits for its write to totk.ini (opt_save_tick) or for its folders to start (folders_tick)
|
||||
static int g_save_pending;
|
||||
|
||||
// ---- the performance overlay (TOTK_PERF_OVERLAY), in the top right corner. "fps": the frame rate over the presents of
|
||||
// the last half second. "full": a panel of perfmon.c's numbers, in the style of SavageWindRecomp's perf_overlay_draw
|
||||
@@ -1656,6 +1801,37 @@ static void perf_draw(const MenuTarget *t, float scale) {
|
||||
dl->AddText(ImVec2(p.x + pad, p.y + pad), IM_COL32(255, 255, 255, 235), g_perf_text);
|
||||
}
|
||||
|
||||
// ---- a toast: one short line of ui_text at the top centre of the picture, over the game, for a few seconds and fading
|
||||
// out in its last half second (quick save's "Game saved", quicksave.c). Any thread sets it; the overlay draws it.
|
||||
static std::atomic<int> g_toast_text{-1};
|
||||
static std::atomic<uint64_t> g_toast_until{0};
|
||||
extern "C" void menu_toast(int text, int ms) {
|
||||
g_toast_until.store(plat_now_ns() + (uint64_t)(ms > 0 ? ms : 1) * 1000000ull, std::memory_order_relaxed);
|
||||
g_toast_text.store(text, std::memory_order_release);
|
||||
}
|
||||
|
||||
static bool toast_live(void) {
|
||||
return g_toast_text.load(std::memory_order_acquire) >= 0 &&
|
||||
plat_now_ns() < g_toast_until.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
static void toast_draw(const MenuTarget *t, float scale) {
|
||||
int id = g_toast_text.load(std::memory_order_acquire);
|
||||
uint64_t now = plat_now_ns(), until = g_toast_until.load(std::memory_order_relaxed);
|
||||
if (id < 0 || id >= UI_TEXT_COUNT || now >= until) return;
|
||||
double left_ms = (until - now) / 1e6;
|
||||
float a = left_ms < 500 ? (float)(left_ms / 500) : 1.0f;
|
||||
const char *text = ui_text((UiTextId)id);
|
||||
ImDrawList *dl = ImGui::GetForegroundDrawList();
|
||||
ImFont *font = ImGui::GetFont();
|
||||
float size = ImGui::GetFontSize() * 1.25f, pad = 10 * scale;
|
||||
ImVec2 sz = font->CalcTextSizeA(size, FLT_MAX, 0, text);
|
||||
ImVec2 p((t->width - sz.x) / 2 - pad, 48 * scale); // under the top edge, between the hearts and the corner
|
||||
ImVec2 q(p.x + sz.x + 2 * pad, p.y + sz.y + 2 * pad);
|
||||
dl->AddRectFilled(p, q, IM_COL32(0, 0, 0, (int)(160 * a)), 6 * scale);
|
||||
dl->AddText(font, size, ImVec2(p.x + pad, p.y + pad), IM_COL32(255, 255, 255, (int)(240 * a)), text);
|
||||
}
|
||||
|
||||
extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) {
|
||||
*shot = NULL;
|
||||
cheats_frame(frame); // the data cheats and the buttons of the cheats that need them held
|
||||
@@ -1666,14 +1842,15 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
||||
amiibo_tick();
|
||||
bool open = g_open.load(std::memory_order_relaxed);
|
||||
if (!open) {
|
||||
if (g_save_pending) g_save_pending = opt_save_tick(1); // closed: the last change goes to totk.ini now
|
||||
// closed: the last change goes to totk.ini now, and the folders it needs start being made
|
||||
if (g_save_pending) g_save_pending = opt_save_tick(1) | folders_tick(true);
|
||||
if (g_test.at && !g_test.opened && frame >= g_test.at) {
|
||||
g_test.opened = frame;
|
||||
g_test.page = 0;
|
||||
g_tab_request = 0;
|
||||
set_open(1);
|
||||
open = true;
|
||||
} else if (!g_perf_mode) {
|
||||
} else if (!g_perf_mode && !toast_live()) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1723,10 +1900,12 @@ extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const cha
|
||||
}
|
||||
ImGui_ImplVulkan_NewFrame();
|
||||
ImGui::NewFrame();
|
||||
int folders_wait = open ? folders_tick(false) : 0; // before the rows, whose notes it sets
|
||||
if (open) layout_menu(t->width, t->height, scale);
|
||||
perf_draw(t, scale);
|
||||
toast_draw(t, scale);
|
||||
ImGui::Render();
|
||||
if (open) g_save_pending = opt_save_tick(0);
|
||||
if (open) g_save_pending = opt_save_tick(0) | folders_wait;
|
||||
g_cost_ns += plat_now_ns() - t0;
|
||||
if (g_test.page >= 0 && frame >= g_test.opened + g_test.per_page * (uint64_t)(g_test.page + 1)) {
|
||||
static char path[512]; // this frame's image goes to a file; then the next tab, or the menu closes
|
||||
|
||||
@@ -26,6 +26,7 @@ extern "C" {
|
||||
int menu_is_open(void);
|
||||
void menu_toggle(void); // F1 / Esc on the keyboard, Minus+Plus on the pad
|
||||
void menu_perf_cycle(void); // F10: the performance overlay off, fps, full
|
||||
void menu_toast(int text, int ms); // a short line (a UiTextId) at the top of the picture for ms, any thread
|
||||
|
||||
// ---- events from the window adapter, used only while the menu is open. key: an ImGuiKey; coordinates in pixels of the
|
||||
// window's client area, which is the swapchain image.
|
||||
|
||||
+272
-44
@@ -67,6 +67,11 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
||||
"more video memory and GPU time. A wider size (21:9) widens the camera's view and moves "
|
||||
"the HUD to the screen's corners; a taller one (16:10, 3:2) moves it to the top "
|
||||
"and bottom edges.",
|
||||
[UI_MENU_HUD_WIDTH] = "HUD width",
|
||||
[UI_MENU_HUD_WIDTH_DESC] = "On a screen wider than 16:9, how far apart the HUD's left and right sides are. Full puts "
|
||||
"them at the screen's edges; 21:9 or 16:9 keeps the HUD within the middle of the screen "
|
||||
"of that shape. A missing layout is made in the background and used after a restart.",
|
||||
[UI_MENU_HUD_WIDTH_FULL] = "Full screen",
|
||||
[UI_MENU_RENDER_SCALE] = "3D render scale",
|
||||
[UI_MENU_RENDER_SCALE_DESC] = "Size of the 3D scene relative to the game resolution; the game's FSR scales it to "
|
||||
"that size. Above 100 % smooths jagged edges (supersampling) at a high GPU cost.",
|
||||
@@ -86,7 +91,7 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
||||
"bars, or stretch them over the whole picture. Applies from the next movie.",
|
||||
[UI_MENU_MOVIE_ASPECT_KEEP] = "Black bars", [UI_MENU_MOVIE_ASPECT_STRETCH] = "Stretch",
|
||||
[UI_MENU_FOV] = "Field of view",
|
||||
[UI_MENU_FOV_DESC] = "How much of the world the camera shows, in percent of the game's own. Game versions 1.1.0 and 1.4.3.",
|
||||
[UI_MENU_FOV_DESC] = "How much of the world the camera shows, in percent of the game's own. Game versions 1.1.0, 1.2.1 and 1.4.3.",
|
||||
[UI_MENU_SHADOW_RES] = "Shadow map size",
|
||||
[UI_MENU_SHADOW_RES_DESC] = "Size of the sun's shadow map. The game's own size changes with the view, down to about 400 "
|
||||
"near the ground, so leaf shadows look blocky and jump; a fixed size keeps them still and "
|
||||
@@ -219,11 +224,12 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_MODS_ROW_DESC] = "Game files it replaces: %u. New files it adds: %u.",
|
||||
[UI_MENU_MODS_OVERRIDDEN] = "%u of its files come from %s, which is higher in the list.",
|
||||
[UI_MENU_MODS_MOVE_HINT] = "The top face button or Ctrl+Up moves it up, the left face button or Ctrl+Down moves it "
|
||||
"down. When two mods change the same file, the higher one wins. Changes apply after a "
|
||||
"restart.",
|
||||
"down. When two mods change the same file, game data or code, the higher one wins. "
|
||||
"Changes apply after a restart.",
|
||||
[UI_MENU_MODS_EMPTY] = "This folder has no romfs, exefs or cheats files.",
|
||||
[UI_MENU_MODS_SUBSDK] = "This mod brings its own game code (a subsdk plugin or a replaced main). The port cannot "
|
||||
"load code modules, so the whole mod stays off.",
|
||||
"load code modules, so the whole mod stays off. Its switch \"Use ... without its code\" "
|
||||
"below uses the rest of it.",
|
||||
[UI_MENU_MODS_EXEFS_LATER] = "This mod patches the game code (exefs). The game builds the patches in when it "
|
||||
"starts next (a rebuild of a few minutes); until then the whole mod stays off.",
|
||||
[UI_MENU_MODS_CHEATS] = "Cheats: %d. Switch them on the Cheats tab.",
|
||||
@@ -268,6 +274,10 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_GYRO_CALIBRATED] = "%s, calibrated",
|
||||
[UI_MENU_GYRO_CALIBRATE_FAILED] = "Calibration failed",
|
||||
[UI_MENU_GYRO_CALIBRATE_MOVED] = "Controller moved: hold it still and try again",
|
||||
[UI_MENU_GYRO_AUTO_BIAS] = "Gyro drift learning at rest",
|
||||
[UI_MENU_GYRO_AUTO_BIAS_DESC] = "Learns the drift left in the gyro whenever the controller lies still on a "
|
||||
"table, and subtracts it. For a bow aim that slowly slides even after "
|
||||
"calibration. A controller held in the hand is not learned from. Experimental.",
|
||||
[UI_MENU_RUMBLE_STRENGTH] = "Vibration strength",
|
||||
[UI_MENU_RUMBLE_STRENGTH_DESC] = "How strong the controller vibrates.",
|
||||
[UI_MENU_RUMBLE_CURVE] = "Vibration curve",
|
||||
@@ -286,19 +296,23 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_PROMPTS_DESC] = "Which controller's buttons the game's prompts show. Nintendo: the game's own. Xbox: LB, "
|
||||
"RB, LT, RT, Menu, View and a d-pad cross, and A, B, X and Y as labelled on the button "
|
||||
"the layout above presses (with Nintendo (A right) the right button is labelled B, so the "
|
||||
"prompts for A show B). PC: the keys and mouse buttons of the keyboard's default layout "
|
||||
"(E, Shift, Space, left click...) and the mouse for the camera. The game reads its prompts "
|
||||
"at start, so they change after a restart. They are part of the game's files, so a button "
|
||||
"you remap in Controls keeps its old prompt on screen.",
|
||||
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox", [UI_MENU_PROMPTS_PC] = "PC",
|
||||
"prompts for A show B). PlayStation: the shapes on a PlayStation pad (○ × △ □, L1, R1, "
|
||||
"L2, R2, Options and Share), on the button the layout above presses. PC: the keys and "
|
||||
"mouse buttons of the keyboard's default layout (E, Shift, Space, left click...) and the "
|
||||
"mouse for the camera. The game reads its prompts at start, so they change after a "
|
||||
"restart. They are part of the game's files, so a button you remap in Controls keeps its "
|
||||
"old prompt on screen.",
|
||||
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox",
|
||||
[UI_MENU_PROMPTS_PLAYSTATION] = "PlayStation", [UI_MENU_PROMPTS_PC] = "PC",
|
||||
[UI_MENU_PROMPTS_MISSING] = "prompt files missing: run the setup again",
|
||||
[UI_MENU_PROMPTS_FAILED] = "prompt files damaged: run the setup again",
|
||||
[UI_MENU_PROMPTS_RESTART] = "prompts change after restart",
|
||||
[UI_MENU_PROMPTS_OFF_SHAPE] = "off at this game resolution (no layout made for it)",
|
||||
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "no layout made for this shape: run the setup again",
|
||||
[UI_MENU_OUTPUT_RES_PREPARING] = "layout being made in the background; used at the next start",
|
||||
[UI_MENU_SHAPE_PREPARE] = "Prepare the layout for this screen",
|
||||
[UI_MENU_SHAPE_PREPARE_DESC] = "Makes the interface layout and the chosen button prompts for this game resolution's shape in the background, with the setup's tools, as the setup does for the displays it saw. The game keeps running; it uses them from its next start.",
|
||||
[UI_MENU_PROMPTS_PREPARING] = "prompt files being made in the background; used at the next start",
|
||||
[UI_MENU_PREPARE_RETRY] = "Try again",
|
||||
[UI_MENU_PREPARE_RETRY_DESC] = "Starts the setup's tools again to make the missing interface layout or button prompt files in the background. The game keeps running; it uses them from its next start.",
|
||||
[UI_MENU_SHAPE_PREPARE_FAILED] = "the setup's tools did not start: run the setup again",
|
||||
[UI_MENU_PROMPTS_OFF_MODS] = "off: a RomFS mod replaces their files",
|
||||
[UI_MENU_PROMPTS_OFF_PATCHES] = "off while TOTK_ROMFS_PATCHES is set",
|
||||
@@ -324,6 +338,17 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_DIALOGUE_CLICK_DESC] = "While a dialogue box is open, left click presses B (it continues the text and skips its scroll) and right click presses A, instead of the buttons they are bound to (Y by default, which opens the dialogue log, and ZL). Dialogue choices keep the pointer: left click picks (game 1.4.3).",
|
||||
[UI_MENU_POINTER_IMAGE] = "Game pointer",
|
||||
[UI_MENU_POINTER_IMAGE_DESC] = "While the cursor is not captured (the game's menus, this menu, after Esc), the window shows a gold arrowhead of its own instead of the system arrow, sized for the screen's scale.",
|
||||
[UI_MENU_QUICKSAVE] = "Quick save and load",
|
||||
[UI_MENU_QUICKSAVE_DESC] = "One key saves the game at once and another loads that save (the two rows below: F6 and F7 by default, as in Half-Life), with no menu on the screen. Keyboard and mouse keys only, game 1.4.3 only. Quick save asks the game for one of its own autosaves, so it replaces the oldest autosave (the manual save stays), keeps a copy of it as the quick save (the quicksave folder of the profile) and shows \"Game saved\" at the top of the picture. Quick load holds the picture on \"Loading the quick save\" while it goes through the game's load list out of sight, and the game loads the quick save (about 5 s). Where the game would not make an autosave itself (a cutscene, a dialogue), nothing is saved and the line says so.",
|
||||
[UI_MENU_QUICKSAVE_KEY] = "Quick save key",
|
||||
[UI_MENU_QUICKLOAD_KEY] = "Quick load key",
|
||||
[UI_MENU_QUICKSAVE_KEY_DESC] = "The key that starts quick save or quick load; F6 and F7 by default, as in Half-Life. Select the cell and press any key or mouse button; Delete leaves that one without a key. While quick save is on, the two keys do nothing else (a note shows when a binding also uses the key). totk.ini takes any key name of the bindings (quicksave_key, quickload_key).",
|
||||
[UI_QS_SAVED] = "Game saved",
|
||||
[UI_QS_LOADING] = "Loading the quick save",
|
||||
[UI_QS_NOT_NOW] = "Quick save is not possible right now",
|
||||
[UI_QS_NONE] = "There is no quick save yet (the quick save key makes one)",
|
||||
[UI_QS_FAILED] = "Quick save failed: see totk.log",
|
||||
[UI_QS_LOAD_FAILED] = "Quick load failed: see totk.log",
|
||||
[UI_MENU_MOUSE_SENS] = "Mouse camera sensitivity",
|
||||
[UI_MENU_MOUSE_SENS_DESC] = "How fast the mouse turns the camera.",
|
||||
[UI_MENU_WALK_KEY] = "Walk key",
|
||||
@@ -495,6 +520,17 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_FIX_C0_DESC] = "Fills the driver-reserved constant bank c0 (storage sizes, dispatch size, point size, base instance) instead of reading zeros.",
|
||||
[UI_MENU_FIX_ZERO] = "Zero new GPU memory",
|
||||
[UI_MENU_FIX_ZERO_DESC] = "New GPU memory pools start zero-filled, as Switch memory does.",
|
||||
[UI_MENU_DLAA_EFFECTS_AFTER] = "Fog and particles after DLAA",
|
||||
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "With DLAA, fog, dust and other particles are drawn over the picture DLSS has"
|
||||
" already smoothed, as the game draws them without DLSS: small particles in "
|
||||
"fog (shrines) no longer vanish or leave trails. Off: DLSS also processes "
|
||||
"these effects, as before. DLAA mode only; the upscaling DLSS modes always "
|
||||
"process them. Applies at once.",
|
||||
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Fixed DLSS exposure",
|
||||
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS takes the brightness of the game's picture as it is instead of "
|
||||
"estimating the exposure from each frame: in dark scenes (the Depths) large "
|
||||
"fogged areas no longer turn darker or lighter for a frame while the camera "
|
||||
"moves. Off: DLSS estimates the exposure itself, as before. Applies at once.",
|
||||
[UI_MENU_BIND_SKIP] = "Skip repeated binds",
|
||||
[UI_MENU_BIND_SKIP_DESC] = "Optimisation: skips bindings that did not change.",
|
||||
[UI_MENU_SHADER_MEMO] = "Shader memo", [UI_MENU_SHADER_MEMO_DESC] = "Optimisation: remembers shader lookups.",
|
||||
@@ -577,11 +613,36 @@ static const char *const text_en[UI_TEXT_COUNT] = {
|
||||
"builds them in (a few minutes) and starts the game again. Progress since your "
|
||||
"last save is lost.",
|
||||
[UI_MENU_MODS_EXEFS_UNSUPPORTED] = "This mod patches the game code (exefs) in a way the port cannot apply, so the "
|
||||
"whole mod stays off. %s",
|
||||
"whole mod stays off. Its switch \"Use ... without its code\" below uses the "
|
||||
"rest of it. %s",
|
||||
[UI_MENU_MODS_EXEFS_OTHER] = "Its code patches (exefs) are made for another game version.",
|
||||
[UI_MENU_MODS_EXEFS_ON] = "Code patches in use: %d files.",
|
||||
[UI_MENU_MODS_REPLACES_BUILTIN] = "Code patches in use: %d files. They replace the port's own patch %s, which "
|
||||
"stays off while this mod is on.",
|
||||
[UI_MENU_MODS_CODE_SKIPPED] = "Its own game code (%s) does not load: the rest of the mod is used. Switch the mod "
|
||||
"off if the game misbehaves with it.",
|
||||
[UI_MENU_MODS_PLUGIN_ON] = "Its plugin runs: %d hooks into the game code.",
|
||||
[UI_MENU_MODS_PLUGIN_REFUSED] = "Its plugin %s cannot run in the port: %s.",
|
||||
[UI_MENU_MODS_PLUGIN_STAYS_OFF] = "The whole mod stays off. Its switch \"Use ... without its code\" below uses the "
|
||||
"rest of it.",
|
||||
[UI_MENU_MODS_PLUGIN_OFF] = "Its plugin stays off this time: it started differently from the build (%s). The game "
|
||||
"rebuilds it at the next start.",
|
||||
[UI_MENU_MODS_WITHOUT_CODE] = "Use %s without its code",
|
||||
[UI_MENU_MODS_WITHOUT_CODE_DESC] = "The mod above brings code the port cannot run: its own game code (a subsdk "
|
||||
"plugin or a replaced main) or code patches (exefs) the port cannot apply. Off: "
|
||||
"the whole mod stays off. On: that code is left out and the rest of the mod is "
|
||||
"used: its RomFS files, cheats and the code patches that work. Its files may "
|
||||
"expect the missing code; switch it off again if the game misbehaves. Applies "
|
||||
"at the next start.",
|
||||
[UI_MENU_MODS_WITHOUT_CODE_ALL] = "On for every mod: mods_without_code = 1 in totk.ini.",
|
||||
[UI_MENU_MODS_EXEFS_SKIPPED] = "%u of its code patch files (exefs) cannot be applied and are left out: the rest of "
|
||||
"the mod is used. %s",
|
||||
[UI_MENU_MODS_OVERRIDES_FILES] = "%u of its files replace those of %s, which is lower in the list.",
|
||||
[UI_MENU_MODS_DATA_OVERRIDDEN] = "%u bytes of its game data changes come from %s, which is higher in the list.",
|
||||
[UI_MENU_MODS_OVERRIDES_DATA] = "%u bytes of its game data changes replace those of %s, which is lower in the "
|
||||
"list.",
|
||||
[UI_MENU_MODS_CODE_OVERRIDDEN] = "%u of its code patch sites are overridden by %s, which is higher in the list.",
|
||||
[UI_MENU_MODS_OVERRIDES_CODE] = "It overrides %u code patch sites of %s, which is lower in the list.",
|
||||
};
|
||||
|
||||
static const char *const text_ru[UI_TEXT_COUNT] = {
|
||||
@@ -618,6 +679,11 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
||||
"видеопамяти и времени GPU. Более широкий размер (21:9) расширяет обзор камеры и "
|
||||
"переносит интерфейс в углы экрана, более высокий (16:10, 3:2) переносит его к "
|
||||
"верхнему и нижнему краям.",
|
||||
[UI_MENU_HUD_WIDTH] = "Ширина интерфейса",
|
||||
[UI_MENU_HUD_WIDTH_DESC] = "На экране шире 16:9: как далеко друг от друга левая и правая части интерфейса. "
|
||||
"«Весь экран» ставит их у краёв экрана; 21:9 или 16:9 держит интерфейс в середине "
|
||||
"экрана такой формы. Недостающая раскладка создаётся в фоне и будет после перезапуска.",
|
||||
[UI_MENU_HUD_WIDTH_FULL] = "Весь экран",
|
||||
[UI_MENU_RENDER_SCALE] = "Масштаб 3D-отрисовки",
|
||||
[UI_MENU_RENDER_SCALE_DESC] = "Размер 3D-сцены относительно разрешения игры; FSR игры доводит её до этого размера. "
|
||||
"Выше 100 % сглаживает лесенки на краях (суперсэмплинг) ценой большой нагрузки на GPU.",
|
||||
@@ -637,7 +703,7 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
||||
"растянуть их на всю картинку. Действует со следующего ролика.",
|
||||
[UI_MENU_MOVIE_ASPECT_KEEP] = "Чёрные полосы", [UI_MENU_MOVIE_ASPECT_STRETCH] = "Растянуть",
|
||||
[UI_MENU_FOV] = "Поле зрения",
|
||||
[UI_MENU_FOV_DESC] = "Сколько мира показывает камера, в процентах от игрового. Для версий игры 1.1.0 и 1.4.3.",
|
||||
[UI_MENU_FOV_DESC] = "Сколько мира показывает камера, в процентах от игрового. Для версий игры 1.1.0, 1.2.1 и 1.4.3.",
|
||||
[UI_MENU_SHADOW_RES] = "Размер карты теней",
|
||||
[UI_MENU_SHADOW_RES_DESC] = "Размер карты теней от солнца. Собственный размер игры меняется вместе с видом, у земли до "
|
||||
"примерно 400, поэтому тени листвы выглядят квадратными и дёргаются; постоянный размер делает "
|
||||
@@ -770,10 +836,12 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_MODS_ROW_DESC] = "Заменяет файлов игры: %u. Добавляет новых файлов: %u.",
|
||||
[UI_MENU_MODS_OVERRIDDEN] = "%u его файлов берутся из мода %s, он выше в списке.",
|
||||
[UI_MENU_MODS_MOVE_HINT] = "Верхняя кнопка или Ctrl+Вверх поднимает мод, левая кнопка или Ctrl+Вниз опускает. Если "
|
||||
"два мода меняют один файл, побеждает верхний. Изменения действуют после перезапуска.",
|
||||
"два мода меняют один файл, данные или код игры, побеждает верхний. Изменения действуют "
|
||||
"после перезапуска.",
|
||||
[UI_MENU_MODS_EMPTY] = "В этой папке нет файлов romfs, exefs или cheats.",
|
||||
[UI_MENU_MODS_SUBSDK] = "Этот мод приносит свой код игры (плагин subsdk или заменённый main). Порт не загружает "
|
||||
"модули кода, поэтому мод выключен целиком.",
|
||||
"модули кода, поэтому мод выключен целиком. Его переключатель «... без его кода» ниже "
|
||||
"включает остальную часть мода.",
|
||||
[UI_MENU_MODS_EXEFS_LATER] = "Этот мод меняет код игры (exefs). Игра соберёт эти патчи при следующем запуске "
|
||||
"(пересборка на несколько минут); до тех пор мод выключен целиком.",
|
||||
[UI_MENU_MODS_CHEATS] = "Читов: %d. Они включаются на вкладке «Читы».",
|
||||
@@ -817,6 +885,10 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_GYRO_CALIBRATED] = "%s, откалиброван",
|
||||
[UI_MENU_GYRO_CALIBRATE_FAILED] = "Калибровка не удалась",
|
||||
[UI_MENU_GYRO_CALIBRATE_MOVED] = "Контроллер сдвинулся: держите его неподвижно и повторите",
|
||||
[UI_MENU_GYRO_AUTO_BIAS] = "Учёт дрейфа гироскопа в покое",
|
||||
[UI_MENU_GYRO_AUTO_BIAS_DESC] = "Измеряет остаточный дрейф гироскопа, пока контроллер лежит на столе, и вычитает "
|
||||
"его. Для прицела лука, который медленно уплывает даже после калибровки. В руке "
|
||||
"контроллер не измеряется. Экспериментально.",
|
||||
[UI_MENU_RUMBLE_STRENGTH] = "Сила вибрации",
|
||||
[UI_MENU_RUMBLE_STRENGTH_DESC] = "Насколько сильно вибрирует контроллер.",
|
||||
[UI_MENU_RUMBLE_CURVE] = "Кривая вибрации",
|
||||
@@ -835,19 +907,23 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_PROMPTS_DESC] = "Кнопки какого контроллера показывают подсказки игры. Nintendo: как в самой игре. Xbox: "
|
||||
"LB, RB, LT, RT, Menu, View и крестовина, а A, B, X и Y подписаны так же, как кнопка, "
|
||||
"которую нажимает раскладка выше (в Nintendo (A справа) правая кнопка подписана B, и "
|
||||
"подсказки A показывают B). PC: клавиши и кнопки мыши стандартной раскладки клавиатуры "
|
||||
"(E, Shift, пробел, левый клик...) и мышь для камеры. Игра читает подсказки при запуске, "
|
||||
"так что они меняются после перезапуска. Подсказки записаны в файлах игры, поэтому у "
|
||||
"кнопки, переназначенной на вкладке управления, на экране остаётся прежняя подсказка.",
|
||||
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox", [UI_MENU_PROMPTS_PC] = "PC",
|
||||
"подсказки A показывают B). PlayStation: символы геймпада PlayStation (○ × △ □, L1, R1, "
|
||||
"L2, R2, Options и Share) на кнопке, которую нажимает раскладка выше. PC: клавиши и "
|
||||
"кнопки мыши стандартной раскладки клавиатуры (E, Shift, пробел, левый клик...) и мышь "
|
||||
"для камеры. Игра читает подсказки при запуске, так что они меняются после перезапуска. "
|
||||
"Подсказки записаны в файлах игры, поэтому у кнопки, переназначенной на вкладке "
|
||||
"управления, на экране остаётся прежняя подсказка.",
|
||||
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo", [UI_MENU_PROMPTS_XBOX] = "Xbox",
|
||||
[UI_MENU_PROMPTS_PLAYSTATION] = "PlayStation", [UI_MENU_PROMPTS_PC] = "PC",
|
||||
[UI_MENU_PROMPTS_MISSING] = "нет файлов подсказок: запустите установку снова",
|
||||
[UI_MENU_PROMPTS_FAILED] = "файлы подсказок повреждены: запустите установку снова",
|
||||
[UI_MENU_PROMPTS_RESTART] = "подсказки сменятся после перезапуска",
|
||||
[UI_MENU_PROMPTS_OFF_SHAPE] = "выкл. при этом разрешении игры (для него нет раскладки)",
|
||||
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "для этой формы нет раскладки: запустите установщик снова",
|
||||
[UI_MENU_OUTPUT_RES_PREPARING] = "раскладка создаётся в фоне; будет при следующем запуске",
|
||||
[UI_MENU_SHAPE_PREPARE] = "Подготовить раскладку для этого экрана",
|
||||
[UI_MENU_SHAPE_PREPARE_DESC] = "Создаёт в фоне раскладку интерфейса и выбранные подсказки кнопок для формы этого разрешения игры инструментами установщика, как установщик делает для мониторов, которые видел. Игра продолжает работать; раскладка будет со следующего запуска.",
|
||||
[UI_MENU_PROMPTS_PREPARING] = "файлы подсказок создаются в фоне; будут при следующем запуске",
|
||||
[UI_MENU_PREPARE_RETRY] = "Повторить",
|
||||
[UI_MENU_PREPARE_RETRY_DESC] = "Снова запускает инструменты установщика, чтобы создать в фоне недостающую раскладку интерфейса или файлы подсказок кнопок. Игра продолжает работать; они будут со следующего запуска.",
|
||||
[UI_MENU_SHAPE_PREPARE_FAILED] = "инструменты установщика не запустились: запустите установщик снова",
|
||||
[UI_MENU_PROMPTS_OFF_MODS] = "выкл.: мод RomFS заменяет их файлы",
|
||||
[UI_MENU_PROMPTS_OFF_PATCHES] = "выкл., пока задан TOTK_ROMFS_PATCHES",
|
||||
@@ -873,6 +949,17 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_DIALOGUE_CLICK_DESC] = "Пока открыто окно диалога, левый щелчок нажимает B (продолжает текст и пропускает его прокрутку), а правый — A, вместо назначенных им кнопок (по умолчанию Y, она открывает журнал диалога, и ZL). В вариантах ответа по-прежнему работает указатель: левый щелчок выбирает (версия игры 1.4.3).",
|
||||
[UI_MENU_POINTER_IMAGE] = "Игровой курсор",
|
||||
[UI_MENU_POINTER_IMAGE_DESC] = "Пока курсор не захвачен (меню игры, это меню, после Esc), окно показывает собственный золотой наконечник вместо системной стрелки, по масштабу экрана.",
|
||||
[UI_MENU_QUICKSAVE] = "Быстрое сохранение и загрузка",
|
||||
[UI_MENU_QUICKSAVE_DESC] = "Одна клавиша сразу сохраняет игру, другая загружает это сохранение (две строки ниже: по умолчанию F6 и F7, как в Half-Life), без всяких меню на экране. Только клавиатура и мышь, только версия игры 1.4.3. Быстрое сохранение просит игру сделать одно из её собственных автосохранений, поэтому заменяет самое старое автосохранение (ручное сохранение остаётся), держит его копию как быстрое сохранение (папка quicksave профиля) и пишет «Игра сохранена» вверху экрана. Быстрая загрузка держит картинку с надписью «Загрузка быстрого сохранения», пока за кадром проходит список загрузки игры, и игра загружает быстрое сохранение (около 5 с). Где игра сама не стала бы автосохраняться (сценка, диалог), ничего не сохраняется, и надпись говорит об этом.",
|
||||
[UI_MENU_QUICKSAVE_KEY] = "Клавиша быстрого сохранения",
|
||||
[UI_MENU_QUICKLOAD_KEY] = "Клавиша быстрой загрузки",
|
||||
[UI_MENU_QUICKSAVE_KEY_DESC] = "Клавиша, которая запускает быстрое сохранение или быструю загрузку; по умолчанию F6 и F7, как в Half-Life. Выберите ячейку и нажмите любую клавишу или кнопку мыши; Delete оставляет действие без клавиши. Пока быстрое сохранение включено, эти две клавиши больше ничего не делают (если клавиша занята в раскладке, это написано под значением). В totk.ini подходит любое имя клавиши из раскладки (quicksave_key, quickload_key).",
|
||||
[UI_QS_SAVED] = "Игра сохранена",
|
||||
[UI_QS_LOADING] = "Загрузка быстрого сохранения",
|
||||
[UI_QS_NOT_NOW] = "Сейчас быстрое сохранение невозможно",
|
||||
[UI_QS_NONE] = "Быстрого сохранения ещё нет (его делает клавиша быстрого сохранения)",
|
||||
[UI_QS_FAILED] = "Быстрое сохранение не удалось: см. totk.log",
|
||||
[UI_QS_LOAD_FAILED] = "Быстрая загрузка не удалась: см. totk.log",
|
||||
[UI_MENU_MOUSE_SENS] = "Чувствительность мыши",
|
||||
[UI_MENU_MOUSE_SENS_DESC] = "Как быстро мышь поворачивает камеру.",
|
||||
[UI_MENU_WALK_KEY] = "Клавиша шага",
|
||||
@@ -1048,6 +1135,17 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_FIX_C0_DESC] = "Заполняет зарезервированный драйвером банк констант c0 (размеры хранилищ, размер запуска, размер точки, базовый экземпляр) вместо чтения нулей.",
|
||||
[UI_MENU_FIX_ZERO] = "Обнулять новую память GPU",
|
||||
[UI_MENU_FIX_ZERO_DESC] = "Новые пулы памяти GPU заполняются нулями, как память Switch.",
|
||||
[UI_MENU_DLAA_EFFECTS_AFTER] = "Туман и частицы после DLAA",
|
||||
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "С DLAA туман, пыль и другие частицы рисуются поверх картинки, уже сглаженной"
|
||||
" DLSS, как игра рисует их без DLSS: мелкие частицы в тумане (святилища) "
|
||||
"больше не пропадают и не оставляют шлейфов. Выкл.: DLSS обрабатывает и эти "
|
||||
"эффекты, как раньше. Только в режиме DLAA; режимы DLSS с повышением "
|
||||
"разрешения обрабатывают их всегда. Применяется сразу.",
|
||||
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Фиксированная экспозиция DLSS",
|
||||
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS берёт яркость картинки игры как есть, а не оценивает экспозицию по "
|
||||
"каждому кадру: в тёмных сценах (Глубины) большие участки в тумане больше не "
|
||||
"темнеют и не светлеют на кадр при движении камеры. Выкл.: DLSS сам "
|
||||
"оценивает экспозицию, как раньше. Применяется сразу.",
|
||||
[UI_MENU_BIND_SKIP] = "Пропуск повторных привязок",
|
||||
[UI_MENU_BIND_SKIP_DESC] = "Оптимизация: пропускает неизменившиеся привязки.",
|
||||
[UI_MENU_SHADER_MEMO] = "Память шейдеров", [UI_MENU_SHADER_MEMO_DESC] = "Оптимизация: запоминает поиск шейдеров.",
|
||||
@@ -1131,11 +1229,35 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
|
||||
"собирает их (несколько минут) и снова запускает игру. Прогресс после последнего "
|
||||
"сохранения будет потерян.",
|
||||
[UI_MENU_MODS_EXEFS_UNSUPPORTED] = "Этот мод меняет код игры (exefs) так, как порт применить не может, поэтому мод "
|
||||
"выключен целиком. %s",
|
||||
"выключен целиком. Его переключатель «... без его кода» ниже включает остальную "
|
||||
"часть мода. %s",
|
||||
[UI_MENU_MODS_EXEFS_OTHER] = "Его патчи кода (exefs) сделаны для другой версии игры.",
|
||||
[UI_MENU_MODS_EXEFS_ON] = "Патчи кода в работе: файлов: %d.",
|
||||
[UI_MENU_MODS_REPLACES_BUILTIN] = "Патчи кода в работе: файлов: %d. Они заменяют собственный патч порта %s, "
|
||||
"который выключен, пока этот мод включён.",
|
||||
[UI_MENU_MODS_CODE_SKIPPED] = "Его собственный код игры (%s) не загружается: используется остальная часть мода. "
|
||||
"Выключите мод, если игра с ним ведёт себя странно.",
|
||||
[UI_MENU_MODS_PLUGIN_ON] = "Его плагин работает: перехватов в коде игры: %d.",
|
||||
[UI_MENU_MODS_PLUGIN_REFUSED] = "Его плагин %s не может работать в порте: %s.",
|
||||
[UI_MENU_MODS_PLUGIN_STAYS_OFF] = "Мод выключен целиком. Его переключатель «... без его кода» ниже включает "
|
||||
"остальную часть мода.",
|
||||
[UI_MENU_MODS_PLUGIN_OFF] = "Его плагин в этот раз выключен: он запустился не так, как при сборке (%s). Игра "
|
||||
"пересоберёт его при следующем запуске.",
|
||||
[UI_MENU_MODS_WITHOUT_CODE] = "%s без его кода",
|
||||
[UI_MENU_MODS_WITHOUT_CODE_DESC] = "Мод выше приносит код, который порт не может запустить: свой код игры (плагин "
|
||||
"subsdk или заменённый main) или патчи кода (exefs), которые порт не может "
|
||||
"применить. Выкл.: мод выключен целиком. Вкл.: этот код пропускается, а "
|
||||
"остальная часть мода используется — его файлы RomFS, читы и работающие патчи "
|
||||
"кода. Его файлы могут рассчитывать на отсутствующий код; выключите снова, если "
|
||||
"игра ведёт себя странно. Применяется при следующем запуске.",
|
||||
[UI_MENU_MODS_WITHOUT_CODE_ALL] = "Включено для всех модов: mods_without_code = 1 в totk.ini.",
|
||||
[UI_MENU_MODS_EXEFS_SKIPPED] = "Патчи кода (exefs), которые порт не может применить, пропущены (файлов: %u): "
|
||||
"используется остальная часть мода. %s",
|
||||
[UI_MENU_MODS_OVERRIDES_FILES] = "%u его файлов заменяют файлы мода %s, он ниже в списке.",
|
||||
[UI_MENU_MODS_DATA_OVERRIDDEN] = "%u байт его изменений данных игры берутся из мода %s, он выше в списке.",
|
||||
[UI_MENU_MODS_OVERRIDES_DATA] = "%u байт его изменений данных игры заменяют изменения мода %s, он ниже в списке.",
|
||||
[UI_MENU_MODS_CODE_OVERRIDDEN] = "%u мест его патчей кода перекрыты модом %s, он выше в списке.",
|
||||
[UI_MENU_MODS_OVERRIDES_CODE] = "Он перекрывает %u мест патчей кода мода %s, он ниже в списке.",
|
||||
};
|
||||
|
||||
static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
||||
@@ -1157,10 +1279,12 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_MODS_ROW_DESC] = "Arquivos do jogo que substitui: %u. Arquivos novos que adiciona: %u.",
|
||||
[UI_MENU_MODS_OVERRIDDEN] = "%u dos seus arquivos vêm de %s, que está acima na lista.",
|
||||
[UI_MENU_MODS_MOVE_HINT] = "O botão de cima ou Ctrl+Cima sobe o mod, o botão da esquerda ou Ctrl+Baixo desce. "
|
||||
"Quando dois mods mudam o mesmo arquivo, vale o de cima. As mudanças valem após reiniciar.",
|
||||
"Quando dois mods mudam o mesmo arquivo, dado ou código do jogo, vale o de cima. As "
|
||||
"mudanças valem após reiniciar.",
|
||||
[UI_MENU_MODS_EMPTY] = "Esta pasta não tem arquivos romfs, exefs ou cheats.",
|
||||
[UI_MENU_MODS_SUBSDK] = "Este mod traz código próprio do jogo (um plugin subsdk ou um main substituído). O port não "
|
||||
"carrega módulos de código, então o mod inteiro fica desligado.",
|
||||
[UI_MENU_MODS_SUBSDK] = "Este mod traz código próprio do jogo (um plugin subsdk ou um main substituído). O port "
|
||||
"não carrega módulos de código, então o mod inteiro fica desligado. A chave \"Usar ... sem "
|
||||
"o código dele\", abaixo, usa o resto dele.",
|
||||
[UI_MENU_MODS_EXEFS_LATER] = "Este mod altera o código do jogo (exefs). O jogo compila esses patches na próxima "
|
||||
"vez que iniciar (uma recompilação de alguns minutos); até lá o mod inteiro fica "
|
||||
"desligado.",
|
||||
@@ -1208,6 +1332,11 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
||||
"precisa de mais memória de vídeo e tempo de GPU. Um tamanho mais largo (21:9) amplia a "
|
||||
"visão da câmera e leva o HUD para os cantos da tela; um mais alto (16:10, 3:2) "
|
||||
"leva-o para as bordas de cima e de baixo.",
|
||||
[UI_MENU_HUD_WIDTH] = "Largura do HUD",
|
||||
[UI_MENU_HUD_WIDTH_DESC] = "Em uma tela mais larga que 16:9: a distância entre os lados esquerdo e direito do HUD. "
|
||||
"Tela cheia os coloca nas bordas da tela; 21:9 ou 16:9 mantém o HUD no meio da tela "
|
||||
"desse formato. Um layout ausente é feito em segundo plano e usado depois de reiniciar o jogo.",
|
||||
[UI_MENU_HUD_WIDTH_FULL] = "Tela cheia",
|
||||
[UI_MENU_RENDER_SCALE] = "Escala da renderização 3D",
|
||||
[UI_MENU_RENDER_SCALE_DESC] = "Tamanho da cena 3D em relação à resolução do jogo; o FSR do jogo a amplia até esse "
|
||||
"tamanho. Acima de 100 % suaviza bordas serrilhadas (supersampling) com alto custo de "
|
||||
@@ -1283,6 +1412,10 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_GYRO_CALIBRATED] = "%s, calibrado",
|
||||
[UI_MENU_GYRO_CALIBRATE_FAILED] = "Falha na calibração",
|
||||
[UI_MENU_GYRO_CALIBRATE_MOVED] = "O controle se moveu: segure-o parado e tente de novo",
|
||||
[UI_MENU_GYRO_AUTO_BIAS] = "Aprender o desvio do giroscópio em repouso",
|
||||
[UI_MENU_GYRO_AUTO_BIAS_DESC] = "Mede o desvio que resta no giroscópio sempre que o controle fica parado sobre a "
|
||||
"mesa e o subtrai. Para a mira do arco que desliza devagar mesmo após a "
|
||||
"calibração. Na mão, o controle não é medido. Experimental.",
|
||||
[UI_MENU_RUMBLE_STRENGTH] = "Intensidade da vibração",
|
||||
[UI_MENU_RUMBLE_STRENGTH_DESC] = "Quão forte o controle vibra.",
|
||||
[UI_MENU_RUMBLE_CURVE] = "Curva da vibração",
|
||||
@@ -1451,6 +1584,18 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_FIX_C0_DESC] = "Preenche o banco de constantes c0 reservado ao driver (tamanhos de armazenamento, tamanho do dispatch, tamanho do ponto, instância base) em vez de ler zeros.",
|
||||
[UI_MENU_FIX_ZERO] = "Zerar memória nova da GPU",
|
||||
[UI_MENU_FIX_ZERO_DESC] = "Novos pools de memória da GPU começam zerados, como a memória do Switch.",
|
||||
[UI_MENU_DLAA_EFFECTS_AFTER] = "Névoa e partículas após o DLAA",
|
||||
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "Com DLAA, a névoa, a poeira e outras partículas são desenhadas sobre a "
|
||||
"imagem já suavizada pelo DLSS, como o jogo as desenha sem DLSS: partículas "
|
||||
"pequenas na névoa (santuários) não somem mais nem deixam rastros. Desligado:"
|
||||
" o DLSS também processa esses efeitos, como antes. Só no modo DLAA; os modos"
|
||||
" de DLSS que aumentam a resolução sempre os processam. Aplica-se na hora.",
|
||||
[UI_MENU_DLSS_FIXED_EXPOSURE] = "Exposição fixa do DLSS",
|
||||
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "O DLSS usa o brilho da imagem do jogo como ele é, em vez de estimar a "
|
||||
"exposição a cada quadro: em cenas escuras (as Profundezas), grandes áreas com "
|
||||
"névoa não ficam mais escuras ou claras por um quadro enquanto a câmera se "
|
||||
"move. Desligado: o DLSS estima a exposição sozinho, como antes. Aplica-se na "
|
||||
"hora.",
|
||||
[UI_MENU_BIND_SKIP] = "Pular bindings repetidos",
|
||||
[UI_MENU_BIND_SKIP_DESC] = "Otimização: pula bindings que não mudaram.",
|
||||
[UI_MENU_SHADER_MEMO] = "Memória de shaders", [UI_MENU_SHADER_MEMO_DESC] = "Otimização: lembra as buscas de shaders.",
|
||||
@@ -1510,8 +1655,8 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_OV_FMT_FSR] = "AMD FSR 1, nitidez %d%%", [UI_MENU_OV_SCALE_NONE] = "nenhuma (1:1)",
|
||||
[UI_MENU_OV_SCALE_BILINEAR] = "bilinear",
|
||||
[UI_MENU_FOV] = "Campo de visão",
|
||||
[UI_MENU_FOV_DESC] = "Quanto do mundo a câmera mostra, em porcentagem do original do jogo. Nas versões 1.1.0 e 1.4.3 do "
|
||||
"jogo.",
|
||||
[UI_MENU_FOV_DESC] = "Quanto do mundo a câmera mostra, em porcentagem do original do jogo. Nas versões 1.1.0, 1.2.1 e 1.4.3 "
|
||||
"do jogo.",
|
||||
[UI_MENU_SHADOW_RES] = "Tamanho do mapa de sombras",
|
||||
[UI_MENU_SHADOW_RES_DESC] = "Tamanho do mapa de sombras do sol. O tamanho do jogo muda com a vista, até cerca de "
|
||||
"400 perto do chão, então as sombras das folhas ficam quadriculadas e pulam; um "
|
||||
@@ -1564,13 +1709,15 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_PROMPTS_DESC] = "Os botões de qual controle os ícones do jogo mostram. Nintendo: os do próprio jogo. "
|
||||
"Xbox: LB, RB, LT, RT, Menu, Exibir e uma cruz direcional, e A, B, X e Y com a letra do "
|
||||
"botão que o layout acima aperta (com Nintendo (A à direita) o botão da direita tem a "
|
||||
"letra B, então os ícones de A mostram B). PC: as teclas e os botões do mouse do layout "
|
||||
"padrão do teclado (E, Shift, Espaço, clique esquerdo...) e o mouse para a câmera. O jogo "
|
||||
"lê os ícones ao iniciar, então eles mudam depois de reiniciar. Eles fazem parte dos "
|
||||
"arquivos do jogo, então um botão remapeado em Controles continua com o ícone antigo na "
|
||||
"tela.",
|
||||
"letra B, então os ícones de A mostram B). PlayStation: os símbolos de um controle "
|
||||
"PlayStation (○ × △ □, L1, R1, L2, R2, Options e Share), no botão que o layout acima "
|
||||
"aperta. PC: as teclas e os botões do mouse do layout padrão do teclado (E, Shift, "
|
||||
"Espaço, clique esquerdo...) e o mouse para a câmera. O jogo lê os ícones ao iniciar, "
|
||||
"então eles mudam depois de reiniciar. Eles fazem parte dos arquivos do jogo, então um "
|
||||
"botão remapeado em Controles continua com o ícone antigo na tela.",
|
||||
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo",
|
||||
[UI_MENU_PROMPTS_XBOX] = "Xbox",
|
||||
[UI_MENU_PROMPTS_PLAYSTATION] = "PlayStation",
|
||||
[UI_MENU_PROMPTS_PC] = "PC",
|
||||
[UI_MENU_MOUSE_MODE] = "Câmera com o mouse",
|
||||
[UI_MENU_MOUSE_MODE_DESC] = "Direta: a câmera gira o quanto o mouse se move, como num jogo de PC, sem zona morta nem curva do analógico (jogos 1.4.3 e 1.2.1; o 1.1.0 usa a emulação do analógico). Emulação do analógico: o mouse age como o analógico direito.",
|
||||
@@ -1584,14 +1731,26 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_DIALOGUE_CLICK_DESC] = "Enquanto uma caixa de diálogo está aberta, o clique esquerdo aperta B (continua o texto e pula a rolagem) e o direito aperta A, em vez dos botões aos quais estão atribuídos (Y por padrão, que abre o registro do diálogo, e ZL). As escolhas de diálogo continuam com o ponteiro: o clique esquerdo escolhe (jogo 1.4.3).",
|
||||
[UI_MENU_POINTER_IMAGE] = "Ponteiro do jogo",
|
||||
[UI_MENU_POINTER_IMAGE_DESC] = "Enquanto o cursor não está capturado (os menus do jogo, este menu, depois de Esc), a janela mostra uma ponta de flecha dourada própria em vez da seta do sistema, no tamanho da escala da tela.",
|
||||
[UI_MENU_QUICKSAVE] = "Salvamento e carregamento rápidos",
|
||||
[UI_MENU_QUICKSAVE_DESC] = "Uma tecla salva o jogo na hora e outra carrega esse salvamento (as duas linhas abaixo: F6 e F7 por padrão, como no Half-Life), sem nenhum menu na tela. Só teclado e mouse, só o jogo 1.4.3. O salvamento rápido pede ao jogo um dos seus próprios salvamentos automáticos, então substitui o salvamento automático mais antigo (o salvamento manual fica), guarda uma cópia dele como salvamento rápido (a pasta quicksave do perfil) e mostra \"Jogo salvo\" no alto da imagem. O carregamento rápido segura a imagem em \"Carregando o salvamento rápido\" enquanto passa pela lista de carregamento do jogo fora de vista, e o jogo carrega o salvamento rápido (cerca de 5 s). Onde o próprio jogo não faria um salvamento automático (uma cena, um diálogo), nada é salvo e a linha avisa.",
|
||||
[UI_MENU_QUICKSAVE_KEY] = "Tecla de salvamento rápido",
|
||||
[UI_MENU_QUICKLOAD_KEY] = "Tecla de carregamento rápido",
|
||||
[UI_MENU_QUICKSAVE_KEY_DESC] = "A tecla que inicia o salvamento ou o carregamento rápido; F6 e F7 por padrão, como no Half-Life. Selecione a célula e aperte qualquer tecla ou botão do mouse; Delete deixa essa ação sem tecla. Com o salvamento rápido ligado, as duas teclas não fazem mais nada (uma nota aparece quando um mapeamento também usa a tecla). O totk.ini aceita qualquer nome de tecla dos mapeamentos (quicksave_key, quickload_key).",
|
||||
[UI_QS_SAVED] = "Jogo salvo",
|
||||
[UI_QS_LOADING] = "Carregando o salvamento rápido",
|
||||
[UI_QS_NOT_NOW] = "Salvamento rápido não é possível agora",
|
||||
[UI_QS_NONE] = "Ainda não há salvamento rápido (a tecla de salvamento rápido faz um)",
|
||||
[UI_QS_FAILED] = "O salvamento rápido falhou: veja o totk.log",
|
||||
[UI_QS_LOAD_FAILED] = "O carregamento rápido falhou: veja o totk.log",
|
||||
[UI_MENU_PROMPTS_MISSING] = "faltam os arquivos dos ícones: execute a instalação de novo",
|
||||
[UI_MENU_PROMPTS_FAILED] = "arquivos dos ícones danificados: execute a instalação de novo",
|
||||
[UI_MENU_PROMPTS_RESTART] = "os ícones mudam após reiniciar",
|
||||
[UI_MENU_PROMPTS_OFF_SHAPE] = "desligados nesta resolução de jogo (sem layout feito para ela)",
|
||||
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "sem layout feito para este formato: rode o instalador de novo",
|
||||
[UI_MENU_OUTPUT_RES_PREPARING] = "layout sendo feito em segundo plano; usado na próxima vez que o jogo abrir",
|
||||
[UI_MENU_SHAPE_PREPARE] = "Preparar o layout para esta tela",
|
||||
[UI_MENU_SHAPE_PREPARE_DESC] = "Faz em segundo plano o layout da interface e os botões escolhidos para o formato desta resolução de jogo, com as ferramentas do instalador, como o instalador faz para os monitores que viu. O jogo continua rodando; ele os usa a partir da próxima vez que abrir.",
|
||||
[UI_MENU_PROMPTS_PREPARING] = "arquivos dos ícones sendo feitos em segundo plano; usados na próxima vez que o jogo abrir",
|
||||
[UI_MENU_PREPARE_RETRY] = "Tentar de novo",
|
||||
[UI_MENU_PREPARE_RETRY_DESC] = "Abre de novo as ferramentas do instalador para fazer em segundo plano o layout da interface ou os arquivos dos ícones que faltam. O jogo continua rodando; ele os usa a partir da próxima vez que abrir.",
|
||||
[UI_MENU_SHAPE_PREPARE_FAILED] = "as ferramentas do instalador não abriram: rode o instalador de novo",
|
||||
[UI_MENU_PROMPTS_OFF_MODS] = "desligados: um mod de RomFS substitui os arquivos deles",
|
||||
[UI_MENU_PROMPTS_OFF_PATCHES] = "desligados enquanto TOTK_ROMFS_PATCHES está definido",
|
||||
@@ -1720,11 +1879,38 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = {
|
||||
"jogo; o instalador os compila (alguns minutos) e inicia o jogo de novo. O "
|
||||
"progresso desde o último salvamento é perdido.",
|
||||
[UI_MENU_MODS_EXEFS_UNSUPPORTED] = "Este mod altera o código do jogo (exefs) de um jeito que o port não consegue "
|
||||
"aplicar, então o mod inteiro fica desligado. %s",
|
||||
"aplicar, então o mod inteiro fica desligado. A chave \"Usar ... sem o código "
|
||||
"dele\", abaixo, usa o resto dele. %s",
|
||||
[UI_MENU_MODS_EXEFS_OTHER] = "Os patches de código dele (exefs) são para outra versão do jogo.",
|
||||
[UI_MENU_MODS_EXEFS_ON] = "Patches de código em uso: %d arquivos.",
|
||||
[UI_MENU_MODS_REPLACES_BUILTIN] = "Patches de código em uso: %d arquivos. Eles substituem o patch do próprio port "
|
||||
"%s, que fica desligado enquanto este mod está ligado.",
|
||||
[UI_MENU_MODS_CODE_SKIPPED] = "O código próprio do jogo dele (%s) não é carregado: o resto do mod é usado. "
|
||||
"Desligue o mod se o jogo se comportar mal com ele.",
|
||||
[UI_MENU_MODS_PLUGIN_ON] = "O plugin dele está ativo: %d ganchos no código do jogo.",
|
||||
[UI_MENU_MODS_PLUGIN_REFUSED] = "O plugin %s dele não pode rodar no port: %s.",
|
||||
[UI_MENU_MODS_PLUGIN_STAYS_OFF] = "O mod inteiro fica desligado. A chave \"Usar ... sem o código dele\", abaixo, "
|
||||
"usa o resto dele.",
|
||||
[UI_MENU_MODS_PLUGIN_OFF] = "O plugin dele fica desligado desta vez: ele iniciou de forma diferente da compilação "
|
||||
"(%s). O jogo o recompila na próxima inicialização.",
|
||||
[UI_MENU_MODS_WITHOUT_CODE] = "Usar %s sem o código dele",
|
||||
[UI_MENU_MODS_WITHOUT_CODE_DESC] = "O mod acima traz código que o port não consegue rodar: código próprio do jogo "
|
||||
"(um plugin subsdk ou um main substituído) ou patches de código (exefs) que o "
|
||||
"port não consegue aplicar. Desligado: o mod inteiro fica desligado. Ligado: "
|
||||
"esse código fica de fora e o resto do mod é usado: os arquivos RomFS, cheats e "
|
||||
"os patches de código que funcionam. Os arquivos dele podem depender do código "
|
||||
"que falta; desligue de novo se o jogo se comportar mal. Vale na próxima "
|
||||
"inicialização.",
|
||||
[UI_MENU_MODS_WITHOUT_CODE_ALL] = "Ligado para todos os mods: mods_without_code = 1 no totk.ini.",
|
||||
[UI_MENU_MODS_EXEFS_SKIPPED] = "%u arquivos de patch de código (exefs) dele não podem ser aplicados e ficam de "
|
||||
"fora: o resto do mod é usado. %s",
|
||||
[UI_MENU_MODS_OVERRIDES_FILES] = "%u dos seus arquivos substituem os de %s, que está abaixo na lista.",
|
||||
[UI_MENU_MODS_DATA_OVERRIDDEN] = "%u bytes das suas mudanças nos dados do jogo vêm de %s, que está acima na lista.",
|
||||
[UI_MENU_MODS_OVERRIDES_DATA] = "%u bytes das suas mudanças nos dados do jogo substituem as de %s, que está abaixo "
|
||||
"na lista.",
|
||||
[UI_MENU_MODS_CODE_OVERRIDDEN] = "%u pontos dos seus patches de código são sobrepostos por %s, que está acima na "
|
||||
"lista.",
|
||||
[UI_MENU_MODS_OVERRIDES_CODE] = "Ele sobrepõe %u pontos dos patches de código de %s, que está abaixo na lista.",
|
||||
};
|
||||
|
||||
// Simplified Chinese: this row covers the software keyboard and the whole menu, so the menu and the overlay read Chinese
|
||||
@@ -1753,10 +1939,9 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_MODS_OPEN_DESC] = "显示游戏加载模组的文件夹。不存在时会创建它。",
|
||||
[UI_MENU_MODS_ROW_DESC] = "替换的游戏文件:%u。新增的文件:%u。",
|
||||
[UI_MENU_MODS_OVERRIDDEN] = "它的 %u 个文件改用列表中更靠上的 %s 的文件。",
|
||||
[UI_MENU_MODS_MOVE_HINT] = "上方按钮或 Ctrl+上 上移,左侧按钮或 Ctrl+下 下移。两个模组修改同一个文件时,以靠上的为准。"
|
||||
"更改在重启后生效。",
|
||||
[UI_MENU_MODS_MOVE_HINT] = "上方按钮或 Ctrl+上 上移,左侧按钮或 Ctrl+下 下移。两个模组修改同一个文件、游戏数据或代码时,以靠上的为准。更改在重启后生效。",
|
||||
[UI_MENU_MODS_EMPTY] = "此文件夹中没有 romfs、exefs 或 cheats 文件。",
|
||||
[UI_MENU_MODS_SUBSDK] = "此模组带有自己的游戏代码(subsdk 插件或替换的 main)。移植版无法加载代码模块,因此整个模组保持关闭。",
|
||||
[UI_MENU_MODS_SUBSDK] = "此模组带有自己的游戏代码(subsdk 插件或替换的 main)。移植版无法加载代码模块,因此整个模组保持关闭。打开下方它的“不带代码使用 ...”开关即可使用其余部分。",
|
||||
[UI_MENU_MODS_EXEFS_LATER] = "此模组修改游戏代码(exefs)。游戏会在下次启动时把这些补丁构建进去(重新构建需要几分钟);在此之前整个模组保持关闭。",
|
||||
[UI_MENU_MODS_CHEATS] = "金手指:%d 个。在“金手指”标签页中开关。",
|
||||
[UI_MENU_MODS_CHEATS_FILE] = "此游戏版本的金手指在启动时从此模组的 cheats\\%s 读取。",
|
||||
@@ -1810,6 +1995,11 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
||||
"高于 1920 x 1080 会占用更多显存和 GPU 时间。"
|
||||
"更宽的尺寸(21:9)会扩大视野,并把界面移到屏幕四角;"
|
||||
"更高的尺寸(16:10、3:2)则移到上下边缘。",
|
||||
[UI_MENU_HUD_WIDTH] = "界面宽度",
|
||||
[UI_MENU_HUD_WIDTH_DESC] = "在比 16:9 更宽的屏幕上,界面左右两侧相距多远。"
|
||||
"“整个屏幕”把它们放在屏幕边缘;21:9 或 16:9 则把界面保持在屏幕中间该比例的区域内。"
|
||||
"缺少的布局会在后台制作,重启游戏后生效。",
|
||||
[UI_MENU_HUD_WIDTH_FULL] = "整个屏幕",
|
||||
[UI_MENU_RENDER_SCALE] = "3D 渲染比例",
|
||||
[UI_MENU_RENDER_SCALE_DESC] = "3D 场景相对于游戏分辨率的尺寸;"
|
||||
"游戏的 FSR 会将其缩放到该尺寸。"
|
||||
@@ -1834,7 +2024,7 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_MOVIE_ASPECT_STRETCH] = "拉伸",
|
||||
[UI_MENU_FOV] = "视野",
|
||||
[UI_MENU_FOV_DESC] = "镜头能看到多大范围,以游戏自身视野的百分比表示。"
|
||||
"支持游戏版本 1.1.0 和 1.4.3。",
|
||||
"支持游戏版本 1.1.0、1.2.1 和 1.4.3。",
|
||||
[UI_MENU_SHARPNESS] = "FSR 锐度",
|
||||
[UI_MENU_SHARPNESS_DESC] = "FSR 缩放后的锐化强度;0 为关闭。",
|
||||
[UI_MENU_COLOR] = "色彩",
|
||||
@@ -1913,6 +2103,9 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_GYRO_CALIBRATED] = "%s,已校准",
|
||||
[UI_MENU_GYRO_CALIBRATE_FAILED] = "校准失败",
|
||||
[UI_MENU_GYRO_CALIBRATE_MOVED] = "手柄移动了:请保持静止后重试",
|
||||
[UI_MENU_GYRO_AUTO_BIAS] = "静止时学习陀螺仪漂移",
|
||||
[UI_MENU_GYRO_AUTO_BIAS_DESC] = "手柄平放在桌上不动时测量陀螺仪的剩余漂移并将其减去。适用于校准后弓箭准星仍缓慢漂"
|
||||
"移的情况。手持时不会测量。实验性功能。",
|
||||
[UI_MENU_RUMBLE_STRENGTH] = "振动强度",
|
||||
[UI_MENU_RUMBLE_STRENGTH_DESC] = "手柄振动的强弱。",
|
||||
[UI_MENU_RUMBLE_CURVE] = "振动曲线",
|
||||
@@ -2157,6 +2350,13 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
||||
"基础实例),而不是读取零值。",
|
||||
[UI_MENU_FIX_ZERO] = "清零新的 GPU 内存",
|
||||
[UI_MENU_FIX_ZERO_DESC] = "新的 GPU 内存池初始内容为零,与 Switch 内存一致。",
|
||||
[UI_MENU_DLAA_EFFECTS_AFTER] = "DLAA 之后绘制雾和粒子",
|
||||
[UI_MENU_DLAA_EFFECTS_AFTER_DESC] = "开启 DLAA 时,雾、灰尘和其他粒子绘制在 DLSS 已平滑的画面之上,与游戏不用 DLSS 时的"
|
||||
"绘制方式相同:雾中的细小粒子(神庙中)不再消失,也不再留下拖影。关闭:DLSS 也处理这些效果,与以"
|
||||
"前相同。仅用于 DLAA 模式;提升分辨率的 DLSS 模式始终处理它们。立即生效。",
|
||||
[UI_MENU_DLSS_FIXED_EXPOSURE] = "固定 DLSS 曝光",
|
||||
[UI_MENU_DLSS_FIXED_EXPOSURE_DESC] = "DLSS 直接使用游戏画面的亮度,而不是逐帧自行估算曝光:在暗场景(地底)中,"
|
||||
"镜头移动时大片雾中区域不再忽暗忽亮一帧。关闭:DLSS 自行估算曝光,与以前相同。立即生效。",
|
||||
[UI_MENU_BIND_SKIP] = "跳过重复绑定",
|
||||
[UI_MENU_BIND_SKIP_DESC] = "优化:跳过没有变化的绑定。",
|
||||
[UI_MENU_SHADER_MEMO] = "着色器查找缓存",
|
||||
@@ -2266,10 +2466,12 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_PROMPTS] = "按键提示",
|
||||
[UI_MENU_PROMPTS_DESC] = "游戏的按键提示显示哪种手柄的按键。Nintendo:游戏原有的提示。Xbox:LB、RB、LT、RT、Menu、View 和十字键,以及上方布局所按下的按键上标注的 "
|
||||
"A、B、X、Y(使用 Nintendo(A 在右)时右侧按键标为 B,因此 A 的提示显示 "
|
||||
"B)。PC:键盘默认布局的按键和鼠标按键(E、Shift、空格、左键……),镜头用鼠标。"
|
||||
"B)。PlayStation:PlayStation 手柄上的符号(○ × △ □、L1、R1、L2、R2、Options 和 Share),"
|
||||
"显示在上方布局所按下的按键上。PC:键盘默认布局的按键和鼠标按键(E、Shift、空格、左键……),镜头用鼠标。"
|
||||
"游戏在启动时读取按键提示,因此重启后才会改变。提示属于游戏文件,在“操作”中重新映射的按键在屏幕上仍显示原来的提示。",
|
||||
[UI_MENU_PROMPTS_NINTENDO] = "Nintendo",
|
||||
[UI_MENU_PROMPTS_XBOX] = "Xbox",
|
||||
[UI_MENU_PROMPTS_PLAYSTATION] = "PlayStation",
|
||||
[UI_MENU_PROMPTS_PC] = "PC",
|
||||
[UI_MENU_MOUSE_MODE] = "鼠标视角",
|
||||
[UI_MENU_MOUSE_MODE_DESC] = "直接:镜头按鼠标移动的距离转动,与电脑游戏相同,没有摇杆死区和响应曲线(游戏 1.4.3 和 1.2.1;1.1.0 使用摇杆模拟)。摇杆模拟:鼠标相当于右摇杆。",
|
||||
@@ -2283,14 +2485,26 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_DIALOGUE_CLICK_DESC] = "对话框打开时,鼠标左键按下 B 键(继续对话并跳过文字滚动),右键按下 A 键,而不是它们所绑定的按键(默认为 Y,会打开对话记录;以及 ZL)。对话选项仍使用指针:左键选择(游戏 1.4.3)。",
|
||||
[UI_MENU_POINTER_IMAGE] = "游戏指针",
|
||||
[UI_MENU_POINTER_IMAGE_DESC] = "光标未被捕获时(游戏菜单、本菜单、按 Esc 之后),窗口显示自带的金色箭头,而不是系统箭头,大小随屏幕缩放。",
|
||||
[UI_MENU_QUICKSAVE] = "快速存档与读档",
|
||||
[UI_MENU_QUICKSAVE_DESC] = "一个键立即保存游戏,另一个键读取该存档(见下方两行:默认 F6 和 F7,与 Half-Life 相同),屏幕上不会出现任何菜单。仅限键盘和鼠标按键,仅限游戏 1.4.3。快速存档会让游戏自己进行一次自动存档,因此会替换最旧的自动存档(手动存档保留),并将其副本保存为快速存档(配置文件中的 quicksave 文件夹),画面顶部显示“游戏已保存”。快速读档时画面停留在“正在读取快速存档”,同时在后台走完游戏的读档列表,游戏随即读取快速存档(约 5 秒)。在游戏本身不会自动存档的地方(过场动画、对话),不会保存,并会显示提示。",
|
||||
[UI_MENU_QUICKSAVE_KEY] = "快速存档键",
|
||||
[UI_MENU_QUICKLOAD_KEY] = "快速读档键",
|
||||
[UI_MENU_QUICKSAVE_KEY_DESC] = "启动快速存档或快速读档的按键;默认 F6 和 F7,与 Half-Life 相同。选中该格后按下任意键盘按键或鼠标按键;按 Delete 则该操作没有按键。快速存档开启时,这两个键不再有其他作用(若按键映射也使用该键,值下方会有提示)。totk.ini 接受按键映射中的任意按键名(quicksave_key、quickload_key)。",
|
||||
[UI_QS_SAVED] = "游戏已保存",
|
||||
[UI_QS_LOADING] = "正在读取快速存档",
|
||||
[UI_QS_NOT_NOW] = "现在无法快速存档",
|
||||
[UI_QS_NONE] = "还没有快速存档(按快速存档键创建)",
|
||||
[UI_QS_FAILED] = "快速存档失败:请查看 totk.log",
|
||||
[UI_QS_LOAD_FAILED] = "快速读档失败:请查看 totk.log",
|
||||
[UI_MENU_PROMPTS_MISSING] = "缺少按键提示文件:请重新运行安装程序",
|
||||
[UI_MENU_PROMPTS_FAILED] = "按键提示文件已损坏:请重新运行安装程序",
|
||||
[UI_MENU_PROMPTS_RESTART] = "按键提示重启后生效",
|
||||
[UI_MENU_PROMPTS_OFF_SHAPE] = "此游戏分辨率下关闭(未为其制作布局)",
|
||||
[UI_MENU_OUTPUT_RES_NO_LAYOUT] = "未为此比例制作布局:请重新运行安装程序",
|
||||
[UI_MENU_OUTPUT_RES_PREPARING] = "布局正在后台制作;下次启动时使用",
|
||||
[UI_MENU_SHAPE_PREPARE] = "为此屏幕准备布局",
|
||||
[UI_MENU_SHAPE_PREPARE_DESC] = "使用安装程序的工具,在后台为此游戏分辨率的比例制作界面布局和所选按键提示,与安装程序为其检测到的显示器所做的相同。游戏继续运行;下次启动时生效。",
|
||||
[UI_MENU_PROMPTS_PREPARING] = "按键提示文件正在后台制作;下次启动时使用",
|
||||
[UI_MENU_PREPARE_RETRY] = "重试",
|
||||
[UI_MENU_PREPARE_RETRY_DESC] = "再次启动安装程序的工具,在后台制作缺少的界面布局或按键提示文件。游戏继续运行;下次启动时生效。",
|
||||
[UI_MENU_SHAPE_PREPARE_FAILED] = "安装程序的工具未能启动:请重新运行安装程序",
|
||||
[UI_MENU_PROMPTS_OFF_MODS] = "已关闭:RomFS 模组替换了它们的文件",
|
||||
[UI_MENU_PROMPTS_OFF_PATCHES] = "设置了 TOTK_ROMFS_PATCHES 时关闭",
|
||||
@@ -2391,10 +2605,24 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = {
|
||||
[UI_MENU_CHEAT_UNSUPPORTED_DESC] = "此金手指不能用于此游戏版本:",
|
||||
[UI_MENU_CHEATS_REBUILD] = "立即重新构建游戏",
|
||||
[UI_MENU_CHEATS_REBUILD_DESC] = "有些金手指会修改游戏代码,但尚未构建进游戏:它们是新增或修改的,或上次重新构建失败或被取消。将关闭游戏;安装程序会把它们构建进去(几分钟)并重新启动游戏。上次存档之后的进度会丢失。",
|
||||
[UI_MENU_MODS_EXEFS_UNSUPPORTED] = "此模组修改游戏代码(exefs)的方式本移植无法应用,因此整个模组保持关闭。%s",
|
||||
[UI_MENU_MODS_EXEFS_UNSUPPORTED] = "此模组修改游戏代码(exefs)的方式本移植无法应用,因此整个模组保持关闭。打开下方它的“不带代码使用 ...”开关即可使用其余部分。%s",
|
||||
[UI_MENU_MODS_EXEFS_OTHER] = "它的代码补丁(exefs)是为其他游戏版本制作的。",
|
||||
[UI_MENU_MODS_EXEFS_ON] = "正在使用的代码补丁:%d 个文件。",
|
||||
[UI_MENU_MODS_REPLACES_BUILTIN] = "正在使用的代码补丁:%d 个文件。它们取代本移植自带的补丁 %s,此模组开启时该补丁保持关闭。",
|
||||
[UI_MENU_MODS_CODE_SKIPPED] = "它自带的游戏代码(%s)不会加载:模组的其余部分照常使用。如果游戏因此表现异常,请关闭此模组。",
|
||||
[UI_MENU_MODS_PLUGIN_ON] = "它的插件正在运行:游戏代码中有 %d 处挂钩。",
|
||||
[UI_MENU_MODS_PLUGIN_REFUSED] = "它的插件 %s 无法在移植版中运行:%s。",
|
||||
[UI_MENU_MODS_PLUGIN_STAYS_OFF] = "整个模组保持关闭。打开下方它的“不带代码使用 ...”开关即可使用其余部分。",
|
||||
[UI_MENU_MODS_PLUGIN_OFF] = "它的插件本次保持关闭:启动情况与构建时不同(%s)。游戏会在下次启动时重新构建它。",
|
||||
[UI_MENU_MODS_WITHOUT_CODE] = "不带代码使用 %s",
|
||||
[UI_MENU_MODS_WITHOUT_CODE_DESC] = "上方的模组带有移植版无法运行的代码:它自己的游戏代码(subsdk 插件或替换的 main),或移植版无法应用的代码补丁(exefs)。关闭:整个模组保持关闭。开启:跳过这些代码,使用模组的其余部分:其 RomFS 文件、金手指和可用的代码补丁。它的文件可能依赖缺失的代码;如果游戏表现异常,请再次关闭。下次启动时生效。",
|
||||
[UI_MENU_MODS_WITHOUT_CODE_ALL] = "已对所有模组开启:totk.ini 中 mods_without_code = 1。",
|
||||
[UI_MENU_MODS_EXEFS_SKIPPED] = "它有 %u 个代码补丁文件(exefs)无法应用,已跳过:模组的其余部分照常使用。%s",
|
||||
[UI_MENU_MODS_OVERRIDES_FILES] = "它的 %u 个文件取代了列表中更靠下的 %s 的文件。",
|
||||
[UI_MENU_MODS_DATA_OVERRIDDEN] = "它对游戏数据的修改中有 %u 字节改用列表中更靠上的 %s 的修改。",
|
||||
[UI_MENU_MODS_OVERRIDES_DATA] = "它对游戏数据的修改中有 %u 字节取代了列表中更靠下的 %s 的修改。",
|
||||
[UI_MENU_MODS_CODE_OVERRIDDEN] = "它有 %u 处代码补丁位置被列表中更靠上的 %s 覆盖。",
|
||||
[UI_MENU_MODS_OVERRIDES_CODE] = "它覆盖了 %u 处代码补丁位置,这些位置原属于列表中更靠下的 %s。",
|
||||
};
|
||||
|
||||
#define SWKBD_ONLY(name, ...) static const char *const name[UI_TEXT_COUNT] = {SWKBD(__VA_ARGS__)}
|
||||
|
||||
+27
-5
@@ -34,6 +34,7 @@ typedef enum {
|
||||
UI_PERF_LINE_FPS,
|
||||
UI_MENU_GRAPHICS, // group heading over the resolution rows
|
||||
UI_MENU_OUTPUT_RES, UI_MENU_OUTPUT_RES_DESC,
|
||||
UI_MENU_HUD_WIDTH, UI_MENU_HUD_WIDTH_DESC, UI_MENU_HUD_WIDTH_FULL,
|
||||
UI_MENU_RENDER_SCALE, UI_MENU_RENDER_SCALE_DESC, UI_MENU_RENDER_SCALE_GAME,
|
||||
UI_MENU_DYNAMIC_RES, UI_MENU_DYNAMIC_RES_DESC,
|
||||
UI_MENU_UPSCALER, UI_MENU_UPSCALER_DESC, UI_MENU_UPSCALER_FSR, UI_MENU_UPSCALER_BILINEAR,
|
||||
@@ -84,13 +85,28 @@ typedef enum {
|
||||
UI_MENU_MODS_NONE, // no mod folder yet: where to unpack one
|
||||
UI_MENU_MODS_OPEN, UI_MENU_MODS_OPEN_DESC,
|
||||
UI_MENU_MODS_ROW_DESC, // printf: files it replaces, files it adds (as of this start)
|
||||
UI_MENU_MODS_OVERRIDDEN, // printf: files a higher mod serves instead, that mod's name
|
||||
UI_MENU_MODS_OVERRIDDEN, // printf: files a higher mod serves instead, that mod's name (the conflict table)
|
||||
UI_MENU_MODS_MOVE_HINT,
|
||||
UI_MENU_MODS_EMPTY, UI_MENU_MODS_SUBSDK, UI_MENU_MODS_EXEFS_LATER, UI_MENU_MODS_BAD_NAME,
|
||||
UI_MENU_MODS_EXEFS_UNSUPPORTED, // printf: the file and why
|
||||
UI_MENU_MODS_EXEFS_OTHER,
|
||||
UI_MENU_MODS_EXEFS_ON, // printf: its ExeFS patch files in use
|
||||
UI_MENU_MODS_REPLACES_BUILTIN, // printf: its ExeFS patch files in use, the port's own patch sets they turn off
|
||||
UI_MENU_MODS_CODE_SKIPPED, // printf: its code modules in exefs, which do not load (used without its code)
|
||||
UI_MENU_MODS_PLUGIN_ON, // printf: the hooks of its plugin (runtime/plugin_init.c) that run
|
||||
UI_MENU_MODS_PLUGIN_REFUSED, // printf: its plugin file, why the build refused it (English, from the tool)
|
||||
UI_MENU_MODS_PLUGIN_STAYS_OFF, // after UI_MENU_MODS_PLUGIN_REFUSED when the whole mod stays off
|
||||
UI_MENU_MODS_PLUGIN_OFF, // printf: why its plugin's start differed from the build (English)
|
||||
UI_MENU_MODS_WITHOUT_CODE, // printf: the mod's name; its switch "use without its code" (TOTK_MODS_NO_CODE)
|
||||
UI_MENU_MODS_WITHOUT_CODE_DESC,
|
||||
UI_MENU_MODS_WITHOUT_CODE_ALL, // why that switch cannot be changed: TOTK_MODS_WITHOUT_CODE=1
|
||||
UI_MENU_MODS_EXEFS_SKIPPED, // printf: its ExeFS patch files left out (used without its code), the first's reason
|
||||
// The conflict table (mods.h ModConflict), printf: the count, the other mod's name
|
||||
UI_MENU_MODS_OVERRIDES_FILES, // files it serves instead of a lower mod's (UI_MENU_MODS_OVERRIDDEN: the reverse)
|
||||
UI_MENU_MODS_DATA_OVERRIDDEN, // bytes of main's data a higher mod wrote over its own
|
||||
UI_MENU_MODS_OVERRIDES_DATA, // bytes of main's data it wrote over a lower mod's
|
||||
UI_MENU_MODS_CODE_OVERRIDDEN, // code sites where a higher mod's patch runs instead of its own
|
||||
UI_MENU_MODS_OVERRIDES_CODE, // code sites where its patch runs instead of a lower mod's
|
||||
UI_MENU_MODS_OTHER_VERSION, // printf: files named for another game version, read only when asked for by name
|
||||
UI_MENU_MODS_UNUSED, // under the switch of a mod the port cannot use
|
||||
UI_MENU_MODS_CHEATS, // printf: its cheats as read at start
|
||||
@@ -111,16 +127,19 @@ typedef enum {
|
||||
UI_MENU_GYRO_CALIBRATION, UI_MENU_GYRO_CALIBRATION_DESC,
|
||||
UI_MENU_GYRO_CALIBRATE, UI_MENU_GYRO_CALIBRATE_DESC, UI_MENU_GYRO_CALIBRATE_WAIT,
|
||||
UI_MENU_GYRO_CALIBRATED, UI_MENU_GYRO_CALIBRATE_FAILED, UI_MENU_GYRO_CALIBRATE_MOVED,
|
||||
UI_MENU_GYRO_AUTO_BIAS, UI_MENU_GYRO_AUTO_BIAS_DESC,
|
||||
UI_MENU_RUMBLE_STRENGTH, UI_MENU_RUMBLE_STRENGTH_DESC,
|
||||
UI_MENU_RUMBLE_CURVE, UI_MENU_RUMBLE_CURVE_DESC,
|
||||
UI_MENU_RUMBLE_TRIGGERS, UI_MENU_RUMBLE_TRIGGERS_DESC,
|
||||
UI_MENU_PAD_LAYOUT, UI_MENU_PAD_LAYOUT_DESC, UI_MENU_PAD_LAYOUT_AUTO, UI_MENU_PAD_LAYOUT_NINTENDO,
|
||||
UI_MENU_PAD_LAYOUT_XBOX, UI_MENU_PAD_LAYOUT_IN_USE,
|
||||
UI_MENU_PROMPTS, UI_MENU_PROMPTS_DESC, UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, UI_MENU_PROMPTS_PC,
|
||||
UI_MENU_PROMPTS, UI_MENU_PROMPTS_DESC, UI_MENU_PROMPTS_NINTENDO, UI_MENU_PROMPTS_XBOX, UI_MENU_PROMPTS_PLAYSTATION,
|
||||
UI_MENU_PROMPTS_PC,
|
||||
// the notes under the prompts: their files are missing or damaged, they change after restart, or why they are off
|
||||
UI_MENU_PROMPTS_MISSING, UI_MENU_PROMPTS_FAILED, UI_MENU_PROMPTS_RESTART, UI_MENU_PROMPTS_OFF_SHAPE,
|
||||
UI_MENU_OUTPUT_RES_NO_LAYOUT, UI_MENU_OUTPUT_RES_PREPARING, UI_MENU_SHAPE_PREPARE, UI_MENU_SHAPE_PREPARE_DESC,
|
||||
UI_MENU_SHAPE_PREPARE_FAILED,
|
||||
// the missing layout and prompts' folders, which the game makes in the background (ui/menu.cpp folders_tick)
|
||||
UI_MENU_OUTPUT_RES_NO_LAYOUT, UI_MENU_OUTPUT_RES_PREPARING, UI_MENU_PROMPTS_PREPARING, UI_MENU_SHAPE_PREPARE_FAILED,
|
||||
UI_MENU_PREPARE_RETRY, UI_MENU_PREPARE_RETRY_DESC,
|
||||
UI_MENU_PROMPTS_OFF_MODS, UI_MENU_PROMPTS_OFF_PATCHES,
|
||||
// "Restart now" under the prompts while they change after restart, and its confirmation (Cancel: UI_MENU_RESET_NO)
|
||||
UI_MENU_RESTART, UI_MENU_RESTART_DESC, UI_MENU_RESTART_CONFIRM, UI_MENU_RESTART_YES, UI_MENU_RESTART_SAVING,
|
||||
@@ -131,6 +150,8 @@ typedef enum {
|
||||
UI_MENU_MAP_CLICK, UI_MENU_MAP_CLICK_DESC,
|
||||
UI_MENU_DIALOGUE_CLICK, UI_MENU_DIALOGUE_CLICK_DESC,
|
||||
UI_MENU_POINTER_IMAGE, UI_MENU_POINTER_IMAGE_DESC,
|
||||
UI_MENU_QUICKSAVE, UI_MENU_QUICKSAVE_DESC, UI_MENU_QUICKSAVE_KEY, UI_MENU_QUICKLOAD_KEY, UI_MENU_QUICKSAVE_KEY_DESC,
|
||||
UI_QS_SAVED, UI_QS_LOADING, UI_QS_NOT_NOW, UI_QS_NONE, UI_QS_FAILED, UI_QS_LOAD_FAILED,
|
||||
UI_MENU_MOUSE_SENS, UI_MENU_MOUSE_SENS_DESC,
|
||||
UI_MENU_WALK_KEY, UI_MENU_WALK_KEY_DESC, UI_MENU_WALK_KEY_TAKEN, UI_MENU_WALK_SCALE, UI_MENU_WALK_SCALE_DESC,
|
||||
|
||||
@@ -226,7 +247,8 @@ typedef enum {
|
||||
UI_MENU_ASTC_BC, UI_MENU_ASTC_BC_DESC,
|
||||
UI_MENU_LOD_GUARD, UI_MENU_LOD_GUARD_DESC,
|
||||
UI_MENU_FIX_C0, UI_MENU_FIX_C0_DESC,
|
||||
UI_MENU_FIX_ZERO, UI_MENU_FIX_ZERO_DESC,
|
||||
UI_MENU_FIX_ZERO, UI_MENU_FIX_ZERO_DESC, UI_MENU_DLAA_EFFECTS_AFTER, UI_MENU_DLAA_EFFECTS_AFTER_DESC,
|
||||
UI_MENU_DLSS_FIXED_EXPOSURE, UI_MENU_DLSS_FIXED_EXPOSURE_DESC,
|
||||
UI_MENU_BIND_SKIP, UI_MENU_BIND_SKIP_DESC,
|
||||
UI_MENU_SHADER_MEMO, UI_MENU_SHADER_MEMO_DESC,
|
||||
UI_MENU_PIPE_MEMO, UI_MENU_PIPE_MEMO_DESC,
|
||||
|
||||
@@ -291,6 +291,7 @@ int vk_mvprev_find(int index, uint64_t addr, uint64_t size, uint64_t *prev, int
|
||||
void vk_mvprev_frame(void); // each present, beside vk_dlaa_frame
|
||||
void vk_mem_mirror_begin(void);
|
||||
int vk_mem_mirror_end(VkCommandBuffer cb, uint64_t fence);
|
||||
void vk_mem_mirror_seal(void); // before vk_mem_shadow_sync: the copies the next vk_mem_mirror_prologue takes
|
||||
int vk_mem_mirror_pending(void);
|
||||
void vk_mem_mirror_prologue(VkCommandBuffer cb);
|
||||
// Shadow storage (vk_memory.c): vk_sync.c calls vk_mem_shadow_sync right before each submit; the replay notes every GPU
|
||||
@@ -303,6 +304,7 @@ void vk_mem_shadow_sync(uint64_t fence); // fence: the value of the part about
|
||||
// vk_mem_mirror_prologue's copies, which read the shadow.
|
||||
int vk_mem_shadow_deferred(void);
|
||||
void vk_mem_shadow_prologue(VkCommandBuffer cb, uint64_t fence);
|
||||
void vk_mem_shadow_read_log(void); // at exit, with TOTK_SYNC_AHEAD: the run total of vk_mem_shadow_read's waits
|
||||
void vk_mem_gpu_pending(uint64_t addr, uint64_t size);
|
||||
void vk_gpu_written(uint64_t addr, uint64_t size);
|
||||
int vk_mem_flush_add_probe(void); // --probe-vkexec: the flush range list; 0 or the number of the failed check
|
||||
@@ -373,6 +375,7 @@ VkResult vk_texture_image(const VkImageCreateInfo *ci, VkImage *img, VmaAllocati
|
||||
// (vk_texture.c UPLOAD_HELD_MAX) so the GPU starts on it and its buffers come back before the pools need new blocks.
|
||||
VkDeviceSize vk_upload_held(void);
|
||||
void vk_upload_pools_init(void); // vk_device.c, after the allocator: the staging and scratch pools and their blocks
|
||||
void vk_defer_buffer_until(VkBuffer buf, VmaAllocation alloc, uint64_t tl); // also not before the GPU reached value tl
|
||||
// ---- ASTC (vk_astc.c). TOTK_ASTC = auto | gpu | native | cpu | check; see vk_astc.c.
|
||||
enum { VK_ASTC_CPU, VK_ASTC_GPU, VK_ASTC_NATIVE, VK_ASTC_CHECK };
|
||||
int vk_astc_mode(void); // decided once per device (logged); VK_ASTC_CPU before vk_init
|
||||
@@ -496,10 +499,16 @@ void vk_sampler_dlss_bias(float bias); // texture LOD bias added for D
|
||||
uint32_t vk_sampler_gen(void); // changes whenever a sampler slot is registered
|
||||
void vk_texture_gpu_written(const tex_t *t); // rendered or copied into by the GPU: no re-upload from storage
|
||||
void vk_texture_storage_bound_locked(const VkTexImage *img); // bound as a storage image in the recording submission
|
||||
void vk_texture_storage_written(const VkTexImage *img); // the same without the texture lock held
|
||||
uint64_t vk_texture_last_write(const tex_t *t); // timeline value of the newest submission recorded to write it; 0: none
|
||||
size_t vk_texture_texel_span(const tex_t *t, const view_t *v, const NVNcopyRegion *r, uint64_t row, uint64_t img); // bytes ReadTexels spans; 0 for a bad region
|
||||
int vk_texture_small_dirty(void); // a small mirrored target holds GPU texels its storage lacks
|
||||
void vk_texture_write_back_small(uint64_t fence); // writes those rendered by work up to fence back to storage
|
||||
// vk_sync_submit, after the replay recorded value fence into cb (no render pass open, cb the recorder's part): copies
|
||||
// the small targets that value rendered into staging so their write-back later needs no GPU wait (TOTK_WB_EAGER).
|
||||
// cb VK_NULL_HANDLE: the value recorded no part, the candidates for it are dropped.
|
||||
void vk_texture_eager_record(VkCommandBuffer cb, uint64_t fence);
|
||||
void vk_texture_eager_log(void); // once at exit: TOTK_WB_EAGER counts
|
||||
void vk_texture_debug(const VkTexImage *img, uint32_t *uploads, int *last_change, int *pages_written); // vk_dump
|
||||
int vk_texture_slot_swz(int id, uint8_t swz[4]); // vk_dump: swizzle of the descriptor in slot id
|
||||
int vk_texture_read_image(const tex_t *t, const view_t *v, const NVNcopyRegion *r, uint8_t *dst, uint64_t row,
|
||||
@@ -671,6 +680,13 @@ int vk_pipeline_vertex_input_dynamic(void); // 1: vertex input is VK_EXT_vert
|
||||
void vk_pipeline_answers(const VkPipeState *s, GfxShaderAnswers *vs, GfxShaderAnswers *fs);
|
||||
int vk_pipeline_tex_type(int nvn_target); // NVN_TEXTURE_TARGET_* -> GFX_TEX_* (GfxShaderAnswers.tex_type)
|
||||
uint32_t vk_pipeline_target_wmask(const VkPipeState *s, int i); // colour write mask of target i the pipeline uses
|
||||
// The sign of the depth bias a volume mask draw gets (vk_pipeline.c, see there), -1 toward smaller depth, 1 toward
|
||||
// larger, 0 for any other draw. vk_pipeline_set_dynamic enables the bias for it; vk_exec_draw.c prepare_draw decides it
|
||||
// where the draw's state changes and record_fixed sets the values, VOLUME_BIAS_UNITS and VOLUME_BIAS_SLOPE times the
|
||||
// sign.
|
||||
int vk_pipeline_volume_bias(const VkPipeState *s);
|
||||
#define VOLUME_BIAS_UNITS 16.0f
|
||||
#define VOLUME_BIAS_SLOPE 1.0f
|
||||
VkPrimitiveTopology vk_pipeline_topology(int nvn_prim); // quads -> triangle list, line loop -> strip: the replay
|
||||
// rewrites those draws; polygon -> fan
|
||||
VkFormat vk_vertex_format(int nvn_format, int *type); // attribute format (supported fallback), GFX_TYPE_* in *type
|
||||
|
||||
@@ -338,12 +338,15 @@ static void replay_log(uint64_t frame, int total) {
|
||||
void gfx_exit_log(void) {
|
||||
static int32_t done;
|
||||
rec_check_log();
|
||||
vk_texture_eager_log();
|
||||
vk_mem_shadow_read_log();
|
||||
if (gfx_replay_async() && r_started && !plat_xchg32(&done, 1)) replay_log(game_frames, 1);
|
||||
}
|
||||
|
||||
static void vk_be_present(const tex_t *t, const int crop[4], uint64_t at_ns) {
|
||||
static _Thread_local int pcore; // the game's render thread: the one that presents
|
||||
if (!pcore) pcore = 1, perf_core_thread(PCORE_RENDER);
|
||||
vk_dlaa_game_present(); // the camera jitter moves on with the game's frames (vk_dlaa.c)
|
||||
vk_sync_start();
|
||||
if (!gfx_replay_async()) {
|
||||
uint64_t frame = __atomic_add_fetch(&gfx_counters.frames, 1, __ATOMIC_RELAXED);
|
||||
|
||||
+45
-13
@@ -18,9 +18,17 @@
|
||||
// a view-space position toward
|
||||
// the sun (the G-buffer shaders compare dot(c4[44].xyz, pos) + c4[44].w with the cascade map). The scene colour images
|
||||
// get STORAGE usage when the setting is on (vk_texture.c create_tex).
|
||||
//
|
||||
// Only sunlit pixels are darkened. The composite reads a half-resolution lighting pass (eight targets at half the scene
|
||||
// size, the first RGBA8) whose first target's alpha is the sun's visibility: 1 in the sun, 0 in the shadow maps'
|
||||
// shadow and everywhere underground (found by comparing frame dumps of a sunny path and a cave). The march's darkening
|
||||
// is scaled by it, so a contact shadow takes away direct sunlight and leaves the ambient light and textures alone;
|
||||
// darkening the whole colour turned caves flat, where nearly every ray toward the sun meets the rock overhead. Without
|
||||
// that pass in the frame every pixel is darkened as before. TOTK_CONTACT_DEBUG=2 shows the visibility in grey.
|
||||
#include "vk.h"
|
||||
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "cfg.h"
|
||||
@@ -36,6 +44,7 @@ static struct {
|
||||
VkPipeline pipe;
|
||||
VkSampler sampler;
|
||||
VkExecTarget scene, depth; // the last G-buffer's scene colour and linear depth
|
||||
VkExecTarget sun; // this frame's half-resolution lighting target (is_lighting); no img: none seen
|
||||
int pending; // the composite into scene ran; the march waits for the next pass
|
||||
uint64_t c4;
|
||||
} C;
|
||||
@@ -53,17 +62,19 @@ static int init(VkCtx *c) {
|
||||
C.tried = 1;
|
||||
vk_contact_strength();
|
||||
if (!C.strength) return 0;
|
||||
const char *e = cfg_get("TOTK_CONTACT_DEBUG"); // 1: the frame shows the contact shadow factor in grey
|
||||
C.debug = e && *e && strcmp(e, "0");
|
||||
const char *e = cfg_get("TOTK_CONTACT_DEBUG"); // 1: the contact shadow factor in grey, 2: the sun visibility
|
||||
C.debug = e ? atoi(e) : 0;
|
||||
C.push = (PFN_vkCmdPushDescriptorSetKHR)vkGetDeviceProcAddr(c->device, "vkCmdPushDescriptorSetKHR");
|
||||
VkDescriptorSetLayoutBinding b[2] = {
|
||||
VkDescriptorSetLayoutBinding b[3] = {
|
||||
{.binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorCount = 1,
|
||||
.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT},
|
||||
{.binding = 1, .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .descriptorCount = 1,
|
||||
.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT},
|
||||
{.binding = 2, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorCount = 1,
|
||||
.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT}};
|
||||
VkDescriptorSetLayoutCreateInfo dci = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
|
||||
.flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR,
|
||||
.bindingCount = 2, .pBindings = b};
|
||||
.bindingCount = 3, .pBindings = b};
|
||||
VkPushConstantRange pr = {VK_SHADER_STAGE_COMPUTE_BIT, 0, 64};
|
||||
VkPipelineLayoutCreateInfo li = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1,
|
||||
.pSetLayouts = &C.dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pr};
|
||||
@@ -91,7 +102,8 @@ static int init(VkCtx *c) {
|
||||
rt_log("vk: contact shadows off: their pipeline could not be created");
|
||||
return 0;
|
||||
}
|
||||
rt_log("vk: contact shadows on, strength %d%%%s", C.strength, C.debug ? " (debug view)" : "");
|
||||
rt_log("vk: contact shadows on, strength %d%%%s", C.strength,
|
||||
C.debug == 2 ? " (debug view: sun visibility)" : C.debug ? " (debug view)" : "");
|
||||
return C.ok = 1;
|
||||
}
|
||||
|
||||
@@ -118,6 +130,13 @@ static void mem_barrier(VkCommandBuffer cb) {
|
||||
vkCmdPipelineBarrier2(cb, &d);
|
||||
}
|
||||
|
||||
// The half-resolution lighting pass after the G-buffer: eight targets at half the scene's size, the first RGBA8.
|
||||
static int is_lighting(const VkExec *ex) {
|
||||
const VkExecTarget *t = &ex->color[0];
|
||||
return C.scene.image && ex->pass_ncolor == 8 && t->image && t->img && !t->level &&
|
||||
t->format == VK_FORMAT_R8G8B8A8_UNORM && ex->pass_w * 2 == C.scene.width && ex->pass_h * 2 == C.scene.height;
|
||||
}
|
||||
|
||||
// The lighting composite: the remembered scene colour as the only target, with a D16 depth of its size.
|
||||
static int is_composite(const VkExec *ex) {
|
||||
return C.scene.image && ex->pass_ncolor >= 1 && ex->color[0].image == C.scene.image && !ex->color[0].level &&
|
||||
@@ -134,7 +153,11 @@ int vk_contact_plan(const VkExec *ex, int pass, VkExecJob *j) {
|
||||
if (b->addr && b->size == 0x940) C.c4 = b->addr;
|
||||
if (is_gbuffer(ex, &scene, &depth)) {
|
||||
C.pending = 0;
|
||||
C.scene = *scene, C.depth = *depth;
|
||||
C.scene = *scene, C.depth = *depth, C.sun = (VkExecTarget){0};
|
||||
return 0;
|
||||
}
|
||||
if (is_lighting(ex)) {
|
||||
C.sun = ex->color[0];
|
||||
return 0;
|
||||
}
|
||||
if (is_composite(ex)) {
|
||||
@@ -149,7 +172,7 @@ int vk_contact_plan(const VkExec *ex, int pass, VkExecJob *j) {
|
||||
float px = u[7 * 4 + 0], py = u[8 * 4 + 1], zfar = u[14 * 4 + 1];
|
||||
if (!(ll > 1e-6f) || !(px > 0) || !(py > 0) || !(zfar > 1)) return 0;
|
||||
float w = (float)C.scene.width, h = (float)C.scene.height;
|
||||
*j = (VkExecJob){.scene = C.scene, .depth = C.depth,
|
||||
*j = (VkExecJob){.scene = C.scene, .depth = C.depth, .sun = C.sun,
|
||||
.pc = {px, py, zfar, (float)C.strength / 100.0f,
|
||||
lx / ll, ly / ll, lz / ll, 0.6f,
|
||||
w, h, 1.0f / w, 1.0f / h,
|
||||
@@ -165,6 +188,9 @@ void vk_contact_exec(VkExec *ex, const VkExecJob *j) {
|
||||
VkImageView out = vk_exec_target_view(j->scene.img, VK_FORMAT_B10G11R11_UFLOAT_PACK32, VK_IMAGE_VIEW_TYPE_2D,
|
||||
VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1, 0);
|
||||
if (!in || !out) return;
|
||||
VkImageView sun = j->sun.img ? vk_exec_target_view(j->sun.img, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_VIEW_TYPE_2D,
|
||||
VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1, 0)
|
||||
: VK_NULL_HANDLE;
|
||||
// A full barrier that also takes the images in the feedback layout back to GENERAL (vk_exec.c barrier_to): the
|
||||
// G-buffer's linear depth and scene colour are such images once a draw sampled them in their own pass, and the march
|
||||
// binds them in GENERAL. A memory barrier alone left them in ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT.
|
||||
@@ -173,21 +199,27 @@ void vk_contact_exec(VkExec *ex, const VkExecJob *j) {
|
||||
float pcv[16];
|
||||
memcpy(pcv, j->pc, sizeof pcv);
|
||||
pcv[12] = (float)C.debug;
|
||||
pcv[13] = sun ? 1.0f : 0.0f;
|
||||
if (!C.logged) {
|
||||
C.logged = 1;
|
||||
rt_log("vk: contact shadows on a %ux%u scene, sun toward %.3f %.3f %.3f (view space), far %g", j->scene.width, j->scene.height,
|
||||
pcv[4], pcv[5], pcv[6], pcv[2]);
|
||||
rt_log("vk: contact shadows on a %ux%u scene, sun toward %.3f %.3f %.3f (view space), far %g; %s", j->scene.width,
|
||||
j->scene.height, pcv[4], pcv[5], pcv[6], pcv[2],
|
||||
sun ? "sunlit pixels only" : "no sun visibility found: every pixel");
|
||||
}
|
||||
VkDescriptorImageInfo ii = {C.sampler, in, VK_IMAGE_LAYOUT_GENERAL}, oi = {VK_NULL_HANDLE, out, VK_IMAGE_LAYOUT_GENERAL};
|
||||
VkWriteDescriptorSet w[2] = {
|
||||
VkDescriptorImageInfo ii = {C.sampler, in, VK_IMAGE_LAYOUT_GENERAL}, oi = {VK_NULL_HANDLE, out, VK_IMAGE_LAYOUT_GENERAL},
|
||||
si = {C.sampler, sun ? sun : in, VK_IMAGE_LAYOUT_GENERAL}; // not read without a sun view
|
||||
VkWriteDescriptorSet w[3] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 0, .descriptorCount = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &ii},
|
||||
{.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 1, .descriptorCount = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &oi}};
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &oi},
|
||||
{.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 2, .descriptorCount = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &si}};
|
||||
vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, C.pipe);
|
||||
rec_push(C.push, cb, VK_PIPELINE_BIND_POINT_COMPUTE, C.layout, 0, 2, w);
|
||||
rec_push(C.push, cb, VK_PIPELINE_BIND_POINT_COMPUTE, C.layout, 0, 3, w);
|
||||
vkCmdPushConstants(cb, C.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof pcv, pcv);
|
||||
vkCmdDispatch(cb, (j->scene.width + 7) / 8, (j->scene.height + 7) / 8, 1);
|
||||
vk_texture_storage_written(j->scene.img); // the march wrote the scene colour: a fence write-back snapshot made before is stale
|
||||
mem_barrier(cb); // and what follows sees the darkened colour
|
||||
ex->recorded += 6;
|
||||
vk_exec_draw_new_cb(ex); // the game's bound compute pipeline and descriptors were replaced: bind them again
|
||||
|
||||
+7
-5
@@ -22,7 +22,10 @@ static PlatMutex g_lock = PLAT_MUTEX_INIT;
|
||||
// the debug messenger. The newest AB_N events stay in a ring written without a lock (one atomic add each), so a device
|
||||
// fault names the object behind its address and whether it was unbound before the fault, which is memory freed while
|
||||
// a submission still used it. One event per image, buffer or memory block made or freed, none per draw.
|
||||
// TOTK_ADDR_REPORT=0 turns it off.
|
||||
// Off by default; TOTK_ADDR_REPORT=1 turns it on for a run that chases a device fault. Our callback is cheap, but with
|
||||
// the feature on AMD's Windows driver (26.10.1) tracks every bound range in a chained hash map it searches on nearly
|
||||
// every recorded command: the chains grow as textures stream in and out, and recording a submission cost 3-4 times
|
||||
// more after minutes of play in a busy area (#1174).
|
||||
#define AB_N (1u << 15)
|
||||
typedef struct { uint64_t seq, base, size, handle, issued, done; int32_t type; uint32_t unbind; } AbEvent;
|
||||
static AbEvent *ab_ring;
|
||||
@@ -137,8 +140,7 @@ static int create_instance(void) {
|
||||
rt_log("vk: TOTK_VK_VALIDATION set but %s is not installed; continuing without", layers[0]);
|
||||
validate = 0;
|
||||
}
|
||||
const char *ar = cfg_get("TOTK_ADDR_REPORT");
|
||||
ab_want = !(ar && !strcmp(ar, "0")) && instance_ext_present(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
|
||||
ab_want = cfg_bool("TOTK_ADDR_REPORT") && instance_ext_present(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
|
||||
if (ab_want && !ab_ring && !(ab_ring = calloc(AB_N, sizeof *ab_ring))) ab_want = 0;
|
||||
if (validate || ab_want) ext[n_ext++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
|
||||
if (vk_hdr_wanted() && instance_ext_present(VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME)) // HDR10 surface formats
|
||||
@@ -405,8 +407,8 @@ static int create_device(void) {
|
||||
// wherever reported; vk_pipeline.c spirv_demote emits OpDemoteToHelperInvocation only when it is.
|
||||
vk_caps.demote = c->f13.shaderDemoteToHelperInvocation;
|
||||
rt_log("vk: GPU address map for device faults: %s",
|
||||
has_abr && c->abr.reportAddressBinding ? "on (VK_EXT_device_address_binding_report; TOTK_ADDR_REPORT=0 turns it off)"
|
||||
: !ab_want ? "off (TOTK_ADDR_REPORT=0 or no VK_EXT_debug_utils)"
|
||||
has_abr && c->abr.reportAddressBinding ? "on (VK_EXT_device_address_binding_report, TOTK_ADDR_REPORT=1)"
|
||||
: !ab_want ? "off (TOTK_ADDR_REPORT=1 turns it on; it slows recording on some drivers)"
|
||||
: "unavailable (no VK_EXT_device_address_binding_report)");
|
||||
g_vk.has_buffer_device_address = c->f12.bufferDeviceAddress;
|
||||
// VkPresentIdKHR on a present needs the presentId feature, not just the extension
|
||||
|
||||
+331
-18
@@ -227,7 +227,8 @@ int vk_dlaa_available(void) { return vk_dlaa_wanted() && N.available; }
|
||||
// So: after the G-buffer, a pass at the scene size with exactly one colour target (R11G11B10F or RGBA16F) and the D32F
|
||||
// depth arms the frame with that pair; the next pass at most a quarter as wide ends the scene (no jitter after it) and,
|
||||
// when the scene is as wide as the output, runs DLAA on the armed target first. Bloom, tonemap, post and HUD then all
|
||||
// work on the anti-aliased picture.
|
||||
// work on the anti-aliased picture. With DLAA the scene ends before that, at the first pass into the light target after
|
||||
// the lighting: the fog and the particles then go over DLAA's picture (effects_point).
|
||||
// Upscaling (a scene smaller than the output: TOTK_DLSS quality/balanced/performance, or the game's own 5/6): measured
|
||||
// at a 960x536 scene, 1920x1080 output, the bloom and its composite write back into the light target at the scene size,
|
||||
// then one full-screen draw (the FXAA shader below, which also scales) reads it into an output-sized R11G11B10F target
|
||||
@@ -262,7 +263,13 @@ static struct {
|
||||
VkImage last_color; // the target DLAA ran on last frame: another one means a new history
|
||||
NgxParam *params;
|
||||
int failed, reset;
|
||||
uint64_t evals, frames_missed;
|
||||
uint64_t evals, frames_missed, fx_frames; // fx_frames: DLAA ran before the effects (effects_point)
|
||||
VkImage glight; // this frame: the light target among the G-buffer's targets (gbuf_light)
|
||||
VkExecTarget glight_z; // that G-buffer's depth, the scene depth
|
||||
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
|
||||
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
|
||||
float jx, jy; // the offset the next scene draws take, render pixels (window x right, y down)
|
||||
@@ -289,6 +296,7 @@ static struct {
|
||||
uint64_t why[3]; // history resets: scene size changed, no camera, scene target changed
|
||||
int on; // the dlaa setting, read at each present (the menu switches it live)
|
||||
int preset, preset_dirty; // the DLSS model features are created with (preset_value); a change pending
|
||||
int fixed_exposure; // dlss_fixed_exposure the features are created with (preset_check)
|
||||
VkExecTarget ids; // this frame's G-buffer target 0 (object classes in green), valid with ids_ok
|
||||
int ids_ok;
|
||||
unsigned cfg_seen; // cfg_version when preset was read
|
||||
@@ -459,6 +467,9 @@ static void times_begin(VkCommandBuffer cb) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- motion vectors
|
||||
static int cam_mode(void); // the jitter in the game's camera (below, "jitter in the game's camera")
|
||||
static int cam_offset(uint64_t blk, float *sx, float *sy);
|
||||
static int unj_put(VkCommandBuffer cb, const float *blk, float sx, float sy, VkBuffer buf, VkDeviceSize off);
|
||||
// The camera's motion first (runtime/shaders/dlaa_mv.comp): this frame's scene camera block is copied out of the
|
||||
// replay's uniform snapshot (vk_usnap.c, as of the submit call) into one slot of camb, last frame's stays in the other,
|
||||
// and the compute pass reprojects every pixel's depth through the two (inv4 and mv_pass below). Then the per-object
|
||||
@@ -572,8 +583,11 @@ static int mv_pass(VkExec *ex, struct Size *e, VkImageView zv, float jx, float j
|
||||
const float *cr = (const float *)vk_usnap_bytes(D.cam_addr + 48, 64);
|
||||
double cur_vp[16], m[16], ci[16];
|
||||
int have_m = 0;
|
||||
float osx = 0.0f, osy = 0.0f;
|
||||
if (cam_mode()) cam_offset(D.cam_addr, &osx, &osy);
|
||||
if (cr) {
|
||||
for (int i = 0; i < 16; i++) cur_vp[i] = cr[i];
|
||||
for (int k = 0; k < 4; k++) cur_vp[k] -= osx * cr[12 + k], cur_vp[4 + k] -= osy * cr[12 + k];
|
||||
if (D.cam_prev_ok && inv4(cur_vp, ci)) {
|
||||
for (int r = 0; r < 4; r++)
|
||||
for (int k = 0; k < 4; k++) {
|
||||
@@ -588,6 +602,8 @@ static int mv_pass(VkExec *ex, struct Size *e, VkImageView zv, float jx, float j
|
||||
VkBufferCopy bc = {cam.offset, (VkDeviceSize)s * CAM_SLOT, CAM_BLOCK};
|
||||
vkCmdCopyBuffer(cb, cam.buffer, D.camb, 1, &bc);
|
||||
full_barrier(cb);
|
||||
const float *cb_bytes = osx != 0.0f || osy != 0.0f ? (const float *)vk_usnap_bytes(D.cam_addr, 0xb0) : NULL;
|
||||
if (cb_bytes && unj_put(cb, cb_bytes, osx, osy, D.camb, (VkDeviceSize)s * CAM_SLOT)) full_barrier(cb);
|
||||
D.cam_slot ^= 1, D.cam_prev_ok = cr != NULL;
|
||||
if (cr) memcpy(D.cam_prev, cur_vp, sizeof cur_vp);
|
||||
if (!had_prev || !have_m) { // nothing to reproject into: zero motion, new history
|
||||
@@ -663,7 +679,8 @@ static int mv_pass(VkExec *ex, struct Size *e, VkImageView zv, float jx, float j
|
||||
int vk_dlaa_prev_camera(VkDescriptorBufferInfo *out, float jitter[2]) {
|
||||
if (!dl_active() || !D.cam_prev_ok || !D.camb) return 0;
|
||||
*out = (VkDescriptorBufferInfo){D.camb, (VkDeviceSize)(D.cam_slot ^ 1) * CAM_SLOT, CAM_BLOCK};
|
||||
jitter[0] = D.jit_ok ? D.jx : 0.0f, jitter[1] = D.jit_ok ? D.jy : 0.0f;
|
||||
if (cam_mode()) jitter[0] = D.jit_used ? D.ux : 0.0f, jitter[1] = D.jit_used ? D.uy : 0.0f;
|
||||
else jitter[0] = D.jit_ok ? D.jx : 0.0f, jitter[1] = D.jit_ok ? D.jy : 0.0f;
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -823,7 +840,8 @@ static struct Snap *mask_pass(VkCommandBuffer cb, VkImageView cv, uint32_t w, ui
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- jitter
|
||||
// The scene's draws (every pass drawing with the scene depth, until the DLAA point) have their viewport moved by a
|
||||
// On 1.4.3 the game's camera carries the jitter instead (below, "jitter in the game's camera"); on the other versions
|
||||
// the scene's draws (every pass drawing with the scene depth, until the DLAA point) have their viewport moved by a
|
||||
// sub-pixel Halton(2,3) offset, which shifts what they rasterise as a jittered projection would; full-screen passes
|
||||
// that shade by window position are unaffected. Jitter only follows a frame DLSS ran on: a jittered frame that DLSS
|
||||
// does not resolve shakes on screen, so a missed DLAA point stops the jitter for a second.
|
||||
@@ -842,6 +860,7 @@ static int ended_at(const VkExec *ex) {
|
||||
}
|
||||
|
||||
void vk_dlaa_viewport(VkExec *ex, VkViewport *v) {
|
||||
if (cam_mode()) return; // the camera carries the jitter
|
||||
if (!D.jit_ok || !ex->depth.image || ex->depth.image != D.jdepth || ended_at(ex)) return;
|
||||
v->x += D.jx, v->y += D.jy;
|
||||
D.ux = D.jx, D.uy = D.jy;
|
||||
@@ -854,8 +873,15 @@ static void note_camera(const VkExec *ex) {
|
||||
const p_bind_buf *b = &ex->ubo[0][1]; // constant bank c4: the replay keeps user banks from c3 on
|
||||
const VkExecTarget *z = &ex->depth;
|
||||
if (b->size == 0x940 && b->addr && z->image && z->width >= DLAA_SCENE_MIN_W && z->format == VK_FORMAT_D32_SFLOAT &&
|
||||
(!D.jdepth || z->image == D.jdepth))
|
||||
(!D.jdepth || z->image == D.jdepth)) {
|
||||
if (cam_mode() && b->addr != D.cam_addr) {
|
||||
float sx, sy;
|
||||
int j = cam_offset(b->addr, &sx, &sy);
|
||||
D.ux = sx * (float)z->width * 0.5f, D.uy = -sy * (float)z->height * 0.5f;
|
||||
__atomic_store_n(&D.jit_used, j, __ATOMIC_RELAXED);
|
||||
}
|
||||
D.cam_addr = b->addr;
|
||||
}
|
||||
}
|
||||
|
||||
void vk_dlaa_draw(VkExec *ex) {
|
||||
@@ -914,6 +940,204 @@ static void next_jitter(uint32_t w, uint32_t ow) {
|
||||
D.jit_ok = !D.hold && !nj;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- jitter in the game's camera (1.4.3)
|
||||
// Moving the viewport jitters what the scene draws rasterise, but not the camera the game reconstructs positions with:
|
||||
// its full-screen passes rebuild each pixel's view ray from the camera block (the half-size lighting's vertex shaders
|
||||
// read the projection's centre terms, P[0][2] and P[1][2], with its tangents) and its depth, so with the depth half a
|
||||
// pixel off they put a surface's points off the surface by half a pixel of its depth slope. On water seen at a low
|
||||
// angle that decides whether a screen-space reflection ray hits or misses, and whole patches of a pond flipped between
|
||||
// the trees' reflection and the sky's with the jitter's phase (a period of three frames), more than DLSS could resolve;
|
||||
// measured without DLSS with the same jitter, the pond's brightness swung 2.3-3.0 levels with the viewport moved and
|
||||
// 0.03-0.04 with the camera moved, the edges shimmering alike. So on 1.4.3 the jitter goes into the camera itself, where
|
||||
// the game copies its matrices into each camera's uniform block (f_70000e31d4: the projection, rows 7-10, then the
|
||||
// view-projection, rows 3-6, each a 64-byte memcpy, which ov_memcpy hands over): a perspective camera with the scene's
|
||||
// aspect, the main one and its half-size copy among them, gets the offset in its projection's centre terms and the same
|
||||
// in its view-projection, x_clip += sx w and y_clip += sy w. Its shadow cascades are orthographic and stay as they are.
|
||||
// The offset moves on at the first projection copied after each of the game's presents (vk_dlaa_game_present): the game
|
||||
// fills two sets of blocks in turn, one per frame, so a block written again is not a new frame.
|
||||
// The replay reads the offset back from the snapshot of the scene camera's block (cam_offset, the snapshot is the block
|
||||
// as of the submit) for DLSS, the motion vectors and the per-object pass, which reproject with the camera unjittered;
|
||||
// after the DLSS point the snapshots of the jittered blocks are written back unjittered (cam_unjitter), so the effects
|
||||
// drawn over DLSS's picture stay unjittered as before. A block's centre terms count as an offset only when they are one
|
||||
// this code gave that block (CJ.given): the game has off-centre projections of its own, such as the inventory's camera,
|
||||
// which draws Link right of the screen's centre with P[0][2] about -0.6, and read as a jitter that sent DLSS an offset
|
||||
// of 1152 pixels, smearing the world behind the inventory into horizontal streaks. TOTK_DLAA_CAM_JITTER=0 (test) moves
|
||||
// the viewport as on the other game versions.
|
||||
#define CAMJ_P_LR 0x70000e3688ull // the return address of the projection's copy (rows 7-10)
|
||||
#define CAMJ_VP_LR 0x70000e36f4ull // and of the view-projection's (rows 3-6)
|
||||
#define CAMJ_BLOCKS 16
|
||||
#define CAMJ_GIVEN 256 // offsets given lately, by block: about 40 frames' worth, the replay is a few behind
|
||||
#define UNJ_SLOTS 4096u // 64-byte patches in flight (cam_unjitter, mv_pass): about 60 frames' worth
|
||||
|
||||
static struct {
|
||||
PlatMutex lk;
|
||||
uint64_t presents, moved; // the game's presents, and their count when the offset last moved on
|
||||
struct { uint64_t blk; float sx, sy; } cur[CAMJ_BLOCKS]; // this frame's blocks and the offset each projection took
|
||||
int ncur;
|
||||
struct { uint64_t blk; float sx, sy; } given[CAMJ_GIVEN]; // each offset given and its block, a ring
|
||||
uint32_t ngiven;
|
||||
uint32_t idx; // phases handed out
|
||||
float sx, sy; // this frame's offset, clip units (0: none)
|
||||
VkBuffer unj; // UNJ_SLOTS host-visible patches the replay copies from
|
||||
VmaAllocation unj_mem;
|
||||
uint8_t *unj_map;
|
||||
uint32_t unj_slot;
|
||||
} CJ = {.lk = PLAT_MUTEX_INIT};
|
||||
|
||||
static int cam_mode(void) {
|
||||
static int on = -1;
|
||||
if (on < 0) on = rt_game_version == 143 && rt_knob("DLAA_CAM_JITTER", "1") && rt_knob("UBO_SNAPSHOT", "1");
|
||||
return on;
|
||||
}
|
||||
|
||||
static int in_list(const uint64_t *l, int n, uint64_t a) {
|
||||
for (int i = 0; i < n; i++)
|
||||
if (l[i] == a) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void vk_dlaa_game_present(void) { __atomic_add_fetch(&CJ.presents, 1, __ATOMIC_RELEASE); }
|
||||
|
||||
// The game's thread, after a 64-byte memcpy: lr is the copy's return address into the game, dst where it copied to, off
|
||||
// the member's offset in the block. f_70000e31d4 takes each offset from the shader's layout of the block (x8 at both
|
||||
// copies, dst = the block's base + x8), so a block takes the offset only with its matrices where the rest of this
|
||||
// code reads and writes them, the projection at 0x70 and the view-projection at 0x30, as in the scene camera's block.
|
||||
void vk_dlaa_camera_copied(uint64_t lr, uint64_t dst, uint64_t off) {
|
||||
if ((lr != CAMJ_P_LR && lr != CAMJ_VP_LR) || !cam_mode() || !dl_active()) return;
|
||||
if (lr == CAMJ_P_LR && off != 0x70) return;
|
||||
float *m = (float *)(uintptr_t)dst;
|
||||
uint64_t blk = dst - off;
|
||||
plat_mutex_lock(&CJ.lk);
|
||||
if (lr == CAMJ_P_LR) {
|
||||
unsigned o[2], s[2];
|
||||
res_sizes(o, s);
|
||||
float asp = s[1] ? (float)s[0] / (float)s[1] : 0.0f;
|
||||
// perspective (w = -z), symmetric, with the scene's aspect
|
||||
if (m[14] != -1.0f || m[15] != 0.0f || m[2] != 0.0f || m[6] != 0.0f || !(m[0] > 0.0f) ||
|
||||
fabsf(m[5] / m[0] - asp) > 0.01f * asp) {
|
||||
plat_mutex_unlock(&CJ.lk);
|
||||
return;
|
||||
}
|
||||
uint64_t pf = __atomic_load_n(&CJ.presents, __ATOMIC_ACQUIRE);
|
||||
if (pf != CJ.moved) { // the first projection of a new frame
|
||||
static int nj = -1;
|
||||
if (nj < 0) nj = !rt_knob("DLAA_JITTER", "1");
|
||||
CJ.moved = pf, CJ.ncur = 0, CJ.sx = CJ.sy = 0.0f;
|
||||
if (dl_active() && !__atomic_load_n(&D.hold, __ATOMIC_RELAXED) && !nj && s[0] && s[1]) {
|
||||
double r = (double)o[0] / s[0];
|
||||
uint32_t ph = (uint32_t)ceil(8.0 * r * r - 1e-6);
|
||||
ph = ph < 16 ? 16 : ph > 72 ? 72 : ph;
|
||||
uint32_t i = CJ.idx++ % ph + 1;
|
||||
CJ.sx = 2.0f * (halton(i, 2) - 0.5f) / (float)s[0]; // content right by the offset in pixels
|
||||
CJ.sy = -2.0f * (halton(i, 3) - 0.5f) / (float)s[1]; // and down: NDC +y is the top row
|
||||
}
|
||||
}
|
||||
int i = 0;
|
||||
while (i < CJ.ncur && CJ.cur[i].blk != blk) i++;
|
||||
if ((CJ.sx != 0.0f || CJ.sy != 0.0f) && i < CAMJ_BLOCKS) { // no room: no offset, its view-projection takes none
|
||||
m[2] -= CJ.sx, m[6] -= CJ.sy;
|
||||
CJ.cur[i].blk = blk, CJ.cur[i].sx = CJ.sx, CJ.cur[i].sy = CJ.sy, CJ.ncur += i == CJ.ncur;
|
||||
}
|
||||
} else { // the view-projection takes the offset its block's projection took this frame
|
||||
for (int i = 0; i < CJ.ncur; i++)
|
||||
if (CJ.cur[i].blk == blk) {
|
||||
if (off != 0x30) { // elsewhere in this block: the projection goes back to its centre terms of 0
|
||||
float *pm = (float *)(uintptr_t)(blk + 0x70);
|
||||
pm[2] += CJ.cur[i].sx, pm[6] += CJ.cur[i].sy;
|
||||
CJ.cur[i] = CJ.cur[--CJ.ncur];
|
||||
break;
|
||||
}
|
||||
for (int k = 0; k < 4; k++) m[k] += CJ.cur[i].sx * m[12 + k], m[4 + k] += CJ.cur[i].sy * m[12 + k];
|
||||
// Given only now that both matrices carry it: a block whose view-projection did not take it is never
|
||||
// read back as jittered, nor written back by cam_unjitter.
|
||||
uint32_t g = CJ.ngiven++ % CAMJ_GIVEN;
|
||||
CJ.given[g].blk = blk, CJ.given[g].sx = CJ.cur[i].sx, CJ.given[g].sy = CJ.cur[i].sy;
|
||||
break;
|
||||
}
|
||||
}
|
||||
plat_mutex_unlock(&CJ.lk);
|
||||
}
|
||||
|
||||
// The offset a camera block took (clip units), from its snapshot, else from guest memory: a chunked replay's scan can
|
||||
// come before the snapshot, and the block holds this frame's bytes until the game's next frame. Centre terms this code
|
||||
// did not give the block are the game's own and read as no offset.
|
||||
static int cam_offset(uint64_t blk, float *sx, float *sy) {
|
||||
*sx = *sy = 0.0f;
|
||||
if (!blk) return 0;
|
||||
const float *p = (const float *)vk_usnap_bytes(blk + 0x70, 32);
|
||||
if (!p) p = (const float *)(uintptr_t)(blk + 0x70);
|
||||
float x = -p[2], y = -p[6];
|
||||
if (x == 0.0f && y == 0.0f) return 0;
|
||||
int ours = 0;
|
||||
plat_mutex_lock(&CJ.lk);
|
||||
for (uint32_t i = 0, n = CJ.ngiven < CAMJ_GIVEN ? CJ.ngiven : CAMJ_GIVEN; i < n && !ours; i++)
|
||||
ours = CJ.given[i].blk == blk && CJ.given[i].sx == x && CJ.given[i].sy == y;
|
||||
plat_mutex_unlock(&CJ.lk);
|
||||
if (ours) *sx = x, *sy = y;
|
||||
return ours;
|
||||
}
|
||||
|
||||
// Records copies that write a block's view-projection rows 3-4 and projection rows 7-8 back without the offset (blk:
|
||||
// the block's bytes as the snapshot holds them) into buf at off, the block's place there. 0: no room.
|
||||
static int unj_put(VkCommandBuffer cb, const float *blk, float sx, float sy, VkBuffer buf, VkDeviceSize off) {
|
||||
if (!CJ.unj) {
|
||||
VkBufferCreateInfo bi = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = UNJ_SLOTS * 64u,
|
||||
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT};
|
||||
VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST,
|
||||
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
|
||||
VMA_ALLOCATION_CREATE_MAPPED_BIT};
|
||||
VmaAllocationInfo inf;
|
||||
if (vmaCreateBuffer(vk_ctx()->vma, &bi, &ai, &CJ.unj, &CJ.unj_mem, &inf) != VK_SUCCESS) return CJ.unj = 0, 0;
|
||||
CJ.unj_map = inf.pMappedData;
|
||||
}
|
||||
uint32_t sl = __atomic_fetch_add(&CJ.unj_slot, 1, __ATOMIC_RELAXED) % UNJ_SLOTS;
|
||||
float v[16];
|
||||
for (int k = 0; k < 4; k++) v[k] = blk[12 + k] - sx * blk[24 + k], v[4 + k] = blk[16 + k] - sy * blk[24 + k];
|
||||
memcpy(v + 8, blk + 28, 32);
|
||||
v[10] = 0.0f, v[14] = 0.0f;
|
||||
memcpy(CJ.unj_map + (size_t)sl * 64, v, sizeof v);
|
||||
vmaFlushAllocation(vk_ctx()->vma, CJ.unj_mem, (VkDeviceSize)sl * 64, 64);
|
||||
VkBufferCopy r[2] = {{(VkDeviceSize)sl * 64, off + 0x30, 32}, {(VkDeviceSize)sl * 64 + 32, off + 0x70, 32}};
|
||||
vkCmdCopyBuffer(cb, CJ.unj, buf, 2, r);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// After the DLSS point, once in each command buffer of the frame: the snapshots of the blocks that took an offset are
|
||||
// written back without it, so the effects drawn over DLSS's picture use the camera unjittered, as before the move.
|
||||
static void cam_unjitter(VkExec *ex) {
|
||||
if (!cam_mode() || !dl_active() || !ended_at(ex)) return;
|
||||
static PlatMutex lk = PLAT_MUTEX_INIT;
|
||||
static VkCommandBuffer done[32];
|
||||
static int nd;
|
||||
static uint64_t done_frame = UINT64_MAX;
|
||||
uint64_t f = __atomic_load_n(&gfx_counters.frames, __ATOMIC_RELAXED);
|
||||
plat_mutex_lock(&lk);
|
||||
if (f != done_frame) done_frame = f, nd = 0;
|
||||
int dup = 0;
|
||||
for (int i = 0; i < nd && !dup; i++) dup = done[i] == ex->cb;
|
||||
if (!dup && nd < 32) done[nd++] = ex->cb;
|
||||
plat_mutex_unlock(&lk);
|
||||
if (dup) return;
|
||||
uint64_t blocks[CAMJ_BLOCKS]; // the blocks given an offset lately, newest first
|
||||
int n = 0;
|
||||
plat_mutex_lock(&CJ.lk);
|
||||
for (uint32_t k = 0, m = CJ.ngiven < CAMJ_GIVEN ? CJ.ngiven : CAMJ_GIVEN; k < m && n < CAMJ_BLOCKS; k++) {
|
||||
uint64_t blk = CJ.given[(CJ.ngiven - 1 - k) % CAMJ_GIVEN].blk;
|
||||
if (!in_list(blocks, n, blk)) blocks[n++] = blk;
|
||||
}
|
||||
plat_mutex_unlock(&CJ.lk);
|
||||
int any = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
VkDescriptorBufferInfo bi;
|
||||
float sx, sy;
|
||||
const float *b = (const float *)vk_usnap_bytes(blocks[i], 0xb0);
|
||||
if (!b || !cam_offset(blocks[i], &sx, &sy) || !vk_usnap_find(blocks[i], 0xb0, UINT32_MAX, 4, &bi)) continue;
|
||||
if (!any) full_barrier(ex->cb); // the scene's draws read the jittered rows until here
|
||||
any |= unj_put(ex->cb, b, sx, sy, bi.buffer, bi.offset);
|
||||
}
|
||||
if (any) full_barrier(ex->cb), ex->recorded += 3;
|
||||
}
|
||||
|
||||
// The DLSS model (TOTK_DLSS_PRESET, live): default takes NVIDIA's model per mode (evaluate: K for DLAA, Quality and
|
||||
// Balanced, M for Performance, L for Ultra Performance), 0 here. A letter a..m takes that model in every mode: k pins
|
||||
// K, j is the other transformer model, which NVIDIA describes as slightly less ghosting at the cost of extra flicker, e
|
||||
@@ -1000,8 +1224,13 @@ static void evaluate(VkExec *ex, const VkExecTarget *dst) {
|
||||
p_setu(p, "OutWidth", ow);
|
||||
p_setu(p, "OutHeight", oh);
|
||||
p_seti(p, "PerfQualityValue", perf_quality(w, ow));
|
||||
// IsHDR | MVLowRes | AutoExposure: linear scene light, motion vectors at the render size, no exposure texture
|
||||
p_seti(p, "DLSS.Feature.Create.Flags", (1 << 0) | (1 << 1) | (1 << 6));
|
||||
// IsHDR | MVLowRes: linear scene light, motion vectors at the render size, no exposure texture; AutoExposure
|
||||
// (1 << 6) unless dlss_fixed_exposure. With AutoExposure DLSS estimates the exposure from each frame itself, and
|
||||
// in the Depths, where the whole scene is dark, the estimate moved with the camera; distant blocks under uniform
|
||||
// fog came out up to 0.7 levels (of 255) darker or brighter for a frame, where the game's own picture held one
|
||||
// value (a 64x64 patch at 30.79 without DLAA read 30.09-30.79 frame to frame with AutoExposure and 30.4-30.7,
|
||||
// steady, without it). Without it DLSS takes the exposure as 1.
|
||||
p_seti(p, "DLSS.Feature.Create.Flags", (1 << 0) | (1 << 1) | (D.fixed_exposure ? 0 : 1 << 6));
|
||||
p_seti(p, "DLSS.Enable.Output.Subrects", 0);
|
||||
// The model per mode (NVSDK_NGX_DLSS_Hint_Render_Preset: 1 A ... 11 K, 12 L, 13 M), as NVIDIA recommends for
|
||||
// DLSS 4.5 (310.x): K (transformer) for DLAA, Quality and Balanced, M for Performance, L for Ultra Performance.
|
||||
@@ -1083,11 +1312,12 @@ static void evaluate(VkExec *ex, const VkExecTarget *dst) {
|
||||
vk_exec_draw_new_cb(ex); // NGX bound pipelines and descriptor sets of its own: the next draw binds everything again
|
||||
D.jdepth = z->image;
|
||||
next_jitter(w, ow);
|
||||
cam_unjitter(ex);
|
||||
if (++D.evals == 1 || D.evals == 300 || D.evals % 3600 == 0) // 300: one early line with the frames counted
|
||||
rt_log("dlaa: %llu frames anti-aliased (scene %ux%u, output %ux%u; %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, w, h, ow, oh, (unsigned long long)D.frames_missed,
|
||||
rt_log("dlaa: %llu frames anti-aliased (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, 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);
|
||||
@@ -1127,8 +1357,73 @@ static int bloom_start(const VkExec *ex, uint32_t scene_w) {
|
||||
return a * 20 >= b * 19 && b * 20 >= a * 19;
|
||||
}
|
||||
|
||||
// The light target is one of the G-buffer's targets (the emissive surfaces go into it there), the only one of a scene
|
||||
// colour format and the depth's size. NULL when that is not so.
|
||||
static void gbuf_light(const VkExec *ex) {
|
||||
const VkExecTarget *z = &ex->depth, *l = NULL;
|
||||
for (uint32_t i = 0; i < ex->pass_ncolor && i < 8; i++) {
|
||||
const VkExecTarget *t = &ex->color[i];
|
||||
if (!t->image || !scene_color(t->format) || t->width != z->width || t->height != z->height || t->level ||
|
||||
t->samples > 1 || t->is3d)
|
||||
continue;
|
||||
if (l) return (void)(D.glight = VK_NULL_HANDLE);
|
||||
l = t;
|
||||
}
|
||||
D.glight = l ? l->image : VK_NULL_HANDLE, D.glight_z = *z, D.light_z = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
// DLAA (the scene as wide as the output) runs on the solid scene alone, before the effects. Measured in a shrine and
|
||||
// in the yard of Lookout Landing (3840x2160, frame dumps and a log of the passes into the light target): after the
|
||||
// G-buffer the deferred lighting draws into the light target with a D16 depth of its own, and from there on every draw
|
||||
// into the light target blends: in the shrine a fog layer with the scene depth, the volumetric fog drawn at half size
|
||||
// and blended over the whole picture by a full-screen draw without depth (79 % of the pixels change), and the dust with
|
||||
// the scene depth (dots of 1-3 pixels and soft discs); in the yard the field's effects composite without depth, then
|
||||
// the particles with the scene depth; with an ability's targeting view open, the highlight of the objects it can take,
|
||||
// with a D16 depth of its own, another one than the lighting's. Run at the bloom, DLSS took the dust and the fog in
|
||||
// with the motion of the walls behind them and no jitter of their own, and wiped out the smallest motes. So the first
|
||||
// pass into the light target after the lighting runs DLSS before it, and the effects are drawn over its picture without
|
||||
// jitter, as the game draws them without DLSS. The lighting is the first pass into the light target with a D16 depth
|
||||
// after the G-buffer, and its depth tells the lighting from the effects: the order of the effects changes from frame
|
||||
// to frame (the yard's half-size effects pass is there in some frames only; the ability highlight comes before the
|
||||
// fog layer in some frames and after it in others), and every rule that waited for one of them, or took any D16 pass
|
||||
// for the lighting, ran DLSS before some effects in one frame and after them in the next, and the picture flickered.
|
||||
// The point is also taken only where it held for FX_STEADY frames in a row with nothing of the scene drawn after it
|
||||
// (fx_watch: a G-buffer pass, or the lighting's depth into the light target again, up to the bloom): a frame that
|
||||
// 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.
|
||||
#define FX_STEADY 60u
|
||||
|
||||
static int effects_point(const VkExec *ex) {
|
||||
const VkExecTarget *c = &ex->color[0], *z = &ex->depth;
|
||||
if (!D.fx_on || D.fx_bad || !D.glight || D.ended || ex->pass_ncolor != 1 || c->image != D.glight || c->level) return 0;
|
||||
if (!D.light_z) {
|
||||
if (z->image && z->format == VK_FORMAT_D16_UNORM) D.light_z = z->image;
|
||||
return 0;
|
||||
}
|
||||
if (z->image == D.light_z) return 0;
|
||||
unsigned o[2], s[2];
|
||||
res_sizes(o, s);
|
||||
if (c->width < o[0] || !scene_shaped(c) || !scene_large(c)) return 0;
|
||||
D.fx_seen = D.fx_open = 1;
|
||||
return D.fx_steady >= FX_STEADY;
|
||||
}
|
||||
|
||||
static void fx_watch(const VkExec *ex) {
|
||||
const VkExecTarget *z = &ex->depth;
|
||||
if (bloom_start(ex, D.glight_z.width)) {
|
||||
D.fx_open = 0;
|
||||
return;
|
||||
}
|
||||
int light = 0;
|
||||
for (uint32_t i = 0; i < ex->pass_ncolor && i < 8; i++) light |= ex->color[i].image == D.glight;
|
||||
int geometry = ex->pass_ncolor >= 3 && z->image && z->format == VK_FORMAT_D32_SFLOAT && z->width >= D.gbuf_w;
|
||||
if (geometry || (light && z->image && z->image == D.light_z)) D.fx_seen = D.fx_open = 0, D.fx_bad = 1;
|
||||
}
|
||||
|
||||
int vk_dlaa_plan(const VkExec *ex, VkExecJob *j) {
|
||||
const VkExecTarget *c = &ex->color[0], *z = &ex->depth;
|
||||
if (D.fx_open && dl_active()) fx_watch(ex);
|
||||
if (!dl_active() || D.done) return 0;
|
||||
// The G-buffer: several colour targets with a D32F depth of at least DLAA_SCENE_MIN_W wide. Only the light target drawn after it
|
||||
// arms the frame; at night the game draws into the light target alone with the scene depth before the G-buffer too,
|
||||
@@ -1141,8 +1436,17 @@ int vk_dlaa_plan(const VkExec *ex, VkExecJob *j) {
|
||||
if (c->image && c->format == VK_FORMAT_R8G8B8A8_UNORM && c->width == z->width && c->height == z->height &&
|
||||
c->samples <= 1 && !c->is3d && (!D.ids_ok || c->width >= D.ids.width))
|
||||
D.ids = *c, D.ids_ok = 1;
|
||||
if (z->width >= D.gbuf_w) gbuf_light(ex);
|
||||
return 0;
|
||||
}
|
||||
if (effects_point(ex)) {
|
||||
D.color = *c, D.depth = D.glight_z, D.armed = 1;
|
||||
D.end_fence = ex->fence, D.end_pos = ex->pos;
|
||||
__atomic_store_n(&D.ended, 1, __ATOMIC_RELEASE);
|
||||
D.done = 1, D.fx_frames++;
|
||||
*j = (VkExecJob){.kind = VK_JOB_DLSS}; // DLAA in place
|
||||
return 1;
|
||||
}
|
||||
// A pass into one scene colour target of the G-buffer's size or larger without depth while nothing is armed ends
|
||||
// the scene once the bloom chain follows with still nothing armed: in the inventory (1.4.3) the preview's light
|
||||
// target is drawn that way before the bloom, and with the scene depth only after it, while the menu is composed;
|
||||
@@ -1228,6 +1532,7 @@ void vk_dlaa_exec(VkExec *ex, const VkExecJob *j) {
|
||||
}
|
||||
|
||||
void vk_dlaa_pass(VkExec *ex) {
|
||||
cam_unjitter(ex);
|
||||
VkExecJob j;
|
||||
if (!ex->chunked && vk_dlaa_plan(ex, &j)) vk_dlaa_exec(ex, &j);
|
||||
}
|
||||
@@ -1248,18 +1553,21 @@ static void dlss_mode(void) {
|
||||
}
|
||||
|
||||
|
||||
// The preset, read again when a setting changed (the menu); a different one recreates the features at the next DLAA run.
|
||||
// The preset and dlss_fixed_exposure, read again when a setting changed (the menu); a different one recreates the
|
||||
// features at the next DLAA run.
|
||||
static void preset_check(void) {
|
||||
unsigned v = cfg_version();
|
||||
if (v == D.cfg_seen) return;
|
||||
D.cfg_seen = v;
|
||||
int p = preset_value();
|
||||
if (p == D.preset) return;
|
||||
if (D.evals) {
|
||||
int p = preset_value(), x = cfg_bool("TOTK_DLSS_FIXED_EXPOSURE");
|
||||
if (p == D.preset && x == D.fixed_exposure) return;
|
||||
if (D.evals && p != D.preset) {
|
||||
if (p) rt_log("dlaa: DLSS preset %c in every mode; the features are created again", 'A' + p - 1);
|
||||
else rt_log("dlaa: DLSS presets per mode; the features are created again");
|
||||
}
|
||||
D.preset = p, D.preset_dirty = 1, D.reset = 1;
|
||||
if (D.evals && x != D.fixed_exposure)
|
||||
rt_log("dlaa: DLSS %s; the features are created again", x ? "exposure fixed at 1" : "auto exposure");
|
||||
D.preset = p, D.fixed_exposure = x, D.preset_dirty = 1, D.reset = 1;
|
||||
}
|
||||
|
||||
void vk_dlaa_frame(void) {
|
||||
@@ -1272,16 +1580,21 @@ void vk_dlaa_frame(void) {
|
||||
D.on = on;
|
||||
// either way the next DLAA frame starts a new history from an unjittered frame
|
||||
D.reset = 1, D.cam_prev_ok = 0, D.jit_ok = D.jit_used = D.armed = D.done = D.gbuf = D.ended = D.up = 0;
|
||||
D.nodepth = VK_NULL_HANDLE;
|
||||
D.fx_seen = D.fx_open = D.fx_bad = 0, D.fx_steady = 0;
|
||||
D.nodepth = D.glight = D.light_z = VK_NULL_HANDLE;
|
||||
D.hold = 0;
|
||||
return;
|
||||
}
|
||||
if (!dl_active()) return;
|
||||
D.fx_on = cfg_bool("TOTK_DLAA_EFFECTS_AFTER");
|
||||
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;
|
||||
if (D.jit_used && !D.done) D.hold = 60, D.holds++; // jittered but not resolved: that frame shook
|
||||
else if (D.hold) D.hold--;
|
||||
if (!D.done) D.jit_ok = 0;
|
||||
D.armed = D.done = D.jit_used = D.gbuf = D.ended = D.up = D.ids_ok = 0, D.nodepth = VK_NULL_HANDLE;
|
||||
D.armed = D.done = D.jit_used = D.gbuf = D.ended = D.up = D.ids_ok = 0;
|
||||
D.nodepth = D.glight = D.light_z = VK_NULL_HANDLE;
|
||||
D.cam_addr = 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,9 @@ void vk_mvprev_draw(VkExec *ex); // vk_mvprev.c: notes the scene draw's object
|
||||
int vk_mvobj_execute(VkExec *ex, uint64_t cam, VkImageView mv, VkImageView depth, VkFormat depth_fmt, uint32_t w,
|
||||
uint32_t h);
|
||||
int vk_dlaa_prev_camera(VkDescriptorBufferInfo *out, float jitter[2]);
|
||||
// nvn_api_core.c ov_memcpy, after a 64-byte copy on the game's thread: the camera jitter of 1.4.3 (vk_dlaa.c).
|
||||
void vk_dlaa_camera_copied(uint64_t lr, uint64_t dst, uint64_t off);
|
||||
void vk_dlaa_game_present(void); // vk_backend.c, each of the game's presents, on its thread
|
||||
// vk_mvcheck.c (TOTK_MV_CHECK, test): mv_pass hands it the motion image after the camera pass and, after the object
|
||||
// pass, the motion image again and the scene light target it ran on; it measures how well the vectors fit the picture.
|
||||
void vk_mvcheck_camera(VkCommandBuffer cb, VkImage mv, uint32_t w, uint32_t h, float jx, float jy);
|
||||
|
||||
+47
-4
@@ -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; 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) 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->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->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;
|
||||
@@ -136,6 +136,7 @@ static void state_reset(VkExec *ex) {
|
||||
vk_pipe_state_defaults(&ex->pipe);
|
||||
ex->barrier_at = -1;
|
||||
ex->oq_open = -1;
|
||||
ex->bmerge = (uint8_t)vk_exec_barrier_merge_on();
|
||||
vk_exec_dirty_all(ex);
|
||||
}
|
||||
|
||||
@@ -644,6 +645,7 @@ static VkImageMemoryBarrier2 layout_barrier(VkImage img, VkImageAspectFlags aspe
|
||||
// go back to GENERAL and the new ones leave it, in the same command.
|
||||
static void barrier_to(VkExec *ex, const VkImage *want, const VkImageAspectFlags *wasp, int nwant) {
|
||||
vk_exec_pass_end(ex);
|
||||
ex->pass_storage = ex->pass_merged = 0; // barrier_merge: every pass begins behind this barrier
|
||||
vk_exec_ub_flush(ex); // uniform updates overlaid in the pass reach their buffers before the barrier below
|
||||
VkImageMemoryBarrier2 ib[18];
|
||||
uint32_t n = 0;
|
||||
@@ -889,8 +891,36 @@ 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
|
||||
// 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
|
||||
// draw that samples it, with a by-region barrier inside the pass. So the pass keeps going, unless a draw of it has a shader
|
||||
// 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.
|
||||
int vk_exec_barrier_merge_on(void) {
|
||||
static int on = -1;
|
||||
if (on < 0) on = cfg_bool("TOTK_BARRIER_MERGE");
|
||||
return on;
|
||||
}
|
||||
|
||||
static int barrier_merges(const VkExec *ex, int bits) {
|
||||
if (!ex->bmerge || !ex->in_pass || ex->pass_storage || !(bits & 0x10) || (bits & ~0x12) ||
|
||||
vk_ctx()->feedback != VK_FEEDBACK_LAYOUT)
|
||||
return 0;
|
||||
for (int i = 0; i < ex->pass_ncolor && i < 8; i++)
|
||||
if (ex->color[i].image && ex->color[i].img && ex->color[i].img->image != ex->color[i].image) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void set_rt(VkExec *ex, const p_set_rt *r) {
|
||||
if (!memcmp(&ex->rt, r, sizeof *r)) return; // the same targets again: the pass goes on
|
||||
if (ex->in_pass) ex->fr.pass_end_rt++;
|
||||
vk_exec_pass_end(ex);
|
||||
ex->rt = *r;
|
||||
ex->rt_resolved = 0;
|
||||
@@ -1016,8 +1046,11 @@ static void run_job(VkExec *ex) {
|
||||
if (j.kind != VK_JOB_CONTACT) {
|
||||
vk_dlaa_exec(ex, &j);
|
||||
} else {
|
||||
// The scan resolved the scene and its depth without creating entries (vk_texture_revive): their images now.
|
||||
// The scan resolved the scene, its depth and the lighting target without creating entries (vk_texture_revive):
|
||||
// their images now. A lighting target without one leaves the march darkening every pixel.
|
||||
const VkTexImage *si = vk_texture_get(j.scene.tex), *di = vk_texture_get(j.depth.tex);
|
||||
const VkTexImage *ui = j.sun.img ? vk_texture_get(j.sun.tex) : NULL;
|
||||
j.sun.img = ui, j.sun.image = ui ? ui->image : VK_NULL_HANDLE;
|
||||
if (si && di) {
|
||||
j.scene.img = si, j.scene.image = si->image, j.depth.img = di, j.depth.image = di->image;
|
||||
vk_contact_exec(ex, &j);
|
||||
@@ -1054,7 +1087,17 @@ static int walk(VkExec *ex, const op_hdr *h, int depth, const op_hdr *stop) {
|
||||
case OP_SET_RT: set_rt(ex, a); break;
|
||||
case OP_CLEAR_COLOR: clear_color(ex, a); break;
|
||||
case OP_CLEAR_DS: clear_ds(ex, a); break;
|
||||
case OP_BARRIER: vk_exec_barrier(ex); break;
|
||||
case OP_BARRIER:
|
||||
if (barrier_merges(ex, ((const p_barrier *)a)->bits)) { // barrier_merge: the pass goes on (see barrier_merges)
|
||||
ex->pass_merged = 1;
|
||||
ex->fr.barrier_merged++;
|
||||
break;
|
||||
}
|
||||
if (ex->in_pass) ex->fr.pass_end_barrier++;
|
||||
if (rt_trace & RT_TRACE_GFX)
|
||||
for (int i = 0; i < 8; i++) ex->fr.barrier_bit[i] += (uint32_t)((const p_barrier *)a)->bits >> i & 1;
|
||||
vk_exec_barrier(ex);
|
||||
break;
|
||||
case OP_DRAW: case OP_DRAW_IDX: case OP_DISPATCH: case OP_UPDATE_UB: case OP_DRAW_IDX_IND: case OP_DISPATCH_IND:
|
||||
if (h->op == OP_DRAW || h->op == OP_DRAW_IDX || h->op == OP_DRAW_IDX_IND) ex->fr.draws_seen++, ex->split_draws++;
|
||||
if (h->op == OP_DISPATCH || h->op == OP_DISPATCH_IND) ex->fr.dispatches++, ex->split_draws++;
|
||||
|
||||
@@ -54,6 +54,10 @@ typedef struct {
|
||||
// TOTK_TRACE=gfx: replay counters of the current frame, logged and reset at each present (vk_exec_frame_log).
|
||||
typedef struct {
|
||||
uint64_t passes, draws_seen, draws, clears, copies, dispatches, submits;
|
||||
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 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
|
||||
// transitions
|
||||
@@ -69,6 +73,8 @@ typedef struct VkExecJob {
|
||||
int chunk; // vk_exec.c: the chunk that holds the op
|
||||
VkExecTarget scene, depth; // contact: the scene colour and the linear depth; DLSS: the light target to copy
|
||||
// (mask) or the scaling pass's target (evaluation; no tex: in place)
|
||||
VkExecTarget sun; // contact: the half-resolution lighting target whose alpha is sun visibility
|
||||
// (no img: none in this frame)
|
||||
float pc[16]; // the march's push constants
|
||||
} VkExecJob;
|
||||
|
||||
@@ -115,6 +121,7 @@ typedef struct VkExec {
|
||||
uint32_t st_vmask[2], st_wmask[2], st_ref[2]; // OP_STENCIL per face (0 front, 1 back): compare mask, write mask, ref
|
||||
float point_size; // OP_BIND_STATE kind 6: NVN point size for the support buffer; 0 = never set = 1
|
||||
p_poly_offset poly_offset; // OP_POLY_OFFSET: depth bias factor, units, clamp
|
||||
int8_t volume_bias; // the sign of the volume bias recorded in place of poly_offset: set by prepare_draw, used by record_fixed
|
||||
p_prim_restart prim_restart; // OP_PRIM_RESTART: applied to indexed strip and fan draws (op_draw_idx)
|
||||
float blend_color[4]; // OP_BLEND_COLOR
|
||||
int64_t copy_stride; // OP_COPY_STRIDE: row stride of buffer <-> texture copies (vk_exec_xfer.c)
|
||||
@@ -158,6 +165,12 @@ typedef struct VkExec {
|
||||
// or the last in-pass barrier
|
||||
const void *fb_fs; // feedback_scan's memo: fragment shader, texture bind serial, pass serial
|
||||
uint32_t fb_serial, fb_pass, fb_sampled;
|
||||
// barrier_merge (vk_exec.c barrier_merges): bmerge is TOTK_BARRIER_MERGE, read once when the context is reset;
|
||||
// pass_storage: a draw of the open pass may write a storage buffer or image; pass_merged: the open pass went on
|
||||
// through a game Barrier. Both are cleared by the full barrier of every pass begin (barrier_to).
|
||||
uint8_t bmerge, pass_storage, pass_merged;
|
||||
const void *bm_vs; // merge_guard's memo: vertex shader, texture bind serial, pass serial, answer
|
||||
uint32_t bm_serial, bm_pass, bm_hit;
|
||||
uint32_t tex_serial, pass_serial; // bumped by every texture or image bind and pass begin
|
||||
// TOTK_BIND_INC (vk_exec_draw.c): the slots the bind ops changed since this context's last prepared draw, cleared
|
||||
// by that draw; vk_exec_draw_new_cb and copy_state set every bit. pipe_gen: bumped by every write that changes
|
||||
@@ -199,6 +212,7 @@ void vk_exec_pass_end(VkExec *ex);
|
||||
// Full memory barrier (all commands, all memory); ends the open pass first. Copies and dispatches order themselves with
|
||||
// it. Skipped when nothing was recorded since the last one.
|
||||
void vk_exec_barrier(VkExec *ex);
|
||||
int vk_exec_barrier_merge_on(void); // TOTK_BARRIER_MERGE, read once (vk_exec.c barrier_merges)
|
||||
// UpdateUniformBuffer overlays (vk_exec_draw.c): the copies into the real buffers that updates inside a pass left for
|
||||
// the next barrier (barrier_to records them first), and a GPU write of another kind into [addr, addr+n) of this
|
||||
// submission (a copy, a fill, a storage write), which retires the overlays it touches.
|
||||
|
||||
+54
-1
@@ -2784,8 +2784,11 @@ static VkViewport draw_viewport(VkExec *ex) {
|
||||
return v;
|
||||
}
|
||||
|
||||
// A volume mask draw records its own depth bias in place of the game's: ex->volume_bias, which prepare_draw sets from
|
||||
// vk_pipeline_volume_bias where the draw's dynamic state changes.
|
||||
static void record_fixed(VkExec *ex) {
|
||||
VkCommandBuffer cb = ex->cb;
|
||||
int vb = ex->volume_bias;
|
||||
if (ex->dirty & VK_EXEC_DIRTY_VIEWPORT) {
|
||||
VkViewport v = draw_viewport(ex);
|
||||
vkCmdSetViewportWithCount(cb, 1, &v);
|
||||
@@ -2797,7 +2800,8 @@ static void record_fixed(VkExec *ex) {
|
||||
ex->recorded++;
|
||||
}
|
||||
if (ex->dirty & VK_EXEC_DIRTY_DEPTH_BIAS) {
|
||||
vkCmdSetDepthBias(cb, ex->poly_offset.units, ex->poly_offset.clamp, ex->poly_offset.factor);
|
||||
if (vb) vkCmdSetDepthBias(cb, VOLUME_BIAS_UNITS * (float)vb, 0.0f, VOLUME_BIAS_SLOPE * (float)vb);
|
||||
else vkCmdSetDepthBias(cb, ex->poly_offset.units, ex->poly_offset.clamp, ex->poly_offset.factor);
|
||||
ex->recorded++;
|
||||
}
|
||||
if (ex->dirty & VK_EXEC_DIRTY_BLEND_CONST) {
|
||||
@@ -2992,6 +2996,44 @@ static int pipe_memo_on(void) {
|
||||
return on;
|
||||
}
|
||||
|
||||
// barrier_merge (vk_exec.c barrier_merges). A shader that may write a storage buffer or image: a written SSBO (flags
|
||||
// bit 0) or any storage image. gfx_shader_resources only reads the shader's parsed arrays.
|
||||
static int shader_may_write_storage(const GfxShader *sh) {
|
||||
const GfxShaderRes *r;
|
||||
if (!sh) return 0;
|
||||
if (gfx_shader_resources(sh, GFX_RES_IMG, &r)) return 1;
|
||||
int n = gfx_shader_resources(sh, GFX_RES_SSBO, &r);
|
||||
for (int i = 0; i < n; i++)
|
||||
if (r[i].flags & 1) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// barrier_merge: a draw in a pass that went on through a game Barrier whose reads the in-pass by-region barrier
|
||||
// (feedback_barrier: fragment shader sampling only, found by feedback_scan) would not order. Those are a storage image
|
||||
// of either stage (an imageLoad of a target) and a vertex shader texture that is an attachment of the pass. Such a draw
|
||||
// ends the pass, and the next one begins behind the full barrier, as the game's Barrier would have done. The vertex
|
||||
// scan is kept while the shader, the texture bindings and the pass stay the same, as feedback_scan's.
|
||||
static int merge_guard(VkExec *ex, const GfxShader *vs, const GfxShader *fs) {
|
||||
const GfxShaderRes *res;
|
||||
if (gfx_shader_resources(vs, GFX_RES_IMG, &res) || (fs && gfx_shader_resources(fs, GFX_RES_IMG, &res))) return 1;
|
||||
int n = gfx_shader_resources(vs, GFX_RES_TEX, &res);
|
||||
if (!n) return 0;
|
||||
if (ex->bm_vs == vs && ex->bm_serial == ex->tex_serial && ex->bm_pass == ex->pass_serial) return (int)ex->bm_hit;
|
||||
uint32_t m = 0;
|
||||
vk_texture_lock();
|
||||
for (int r = 0; r < n && !m; r++)
|
||||
for (int k = 0; k < (res[r].count ? res[r].count : 1) && !m; k++) {
|
||||
int slot = res[r].slot + k;
|
||||
uint64_t h = slot >= 0 && slot < 128 ? ex->tex[NVN_STAGE_VS][slot] : 0;
|
||||
if (!h) continue;
|
||||
SubRange sr = sampled_sub(h);
|
||||
m = attached_as(ex, &sr);
|
||||
}
|
||||
vk_texture_unlock();
|
||||
ex->bm_vs = vs, ex->bm_serial = ex->tex_serial, ex->bm_pass = ex->pass_serial, ex->bm_hit = m != 0;
|
||||
return m != 0;
|
||||
}
|
||||
|
||||
// ---- 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
|
||||
@@ -3265,6 +3307,11 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) {
|
||||
}
|
||||
if (!vs || (has_fs && !fs)) return 0;
|
||||
if (vk_dlaa_skip_draw(ex, fs)) return 0; // the game's FXAA off, or its scaling replaced by DLSS (vk_dlaa.c)
|
||||
if (ex->pass_merged && merge_guard(ex, vs, fs)) { // barrier_merge: the full barrier the merged Barrier skipped
|
||||
vk_exec_pass_end(ex);
|
||||
vk_exec_pass_begin(ex);
|
||||
ex->fr.barrier_undone++;
|
||||
}
|
||||
uint32_t fbl = feedback_prepare(ex, fs);
|
||||
uint8_t fb = (uint8_t)((fbl & 0xff ? 1 : 0) | (fbl & 0x100 ? 2 : 0)), dmw = (uint8_t)(nvn_depth_minus_w() != 0);
|
||||
// TOTK_BIND_INC: the pipeline memo's state is this draw's when pipe was not written since the memo's state was built
|
||||
@@ -3378,6 +3425,10 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) {
|
||||
__atomic_fetch_add(&DD.calls, 1, __ATOMIC_RELAXED), __atomic_fetch_add(&DD.cmds, cmds, __ATOMIC_RELAXED);
|
||||
if (!cmds) __atomic_fetch_add(&DD.empty, 1, __ATOMIC_RELAXED);
|
||||
ex->recorded += cmds != 0;
|
||||
// The volume bias follows the state alone, so it is decided here, once per state change, and a draw with the
|
||||
// state recorded last keeps it. A new command buffer or a pipeline bind clears st_valid and comes here.
|
||||
int vb = vk_pipeline_volume_bias(sp);
|
||||
if (vb != ex->volume_bias) ex->dirty |= VK_EXEC_DIRTY_DEPTH_BIAS, ex->volume_bias = (int8_t)vb;
|
||||
MX_CPY(&D->B.st, sp, sizeof *sp), D->B.st_valid = 1;
|
||||
if (ex->mark && ex->fr.draws == ex->mark_draws0) ex->mark->first[0] = vs, ex->mark->first[1] = fs;
|
||||
}
|
||||
@@ -3400,6 +3451,8 @@ static int prepare_draw(VkExec *ex, int prim, int32_t count, int restart) {
|
||||
if (vk_hdr_track) vk_hdr_draw(ex, info);
|
||||
vk_exec_oq_draw(ex);
|
||||
if (bim) bi_done(ex, info, sp, bgt, bgb, bsg);
|
||||
// barrier_merge: noted last, in the pass the draw is recorded in (bind_resources may restart the pass, ub_written)
|
||||
if (ex->bmerge && !ex->pass_storage && (shader_may_write_storage(vs) || shader_may_write_storage(fs))) ex->pass_storage = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
+258
-45
@@ -989,14 +989,21 @@ static int query_stamp(uint64_t lo, uint64_t hi, uint32_t g) {
|
||||
// - CPU -> shadow: right before each submit (vk_mem_shadow_sync), the pools the replay resolved since the last one are
|
||||
// queried for written pages; pages stamped after a pool's sgen are copied in by the CPU.
|
||||
// - GPU -> guest: the replay notes each GPU write into CPU-visible memory at record time (vk_mem_gpu_pending) and
|
||||
// reports it at the fence (vk_gpu_written), which copies those bytes back into guest memory. Until then the CPU
|
||||
// copies skip them: a page the CPU and the GPU both write keeps the GPU's bytes.
|
||||
// reports it at the fence (vk_gpu_written), which copies the bytes the GPU changed back into guest memory.
|
||||
// Both directions go word by word while a write is pending, as the write-back merge does for imported pools: TotK's
|
||||
// particle emitters write a new particle's whole record into a free slot of a buffer the simulation shaders update
|
||||
// every frame, so that buffer is always pending. A whole-range copy back put the shadow's stale words over the fresh
|
||||
// spawns, and a CPU copy that skipped pending ranges never let them reach the GPU: falling rain showed only its
|
||||
// splashes. Each pending range keeps a base, the words guest memory and the shadow last agreed on (the shadow's bytes
|
||||
// when the range became pending). The CPU copy takes the words where guest memory differs from the base; the fence
|
||||
// copy back takes the words where the shadow differs from it. A word both changed takes the GPU's. TOTK_WB_MERGE=0
|
||||
// skips the pending ranges in the CPU copy and copies them back whole, as before.
|
||||
// TOTK_SHADOW=1/0 (shadow in totk.ini) forces the mode on or off; the default is on for Linux and Wine.
|
||||
typedef struct { uint64_t lo, hi; } SRange;
|
||||
static PlatMutex shadow_lock = PLAT_MUTEX_INIT; // after pool_lock; before gen_lock
|
||||
typedef struct { uint64_t lo, hi; uint8_t *base; int refs; } SRange;
|
||||
static PlatMutex shadow_lock = PLAT_MUTEX_INIT; // after mirror_lock and pool_lock; before gen_lock
|
||||
static PoolRec **stouch; // shadow_lock: pools resolved since the last sync
|
||||
static int nstouch, cstouch;
|
||||
static SRange *spend; // shadow_lock: GPU writes recorded and not copied back yet
|
||||
static SRange *spend; // shadow_lock: distinct GPU writes recorded and not copied back yet
|
||||
static int nspend, cspend;
|
||||
static int64_t s_live_n, s_live_bytes; // shadow_lock
|
||||
static uint64_t s_syncs, s_copied, s_queries, s_untracked, s_wb_bytes, s_ticks; // shadow_lock: since the last log
|
||||
@@ -1062,15 +1069,102 @@ static void shadow_forget(PoolRec *r) {
|
||||
plat_mutex_unlock(&shadow_lock);
|
||||
}
|
||||
|
||||
// shadow_lock held: copies guest [a, b) into the shadow, leaving out the bytes of GPU writes not copied back yet
|
||||
// (spend from index i on).
|
||||
// TOTK_WB_MERGE: the write-back merge of mirrors (wb_merge_record) and the word merge of the shadow's pending ranges.
|
||||
static int merge_on = -1;
|
||||
static int merge_wanted(void) {
|
||||
if (merge_on < 0) {
|
||||
merge_on = cfg_bool("TOTK_WB_MERGE");
|
||||
rt_log("mem: write-back merge %s (TOTK_WB_MERGE)", merge_on ? "on" : "off");
|
||||
}
|
||||
return merge_on;
|
||||
}
|
||||
|
||||
// The word at byte offset i of p's n bytes; a last word shorter than 4 bytes reads as zero-extended. The common case
|
||||
// is a fixed 4-byte load: a memcpy of variable size is a library call per word.
|
||||
static uint32_t word_at(const uint8_t *p, uint64_t i, uint64_t n) {
|
||||
uint32_t v = 0;
|
||||
if (n - i >= 4) memcpy(&v, p + i, 4);
|
||||
else memcpy(&v, p + i, n - i);
|
||||
return v;
|
||||
}
|
||||
|
||||
// A run of differing words from *at on, as byte offsets [*at, *end) of x and y (n bytes, the last word may be shorter);
|
||||
// 0 when none is left.
|
||||
static int diff_run(const uint8_t *x, const uint8_t *y, uint64_t n, uint64_t *at, uint64_t *end) {
|
||||
uint64_t i = *at;
|
||||
while (i + 64 <= n && !memcmp(x + i, y + i, 64)) i += 64; // most words are equal: skip them a block at a time
|
||||
while (i < n && word_at(x, i, n) == word_at(y, i, n)) i += 4;
|
||||
if (i >= n) return 0;
|
||||
uint64_t j = i + 4;
|
||||
while (j < n && word_at(x, j, n) != word_at(y, j, n)) j += 4;
|
||||
*at = i, *end = j < n ? j : n;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// The pending ranges with a base over a guest range, found once per merge rather than once per differing run: the
|
||||
// game's particle buffers differ in many short runs, and about a hundred ranges are pending at a time. n < 0: more than
|
||||
// BASES_NEAR, every range is checked.
|
||||
#define BASES_NEAR 16
|
||||
typedef struct { int n, at[BASES_NEAR]; } BaseSet;
|
||||
|
||||
// shadow_lock held: the pending ranges with a base over guest [a, b). Valid while spend is unchanged.
|
||||
static void bases_over(uint64_t a, uint64_t b, BaseSet *s) {
|
||||
s->n = 0;
|
||||
for (int i = 0; i < nspend; i++) {
|
||||
if (!spend[i].base || spend[i].lo >= b || spend[i].hi <= a) continue;
|
||||
if (s->n == BASES_NEAR) { s->n = -1; return; }
|
||||
s->at[s->n++] = i;
|
||||
}
|
||||
}
|
||||
|
||||
// shadow_lock held: src's bytes become guest [a, b) in p's base, where they overlap.
|
||||
static void base_put(const SRange *p, uint64_t a, uint64_t b, const uint8_t *src) {
|
||||
if (!p->base || p->lo >= b || p->hi <= a) return;
|
||||
uint64_t x = a > p->lo ? a : p->lo, y = b < p->hi ? b : p->hi;
|
||||
memcpy(p->base + (x - p->lo), src + (x - a), y - x);
|
||||
}
|
||||
|
||||
// shadow_lock held: src's bytes become guest [a, b) in the base of every pending range over them; s holds those
|
||||
// ranges for a span that contains [a, b).
|
||||
static void base_set(const BaseSet *s, uint64_t a, uint64_t b, const uint8_t *src) {
|
||||
if (s->n < 0) {
|
||||
for (int i = 0; i < nspend; i++) base_put(&spend[i], a, b, src);
|
||||
return;
|
||||
}
|
||||
for (int k = 0; k < s->n; k++) base_put(&spend[s->at[k]], a, b, src);
|
||||
}
|
||||
|
||||
static void shadow_put(PoolRec *r, uint64_t a, uint64_t b);
|
||||
|
||||
// shadow_lock held: the words of guest [a, b), inside pending range p, that differ from p's base go into the shadow.
|
||||
static void shadow_merge(PoolRec *r, uint64_t a, uint64_t b, const SRange *p) {
|
||||
const uint8_t *g = (const uint8_t *)(uintptr_t)a;
|
||||
uint64_t x = 0, y;
|
||||
BaseSet bs;
|
||||
bases_over(a, b, &bs);
|
||||
while (diff_run(g, p->base + (a - p->lo), b - a, &x, &y)) {
|
||||
base_set(&bs, a + x, a + y, g + x);
|
||||
shadow_put(r, a + x, a + y);
|
||||
x = y;
|
||||
}
|
||||
}
|
||||
|
||||
// shadow_lock held: copies guest [a, b) into the shadow; the bytes of GPU writes not copied back yet (spend from index
|
||||
// i on) only where the CPU changed them.
|
||||
static void shadow_copy(PoolRec *r, uint64_t a, uint64_t b, int i) {
|
||||
for (; i < nspend; i++)
|
||||
if (spend[i].lo < b && spend[i].hi > a) {
|
||||
if (spend[i].lo > a) shadow_copy(r, a, spend[i].lo, i + 1);
|
||||
if (spend[i].hi < b) shadow_copy(r, spend[i].hi, b, i + 1);
|
||||
if (spend[i].base)
|
||||
shadow_merge(r, a > spend[i].lo ? a : spend[i].lo, b < spend[i].hi ? b : spend[i].hi, &spend[i]);
|
||||
return;
|
||||
}
|
||||
shadow_put(r, a, b);
|
||||
}
|
||||
|
||||
// shadow_lock held: guest [a, b) into the shadow.
|
||||
static void shadow_put(PoolRec *r, uint64_t a, uint64_t b) {
|
||||
if (sdefer_now) { // the GPU copies it later: the bytes are read from guest memory when the prologue is recorded
|
||||
if (ndq == cdq) grow((void **)&dq, &cdq, sizeof *dq);
|
||||
dq[ndq++] = (DRange){r, a, b - a};
|
||||
@@ -1209,6 +1303,65 @@ void vk_mem_shadow_fence(void) {
|
||||
plat_mutex_unlock(&shadow_lock);
|
||||
}
|
||||
|
||||
// TOTK_SYNC_AHEAD, nvnMemoryPoolInvalidateMappedRange: the game is about to read [addr, addr+size) of what the GPU
|
||||
// writes into pool storage. While the guard is not done, a write into the range that is still pending can belong to a
|
||||
// value the game was told is done, and its bytes come back only with that value's fence (vk_gpu_written). A range the
|
||||
// game reads again and again (its depth queries and visibility maps: one buffer written every frame or every few)
|
||||
// then still holds the result of the write before, and the game gets that one, a sample late: what the switch trades
|
||||
// for the frame in flight. A range it has not read lately holds no such result. TotK reads single pixels back
|
||||
// (main+0x407ed8 on 1.4.3) through a 64-byte buffer per request, taken in turn from rings of 64 to 256 and read once,
|
||||
// right after the frame wait: read early, the pixel is 0 0 0 0 in a buffer never used, and the answer to another
|
||||
// request, about 27 s old, once the ring came round. In the Depths the zeros put Link in gloom where there is none. So
|
||||
// a range with a pending write that is not known waits for the guard here. Known: the game invalidated this very
|
||||
// range within the last SREAD_AGE fence values (about 30 frames), when it held a result or was waited for.
|
||||
#define SREAD_N 64
|
||||
#define SREAD_AGE 64
|
||||
typedef struct { uint64_t addr, size, at; } SRead;
|
||||
static SRead sread[SREAD_N]; // shadow_lock: the ranges the game invalidated last, with the value issued then
|
||||
static uint64_t s_read_waits, s_read_ticks; // shadow_lock: since the last log
|
||||
static uint64_t r_read_waits, r_read_ticks, r_read_max; // shadow_lock: over the run (vk_mem_shadow_read_log)
|
||||
|
||||
void vk_mem_shadow_read(uint64_t addr, uint64_t size) {
|
||||
if (!shadow_on || !size || !nvn_sync_ahead_guard()) return;
|
||||
plat_mutex_lock(&shadow_lock);
|
||||
uint64_t now = vk_sync_issued();
|
||||
SRead *e = &sread[0]; // the range's entry, else the oldest
|
||||
for (int i = 0; i < SREAD_N; i++) {
|
||||
if (sread[i].addr == addr && sread[i].size == size) { e = &sread[i]; break; }
|
||||
if (sread[i].at < e->at) e = &sread[i];
|
||||
}
|
||||
int known = e->addr == addr && e->size == size && e->at + SREAD_AGE >= now, pending = 0;
|
||||
for (int i = 0; i < nspend && !pending; i++) pending = spend[i].lo < addr + size && spend[i].hi > addr;
|
||||
uint64_t g = nvn_sync_ahead_guard(), wait = pending && !known && g > vk_sync_fence_done() ? g : 0;
|
||||
// A pending write of a value the game was not told is done, in a range not known: the game reads ahead of its own
|
||||
// wait and the range stays unknown.
|
||||
if (known || !pending || wait) *e = (SRead){addr, size, now};
|
||||
plat_mutex_unlock(&shadow_lock);
|
||||
if (!wait) return;
|
||||
uint64_t t0 = qpc();
|
||||
{
|
||||
NVN_BLOCKING();
|
||||
vk_sync_fence_wait(wait, UINT64_MAX);
|
||||
}
|
||||
uint64_t dt = qpc() - t0;
|
||||
plat_mutex_lock(&shadow_lock);
|
||||
s_read_waits++, s_read_ticks += dt;
|
||||
r_read_waits++, r_read_ticks += dt;
|
||||
if (dt > r_read_max) r_read_max = dt;
|
||||
plat_mutex_unlock(&shadow_lock);
|
||||
}
|
||||
|
||||
// The run total of the waits above, once at exit, while frame-ahead is in effect: without TOTK_TRACE=perf the shadow
|
||||
// log lines come only at frames 600 and 1800.
|
||||
void vk_mem_shadow_read_log(void) {
|
||||
static int32_t done;
|
||||
if (!shadow_on || !nvn_sync_ahead_on() || plat_xchg32(&done, 1)) return;
|
||||
plat_mutex_lock(&shadow_lock);
|
||||
rt_log("mem: the game waited for a GPU write it reads %llu times, %.1f ms in all, longest %.2f ms",
|
||||
(unsigned long long)r_read_waits, qpc_ms(r_read_ticks), qpc_ms(r_read_max));
|
||||
plat_mutex_unlock(&shadow_lock);
|
||||
}
|
||||
|
||||
int vk_mem_shadow_on(void) { return shadow_on; }
|
||||
|
||||
void vk_mem_shadow_sync(uint64_t fence) {
|
||||
@@ -1240,12 +1393,35 @@ void vk_mem_shadow_sync(uint64_t fence) {
|
||||
|
||||
int vk_mem_shadow_deferred(void) { return ndq; }
|
||||
|
||||
// Record time: the range's base is the shadow's bytes, except where an overlapping pending range has one: the GPU may
|
||||
// have written those shadow bytes since.
|
||||
void vk_mem_gpu_pending(uint64_t addr, uint64_t size) {
|
||||
if (!shadow_on || !size) return;
|
||||
uint64_t lo = addr, hi = addr + size;
|
||||
plat_mutex_lock_shared(&pool_lock);
|
||||
const pidx_ent *e = pidx_find(&pool_index, addr, size);
|
||||
PoolRec *r = e ? e->buf : NULL;
|
||||
plat_mutex_lock(&shadow_lock);
|
||||
if (nspend == cspend) grow((void **)&spend, &cspend, sizeof *spend);
|
||||
spend[nspend++] = (SRange){addr, addr + size};
|
||||
int i = 0;
|
||||
while (i < nspend && (spend[i].lo != lo || spend[i].hi != hi)) i++;
|
||||
if (i < nspend) {
|
||||
spend[i].refs++;
|
||||
} else {
|
||||
uint8_t *base = NULL;
|
||||
if (r && r->smap && lo >= r->import_lo && hi <= r->import_hi && merge_wanted() && (base = malloc(size))) {
|
||||
memcpy(base, r->smap + (lo - r->import_lo), size);
|
||||
for (int k = 0; k < nspend; k++) {
|
||||
const SRange *p = &spend[k];
|
||||
if (!p->base || p->lo >= hi || p->hi <= lo) continue;
|
||||
uint64_t x = lo > p->lo ? lo : p->lo, y = hi < p->hi ? hi : p->hi;
|
||||
memcpy(base + (x - lo), p->base + (x - p->lo), y - x);
|
||||
}
|
||||
}
|
||||
if (nspend == cspend) grow((void **)&spend, &cspend, sizeof *spend);
|
||||
spend[nspend++] = (SRange){lo, hi, base, 1};
|
||||
}
|
||||
plat_mutex_unlock(&shadow_lock);
|
||||
plat_mutex_unlock_shared(&pool_lock);
|
||||
}
|
||||
|
||||
void vk_gpu_written(uint64_t addr, uint64_t size) {
|
||||
@@ -1254,13 +1430,27 @@ void vk_gpu_written(uint64_t addr, uint64_t size) {
|
||||
const pidx_ent *e = pidx_find(&pool_index, addr, size);
|
||||
PoolRec *r = e ? e->buf : NULL;
|
||||
plat_mutex_lock(&shadow_lock);
|
||||
int k = 0;
|
||||
while (k < nspend && (spend[k].lo != addr || spend[k].hi != addr + size)) k++;
|
||||
if (r && r->smap && addr >= r->import_lo && addr + size <= r->import_hi) {
|
||||
mem_thaw(addr, size);
|
||||
memcpy((void *)(uintptr_t)addr, r->smap + (addr - r->import_lo), size);
|
||||
s_wb_bytes += size;
|
||||
const uint8_t *s = r->smap + (addr - r->import_lo);
|
||||
if (k < nspend && spend[k].base) {
|
||||
uint64_t x = 0, y;
|
||||
BaseSet bs;
|
||||
bases_over(addr, addr + size, &bs);
|
||||
while (diff_run(s, spend[k].base, size, &x, &y)) {
|
||||
memcpy((void *)(uintptr_t)(addr + x), s + x, y - x);
|
||||
base_set(&bs, addr + x, addr + y, (const uint8_t *)(uintptr_t)(addr + x));
|
||||
s_wb_bytes += y - x;
|
||||
x = y;
|
||||
}
|
||||
} else {
|
||||
memcpy((void *)(uintptr_t)addr, s, size);
|
||||
s_wb_bytes += size;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < nspend; i++)
|
||||
if (spend[i].lo == addr && spend[i].hi == addr + size) { spend[i] = spend[--nspend]; break; }
|
||||
if (k < nspend && !--spend[k].refs) free(spend[k].base), spend[k] = spend[--nspend];
|
||||
plat_mutex_unlock(&shadow_lock);
|
||||
plat_mutex_unlock_shared(&pool_lock);
|
||||
}
|
||||
@@ -1277,10 +1467,11 @@ static void shadow_log(uint64_t frame) {
|
||||
qpc_ms(s_ticks), nspend);
|
||||
if (defer_on || s_waits) // only with TOTK_SYNC_AHEAD: the shadow log of everyone else stays as it was
|
||||
rt_log("mem: shadow deferred (%s): %llu pools, %.1f MiB in %llu copies; replay waited for a reader %llu times, "
|
||||
"%.2f ms", defer_on ? "on" : "off", (unsigned long long)s_defer_pools, s_defer_bytes / 1048576.0,
|
||||
(unsigned long long)s_defer_copies, (unsigned long long)s_waits, qpc_ms(s_wait_ticks));
|
||||
"%.2f ms; the game waited for a GPU write it reads %llu times, %.2f ms", defer_on ? "on" : "off",
|
||||
(unsigned long long)s_defer_pools, s_defer_bytes / 1048576.0, (unsigned long long)s_defer_copies,
|
||||
(unsigned long long)s_waits, qpc_ms(s_wait_ticks), (unsigned long long)s_read_waits, qpc_ms(s_read_ticks));
|
||||
s_syncs = s_queries = s_copied = s_untracked = s_wb_bytes = s_ticks = 0;
|
||||
s_defer_pools = s_defer_bytes = s_defer_copies = s_wait_ticks = s_waits = 0;
|
||||
s_defer_pools = s_defer_bytes = s_defer_copies = s_wait_ticks = s_waits = s_read_waits = s_read_ticks = 0;
|
||||
plat_mutex_unlock(&shadow_lock);
|
||||
}
|
||||
|
||||
@@ -1445,13 +1636,15 @@ static uint32_t mepoch; // replay: its write-watch snapshot epoch
|
||||
typedef struct { PoolRec *r; uint64_t off, size; } MRange;
|
||||
static MRange *pend, *wbl; // replay: copies for the next prologue; GPU writes into mirrors this submission
|
||||
static int npend, cpend, nwbl, cwbl;
|
||||
static int pend_seal, snl_seal; // mirror_lock: the copies the next prologue takes (vk_mem_mirror_seal)
|
||||
static VkBufferCopy *mregions; // replay: vkCmdCopyBuffer regions
|
||||
static int cregions;
|
||||
static PlatMutex flush_lock = PLAT_MUTEX_INIT;
|
||||
static int flush_cap = FLUSH_RANGES; // ranges a pool keeps; 1 with TOTK_FLUSH_SPAN=1
|
||||
// The first uses of a submission's mirrors, the copies they queue, the GPU writes noted and their snapshots (pend, wbl, snl, mrep): threads
|
||||
// recording chunks of one submission take it. A mirror synced in this submission is read without it (vk_mem_use): its
|
||||
// acc_sub is stored last. Before pool_lock, gen_lock and flush_lock.
|
||||
// acc_sub is stored last. Before pool_lock, shadow_lock (mirror_sync and mirror_create touch the shadow), gen_lock and
|
||||
// flush_lock.
|
||||
static PlatMutex mirror_lock = PLAT_MUTEX_INIT;
|
||||
|
||||
typedef struct {
|
||||
@@ -1509,8 +1702,9 @@ static void mirror_mode(int discrete) {
|
||||
"slower than mirror (the auto default on a discrete GPU); use memory = auto unless testing");
|
||||
}
|
||||
|
||||
static void range_add(MRange **a, int *n, int *cap, PoolRec *r, uint64_t off, uint64_t size) {
|
||||
if (*n && (*a)[*n - 1].r == r && (*a)[*n - 1].off + (*a)[*n - 1].size == off) {
|
||||
// keep: the entries before it are sealed and do not grow.
|
||||
static void range_add(MRange **a, int *n, int *cap, int keep, PoolRec *r, uint64_t off, uint64_t size) {
|
||||
if (*n > keep && (*a)[*n - 1].r == r && (*a)[*n - 1].off + (*a)[*n - 1].size == off) {
|
||||
(*a)[*n - 1].size += size;
|
||||
return;
|
||||
}
|
||||
@@ -1631,7 +1825,8 @@ static void mirror_create(PoolRec *r) {
|
||||
mlist[at] = r;
|
||||
nm++;
|
||||
plat_mutex_unlock(&pool_lock);
|
||||
range_add(&pend, &npend, &cpend, r, 0, n);
|
||||
range_add(&pend, &npend, &cpend, pend_seal, r, 0, n);
|
||||
if (r->smap) shadow_touch(r); // the copy reads the shadow: see vk_mem_mirror_seal
|
||||
__atomic_store_n(&r->acc_sub, msub, __ATOMIC_RELEASE);
|
||||
__atomic_store_n(&r->mstate, MS_ON, __ATOMIC_RELEASE);
|
||||
mrep.first_n++, mrep.first_bytes += n;
|
||||
@@ -1695,7 +1890,7 @@ static void mirror_sync(PoolRec *r) {
|
||||
if (!ch) continue;
|
||||
for (uint64_t x = a; x < b; x += 1ull << GEN_PAGE_SHIFT)
|
||||
if (ch[(x >> GEN_PAGE_SHIFT) & (GEN_PER_CHUNK - 1)] > since)
|
||||
range_add(&pend, &npend, &cpend, r, x - lo, 1ull << GEN_PAGE_SHIFT), mrep.page_bytes += 1ull << GEN_PAGE_SHIFT;
|
||||
range_add(&pend, &npend, &cpend, pend_seal, r, x - lo, 1ull << GEN_PAGE_SHIFT), mrep.page_bytes += 1ull << GEN_PAGE_SHIFT;
|
||||
}
|
||||
r->mgen = gen_now;
|
||||
if (excl) plat_mutex_unlock(&gen_lock);
|
||||
@@ -1712,7 +1907,7 @@ static void mirror_sync(PoolRec *r) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
uint64_t a = fl[i].lo > lo ? fl[i].lo : lo, b = fl[i].hi < hi ? fl[i].hi : hi;
|
||||
if (a >= b) continue;
|
||||
range_add(&pend, &npend, &cpend, r, a - lo, b - a);
|
||||
range_add(&pend, &npend, &cpend, pend_seal, r, a - lo, b - a);
|
||||
mrep.flush_n++, mrep.flush_bytes += b - a;
|
||||
if ((rt_trace & RT_TRACE_PERF) && b - a >= 16u << 20)
|
||||
rt_log("mem: mirror frame %llu: flush range %.1f MiB at +%.1f MiB of a %.1f MiB pool (%d ranges from %llu "
|
||||
@@ -1720,6 +1915,7 @@ static void mirror_sync(PoolRec *r) {
|
||||
(hi - lo) / 1048576.0, n, (unsigned long long)calls, sum / 1048576.0);
|
||||
}
|
||||
}
|
||||
if (r->smap) shadow_touch(r); // the copies read the shadow: see vk_mem_mirror_seal
|
||||
mrep.syncs++;
|
||||
mrep.sync_t += qpc() - t0;
|
||||
__atomic_store_n(&r->acc_sub, msub, __ATOMIC_RELEASE);
|
||||
@@ -1802,7 +1998,6 @@ static PlatMutex snap_pool_lock = PLAT_MUTEX_INIT;
|
||||
static SnapChunk snap_pool[SNAP_POOL_N];
|
||||
static int nsnap_pool;
|
||||
static uint64_t snap_pool_bytes;
|
||||
static int merge_on = -1;
|
||||
static struct {
|
||||
int tried, ok;
|
||||
PFN_vkCmdPushDescriptorSetKHR push;
|
||||
@@ -1845,11 +2040,7 @@ fail:
|
||||
}
|
||||
|
||||
static int merging(void) {
|
||||
if (merge_on < 0) {
|
||||
merge_on = cfg_bool("TOTK_WB_MERGE");
|
||||
rt_log("mem: write-back merge %s (TOTK_WB_MERGE)", merge_on ? "on" : "off");
|
||||
}
|
||||
if (!merge_on) return 0;
|
||||
if (!merge_wanted()) return 0;
|
||||
if (!WM.tried) merge_init(vk_ctx());
|
||||
return WM.ok;
|
||||
}
|
||||
@@ -1903,12 +2094,12 @@ static int snap_add(PoolRec *r, uint64_t off, uint64_t size) {
|
||||
|
||||
// Prologue: the snapshot copies of the ranges added since the last prologue.
|
||||
static void snap_copies(VkCommandBuffer cb) {
|
||||
for (int i = snl_copied; i < nsnl; i++) {
|
||||
for (int i = snl_copied; i < snl_seal; i++) {
|
||||
VkBufferCopy cp = {snl[i].off, snl[i].soff, snl[i].size};
|
||||
vkCmdCopyBuffer(cb, snl[i].r->mbuf, chunks[snl[i].chunk].buf, 1, &cp);
|
||||
mrep.snap_bytes += snl[i].size;
|
||||
}
|
||||
snl_copied = nsnl;
|
||||
snl_copied = snl_seal;
|
||||
}
|
||||
|
||||
static int snap_cmp(const void *x, const void *y) {
|
||||
@@ -2025,7 +2216,7 @@ static void gpu_wrote(const VkMemSpan *sp, uint64_t size, int shader) {
|
||||
plat_mutex_unlock(&mirror_lock);
|
||||
return;
|
||||
}
|
||||
range_add(&wbl, &nwbl, &cwbl, r, sp->offset, size);
|
||||
range_add(&wbl, &nwbl, &cwbl, 0, r, sp->offset, size);
|
||||
plat_mutex_unlock(&mirror_lock);
|
||||
}
|
||||
void vk_mem_gpu_wrote(const VkMemSpan *sp, uint64_t size) { gpu_wrote(sp, size, 0); }
|
||||
@@ -2126,7 +2317,7 @@ void vk_mem_mirror_begin(void) {
|
||||
return;
|
||||
}
|
||||
uint64_t t0 = qpc();
|
||||
nsnl = snl_copied = nchunks = 0; // the previous submission handed its chunks to snap_free
|
||||
nsnl = snl_seal = snl_copied = nchunks = 0; // the previous submission handed its chunks to snap_free
|
||||
uint32_t prev = msub;
|
||||
msub = msub + 1 ? msub + 1 : 1;
|
||||
__atomic_add_fetch(&mirror_gen, 1, __ATOMIC_RELEASE);
|
||||
@@ -2158,30 +2349,45 @@ void vk_mem_mirror_begin(void) {
|
||||
mrep.presnap_t += qpc() - t0;
|
||||
}
|
||||
|
||||
// With shadow storage a mirror copies from the shadow, which vk_mem_shadow_sync brings up to date only for the pools
|
||||
// touched before it runs; mirror_sync and mirror_create touch theirs after queuing the copies. In a chunked replay the
|
||||
// recording threads queue copies while the replay thread runs a part's prologue: a copy queued after that prologue's
|
||||
// shadow sync read the shadow before the CPU's write reached it (with TOTK_SHADOW_DEFER the write is a GPU copy of
|
||||
// the next prologue, so always), and the mirror, marked synced, kept the old bytes until the CPU wrote the page again.
|
||||
// In the Depths, terrain loaded with those pages stood as stretched slabs over the ground for the rest of the session.
|
||||
// So the prologue seals the queues before the shadow sync and copies only what was sealed; the rest waits for the next
|
||||
// prologue, whose shadow sync comes first.
|
||||
void vk_mem_mirror_seal(void) {
|
||||
plat_mutex_lock(&mirror_lock);
|
||||
pend_seal = npend, snl_seal = nsnl;
|
||||
plat_mutex_unlock(&mirror_lock);
|
||||
}
|
||||
|
||||
int vk_mem_mirror_pending(void) {
|
||||
plat_mutex_lock(&mirror_lock);
|
||||
int n = npend || snl_copied < nsnl;
|
||||
int n = pend_seal || snl_copied < snl_seal;
|
||||
plat_mutex_unlock(&mirror_lock);
|
||||
return n;
|
||||
}
|
||||
|
||||
void vk_mem_mirror_prologue(VkCommandBuffer cb) {
|
||||
plat_mutex_lock(&mirror_lock);
|
||||
if (!npend && snl_copied == nsnl) {
|
||||
if (!pend_seal && snl_copied == snl_seal) {
|
||||
plat_mutex_unlock(&mirror_lock);
|
||||
return;
|
||||
}
|
||||
mbarrier(cb, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_2_COPY_BIT,
|
||||
VK_ACCESS_2_TRANSFER_READ_BIT | VK_ACCESS_2_TRANSFER_WRITE_BIT);
|
||||
copy_ranges(cb, pend, npend, 1, &mrep.upload_bytes, &mrep.upload_copies);
|
||||
if (snl_copied < nsnl) { // the snapshots read what the uploads above wrote
|
||||
if (npend) mbarrier(cb, VK_PIPELINE_STAGE_2_COPY_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_COPY_BIT,
|
||||
copy_ranges(cb, pend, pend_seal, 1, &mrep.upload_bytes, &mrep.upload_copies);
|
||||
if (snl_copied < snl_seal) { // the snapshots read what the uploads above wrote
|
||||
if (pend_seal) mbarrier(cb, VK_PIPELINE_STAGE_2_COPY_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_COPY_BIT,
|
||||
VK_ACCESS_2_TRANSFER_READ_BIT);
|
||||
snap_copies(cb);
|
||||
}
|
||||
mbarrier(cb, VK_PIPELINE_STAGE_2_COPY_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT,
|
||||
VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT);
|
||||
npend = 0;
|
||||
memmove(pend, pend + pend_seal, sizeof *pend * (size_t)(npend - pend_seal));
|
||||
npend -= pend_seal, pend_seal = 0;
|
||||
mrep.prologues++;
|
||||
plat_mutex_unlock(&mirror_lock);
|
||||
}
|
||||
@@ -2284,7 +2490,7 @@ int vk_mem_mirror_end(VkCommandBuffer cb, uint64_t fence) {
|
||||
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT);
|
||||
int m = wb_merge_record(cb);
|
||||
if (!m) { // no range list: copy them plainly
|
||||
for (int i = 0; i < nsnl; i++) range_add(&wbl, &nwbl, &cwbl, snl[i].r, snl[i].off, snl[i].size);
|
||||
for (int i = 0; i < nsnl; i++) range_add(&wbl, &nwbl, &cwbl, 0, snl[i].r, snl[i].off, snl[i].size);
|
||||
}
|
||||
rec += m + 1;
|
||||
mbarrier(cb, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT,
|
||||
@@ -2844,7 +3050,7 @@ uint64_t vk_upload_flush(int wait) {
|
||||
return seq;
|
||||
}
|
||||
|
||||
static void defer(int kind, uint64_t handle, VmaAllocation alloc) {
|
||||
static void defer(int kind, uint64_t handle, VmaAllocation alloc, uint64_t min_tl) {
|
||||
plat_once(&cmd_once, cmd_init, NULL);
|
||||
plat_rmutex_lock(&cmd_lock);
|
||||
if (ndead == cap_dead) grow((void **)&dead, &cap_dead, sizeof *dead);
|
||||
@@ -2860,6 +3066,7 @@ static void defer(int kind, uint64_t handle, VmaAllocation alloc) {
|
||||
// textures.c defer: vk_pending_seq).
|
||||
uint64_t tl = tl_noted;
|
||||
if (kind != DEAD_HOST && tl > vk_sync_issued() && tl_noted_here != tl) n_cross_defer++, cross_defer_tl = tl;
|
||||
if (min_tl > tl) tl = min_tl; // vk_defer_buffer_until
|
||||
dead[ndead++] = (Dead){kind, handle, alloc, open_active ? open_b.seq : next_seq, tl};
|
||||
if (kind != DEAD_HOST)
|
||||
rec_check_handle(kind == DEAD_VIEW ? REC_VIEW : kind == DEAD_BUFFER_VMA ? REC_BUFFER : REC_IMAGE, handle, 0, tl,
|
||||
@@ -2876,13 +3083,18 @@ static int dead_pending(void) {
|
||||
}
|
||||
|
||||
void vk_defer_image(VkImage img, VmaAllocation alloc) {
|
||||
if (img) defer(alloc ? DEAD_IMAGE_VMA : DEAD_IMAGE, (uint64_t)(uintptr_t)img, alloc);
|
||||
if (img) defer(alloc ? DEAD_IMAGE_VMA : DEAD_IMAGE, (uint64_t)(uintptr_t)img, alloc, 0);
|
||||
}
|
||||
void vk_defer_view(VkImageView view) { if (view) defer(DEAD_VIEW, (uint64_t)(uintptr_t)view, NULL); }
|
||||
void vk_defer_view(VkImageView view) { if (view) defer(DEAD_VIEW, (uint64_t)(uintptr_t)view, NULL, 0); }
|
||||
void vk_defer_buffer(VkBuffer buf, VmaAllocation alloc) {
|
||||
if (buf) defer(DEAD_BUFFER_VMA, (uint64_t)(uintptr_t)buf, alloc);
|
||||
if (buf) defer(DEAD_BUFFER_VMA, (uint64_t)(uintptr_t)buf, alloc, 0);
|
||||
}
|
||||
void vk_defer_free(void *p) { if (p) defer(DEAD_HOST, (uint64_t)(uintptr_t)p, NULL); }
|
||||
// A buffer a submission of timeline value tl writes or reads that may not be submitted yet (vk_texture.c eager
|
||||
// write-back snapshots): it goes once the GPU has reached tl, whatever vk_mem_note_submit has seen.
|
||||
void vk_defer_buffer_until(VkBuffer buf, VmaAllocation alloc, uint64_t tl) {
|
||||
if (buf) defer(DEAD_BUFFER_VMA, (uint64_t)(uintptr_t)buf, alloc, tl);
|
||||
}
|
||||
void vk_defer_free(void *p) { if (p) defer(DEAD_HOST, (uint64_t)(uintptr_t)p, NULL, 0); }
|
||||
|
||||
// The device fault report: no lock, since a thread that holds cmd_lock may be waiting for the report's own lock
|
||||
// (vk_upload_flush reports a failed submit with cmd_lock held).
|
||||
@@ -2982,12 +3194,13 @@ void vk_mem_shutdown(void) {
|
||||
plat_mutex_lock(&pool_lock);
|
||||
for (int i = 0; i < pool_index.n; i++) destroy_rec(c, pool_index.e[i].buf);
|
||||
pool_index.n = 0;
|
||||
nm = npend = nwbl = nsnl = snl_copied = ndq = 0; // mirrors went with their pools
|
||||
nm = npend = pend_seal = nwbl = nsnl = snl_seal = snl_copied = ndq = 0; // mirrors went with their pools
|
||||
plat_mutex_lock(&snap_pool_lock);
|
||||
for (int i = 0; i < nsnap_pool; i++) vmaDestroyBuffer(c->vma, snap_pool[i].buf, snap_pool[i].alloc);
|
||||
nsnap_pool = 0, snap_pool_bytes = 0;
|
||||
plat_mutex_unlock(&snap_pool_lock);
|
||||
plat_mutex_lock(&shadow_lock);
|
||||
for (int i = 0; i < nspend; i++) free(spend[i].base);
|
||||
nstouch = nspend = 0; // shadows too
|
||||
s_live_n = s_live_bytes = 0;
|
||||
plat_mutex_unlock(&shadow_lock);
|
||||
|
||||
+31
-2
@@ -3234,7 +3234,7 @@ uint32_t vk_pipeline_set_dynamic(VkCommandBuffer cb, const VkPipeState *s) {
|
||||
compare_op(d->sf_b));
|
||||
// NVN_POLYGON_OFFSET_ENABLE_* bit of the polygon mode in use: point 1, line 2, fill 4
|
||||
unsigned mode = pl->mode <= NVN_POLYGON_MODE_FILL ? pl->mode : NVN_POLYGON_MODE_FILL;
|
||||
vkCmdSetDepthBiasEnable(cb, (pl->offset_en >> mode & 1) != 0);
|
||||
vkCmdSetDepthBiasEnable(cb, (pl->offset_en >> mode & 1) || vk_pipeline_volume_bias(s));
|
||||
vkCmdSetRasterizerDiscardEnable(cb, s->raster_discard != 0);
|
||||
vkCmdSetPrimitiveRestartEnable(cb, s->prim_restart != 0);
|
||||
// The vertex bindings the draw reads: those of its vertex input, set here or made into the pipeline from the same
|
||||
@@ -3268,6 +3268,35 @@ uint32_t vk_pipeline_set_dynamic(VkCommandBuffer cb, const VkPipeState *s) {
|
||||
return streams;
|
||||
}
|
||||
|
||||
// TotK marks the pixels inside its water volumes (seen at puddles) in a quarter-size mask: it draws a volume's front
|
||||
// faces with a LEQUAL depth test and no depth write, blending ONE/ONE with reverse subtract into one channel, against a
|
||||
// depth it rebuilt at that size from its linear depth. The volume's top face lies on the water surface, so the test
|
||||
// compares that surface with itself through two roundings and two sampling positions: on a puddle the face came out
|
||||
// up to 7 ulp in front of or behind the rebuilt depth, and up to about 0.6 of a pixel of its depth slope (64 ulp) behind
|
||||
// it. The camera's sub-millimetre idle motion moved that pattern every frame and the mask with it: the puddle's
|
||||
// reflection, which the mask turns on, flickered over a few hundred pixels a frame, and more with DLAA, whose jitter
|
||||
// moves the rebuilt depth but not the volume. Such a draw, when the game sets no polygon offset for it, gets a depth
|
||||
// bias toward the viewer of VOLUME_BIAS_UNITS plus VOLUME_BIAS_SLOPE times its depth slope (one pixel of it), so a
|
||||
// surface the face lies on counts as inside, as the test's equal case means; a surface farther from the face than a
|
||||
// pixel of its slope is decided as before. Only tests whose equal case passes (LEQUAL, GEQUAL) get the bias, toward
|
||||
// passing. The same pass also draws state-alike draws with GREATER, whose equal case fails: the volume's back faces
|
||||
// into the same channel and, in towns and in rain, another shader's front faces into the red channel. Biasing those
|
||||
// toward passing would turn the game's tie the other way, so they are left as the game sets them.
|
||||
// TOTK_VOLUME_MASK_BIAS=0 (test) leaves every such draw as the game sets it.
|
||||
int vk_pipeline_volume_bias(const VkPipeState *s) {
|
||||
static int knob = -1;
|
||||
if (knob < 0) knob = rt_knob("VOLUME_MASK_BIAS", "1");
|
||||
if (!RT_KNOB_ON(knob)) return 0;
|
||||
const poly_st *pl = &s->poly;
|
||||
const ds_st *d = &s->ds;
|
||||
const blend_st *b = &s->blend[0];
|
||||
unsigned mode = pl->mode <= NVN_POLYGON_MODE_FILL ? pl->mode : NVN_POLYGON_MODE_FILL;
|
||||
if (!d->dt || d->dw || (pl->offset_en >> mode & 1) || !(s->color.blend_en & 1) ||
|
||||
b->eq_rgb != NVN_BLEND_EQUATION_REVERSE_SUB || b->src_rgb != NVN_BLEND_FUNC_ONE || b->dst_rgb != NVN_BLEND_FUNC_ONE)
|
||||
return 0;
|
||||
return d->df == NVN_DEPTH_FUNC_LEQUAL ? -1 : d->df == NVN_DEPTH_FUNC_GEQUAL;
|
||||
}
|
||||
|
||||
// The values vk_pipeline_set_dynamic records for a state, as the commands take them.
|
||||
typedef struct {
|
||||
VkCullModeFlags cull;
|
||||
@@ -3296,7 +3325,7 @@ static void dyn_vals(const VkPipeState *s, DynVals *o) {
|
||||
o->sop[1][0] = stencil_op(d->fail_b), o->sop[1][1] = stencil_op(d->zpass_b), o->sop[1][2] = stencil_op(d->zfail_b);
|
||||
o->scmp[0] = compare_op(d->sf_f), o->scmp[1] = compare_op(d->sf_b);
|
||||
unsigned mode = pl->mode <= NVN_POLYGON_MODE_FILL ? pl->mode : NVN_POLYGON_MODE_FILL;
|
||||
o->bias = (pl->offset_en >> mode & 1) != 0;
|
||||
o->bias = (pl->offset_en >> mode & 1) || vk_pipeline_volume_bias(s);
|
||||
o->discard = s->raster_discard != 0, o->restart = s->prim_restart != 0;
|
||||
o->clamp = s->depth_clamp != 0, o->a2c = s->ms.a2c != 0;
|
||||
o->poly = polygon_mode(pl->mode);
|
||||
|
||||
+5
-1
@@ -369,7 +369,9 @@ static CmdSlot *take_slot(VkCtx *c, uint64_t fence) {
|
||||
// (vk_sync_part, which the caller made the recorder idle for).
|
||||
static VkCommandBuffer prologue(VkCtx *c, uint64_t fence, int direct) {
|
||||
// Shadow storage: the CPU's writes go in before the part is submitted (TOTK_SYNC_AHEAD: queued for the GPU or
|
||||
// made after the GPU finished the readers the game may think done, vk_memory.c).
|
||||
// made after the GPU finished the readers the game may think done, vk_memory.c). The mirror copies queued before it
|
||||
// are the ones this prologue makes, as they read the shadow (vk_mem_mirror_seal).
|
||||
vk_mem_mirror_seal();
|
||||
vk_mem_shadow_sync(fence);
|
||||
if (!vk_mem_mirror_pending() && !vk_mem_shadow_deferred()) return VK_NULL_HANDLE;
|
||||
int i = claim_slot(c, fence); // before reading slots: the claim may move it
|
||||
@@ -461,6 +463,8 @@ uint64_t vk_sync_submit(const uint64_t *handles, int n) {
|
||||
ts_begin(s->cb);
|
||||
int recorded = vk_exec_record(s->cb, handles, n, fence);
|
||||
s = &slots[cur_slot]; // the last part (vk_sync_split)
|
||||
// No render pass is open here (vk_exec_record ended it), and s->cb is the recorder's like the commands before it.
|
||||
vk_texture_eager_record(recorded ? s->cb : VK_NULL_HANDLE, fence);
|
||||
if (recorded) ts_end(s->cb, fence);
|
||||
else ts_drop();
|
||||
// The recorder is done with the part: the end-of-submission crumb, then the end, by the recorder when it records.
|
||||
|
||||
+339
-33
@@ -60,6 +60,9 @@ typedef struct Tex {
|
||||
uint64_t wr_fence; // any entry: newest submission recorded to write its image (render, copy, clear,
|
||||
// storage binding); ReadTexels waits for it instead of draining the replay queue
|
||||
uint8_t listed; // in owned[]
|
||||
uint8_t eager_cand; // in eager_c[]: rendered by the value being recorded, snapshot not taken yet
|
||||
struct EagerSnap *eager; // wb_eager: the staging copy of the image that value eager->value ended with
|
||||
uint64_t wb_last; // wb_eager: gpu_fence of the newest render a write-back took (0: never written back)
|
||||
uint8_t *snap; // a texture that fills no page: its storage bytes when the GPU write was recorded
|
||||
uint32_t wt_n; // WriteTexels into the storage since the last upload
|
||||
struct Tex *rel_prev, *rel_next; // while released: the list of released entries, oldest first
|
||||
@@ -628,7 +631,10 @@ static void dropped_check(const TexKey *k) {
|
||||
dropped[i].hash = 0;
|
||||
}
|
||||
|
||||
static void eager_forget(Tex *e);
|
||||
|
||||
static void destroy_tex(Tex *e) {
|
||||
eager_forget(e);
|
||||
own_remove(e);
|
||||
tex_gen_bump(e->key.addr);
|
||||
nvn_hm_del(&by_key, &e->key);
|
||||
@@ -1532,6 +1538,61 @@ static void wb_cfg_init(void) {
|
||||
// up to 9 frames in a row while a tile loads.
|
||||
static int wb_wanted(const Tex *e) { return e->t.L.size <= wb_limit || e->run < WB_RUN; }
|
||||
|
||||
// TOTK_WB_EAGER (wb_eager; 0, 1 or check, default 1). The fence write-back (write_back_n) read a target's image through
|
||||
// a staging copy submitted at that moment, which queued behind the frame already on the GPU and held the game thread
|
||||
// for 4.5 to 7 ms about every 9th frame. With wb_eager the copy is instead recorded at the end of the value that rendered
|
||||
// the target (vk_texture_eager_record), so when that value has passed the bytes are already in host-visible staging and
|
||||
// the write-back only copies them into the target's storage. Which targets go back, at which fence, and in which order
|
||||
// does not change. check also reads the old way and compares (slow, for validation).
|
||||
// Only frame-ahead (sync_ahead on and not refused, nvn_sync_ahead_on) makes the game thread stall on these copies in a
|
||||
// way that costs frame time, so with it off wb_eager stays EAGER_OFF: no candidates, no staging, one branch per use.
|
||||
// A target is snapshotted only while it is being written back: one whose last write-back (wb_last) lies more than
|
||||
// EAGER_WINDOW timeline values behind the value being recorded gets none, and its first write-back takes the blocking
|
||||
// path. Only where the bytes come from changes, never what goes back to the game or when.
|
||||
enum { EAGER_OFF, EAGER_ON, EAGER_CHECK, EAGER_WINDOW = 64 };
|
||||
static int wb_eager = -1;
|
||||
static Tex **eager_c; // candidates for the value being recorded (tex_lock)
|
||||
static int neager_c, ceager_c;
|
||||
static int neager_c_seen; // neager_c, readable without tex_lock
|
||||
static uint64_t eager_allocs, eager_snapshots, eager_taken, eager_fallback, eager_compared, eager_differ; // tex_lock
|
||||
// Why a write-back did not use a snapshot (eager_state), counted in write_back_n.
|
||||
enum { EB_READY, EB_NONE, EB_OTHER_VALUE, EB_WR_FENCE, EB_NOT_DONE, EB_N };
|
||||
static uint64_t eager_why[EB_N]; // tex_lock
|
||||
static uint64_t eager_logged; // fallbacks logged one by one, up to EAGER_LOG_MAX
|
||||
// Fence write-backs that waited for a staging copy (vk_upload_flush(1) in write_back_n) and the time they waited, the
|
||||
// stall wb_eager removes; counted with wb_eager = 0 too while frame-ahead is in effect, so both settings compare (tex_lock).
|
||||
static uint64_t wb_block_n, wb_block_ns, wb_block_max_ns;
|
||||
static int wb_count_blocks; // frame-ahead in effect: the exit line is written whatever wb_eager is
|
||||
enum { EAGER_LOG_MAX = 20 };
|
||||
|
||||
static void eager_release(Tex *e);
|
||||
|
||||
static void wb_eager_init(void) {
|
||||
const char *v = cfg_get("TOTK_WB_EAGER");
|
||||
int want = v && !strcmp(v, "0") ? EAGER_OFF : v && !strcmp(v, "check") ? EAGER_CHECK : EAGER_ON;
|
||||
wb_count_blocks = nvn_sync_ahead_on();
|
||||
wb_eager = want != EAGER_OFF && !wb_count_blocks ? EAGER_OFF : want;
|
||||
if (want != EAGER_OFF && wb_eager == EAGER_OFF)
|
||||
rt_log("vk: wb_eager: off, frame-ahead (sync_ahead) is not in effect");
|
||||
}
|
||||
|
||||
// tex_lock held, in vk_texture_gpu_written: e was rendered by the value being recorded and will be written back.
|
||||
static void eager_candidate(Tex *e) {
|
||||
if (wb_eager < 0) wb_eager_init();
|
||||
if (wb_eager == EAGER_OFF || e->eager_cand || !e->gpu_fence) return;
|
||||
if (!e->wb_last || e->gpu_fence > e->wb_last + EAGER_WINDOW) { // not written back lately: no snapshot, free the old
|
||||
eager_release(e);
|
||||
return;
|
||||
}
|
||||
if (neager_c == ceager_c) {
|
||||
ceager_c = ceager_c ? 2 * ceager_c : 32;
|
||||
if (!(eager_c = realloc(eager_c, sizeof *eager_c * (size_t)ceager_c))) rt_fatal("vk: out of memory for the eager write-back list");
|
||||
}
|
||||
eager_c[neager_c++] = e;
|
||||
e->eager_cand = 1;
|
||||
__atomic_store_n(&neager_c_seen, neager_c, __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
void vk_texture_gpu_written(const tex_t *t) {
|
||||
if (!t || !t->mem) return;
|
||||
vk_exec_frame_written(t);
|
||||
@@ -1561,7 +1622,10 @@ void vk_texture_gpu_written(const tex_t *t) {
|
||||
e->run_frame = fr;
|
||||
}
|
||||
wb_cfg_init();
|
||||
if (wb_wanted(e)) __atomic_store_n(&small_pending, 1, __ATOMIC_RELEASE);
|
||||
if (wb_wanted(e)) {
|
||||
__atomic_store_n(&small_pending, 1, __ATOMIC_RELEASE);
|
||||
eager_candidate(e);
|
||||
} else if (wb_eager > EAGER_OFF) eager_release(e); // no longer written back at fence waits
|
||||
own_add(e);
|
||||
}
|
||||
}
|
||||
@@ -1576,6 +1640,7 @@ void vk_texture_release(const tex_t *t) {
|
||||
Tex *e = nvn_hm_get(&by_key, &k);
|
||||
if (e && !e->released) {
|
||||
e->released = 1;
|
||||
eager_forget(e); // a released target is not written back at fence waits: its staging goes
|
||||
e->rel_ms = coarse_ms;
|
||||
e->rel_seq = use_counter;
|
||||
nreleased++;
|
||||
@@ -1873,18 +1938,20 @@ typedef struct {
|
||||
VmaAllocation sa;
|
||||
const uint8_t *stg;
|
||||
size_t slice, ib; // ib: bytes per texel of an expanded RGB image, 0 when the image holds the storage layout
|
||||
size_t bytes; // the size of the staging buffer: slice times the depth of the region
|
||||
uint32_t w;
|
||||
VkImageAspectFlags aspect;
|
||||
} TexRead;
|
||||
|
||||
static int texels_read_record(Tex *e, const Region *g, const NVNcopyRegion *r, TexRead *t) {
|
||||
// The sizes of the staging buffer for a read of region r, and the aspect to copy; 0 when the image cannot be read back.
|
||||
static int texels_read_plan(Tex *e, const Region *g, const NVNcopyRegion *r, TexRead *t) {
|
||||
static volatile int32_t n_astc, n_ds;
|
||||
VkImageAspectFlags aspect;
|
||||
if (e->f.astc_bw) {
|
||||
log_limited(&n_astc, "ReadTexels of ASTC texture %#llx: the image holds decoded RGBA8; zeros returned",
|
||||
(unsigned long long)e->pub.addr);
|
||||
return 0;
|
||||
}
|
||||
if (!read_aspect(e, &aspect)) {
|
||||
if (!read_aspect(e, &t->aspect)) {
|
||||
log_limited(&n_ds, "texels of packed depth-stencil format %#x are not copied", e->t.d.format);
|
||||
return 0;
|
||||
}
|
||||
@@ -1893,25 +1960,40 @@ static int texels_read_record(Tex *e, const Region *g, const NVNcopyRegion *r, T
|
||||
t->w = w;
|
||||
t->ib = e->f.expand_rgb ? (size_t)g->bpb / 3 * 4 : 0;
|
||||
t->slice = t->ib ? (size_t)w * h * t->ib : g->wb * g->hb;
|
||||
t->stg = vk_staging(t->slice * (size_t)g->nz, &t->sb, &t->sa);
|
||||
t->bytes = t->slice * (size_t)g->nz;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// The copy of the region from the image into t->sb, with no barriers.
|
||||
static void texels_read_copy_cmd(VkCommandBuffer cb, Tex *e, const Region *g, const NVNcopyRegion *r, const TexRead *t) {
|
||||
VkBufferImageCopy *rg = calloc((size_t)g->nz, sizeof *rg);
|
||||
if (!rg) rt_fatal("vk: out of memory for a texture read");
|
||||
for (int z = 0; z < g->nz; z++)
|
||||
rg[z] = (VkBufferImageCopy){.bufferOffset = t->slice * (size_t)z,
|
||||
.imageSubresource = {aspect, g->level, g->is3d ? 0 : g->layer0 + (uint32_t)r->zoffset + (uint32_t)z, 1},
|
||||
.imageSubresource = {t->aspect, g->level, g->is3d ? 0 : g->layer0 + (uint32_t)r->zoffset + (uint32_t)z, 1},
|
||||
.imageOffset = {r->xoffset, r->yoffset, g->is3d ? r->zoffset + z : 0},
|
||||
.imageExtent = {w, h, 1}};
|
||||
.imageExtent = {t->w, (uint32_t)r->height, 1}};
|
||||
vkCmdCopyImageToBuffer(cb, e->pub.image, VK_IMAGE_LAYOUT_GENERAL, t->sb, (uint32_t)g->nz, rg);
|
||||
free(rg);
|
||||
}
|
||||
|
||||
// An image region read through a staging buffer. texels_read_record records the copy into the open upload batch;
|
||||
// texels_read_take copies the rows out once that batch is done (vk_upload_flush(1)) and frees the buffer. Several
|
||||
// records before one flush cost one GPU round trip instead of one each.
|
||||
static int texels_read_record(Tex *e, const Region *g, const NVNcopyRegion *r, TexRead *t) {
|
||||
if (!texels_read_plan(e, g, r, t)) return 0;
|
||||
t->stg = vk_staging(t->bytes, &t->sb, &t->sa);
|
||||
VkCommandBuffer cb = vk_upload_begin();
|
||||
barrier(cb, ALL_RW, VK_PIPELINE_STAGE_2_COPY_BIT, VK_ACCESS_2_TRANSFER_READ_BIT);
|
||||
vkCmdCopyImageToBuffer(cb, e->pub.image, VK_IMAGE_LAYOUT_GENERAL, t->sb, (uint32_t)g->nz, rg);
|
||||
texels_read_copy_cmd(cb, e, g, r, t);
|
||||
barrier(cb, VK_PIPELINE_STAGE_2_COPY_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_HOST_BIT,
|
||||
VK_ACCESS_2_HOST_READ_BIT);
|
||||
vk_upload_end();
|
||||
free(rg);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void texels_read_take(const Tex *e, const Region *g, const TexRead *t, uint8_t *mem) {
|
||||
// The rows of a finished read into caller memory; the staging buffer stays.
|
||||
static void texels_read_rows(const Tex *e, const Region *g, const TexRead *t, uint8_t *mem) {
|
||||
VkCtx *c = vk_ctx();
|
||||
vmaInvalidateAllocation(c->vma, t->sa, 0, VK_WHOLE_SIZE);
|
||||
for (int z = 0; z < g->nz; z++) {
|
||||
@@ -1922,7 +2004,11 @@ static void texels_read_take(const Tex *e, const Region *g, const TexRead *t, ui
|
||||
else memcpy(m + y * g->row, s + y * g->wb, g->wb);
|
||||
}
|
||||
}
|
||||
vmaDestroyBuffer(c->vma, t->sb, t->sa);
|
||||
}
|
||||
|
||||
static void texels_read_take(const Tex *e, const Region *g, const TexRead *t, uint8_t *mem) {
|
||||
texels_read_rows(e, g, t, mem);
|
||||
vmaDestroyBuffer(vk_ctx()->vma, t->sb, t->sa);
|
||||
}
|
||||
|
||||
// Image <-> caller rows through a staging buffer; the GPU copy is waited for.
|
||||
@@ -2077,52 +2163,263 @@ void vk_write_texels(const tex_t *t, const view_t *v, const NVNcopyRegion *r, co
|
||||
// Every level and layer of every texture in v is copied to staging in one upload batch with one wait: one GPU round
|
||||
// trip per level and layer took 0.1 ms each, and a 260x260 grass map has 9 levels. The storage is then written in the
|
||||
// order of v, so where two textures share storage the later one wins.
|
||||
// One level and layer of a target to write back: its region and the staging read of it. A part of an eager snapshot
|
||||
// carries the staging buffer the GPU filled in advance; else the read is recorded at the write-back.
|
||||
typedef struct { Region g; NVNcopyRegion r; TexRead t; } EagerPart;
|
||||
typedef struct {
|
||||
Tex *e;
|
||||
Region g;
|
||||
NVNcopyRegion r;
|
||||
TexRead t;
|
||||
EagerPart ep;
|
||||
TexRead chk; // wb_eager = check: the same read made the old way, to compare with ep.t
|
||||
uint8_t snap; // ep is a part of e's eager snapshot (kept after the take); else a read recorded now
|
||||
uint8_t has_chk;
|
||||
} WbPart;
|
||||
|
||||
// The levels and layers write-back covers for e, and the region of each.
|
||||
static void wb_dims(const Tex *e, uint32_t *levels, uint32_t *layers) {
|
||||
const nvn_texdesc *d = &e->t.d;
|
||||
int linear = nvn_tex_is_linear(d), is3d = d->target == NVN_TEXTURE_TARGET_3D;
|
||||
*levels = linear ? 1 : e->pub.levels;
|
||||
*layers = linear || is3d ? 1 : e->pub.layers;
|
||||
}
|
||||
|
||||
static int wb_region(const Tex *e, uint32_t lv, uint32_t ly, Region *g, NVNcopyRegion *r) {
|
||||
const nvn_texdesc *d = &e->t.d;
|
||||
int is3d = d->target == NVN_TEXTURE_TARGET_3D;
|
||||
view_t vw = {.set_levels = 1, .set_layers = 1, .base_level = (uint8_t)lv, .min_layer = (uint16_t)ly};
|
||||
*r = (NVNcopyRegion){.width = (int)mip(d->width, lv),
|
||||
.height = d->target == 0 || d->target == 3 ? 1 : (int)mip(d->height, lv),
|
||||
.depth = is3d ? (int)mip(d->depth, lv) : 1};
|
||||
return region_of(&e->t, &vw, r, 0, 0, g);
|
||||
}
|
||||
|
||||
// wb_eager: the staging copy of the image at the end of value `value`, one part per level and layer in the order
|
||||
// write_back_n walks them. The buffers belong to the snapshot; the GPU writes them with the copies recorded in `value`.
|
||||
// p has room for levels * layers parts (wb_dims of the target when it was made), np of them are in use.
|
||||
struct EagerSnap {
|
||||
uint64_t value;
|
||||
uint32_t levels, layers;
|
||||
int np;
|
||||
EagerPart *p;
|
||||
};
|
||||
|
||||
// Frees a snapshot's buffers once the GPU has passed its value: the copies may still be running.
|
||||
static void eager_free_snap(struct EagerSnap *z) {
|
||||
if (!z) return;
|
||||
for (int i = 0; i < z->np; i++) vk_defer_buffer_until(z->p[i].t.sb, z->p[i].t.sa, z->value);
|
||||
free(z->p);
|
||||
free(z);
|
||||
}
|
||||
|
||||
// tex_lock held: frees e's snapshot, if any, through the deferred path.
|
||||
static void eager_release(Tex *e) {
|
||||
eager_free_snap(e->eager);
|
||||
e->eager = NULL;
|
||||
}
|
||||
|
||||
// tex_lock held, from destroy_tex and vk_texture_release.
|
||||
static void eager_forget(Tex *e) {
|
||||
if (e->eager_cand) {
|
||||
for (int i = 0; i < neager_c; i++)
|
||||
if (eager_c[i] == e) {
|
||||
eager_c[i] = eager_c[--neager_c];
|
||||
break;
|
||||
}
|
||||
__atomic_store_n(&neager_c_seen, neager_c, __ATOMIC_RELEASE);
|
||||
e->eager_cand = 0;
|
||||
}
|
||||
eager_release(e);
|
||||
}
|
||||
|
||||
// Whether e's write-back can take its texels from the snapshot (EB_READY), else the first reason it cannot: no snapshot,
|
||||
// one of a value other than the one that last rendered e, a write to its image recorded since (wr_fence: a storage
|
||||
// binding, a copy), or the GPU has not finished the snapshot's value.
|
||||
static int eager_state(const Tex *e) {
|
||||
const struct EagerSnap *z = e->eager;
|
||||
if (!z) return EB_NONE;
|
||||
if (z->value != e->gpu_fence) return EB_OTHER_VALUE;
|
||||
if (z->value != e->wr_fence) return EB_WR_FENCE;
|
||||
return vk_sync_fence_done() >= z->value ? EB_READY : EB_NOT_DONE;
|
||||
}
|
||||
|
||||
// tex_lock held, from vk_texture_write_back_small once per fence wait: frees the snapshots that will not be used soon,
|
||||
// those of targets no longer written back at fence waits (wb_wanted) and those with no pending write-back whose last
|
||||
// one is more than EAGER_WINDOW values behind `now`. A target a candidate list still holds keeps its snapshot: the one
|
||||
// being recorded replaces it. owned[] cannot change while tex_lock is held.
|
||||
static void eager_sweep(uint64_t now) {
|
||||
for (int i = 0; i < nowned; i++) {
|
||||
Tex *e = owned[i];
|
||||
if (!e->eager || e->eager_cand) continue;
|
||||
if (!wb_wanted(e) || (!e->gpu_dirty && now > e->wb_last + EAGER_WINDOW)) eager_release(e);
|
||||
}
|
||||
}
|
||||
|
||||
// tex_lock held, cb the recorder's command buffer of the value `fence` with no render pass open: copies e's image
|
||||
// into staging buffers. *open: the barrier before the copies is already in cb. When e's previous snapshot has the same
|
||||
// level and layer counts and the GPU is done with it (its value has passed on the timeline, so no copy still writes
|
||||
// its buffers and no read of them is pending), the snapshot is reused in place and each part keeps its staging buffer
|
||||
// if the size matches. A snapshot still in flight is not reused: it is freed after its value and a new one is made.
|
||||
static void eager_snapshot(VkCommandBuffer cb, Tex *e, uint64_t fence, int *open) {
|
||||
uint32_t levels, layers;
|
||||
wb_dims(e, &levels, &layers);
|
||||
struct EagerSnap *z = e->eager;
|
||||
int inplace = z && z->levels == levels && z->layers == layers && z->value <= vk_sync_fence_done();
|
||||
int old_np = inplace ? z->np : 0;
|
||||
uint64_t old_value = inplace ? z->value : 0;
|
||||
if (!inplace) {
|
||||
eager_release(e);
|
||||
z = calloc(1, sizeof *z);
|
||||
if (!z || !(z->p = calloc((size_t)levels * layers, sizeof *z->p))) rt_fatal("vk: out of memory for a write-back snapshot");
|
||||
z->levels = levels, z->layers = layers;
|
||||
e->eager = z;
|
||||
}
|
||||
z->value = fence;
|
||||
z->np = 0;
|
||||
for (uint32_t lv = 0; lv < levels; lv++)
|
||||
for (uint32_t ly = 0; ly < layers; ly++) {
|
||||
EagerPart n;
|
||||
memset(&n, 0, sizeof n);
|
||||
if (!wb_region(e, lv, ly, &n.g, &n.r) || !texels_read_plan(e, &n.g, &n.r, &n.t)) continue;
|
||||
EagerPart *q = &z->p[z->np];
|
||||
if (z->np < old_np && q->t.sb && q->t.bytes == n.t.bytes) {
|
||||
n.t.sb = q->t.sb, n.t.sa = q->t.sa, n.t.stg = q->t.stg; // the part's buffer, kept
|
||||
} else {
|
||||
if (z->np < old_np && q->t.sb) vk_defer_buffer_until(q->t.sb, q->t.sa, old_value);
|
||||
n.t.stg = vk_staging(n.t.bytes, &n.t.sb, &n.t.sa);
|
||||
eager_allocs++;
|
||||
}
|
||||
*q = n;
|
||||
z->np++;
|
||||
}
|
||||
for (int i = z->np; i < old_np; i++) { // fewer parts than before: the buffers of the others go
|
||||
vk_defer_buffer_until(z->p[i].t.sb, z->p[i].t.sa, old_value);
|
||||
z->p[i].t.sb = VK_NULL_HANDLE;
|
||||
}
|
||||
if (!z->np) {
|
||||
eager_release(e);
|
||||
return;
|
||||
}
|
||||
if (!*open) barrier(cb, ALL_RW, VK_PIPELINE_STAGE_2_COPY_BIT, VK_ACCESS_2_TRANSFER_READ_BIT), *open = 1;
|
||||
for (int i = 0; i < z->np; i++) texels_read_copy_cmd(cb, e, &z->p[i].g, &z->p[i].r, &z->p[i].t);
|
||||
eager_snapshots++;
|
||||
}
|
||||
|
||||
void vk_texture_eager_record(VkCommandBuffer cb, uint64_t fence) {
|
||||
if (!__atomic_load_n(&neager_c_seen, __ATOMIC_ACQUIRE)) return;
|
||||
lock();
|
||||
int k = 0, open = 0;
|
||||
for (int i = 0; i < neager_c; i++) {
|
||||
Tex *e = eager_c[i];
|
||||
if (e->gpu_fence > fence) { // rendered by a value that is not recorded yet
|
||||
eager_c[k++] = e;
|
||||
continue;
|
||||
}
|
||||
e->eager_cand = 0;
|
||||
if (cb && e->gpu_fence == fence && e->gpu_dirty) eager_snapshot(cb, e, fence, &open);
|
||||
}
|
||||
neager_c = k;
|
||||
__atomic_store_n(&neager_c_seen, k, __ATOMIC_RELEASE);
|
||||
if (open) barrier(cb, VK_PIPELINE_STAGE_2_COPY_BIT, VK_ACCESS_2_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_2_HOST_BIT,
|
||||
VK_ACCESS_2_HOST_READ_BIT);
|
||||
unlock();
|
||||
}
|
||||
|
||||
void vk_texture_eager_log(void) {
|
||||
static int32_t done;
|
||||
if (!wb_count_blocks || plat_xchg32(&done, 1)) return;
|
||||
rt_log("vk: fence write-backs waited for the GPU %llu times, %.1f ms in all, longest %.2f ms (wb_eager %s)",
|
||||
(unsigned long long)wb_block_n, (double)wb_block_ns / 1e6, (double)wb_block_max_ns / 1e6,
|
||||
wb_eager == EAGER_CHECK ? "check, the compare reads included" : wb_eager == EAGER_ON ? "1" : "0");
|
||||
if (wb_eager <= EAGER_OFF) return;
|
||||
rt_log("vk: wb_eager: %llu snapshots, %llu taken without a wait, %llu fell back to the blocking path (%llu staging buffers allocated)",
|
||||
(unsigned long long)eager_snapshots, (unsigned long long)eager_taken, (unsigned long long)eager_fallback,
|
||||
(unsigned long long)eager_allocs);
|
||||
rt_log("vk: wb_eager: fell back because of: no snapshot %llu, snapshot of another value %llu, wr_fence differs %llu, "
|
||||
"value not done %llu", (unsigned long long)eager_why[EB_NONE], (unsigned long long)eager_why[EB_OTHER_VALUE],
|
||||
(unsigned long long)eager_why[EB_WR_FENCE], (unsigned long long)eager_why[EB_NOT_DONE]);
|
||||
if (wb_eager == EAGER_CHECK)
|
||||
rt_log("vk: wb_eager check: %llu compared, %llu differ", (unsigned long long)eager_compared,
|
||||
(unsigned long long)eager_differ);
|
||||
}
|
||||
|
||||
static void write_back_n(Tex **v, int n) {
|
||||
int np = 0, cap = 0;
|
||||
int np = 0, cap = 0, nrec = 0;
|
||||
WbPart *p = NULL;
|
||||
for (int i = 0; i < n; i++) {
|
||||
Tex *e = v[i];
|
||||
const nvn_texdesc *d = &e->t.d;
|
||||
int linear = nvn_tex_is_linear(d), is3d = d->target == NVN_TEXTURE_TARGET_3D;
|
||||
uint32_t levels = linear ? 1 : e->pub.levels, layers = linear || is3d ? 1 : e->pub.layers;
|
||||
int why = wb_eager > EAGER_OFF ? eager_state(e) : EB_READY;
|
||||
int use = wb_eager > EAGER_OFF && why == EB_READY;
|
||||
if (use) eager_taken++;
|
||||
else if (wb_eager > EAGER_OFF) {
|
||||
static const char *const why_text[EB_N] = {"", "no snapshot", "snapshot of another value", "wr_fence differs",
|
||||
"value not done"};
|
||||
eager_fallback++, eager_why[why]++;
|
||||
if (eager_logged++ < EAGER_LOG_MAX)
|
||||
rt_log("vk: wb_eager: blocking write-back of %#llx size %llu fmt %#x: %s",
|
||||
(unsigned long long)e->pub.addr, (unsigned long long)e->t.L.size, e->t.d.format, why_text[why]);
|
||||
}
|
||||
uint32_t levels, layers;
|
||||
wb_dims(e, &levels, &layers);
|
||||
int room = use ? e->eager->np : (int)(levels * layers); // parts this target adds, at most
|
||||
if (np + room > cap) {
|
||||
cap = np + room + 16;
|
||||
if (!(p = realloc(p, sizeof *p * (size_t)cap))) rt_fatal("vk: out of memory for a texture write-back");
|
||||
}
|
||||
if (use) {
|
||||
const struct EagerSnap *z = e->eager;
|
||||
for (int j = 0; j < z->np; j++, np++) {
|
||||
WbPart *q = &p[np];
|
||||
*q = (WbPart){.e = e, .ep = z->p[j], .snap = 1};
|
||||
if (wb_eager == EAGER_CHECK && texels_read_record(e, &q->ep.g, &q->ep.r, &q->chk)) q->has_chk = 1, nrec++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for (uint32_t lv = 0; lv < levels; lv++)
|
||||
for (uint32_t ly = 0; ly < layers; ly++) {
|
||||
if (np == cap) {
|
||||
cap = cap ? cap * 2 : 16;
|
||||
if (!(p = realloc(p, sizeof *p * (size_t)cap))) rt_fatal("vk: out of memory for a texture write-back");
|
||||
}
|
||||
WbPart *q = &p[np];
|
||||
view_t vw = {.set_levels = 1, .set_layers = 1, .base_level = (uint8_t)lv, .min_layer = (uint16_t)ly};
|
||||
q->e = e;
|
||||
q->r = (NVNcopyRegion){.width = (int)mip(d->width, lv),
|
||||
.height = d->target == 0 || d->target == 3 ? 1 : (int)mip(d->height, lv),
|
||||
.depth = is3d ? (int)mip(d->depth, lv) : 1};
|
||||
if (region_of(&e->t, &vw, &q->r, 0, 0, &q->g) && texels_read_record(e, &q->g, &q->r, &q->t)) np++;
|
||||
q->e = e, q->snap = q->has_chk = 0;
|
||||
if (wb_region(e, lv, ly, &q->ep.g, &q->ep.r) && texels_read_record(e, &q->ep.g, &q->ep.r, &q->ep.t)) np++, nrec++;
|
||||
}
|
||||
}
|
||||
if (np) vk_upload_flush(1);
|
||||
if (nrec) {
|
||||
uint64_t t0 = wb_count_blocks ? plat_now_ns() : 0;
|
||||
vk_upload_flush(1);
|
||||
if (wb_count_blocks) {
|
||||
uint64_t d = plat_now_ns() - t0;
|
||||
wb_block_n++, wb_block_ns += d;
|
||||
if (d > wb_block_max_ns) wb_block_max_ns = d;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < np; i++) {
|
||||
WbPart *q = &p[i];
|
||||
size_t bytes = q->g.img * (size_t)q->g.nz;
|
||||
size_t bytes = q->ep.g.img * (size_t)q->ep.g.nz;
|
||||
uint8_t *buf = malloc(bytes);
|
||||
if (!buf) { // waits for memory with the texture lock held, after the release that needs no submit
|
||||
vk_oom_release();
|
||||
buf = rt_realloc_wait(NULL, bytes, "vk: texture write-back buffer");
|
||||
}
|
||||
if (!buf) rt_fatal("vk: out of memory for a texture write-back");
|
||||
texels_read_take(q->e, &q->g, &q->t, buf);
|
||||
storage_texels(&q->e->t, &q->g, &q->r, buf, 1);
|
||||
if (q->snap) texels_read_rows(q->e, &q->ep.g, &q->ep.t, buf);
|
||||
else texels_read_take(q->e, &q->ep.g, &q->ep.t, buf);
|
||||
if (q->has_chk) {
|
||||
vmaInvalidateAllocation(vk_ctx()->vma, q->chk.sa, 0, VK_WHOLE_SIZE);
|
||||
eager_compared++;
|
||||
if (memcmp(q->ep.t.stg, q->chk.stg, q->ep.t.bytes)) {
|
||||
if (eager_differ++ < 20)
|
||||
rt_log("vk: wb_eager check: %#llx fmt %#x %ux%u level %u layer %u differs from the blocking read "
|
||||
"(snapshot of value %llu, gpu_fence %llu)", (unsigned long long)q->e->pub.addr,
|
||||
q->e->t.d.format, q->e->t.d.width, q->e->t.d.height, q->ep.g.level, q->ep.g.layer0,
|
||||
(unsigned long long)q->e->eager->value, (unsigned long long)q->e->gpu_fence);
|
||||
}
|
||||
vmaDestroyBuffer(vk_ctx()->vma, q->chk.sb, q->chk.sa);
|
||||
}
|
||||
storage_texels(&q->e->t, &q->ep.g, &q->ep.r, buf, 1);
|
||||
free(buf);
|
||||
}
|
||||
free(p);
|
||||
for (int i = 0; i < n; i++) v[i]->gpu_dirty = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
v[i]->gpu_dirty = 0;
|
||||
if (wb_eager > EAGER_OFF && v[i]->gpu_fence > v[i]->wb_last) v[i]->wb_last = v[i]->gpu_fence; // eager_candidate's window
|
||||
}
|
||||
}
|
||||
|
||||
// Mirrored textures overlapping [addr, addr+size) that the GPU wrote since their last write-back.
|
||||
@@ -2146,6 +2443,14 @@ void vk_texture_storage_bound_locked(const VkTexImage *img) {
|
||||
if (f > e->wr_fence) e->wr_fence = f;
|
||||
}
|
||||
|
||||
// The same for a caller that does not hold the texture lock (vk_contact.c vk_contact_flush: a compute pass writes the
|
||||
// scene colour). The lock is recursive.
|
||||
void vk_texture_storage_written(const VkTexImage *img) {
|
||||
lock();
|
||||
vk_texture_storage_bound_locked(img);
|
||||
unlock();
|
||||
}
|
||||
|
||||
uint64_t vk_texture_last_write(const tex_t *t) {
|
||||
lock();
|
||||
Tex *e = entry_of(t);
|
||||
@@ -2264,6 +2569,7 @@ void vk_texture_write_back_small(uint64_t fence) {
|
||||
}
|
||||
}
|
||||
plat_mutex_unlock_shared(&owned_lock);
|
||||
if (wb_eager > EAGER_OFF) eager_sweep(fence);
|
||||
if (later) __atomic_store_n(&small_pending, 1, __ATOMIC_RELEASE);
|
||||
int k = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
|
||||
+2
-1
@@ -89,7 +89,8 @@ static Arena *arena_get(uint64_t need) {
|
||||
a->size = need < ARENA_MIN ? ARENA_MIN : (need + (1u << 20) - 1) & ~(uint64_t)((1u << 20) - 1);
|
||||
VkBufferCreateInfo bi = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = a->size,
|
||||
// transfer source: DLAA copies the camera block out (vk_dlaa.c mv_pass)
|
||||
.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT};
|
||||
.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT |
|
||||
VK_BUFFER_USAGE_TRANSFER_DST_BIT};
|
||||
// Device-local through the BAR when the device has it (the GPU reads constants on every draw), else host memory.
|
||||
VmaAllocationCreateInfo ai = {.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE,
|
||||
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
|
||||
|
||||
@@ -209,7 +209,7 @@ class Tool(unittest.TestCase):
|
||||
code, dat, bad = self.key('Code'), self.key('Data'), self.key('Bad')
|
||||
self.assertEqual([status[k][2] for k in (code, dat, bad)], ['code', 'data', 'unsupported'])
|
||||
self.assertEqual([status[k][4] for k in (code, dat)], ['data 1', 'data 9']) # bytes its data lines hold
|
||||
self.assertIn(f'set mod_{code.lower()} TOTK_MODPATCH_{code} 0', (self.d / 'out.txt').read_text())
|
||||
self.assertIn(f'set mod_{code.lower()} TOTK_MODPATCH_{code} 0 ordered', (self.d / 'out.txt').read_text())
|
||||
self.assertEqual(sorted((f[0], f[2], f[3], f[4:]) for f in data),
|
||||
sorted([(code, '2200', '51', []), (dat, '1000', 'aa', []),
|
||||
(dat, '2118', '3100000000000000', ['base'])]))
|
||||
|
||||
@@ -0,0 +1,591 @@
|
||||
"""recomp/layout.py with and without mod plugins, and tools/exefs_plugins.py's check of a plugin service run record:
|
||||
a synthetic exlaunch-shaped record with one inline hook that passes, and one bad record per rule; the check of the
|
||||
code the hooks reach; the patch lines of the three hook kinds; and what recomp/patches.py and recomp/gen.py make of
|
||||
those lines (the hook call, the stub's return, the unpatched copy a replace hook's trampoline reaches, the start-up
|
||||
record in patches.h). The start-up comparison itself runs in the game (runtime/plugin_init.c plugins_start); its
|
||||
mods.c side is in totk.exe --probe-mods. No game files.
|
||||
|
||||
Run with .venv (lz4 and numpy, as recomp/): python tests/exefs_plugins_test.py
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / 'tools'))
|
||||
sys.path.insert(0, str(ROOT / 'recomp'))
|
||||
import exefs_plugins as xp # noqa: E402
|
||||
import gen # noqa: E402
|
||||
import layout # noqa: E402
|
||||
import patches # noqa: E402
|
||||
from nso import Nso # noqa: E402
|
||||
|
||||
|
||||
def nso(size_text, bss=0x1000):
|
||||
"""An uncompressed NSO: .text of size_text bytes (b over MOD0's offset word), .rodata with MOD0 at 0x1000 past
|
||||
.text, .data with an empty .dynamic."""
|
||||
text = bytearray(size_text)
|
||||
struct.pack_into('<II', text, 0, 0x14000002, size_text) # b +8; the MOD0 offset
|
||||
ro = b'MOD0' + struct.pack('<6i', 0x1000, 0, 0, 0, 0, 0) # .dynamic at .rodata + 0x1000 = .data
|
||||
data = bytes(16) # DT_NULL
|
||||
segs = [(0, bytes(text)), (size_text, ro), (size_text + 0x1000, data)]
|
||||
hdr = bytearray(0x100)
|
||||
hdr[0:4] = b'NSO0'
|
||||
off = 0x100
|
||||
for i, (mem, d) in enumerate(segs):
|
||||
struct.pack_into('<IIII', hdr, 0x10 + 0x10 * i, off, mem, len(d), bss if i == 2 else 0)
|
||||
struct.pack_into('<I', hdr, 0x60 + 4 * i, len(d))
|
||||
off += len(d)
|
||||
return bytes(hdr) + b''.join(d for _, d in segs)
|
||||
|
||||
|
||||
def dev_layout_files(exefs, out):
|
||||
"""layout.json and layout.h as recomp/layout.py wrote them before plugins (dev f8505807), the reference for the
|
||||
no-plugin case."""
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
mods, base = [], layout.FIRST_BASE
|
||||
for name in layout.ORDER:
|
||||
if (exefs / name).exists():
|
||||
size = Nso(str(exefs / name)).size
|
||||
mods.append((name, base, size))
|
||||
base = layout.align_up(base + size)
|
||||
(out / 'layout.json').write_text(json.dumps(
|
||||
[{'name': n, 'base': f'{b:#x}', 'size': f'{s:#x}'} for n, b, s in mods], indent=1) + '\n')
|
||||
lines = ['// Module layout chosen by recomp/layout.py. Generated; do not edit.', '#pragma once', '']
|
||||
for n, b, s in mods:
|
||||
lines.append(f'#define MOD_{n.upper()}_BASE {b:#x}ull')
|
||||
lines.append(f'#define MOD_{n.upper()}_SIZE {s:#x}ull')
|
||||
lines += ['', f'#define MOD_COUNT {len(mods)}',
|
||||
'#define MOD_LIST(X) ' + ' '.join(f'X({n}, {n.upper()})' for n, _, _ in mods), '']
|
||||
(out / 'layout.h').write_text('\n'.join(lines))
|
||||
|
||||
|
||||
class Layout(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
cls.dir = Path(cls.tmp.name)
|
||||
cls.exefs = cls.dir / 'exefs'
|
||||
cls.exefs.mkdir()
|
||||
for name, size in (('main', 0x30000), ('subsdk0', 0x5000), ('sdk', 0x21000)):
|
||||
(cls.exefs / name).write_bytes(nso(size))
|
||||
cls.plugins = [cls.dir / 'mod a' / 'subsdk9', cls.dir / 'mod b' / 'subsdk8']
|
||||
for p, size in zip(cls.plugins, (0x9000, 0x3000)):
|
||||
p.parent.mkdir()
|
||||
p.write_bytes(nso(size))
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def test_no_plugins_identical(self):
|
||||
dev, ours = self.dir / 'dev', self.dir / 'ours'
|
||||
dev_layout_files(self.exefs, dev)
|
||||
layout.write(layout.layout(self.exefs), ours, layout.plugin_files([]))
|
||||
for f in ('layout.json', 'layout.h'):
|
||||
self.assertEqual((dev / f).read_bytes(), (ours / f).read_bytes(), f)
|
||||
|
||||
def test_plugins_after_sdk(self):
|
||||
plain = layout.layout(self.exefs)
|
||||
mods = layout.layout(self.exefs, self.plugins)
|
||||
self.assertEqual(mods[:3], plain) # the game modules keep their bases
|
||||
self.assertEqual([n for n, _, _ in mods], ['main', 'subsdk0', 'sdk', 'plugin0', 'plugin1'])
|
||||
for (_, b0, s0), (_, b1, _) in zip(mods, mods[1:]):
|
||||
self.assertEqual(b1, layout.align_up(b0 + s0))
|
||||
self.assertEqual(mods[3][2], Nso(str(self.plugins[0])).size)
|
||||
out = self.dir / 'with'
|
||||
files = layout.plugin_files(self.plugins)
|
||||
layout.write(mods, out, files)
|
||||
data = json.loads((out / 'layout.json').read_text())
|
||||
self.assertNotIn('file', data[2])
|
||||
self.assertEqual(data[3]['file'], self.plugins[0].resolve().as_posix())
|
||||
self.assertEqual(len(data[3]['sha256']), 64)
|
||||
self.assertEqual(layout.read(out), mods)
|
||||
self.assertIn('#define MOD_PLUGIN1_BASE', (out / 'layout.h').read_text())
|
||||
self.assertIn('#define MOD_COUNT 5', (out / 'layout.h').read_text())
|
||||
|
||||
def test_address_limit(self):
|
||||
old = layout.FIRST_BASE
|
||||
layout.FIRST_BASE = layout.ADDRESS_LIMIT - 0x400000 # the plugins end above 2^39
|
||||
try:
|
||||
with self.assertRaises(ValueError):
|
||||
layout.layout(self.exefs, self.plugins)
|
||||
finally:
|
||||
layout.FIRST_BASE = old
|
||||
|
||||
|
||||
# ---- records
|
||||
MAIN, PLUGIN = 0x7000000000, 0x7005200000
|
||||
SITE_OFF, STUB_OFF, TRAMP_OFF, CB_OFF, IMPL_OFF, THUNK_OFF = 0x1000, 0x4000, 0x2000, 0x66f0, 0x73ec, 0xf00
|
||||
MAIN_TEXT, PLUGIN_TEXT = 0x100000, 0x9000
|
||||
|
||||
|
||||
def b(src, dst, link=False):
|
||||
return (0x94000000 if link else 0x14000000) | ((dst - src) >> 2) & 0x3FFFFFF
|
||||
|
||||
|
||||
def record(original=0x94000010, trampoline_first=None, stub=None, writes=None, **extra):
|
||||
"""A record of one inline hook at main+SITE_OFF whose original is `original` (default bl main+SITE_OFF+0x40)."""
|
||||
site, stub_at, tramp = MAIN + SITE_OFF, PLUGIN + STUB_OFF, PLUGIN + TRAMP_OFF
|
||||
img = bytearray(0x14000)
|
||||
words = stub or [xp.STUR_X30, b(stub_at + 4, PLUGIN + IMPL_OFF, True), xp.LDUR_X30, b(stub_at + 12, tramp)]
|
||||
struct.pack_into('<4IQ', img, STUB_OFF, *words, PLUGIN + CB_OFF)
|
||||
if trampoline_first is None:
|
||||
rel = xp.pc_relative(original, site)
|
||||
trampoline_first = (b(tramp, rel[1], True) if rel and rel[0][0] == 'b' else original)
|
||||
struct.pack_into('<II', img, TRAMP_OFF, trampoline_first, b(tramp + 4, site + 4))
|
||||
rec = {
|
||||
'refused': None, 'svcs': {'0x6': 52, '0x1e': 10, '0x27': 18, '0x29': 17, '0x74': 11, '0x75': 7},
|
||||
'get_info': {'2': 1, '3': 1, '12': 1, '13': 1, '65001': 1},
|
||||
'imports': {'_ZN2nn4util8SNPrintfEPcmPKcz': 20, '_ZN2nn2oe17GetDisplayVersionEPNS0_14DisplayVersionE': 1},
|
||||
'modules': [
|
||||
{'name': 'main', 'base': MAIN, 'size': 0x200000, 'text_end': MAIN_TEXT, 'data_off': 0x180000, 'init': 0,
|
||||
'plugin': False},
|
||||
{'name': 'sdk', 'base': 0x7004400000, 'size': 0x100000, 'text_end': 0x80000, 'data_off': 0xc0000,
|
||||
'init': 0, 'plugin': False},
|
||||
{'name': 'plugin0', 'base': PLUGIN, 'size': 0x14000, 'text_end': PLUGIN_TEXT, 'data_off': 0xd000,
|
||||
'init': PLUGIN + 0x50a0, 'plugin': True, 'functions': [hex(CB_OFF), hex(IMPL_OFF), hex(THUNK_OFF)]}],
|
||||
'writes': writes if writes is not None else [
|
||||
{'module': 'main', 'offset': SITE_OFF, 'old': original, 'new': b(site, stub_at)}],
|
||||
'aliases': [], 'images': {'plugin0': bytes(img)}}
|
||||
rec.update(extra)
|
||||
return rec
|
||||
|
||||
|
||||
IMPLS = {PLUGIN + IMPL_OFF: 'exl_inline_hook_impl'}
|
||||
|
||||
|
||||
class Check(unittest.TestCase):
|
||||
def reasons(self, rec):
|
||||
return xp.check_record(rec, IMPLS)[1]
|
||||
|
||||
def refused(self, rec, text):
|
||||
r = self.reasons(rec)
|
||||
self.assertTrue(r, 'accepted')
|
||||
self.assertTrue(any(text in x for x in r), r)
|
||||
|
||||
def test_good(self):
|
||||
hooks, reasons = xp.check_record(record(), IMPLS)
|
||||
self.assertEqual(reasons, [])
|
||||
self.assertEqual(len(hooks), 1)
|
||||
self.assertEqual(hooks[0]['callback'], f'plugin0+{CB_OFF:#x}')
|
||||
self.assertEqual(hooks[0]['trampoline'], f'plugin0+{TRAMP_OFF:#x}')
|
||||
|
||||
def test_good_plain_original(self):
|
||||
self.assertEqual(self.reasons(record(original=0xAA0003F3)), []) # mov x19, x0, copied as it is
|
||||
|
||||
def test_call_site_rewrite(self): # Quick Weapon Durability: bl straight to a thunk of the plugin
|
||||
site = MAIN + SITE_OFF
|
||||
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(site, PLUGIN + THUNK_OFF, True)}]
|
||||
hooks, reasons = xp.check_record(record(writes=w), IMPLS)
|
||||
self.assertEqual(reasons, [])
|
||||
self.assertEqual(hooks[0]['kind'], 'call')
|
||||
self.assertEqual(hooks[0]['target'], f'plugin0+{THUNK_OFF:#x}')
|
||||
|
||||
def test_replace_hook(self): # Full Inventory Expansion: b from a main function start, Orig trampoline in the pool
|
||||
site, prologue = MAIN + SITE_OFF, 0xA9BA7BFD # stp x29, x30, [sp, #-0x60]!
|
||||
w = [{'module': 'main', 'offset': SITE_OFF, 'old': prologue, 'new': b(site, PLUGIN + THUNK_OFF),
|
||||
'fn_start': True}]
|
||||
hooks, reasons = xp.check_record(record(original=prologue, writes=w), IMPLS)
|
||||
self.assertEqual(reasons, [])
|
||||
self.assertEqual(hooks[0]['kind'], 'replace')
|
||||
self.assertEqual(hooks[0]['trampoline'], f'plugin0+{TRAMP_OFF:#x}')
|
||||
|
||||
def test_replace_inside_function(self):
|
||||
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, PLUGIN + THUNK_OFF),
|
||||
'fn_start': False}]
|
||||
self.refused(record(writes=w), 'from inside a main function')
|
||||
|
||||
def test_call_into_function_middle(self):
|
||||
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, PLUGIN + 0xf08, True)}]
|
||||
self.refused(record(writes=w), 'neither an inline-hook stub nor a function start')
|
||||
|
||||
def test_bl_to_stub(self): # an inline stub is entered by b; a bl there would skip the saved x30
|
||||
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, PLUGIN + STUB_OFF, True)}]
|
||||
self.refused(record(writes=w), 'neither an inline-hook stub nor a function start')
|
||||
|
||||
def test_refused_run(self):
|
||||
self.refused(record(refused='svc 0x40 at plugin0+0x76a0'), 'the run was refused')
|
||||
|
||||
def test_svc(self):
|
||||
self.refused(record(svcs={'0x6': 1, '0x40': 1}), 'svc 0x40')
|
||||
|
||||
def test_get_info(self):
|
||||
self.refused(record(get_info={'2': 1, '18': 1}), 'GetInfo id 18')
|
||||
|
||||
def test_import(self):
|
||||
self.refused(record(imports={'_ZN2nn2fs8MountRomEPKcPvm': 1}), 'the import _ZN2nn2fs8MountRom')
|
||||
|
||||
def test_write_main_data(self):
|
||||
w = [{'module': 'main', 'offset': 0x180008, 'old': 0, 'new': 1}]
|
||||
self.refused(record(writes=w), "outside main's .text: main+0x180008")
|
||||
|
||||
def test_write_other_module(self):
|
||||
w = [{'module': 'sdk', 'offset': 0x100, 'old': 0, 'new': 1}]
|
||||
self.refused(record(writes=w), "outside main's .text: sdk+0x100")
|
||||
|
||||
def test_not_a_branch(self):
|
||||
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': 0xD503201F}]
|
||||
self.refused(record(writes=w), 'is no b')
|
||||
|
||||
def test_branch_elsewhere(self):
|
||||
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': b(MAIN + SITE_OFF, MAIN + 0x8000)}]
|
||||
self.refused(record(writes=w), "does not reach into a plugin's .text")
|
||||
|
||||
def test_stub_shape(self):
|
||||
stub_at = PLUGIN + STUB_OFF
|
||||
words = [0xD503201F, b(stub_at + 4, PLUGIN + IMPL_OFF, True), xp.LDUR_X30, b(stub_at + 12, PLUGIN + TRAMP_OFF)]
|
||||
self.refused(record(stub=words), 'neither an inline-hook stub nor a function start')
|
||||
|
||||
def test_stub_impl(self):
|
||||
stub_at = PLUGIN + STUB_OFF
|
||||
words = [xp.STUR_X30, b(stub_at + 4, PLUGIN + 0x100, True), xp.LDUR_X30, b(stub_at + 12, PLUGIN + TRAMP_OFF)]
|
||||
self.refused(record(stub=words), 'not exl_inline_hook_impl')
|
||||
|
||||
def test_callback_outside(self):
|
||||
rec = record()
|
||||
img = bytearray(rec['images']['plugin0'])
|
||||
struct.pack_into('<Q', img, STUB_OFF + 16, MAIN + 0x500)
|
||||
rec['images']['plugin0'] = bytes(img)
|
||||
self.refused(rec, "callback 0x7000000500 is outside plugin0's .text")
|
||||
|
||||
def test_trampoline_not_original(self):
|
||||
self.refused(record(original=0xAA0003F3, trampoline_first=0xAA0003F4), 'not the original')
|
||||
|
||||
def test_trampoline_bl_elsewhere(self):
|
||||
tramp = PLUGIN + TRAMP_OFF
|
||||
self.refused(record(trampoline_first=b(tramp, MAIN + SITE_OFF + 0x44, True)), 'not the original')
|
||||
|
||||
def test_trampoline_return(self):
|
||||
rec = record()
|
||||
img = bytearray(rec['images']['plugin0'])
|
||||
struct.pack_into('<I', img, TRAMP_OFF + 4, b(PLUGIN + TRAMP_OFF + 4, MAIN + SITE_OFF + 8))
|
||||
rec['images']['plugin0'] = bytes(img)
|
||||
self.refused(rec, 'no b to the site + 4')
|
||||
|
||||
def test_indirect_original(self):
|
||||
self.refused(record(original=0xD65F03C0), 'is a br, blr or ret')
|
||||
|
||||
|
||||
class Diff(unittest.TestCase):
|
||||
def test_lists_differing_words(self):
|
||||
a, c = record(), record()
|
||||
img = bytearray(c['images']['plugin0'])
|
||||
struct.pack_into('<Q', img, 0x13450, 0x2345000000)
|
||||
c['images']['plugin0'] = bytes(img)
|
||||
a['pool'] = c['pool'] = {'base': '0x2000000000', 'size': '0x1000000000'}
|
||||
lines = xp.diff_records(a, c)
|
||||
self.assertEqual(len(lines), 1)
|
||||
self.assertIn('plugin0+0x13450', lines[0])
|
||||
self.assertIn('alias pool', lines[0])
|
||||
self.assertEqual(xp.diff_records(a, record()), [])
|
||||
|
||||
|
||||
# ---- the code the hooks reach
|
||||
SVC_40, RET_W, NOP = 0xD4000801, 0xD65F03C0, 0xD503201F
|
||||
|
||||
|
||||
def code(words, at=0):
|
||||
img = bytearray(0x200)
|
||||
for i, w in enumerate(words):
|
||||
struct.pack_into('<I', img, at + 4 * i, w)
|
||||
return bytes(img)
|
||||
|
||||
|
||||
class Reach(unittest.TestCase):
|
||||
BASE = 0x7005200000
|
||||
|
||||
def test_follows_calls_and_finds_svc(self):
|
||||
# root: bl +0x40; ret. callee at 0x40: svc 0x40; ret
|
||||
img = bytearray(code([b(self.BASE, self.BASE + 0x40, True), RET_W]))
|
||||
struct.pack_into('<II', img, 0x40, SVC_40, RET_W)
|
||||
svcs, imports, indirect, outside = xp.reach(bytes(img), self.BASE, 0x200, [self.BASE], {})
|
||||
self.assertEqual(svcs, {0x40})
|
||||
|
||||
def test_imports_through_plt(self):
|
||||
img = code([b(self.BASE, self.BASE + 0x80, True), RET_W])
|
||||
svcs, imports, _, _ = xp.reach(img, self.BASE, 0x200, [self.BASE], {self.BASE + 0x80: 'malloc'})
|
||||
self.assertEqual((svcs, imports), (set(), {'malloc': 1}))
|
||||
|
||||
def test_stub_returns_at_its_trampoline_branch(self):
|
||||
# stur; bl impl; ldur; b trampoline (where an svc sits): the b is the stub's return
|
||||
stub = [xp.STUR_X30, b(self.BASE + 4, self.BASE + 0x40, True), xp.LDUR_X30, b(self.BASE + 12, self.BASE + 0x100)]
|
||||
img = bytearray(code(stub))
|
||||
struct.pack_into('<I', img, 0x40, RET_W)
|
||||
struct.pack_into('<I', img, 0x100, SVC_40)
|
||||
self.assertEqual(xp.reach(bytes(img), self.BASE, 0x200, [self.BASE], {}, stubs={self.BASE})[0], set())
|
||||
self.assertEqual(xp.reach(bytes(img), self.BASE, 0x200, [self.BASE], {})[0], {0x40})
|
||||
|
||||
def test_indirect_calls_counted(self):
|
||||
img = code([0xD63F0100, RET_W]) # blr x8
|
||||
self.assertEqual(xp.reach(img, self.BASE, 0x200, [self.BASE], {})[2], 1)
|
||||
|
||||
def test_check_refuses_svc_in_callback(self):
|
||||
rec = record()
|
||||
img = bytearray(rec['images']['plugin0'])
|
||||
struct.pack_into('<II', img, CB_OFF, SVC_40, RET_W)
|
||||
struct.pack_into('<I', img, IMPL_OFF, RET_W)
|
||||
rec['images']['plugin0'] = bytes(img)
|
||||
hooks, _ = xp.check_record(rec, IMPLS)
|
||||
reasons, _ = xp.reach_check(rec, hooks, IMPLS)
|
||||
self.assertTrue(any('svc 0x40' in r for r in reasons), reasons)
|
||||
|
||||
def test_check_allows_output_debug_string(self):
|
||||
rec = record()
|
||||
img = bytearray(rec['images']['plugin0'])
|
||||
struct.pack_into('<II', img, CB_OFF, 0xD40004E1, RET_W) # svc 0x27
|
||||
struct.pack_into('<I', img, IMPL_OFF, RET_W)
|
||||
rec['images']['plugin0'] = bytes(img)
|
||||
hooks, _ = xp.check_record(rec, IMPLS)
|
||||
self.assertEqual(xp.reach_check(rec, hooks, IMPLS)[0], [])
|
||||
|
||||
|
||||
# ---- patch lines of the three hook kinds
|
||||
class Lines(unittest.TestCase):
|
||||
def lines(self, rec):
|
||||
hooks, reasons = xp.check_record(rec, IMPLS)
|
||||
self.assertEqual(reasons, [])
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
(Path(d) / 'plugin0.img').write_bytes(rec['images']['plugin0'])
|
||||
rec['modules'][2]['image'] = 'plugin0.img'
|
||||
return xp.plugin_lines(rec, xp.hooks_of(hooks, 'plugin0'), 'mod_x', d, 'plugin0')
|
||||
|
||||
def test_inline(self):
|
||||
out = self.lines(record(original=0xAA0003F3))
|
||||
self.assertIn(f'site mod_x main {SITE_OFF:x} aa0003f3 @call:plugin0+{STUB_OFF:x} aa0003f3', out)
|
||||
self.assertIn(f'stub plugin0 {STUB_OFF:x}', out)
|
||||
self.assertIn(f'seed plugin0 {CB_OFF:x} {IMPL_OFF:x}', out)
|
||||
self.assertIn(f'expect mod_x main {SITE_OFF:x} aa0003f3 {b(MAIN + SITE_OFF, PLUGIN + STUB_OFF):08x}', out)
|
||||
self.assertTrue(out[0].startswith('plugin mod_x plugin0 '))
|
||||
|
||||
def test_replace(self):
|
||||
site, prologue = MAIN + SITE_OFF, 0xA9BA7BFD
|
||||
new = b(site, PLUGIN + THUNK_OFF)
|
||||
w = [{'module': 'main', 'offset': SITE_OFF, 'old': prologue, 'new': new, 'fn_start': True}]
|
||||
out = self.lines(record(original=prologue, writes=w))
|
||||
self.assertIn(f'site mod_x main {SITE_OFF:x} a9ba7bfd {new:08x}', out)
|
||||
self.assertIn(f'orig mod_x plugin0 {TRAMP_OFF:x} main {SITE_OFF:x}', out)
|
||||
self.assertIn(f'seed plugin0 {THUNK_OFF:x}', out)
|
||||
|
||||
def test_call(self):
|
||||
new = b(MAIN + SITE_OFF, PLUGIN + THUNK_OFF, True)
|
||||
w = [{'module': 'main', 'offset': SITE_OFF, 'old': 0x94000010, 'new': new}]
|
||||
out = self.lines(record(writes=w))
|
||||
self.assertIn(f'site mod_x main {SITE_OFF:x} 94000010 {new:08x}', out)
|
||||
self.assertFalse(any(x.startswith(('orig', 'stub')) for x in out))
|
||||
|
||||
|
||||
# ---- one service run per plugin
|
||||
class PerPlugin(unittest.TestCase):
|
||||
"""main() with three plugins in three mods and a stand-in for the service run: plugin0 hooks its site, plugin1's
|
||||
init ends the run without a record (a crash), plugin2's run is refused (an svc). Each gets its own status line;
|
||||
only plugin0's set goes into the patch file."""
|
||||
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.d = Path(tmp.name)
|
||||
self.files = []
|
||||
for name in ('A', 'B', 'C'):
|
||||
f = self.d / 'mods' / name / 'exefs' / 'subsdk9'
|
||||
f.parent.mkdir(parents=True)
|
||||
f.write_bytes(nso(PLUGIN_TEXT) + name.encode())
|
||||
self.files.append(f)
|
||||
(self.d / 'patches.txt').write_text('set fps60 TOTK_FPS60 1\n')
|
||||
self.runs = []
|
||||
saved = xp.run, xp.hook_impls
|
||||
self.real_run = xp.run
|
||||
self.addCleanup(lambda: (setattr(xp, 'run', saved[0]), setattr(xp, 'hook_impls', saved[1])))
|
||||
xp.run, xp.hook_impls = self.fake_run, lambda rec: IMPLS
|
||||
|
||||
def fake_run(self, exe, out, tick_offset, timeout, only):
|
||||
self.runs.append(only)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
if only == 'plugin1':
|
||||
return 0xC0000005, 'its init ended the service run without a record (exit 0xc0000005)'
|
||||
rec = record(writes=[] if only != 'plugin0' else None)
|
||||
rec['modules'][2]['file'] = str(self.files[0])
|
||||
for i in (1, 2):
|
||||
rec['modules'].append(dict(rec['modules'][2], name=f'plugin{i}', base=PLUGIN + i * 0x100000,
|
||||
file=str(self.files[i])))
|
||||
for m in rec['modules'][2:]:
|
||||
m['ran'] = m['name'] == only
|
||||
if only == 'plugin2':
|
||||
rec['refused'] = 'svc 0x1 at plugin2+0x50a0'
|
||||
(out / 'plugin0.img').write_bytes(rec.pop('images')['plugin0'])
|
||||
rec['modules'][2]['image'] = 'plugin0.img'
|
||||
(out / 'record.json').write_text(json.dumps(rec))
|
||||
return 3 if rec['refused'] else 0, None
|
||||
|
||||
def test_each_plugin_alone(self):
|
||||
out, status, patched = self.d / 'rec', self.d / 'plugins.status', self.d / 'patches-out.txt'
|
||||
argv = sys.argv
|
||||
sys.argv = ['exefs_plugins.py', '--exe', 'totk.exe', '--out', str(out), '--mods', str(self.d / 'mods'),
|
||||
'--patches', str(self.d / 'patches.txt'), '--patches-out', str(patched), '--status', str(status)]
|
||||
try:
|
||||
code = xp.main()
|
||||
finally:
|
||||
sys.argv = argv
|
||||
self.assertEqual(code, 1)
|
||||
self.assertEqual(self.runs, ['-', 'plugin0', 'plugin0', 'plugin1', 'plugin2'])
|
||||
lines = {line.split('\t')[0]: line.split('\t') for line in status.read_text().splitlines()}
|
||||
key = {n: xp.fnv(f'{n}/exefs/subsdk9'.encode()) for n in 'ABC'}
|
||||
self.assertEqual(lines[key['A']][2:], ['plugin', '-', 'plugin0, 1 hooks'])
|
||||
self.assertEqual(lines[key['B']][2], 'unsupported')
|
||||
self.assertIn('ended the service run', lines[key['B']][4])
|
||||
self.assertEqual(lines[key['C']][2], 'unsupported')
|
||||
self.assertIn('svc 0x1', lines[key['C']][4])
|
||||
text = patched.read_text()
|
||||
self.assertIn(f'set mod_{key["A"].lower()} ', text)
|
||||
self.assertNotIn(f'mod_{key["B"].lower()}', text)
|
||||
self.assertNotIn(f'mod_{key["C"].lower()}', text)
|
||||
self.assertIn((out / 'plugin0' / 'run1' / 'plugin0.img').resolve().as_posix(), text)
|
||||
|
||||
def test_run_reasons(self):
|
||||
# the real run(): a hang becomes its own reason, a crash names the FATAL line
|
||||
saved = xp.subprocess.run
|
||||
self.addCleanup(setattr, xp.subprocess, 'run', saved)
|
||||
|
||||
def hang(cmd, **kw):
|
||||
raise xp.subprocess.TimeoutExpired(cmd, kw['timeout'], output=b'started', stderr=None)
|
||||
xp.subprocess.run = hang
|
||||
self.assertEqual(self.real_run(None, self.d / 'h', 0, 7, 'plugin0'), (None, 'its init did not return within 7 s'))
|
||||
xp.subprocess.run = lambda cmd, **kw: SimpleNamespace(returncode=0xC0000005, stdout='x\nFATAL: access violation '
|
||||
'(0xc0000005) at host 1\n', stderr='')
|
||||
code, why = self.real_run(None, self.d / 'c', 0, 7, 'plugin0')
|
||||
self.assertEqual(why, 'its init crashed the service run: access violation (0xc0000005) at host 1')
|
||||
|
||||
def test_ran_view_leaves_out_plugins_that_did_not_run(self):
|
||||
rec = record()
|
||||
rec['modules'].append(dict(rec['modules'][2], name='plugin1', base=PLUGIN + 0x100000, ran=False))
|
||||
rec['modules'][2]['ran'] = True
|
||||
rec['images']['plugin1'] = rec['images']['plugin0']
|
||||
view = xp.ran_view(rec)
|
||||
self.assertEqual([m['name'] for m in view['modules'] if m['plugin']], ['plugin0'])
|
||||
self.assertEqual(set(view['images']), {'plugin0'})
|
||||
whole = record() # no "ran": every init ran, the record is its own view
|
||||
self.assertIs(xp.ran_view(whole), whole)
|
||||
|
||||
|
||||
# ---- the generator on those lines
|
||||
def code_nso(words_at, size_text=0x5000):
|
||||
"""An NSO as nso() whose .text holds words_at {offset: word}."""
|
||||
raw = bytearray(nso(size_text))
|
||||
for off, w in words_at.items():
|
||||
struct.pack_into('<I', raw, 0x100 + off, w)
|
||||
return bytes(raw)
|
||||
|
||||
|
||||
FN = 0x100 # the hooked main function: mov x19, x0; mov x0, x19; ret
|
||||
|
||||
|
||||
class Generator(unittest.TestCase):
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.d = Path(tmp.name)
|
||||
exefs = self.d / 'exefs'
|
||||
exefs.mkdir()
|
||||
(exefs / 'main').write_bytes(code_nso({FN: 0xAA0003F3, FN + 4: 0xAA1303E0, FN + 8: RET_W}))
|
||||
(exefs / 'sdk').write_bytes(nso(0x1000))
|
||||
stub = PLUGIN_TEXT_STUB = 0x4000
|
||||
self.plugin_file = self.d / 'subsdk9'
|
||||
self.plugin_file.write_bytes(nso(0x5000))
|
||||
self.mods = layout.layout(exefs, [self.plugin_file])
|
||||
self.bases = {n: b_ for n, b_, _ in self.mods}
|
||||
pb = self.bases['plugin0']
|
||||
# the image after the init: a stub at 0x4000 (b to a trampoline at 0x2000), an impl at 0x4100, a callback at
|
||||
# 0x4200
|
||||
img = bytearray(Nso(str(self.plugin_file)).image)
|
||||
struct.pack_into('<4IQ', img, stub, xp.STUR_X30, b(pb + stub + 4, pb + 0x4100, True), xp.LDUR_X30,
|
||||
b(pb + stub + 12, pb + 0x2000), pb + 0x4200)
|
||||
struct.pack_into('<I', img, 0x4100, RET_W)
|
||||
struct.pack_into('<I', img, 0x4200, RET_W)
|
||||
struct.pack_into('<II', img, 0x2000, 0xAA0003F3, b(pb + 0x2004, self.bases['main'] + FN + 4))
|
||||
(self.d / 'plugin0.img').write_bytes(bytes(img))
|
||||
n = Nso(str(self.plugin_file))
|
||||
self.sha = hashlib.sha256(bytes(img[n.text[0]:n.text[0] + n.text[1]])).hexdigest()
|
||||
|
||||
def table(self, site_line, extra=()):
|
||||
text = '\n'.join(['set mod_x TOTK_MODPATCH_X 0 ordered',
|
||||
f'plugin mod_x plugin0 {self.sha} {(self.d / "plugin0.img").as_posix()}',
|
||||
f'expect mod_x main {FN:x} aa0003f3 14000000', site_line, *extra]) + '\n'
|
||||
(self.d / 'p.txt').write_text(text)
|
||||
return patches.load(self.d / 'p.txt', self.mods)
|
||||
|
||||
def emit(self, table, name, entry, end, origs=()):
|
||||
mod = gen.open_module(name, self.d / ('exefs/main' if name == 'main' else 'subsdk9'), self.bases[name], table,
|
||||
plugin=name != 'main')
|
||||
e = gen.Emitter(mod, {entry}, table.for_module(name, self.bases[name]), origs=set(origs))
|
||||
return gen.chunk_text(name, 0, e, [(entry, end)])
|
||||
|
||||
def test_inline_hook_calls_the_stub_then_the_original(self):
|
||||
t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000',
|
||||
'seed plugin0 4100 4200'])
|
||||
m = self.bases['main'] + FN
|
||||
c = self.emit(t, 'main', m, m + 12)
|
||||
stub = self.bases['plugin0'] + 0x4000
|
||||
on = c[c.index('if (rt_patch_on[0])'):]
|
||||
self.assertLess(on.index(f'f_{stub:x}(c);'), on.index('} else {')) # the hook, then the original, when on
|
||||
head = on[:on.index(f'f_{stub:x}(c);')]
|
||||
self.assertNotIn('c->x[30] =', head) # no x30 written for the call
|
||||
self.assertIn(f'void f_{stub:x}(Cpu *c);', c)
|
||||
h = patches.header_text(t, 'MARK')
|
||||
self.assertIn('#define RT_PLUGIN_COUNT 1', h)
|
||||
self.assertIn(f'X(0, "main", {FN:#x}, 0xaa0003f3u, 0x14000000u)', h)
|
||||
self.assertIn('X("plugin0", 0x4100) X("plugin0", 0x4200)', h)
|
||||
|
||||
def test_stub_returns_instead_of_branching_to_its_trampoline(self):
|
||||
t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000'])
|
||||
stub = self.bases['plugin0'] + 0x4000
|
||||
c = self.emit(t, 'plugin0', stub, stub + 16)
|
||||
body = c[c.index(f'void f_{stub:x}(Cpu *c) {{'):]
|
||||
self.assertIn('return;', body)
|
||||
self.assertNotIn(f'{self.bases["plugin0"] + 0x2000:#x}', body) # the trampoline is not reached
|
||||
|
||||
def test_replace_hook_keeps_an_unpatched_copy(self):
|
||||
pb = self.bases['plugin0']
|
||||
m = self.bases['main'] + FN
|
||||
new = b(m, pb + 0x4200)
|
||||
t = self.table(f'site mod_x main {FN:x} aa0003f3 {new:08x}', [f'orig mod_x plugin0 2000 main {FN:x}',
|
||||
'seed plugin0 4200'])
|
||||
self.assertEqual(t.origs_for('main', self.bases['main']), {m})
|
||||
self.assertEqual(t.orig_entries('plugin0', self.bases), {pb + 0x2000: m})
|
||||
c = self.emit(t, 'main', m, m + 12, origs=[m])
|
||||
copy = c[c.index(f'void fo_{m:x}(Cpu *c) {{'):]
|
||||
self.assertNotIn('rt_patch_on', copy)
|
||||
self.assertIn('rt_patch_on[0]', c[:c.index(f'void fo_{m:x}')])
|
||||
tab = gen.table_text('plugin0', [pb + 0x4200, pb + 0x2000], {pb + 0x2000: gen.orig_name(m)})
|
||||
self.assertIn(f'void fo_{m:x}(Cpu *c);', tab)
|
||||
self.assertIn(f'fo_{m:x}', tab[tab.index('_fn_ptrs'):])
|
||||
|
||||
def test_image_must_match_its_hash(self):
|
||||
t = self.table(f'site mod_x main {FN:x} aa0003f3 @call:plugin0+4000 aa0003f3', ['stub plugin0 4000'])
|
||||
t.plugins['plugin0']['sha256'] = '0' * 64
|
||||
with self.assertRaises(patches.PatchError):
|
||||
gen.open_module('plugin0', self.plugin_file, self.bases['plugin0'], t)
|
||||
|
||||
def test_chunk_key_takes_the_unpatched_copy(self):
|
||||
# the lift cache (recomp/gen.py chunk_key): a chunk whose function gets an unpatched copy is keyed apart, and a
|
||||
# chunk without one keeps the key it had before plugins
|
||||
fns = [(0x100, 0x10c)]
|
||||
plain = gen.chunk_key('m', 0, fns, {}, [], {}, [], None, None)
|
||||
self.assertEqual(gen.chunk_key('m', 0, fns, {}, [], {}, [], None, None, {0x200}), plain)
|
||||
self.assertNotEqual(gen.chunk_key('m', 0, fns, {}, [], {}, [], None, None, {0x100}), plain)
|
||||
site = {0x100: [(0, [('call', 0x7005204000), 0xAA0003F3])]}
|
||||
self.assertNotEqual(gen.chunk_key('m', 0, fns, site, [0x100], {}, [], None, None),
|
||||
gen.chunk_key('m', 0, fns, {0x100: [(0, [('call', 0x7005204010), 0xAA0003F3])]}, [0x100],
|
||||
{}, [], None, None))
|
||||
|
||||
def test_no_plugin_lines_no_plugin_header(self):
|
||||
(self.d / 'q.txt').write_text('set fps60 TOTK_FPS60 0\n')
|
||||
self.assertNotIn('PLUGIN', patches.header_text(patches.load(self.d / 'q.txt', self.mods), 'MARK'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Check the production player-position walk used to start the game-time clock.
|
||||
|
||||
python tests/frame_world_check.py --cc path/to/clang
|
||||
"""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
HARNESS = r'''
|
||||
#include <assert.h>
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#define MOD_MAIN_BASE 0x7000000000ull
|
||||
#define RT_V110 (version == 110)
|
||||
#define RT_V143 (version >= 143)
|
||||
static int version;
|
||||
static uint8_t memory[0x8000];
|
||||
static uint64_t singleton;
|
||||
static int plat_mem_read(uint64_t address, void *out, size_t size) {
|
||||
uint64_t slot = MOD_MAIN_BASE + (RT_V143 ? 0x3add238 : RT_V110 ? 0x4630a68 : 0x4728538);
|
||||
if (address == slot && size == 8) { memcpy(out, &singleton, 8); return 1; }
|
||||
if (address > sizeof memory || size > sizeof memory - address) return 0;
|
||||
memcpy(out, memory + address, size);
|
||||
return 1;
|
||||
}
|
||||
static void put64(uint64_t address, uint64_t value) { memcpy(memory + address, &value, 8); }
|
||||
static void put32(uint64_t address, int32_t value) { memcpy(memory + address, &value, 4); }
|
||||
PRODUCTION
|
||||
static void fixture(void) {
|
||||
memset(memory, 0, sizeof memory);
|
||||
singleton = RT_V110 ? 0x800 : 0x1000;
|
||||
put64(0x800, 0x1000); // 1.1.0's GOT entry points to the singleton's storage
|
||||
put64(0x1000 + 0x1e8, 0x2000);
|
||||
put32(0x2000 + 0x50, 14); put64(0x2000 + 0x58, 0x3000);
|
||||
put64(0x3000 + 13 * 8, 0x4000);
|
||||
put32(0x4000 + 0x20, 2); put64(0x4000 + 0x28, 0x5000);
|
||||
// A missing first actor must not hide the valid player in the second entry.
|
||||
put64(0x5000 + 0x70 + 8, 0x5800); put64(0x5800 + 0x40, 0x6000);
|
||||
put64(0x6000 + 0x218, 0x7000); memcpy(memory + 0x7000, "Player", 7);
|
||||
float position[3] = {-700.0f, 140.0f, 870.0f};
|
||||
memcpy(memory + 0x6000 + 0x2b4, position, sizeof position);
|
||||
}
|
||||
int main(void) {
|
||||
const int versions[] = {110, 121, 143};
|
||||
for (unsigned i = 0; i < sizeof versions / sizeof *versions; i++) {
|
||||
version = versions[i]; fixture();
|
||||
float position[3] = {0};
|
||||
assert(player_pos(position));
|
||||
assert(position[0] == -700.0f && position[1] == 140.0f && position[2] == 870.0f);
|
||||
singleton = 0; assert(!player_pos(position));
|
||||
fixture(); put64(0x800, 0); if (RT_V110) assert(!player_pos(position));
|
||||
fixture(); put32(0x2000 + 0x50, 13); assert(!player_pos(position));
|
||||
fixture(); put32(0x4000 + 0x20, 0); assert(!player_pos(position));
|
||||
fixture(); put64(0x4000 + 0x28, 0); assert(!player_pos(position));
|
||||
fixture(); memory[0x7000] = 'X'; assert(!player_pos(position));
|
||||
fixture(); float bad = NAN; memcpy(memory + 0x6000 + 0x2b4, &bad, 4);
|
||||
assert(!player_pos(position));
|
||||
printf("world-clock player walk: version %d passed\n", version);
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--cc", default=shutil.which("clang") or r"C:\msys64\ucrt64\bin\clang.exe")
|
||||
parser.add_argument("--source", type=Path, default=ROOT / "runtime/frame_rate.c")
|
||||
args = parser.parse_args()
|
||||
source = args.source.read_text()
|
||||
start = source.index("static int read_guest(")
|
||||
end = source.index("static void speed_report(", start)
|
||||
with tempfile.TemporaryDirectory(prefix="world-clock-", dir=ROOT / "build") as directory:
|
||||
directory = Path(directory)
|
||||
path, exe = directory / "check.c", directory / "check.exe"
|
||||
path.write_text(HARNESS.replace("PRODUCTION", source[start:end]))
|
||||
subprocess.run([args.cc, "-std=c11", "-O2", "-Wall", "-Werror", str(path), "-o", str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Synthetic HUD layout and generator CLI regressions, without game assets.
|
||||
|
||||
Run with .venv-py314/Scripts/python tests/hud_layout_test.py.
|
||||
"""
|
||||
import ast
|
||||
import compression.zstd as zstd
|
||||
import json
|
||||
import os
|
||||
import importlib.util
|
||||
import math
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TOOL = ROOT / 'tools/make_romfs_patches.py'
|
||||
spec = importlib.util.spec_from_file_location('ultrawide_layout', ROOT / 'tools/ultrawide_layout.py')
|
||||
ui = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(ui)
|
||||
|
||||
|
||||
def archive():
|
||||
"""Build shipped pane fields and animation keys; no copyrighted archive data."""
|
||||
layouts = {name: {'RootPane': {}} for name in ui.KEEP_ROOT | ui.MARKER_ROOT.keys()}
|
||||
for name, panes in ui.MARKER_ROOT.items():
|
||||
for pane in panes: layouts[name][pane] = {}
|
||||
for name, pane, field, value in ui.edits(1, None):
|
||||
layouts.setdefault(name, {'RootPane': {}}).setdefault(pane, {})[field] = value
|
||||
data, members = bytearray(), {}
|
||||
for name, panes in sorted(layouts.items()):
|
||||
blob = bytearray(20)
|
||||
blob[:4] = b'FLYT'
|
||||
struct.pack_into('<H', blob, 6, 20)
|
||||
struct.pack_into('<H', blob, 16, len(panes))
|
||||
for pane, fields in panes.items():
|
||||
section = bytearray(80)
|
||||
section[:4] = b'pan1'
|
||||
struct.pack_into('<I', section, 4, 80)
|
||||
section[12:12 + len(pane)] = pane.encode()
|
||||
struct.pack_into('<2f', section, 68, 1, 1)
|
||||
for field, value in fields.items(): struct.pack_into('<f', section, ui.FIELD[field], value)
|
||||
blob += section
|
||||
members[f'blyt/{name}.bflyt'] = (len(data), len(data) + len(blob))
|
||||
data += blob
|
||||
for anim in {row[0] for row in ui.anim_edits(1, None)}:
|
||||
blob = bytearray(3600)
|
||||
for name, offset, shipped, _ in ui.anim_edits(1, None):
|
||||
if name == anim: struct.pack_into('<f', blob, offset, shipped)
|
||||
members[f'anim/{anim}.bflan'] = (len(data), len(data) + len(blob))
|
||||
data += blob
|
||||
return data, members
|
||||
|
||||
|
||||
def value(data, members, name, pane, field):
|
||||
lo, hi = members[f'blyt/{name}.bflyt']
|
||||
return struct.unpack_from('<f', data, ui.panes(data, lo, hi)[pane] + ui.FIELD[field])[0]
|
||||
|
||||
|
||||
class HudLayoutTest(unittest.TestCase):
|
||||
def test_caps_move_panes_and_animation_together(self):
|
||||
for cap, extension in ((None, 960), (21 / 9, 300), (16 / 9, 0)):
|
||||
with self.subTest(cap=cap):
|
||||
data, members = archive()
|
||||
ui.apply(data, members, 3840, 1080, cap)
|
||||
self.assertAlmostEqual(value(data, members, 'PlayerStatus_00', 'N_HeartPos_00', 'x'), -extension)
|
||||
self.assertAlmostEqual(value(data, members, 'EnvironmentInfo_00', 'RootPane', 'x'), extension / 2)
|
||||
lo, _ = members['anim/AppMap_00_MiniMap.bflan']
|
||||
for offset in (872, 880, 1628, 1636, 3264, 3272, 3468, 3476):
|
||||
self.assertAlmostEqual(struct.unpack_from('<f', data, lo + offset)[0], 765 + extension)
|
||||
self.assertAlmostEqual(value(data, members, 'SaveLoadIcon_00', 'RootPane', 'x'), -extension / 2)
|
||||
self.assertEqual(value(data, members, 'GameOver_00', 'P_BG_00', 'scale_x'), 2)
|
||||
self.assertEqual(value(data, members, 'AttentionLockOn_00', 'RootPane', 'scale_x'), 1)
|
||||
self.assertEqual(value(data, members, 'AttentionLockOn_00', 'N_Offset_00', 'scale_x'), .5)
|
||||
|
||||
def test_unnecessary_caps_equal_full(self):
|
||||
full, members = archive()
|
||||
ui.apply(full, members, 3440, 1440)
|
||||
for cap in (3440 / 1440, 4, 3440 / 1440 * .995):
|
||||
data, members = archive()
|
||||
ui.apply(data, members, 3440, 1440, cap)
|
||||
self.assertEqual(data, full)
|
||||
|
||||
def test_invalid_parameters_do_not_mutate(self):
|
||||
for width, height, cap in ((0, 1080, None), (3840, 0, None), (3840, 1080, 1), (3840, 1080, math.nan)):
|
||||
data, members = archive()
|
||||
before = bytes(data)
|
||||
with self.assertRaises(ValueError): ui.apply(data, members, width, height, cap)
|
||||
self.assertEqual(data, before)
|
||||
|
||||
def test_cli_rejects_invalid_before_output(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
out = Path(folder) / 'output'
|
||||
for arguments in (['--aspect', 'bad'], ['--aspect', '0x1440'], ['--aspect', '1920x1080'],
|
||||
['--hud', '16:9'], ['--aspect', '1280x800', '--hud', '16:9']):
|
||||
result = subprocess.run([sys.executable, str(TOOL), '--out', str(out), *arguments], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertIn('error:', result.stderr)
|
||||
self.assertNotIn('Traceback', result.stderr)
|
||||
self.assertFalse(out.exists())
|
||||
|
||||
def test_default_names_and_explicit_output(self):
|
||||
# Execute only argument handling; input loading and archive generation remain untouched.
|
||||
source = TOOL.read_text().split("index = json.loads", 1)[0]
|
||||
old = sys.argv
|
||||
try:
|
||||
for style in (None, 'xbox', 'xbox-label', 'pc'):
|
||||
for hud in ('full', '21:9', '16:9'):
|
||||
argv = ['tool', '--aspect', '3840X1080', '--hud', hud]
|
||||
if style: argv += ['--prompts', style]
|
||||
sys.argv = argv
|
||||
env = {'__file__': str(TOOL)}
|
||||
exec(compile(source, str(TOOL), 'exec'), env)
|
||||
expected = 'romfs-patches' + (f'-{style}' if style else '') + '-3840x1080'
|
||||
if hud != 'full': expected += '-hud' + hud.replace(':', 'x')
|
||||
self.assertEqual(env['args'].out.name, expected)
|
||||
sys.argv = argv + ['--out', 'chosen']
|
||||
exec(compile(source, str(TOOL), 'exec'), env)
|
||||
self.assertEqual(env['args'].out, Path('chosen'))
|
||||
finally: sys.argv = old
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get('HUD_TEST_ROMFS'), 'set HUD_TEST_ROMFS for local archive comparisons')
|
||||
class RealArchiveTest(unittest.TestCase):
|
||||
def test_full_unchanged_and_caps_valid(self):
|
||||
folder = Path(os.environ['HUD_TEST_ROMFS'])
|
||||
index = json.loads((folder / 'index.json').read_text())
|
||||
files = {entry['path']: entry for entry in index['files']}
|
||||
tree = ast.parse(TOOL.read_text())
|
||||
functions = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in ('sarc_nodes', 'sarc_members')]
|
||||
namespace = {'struct': struct}
|
||||
exec(compile(ast.Module(body=functions, type_ignores=[]), str(TOOL), 'exec'), namespace)
|
||||
sarc = namespace['sarc_members']
|
||||
with (folder / 'romfs.bin').open('rb') as image:
|
||||
def read(path):
|
||||
entry = files[path]
|
||||
image.seek(entry['offset'])
|
||||
return image.read(entry['size'])
|
||||
pack = zstd.decompress(read('Pack/ZsDic.pack.zs'))
|
||||
dictionaries = {}
|
||||
for lo, hi in sarc(pack).values():
|
||||
dictionary = zstd.ZstdDict(pack[lo:hi])
|
||||
dictionaries[dictionary.dict_id] = dictionary
|
||||
path = max(path for path in files if path.startswith('UI/LayoutArchive/Common.Product.') and path.endswith('.blarc.zs'))
|
||||
raw = read(path)
|
||||
original = zstd.decompress(raw, zstd_dict=dictionaries[zstd.get_frame_info(raw).dictionary_id])
|
||||
members = sarc(original)
|
||||
# The dev implementation before the HUD port is the full-width compatibility reference.
|
||||
baseline_source = subprocess.check_output(['git', 'show', 'f85058070e955eae0e45c9adbbe903d340b05b32:tools/ultrawide_layout.py'], cwd=ROOT, text=True)
|
||||
baseline = {}
|
||||
exec(compile(baseline_source, '<dev layout>', 'exec'), baseline)
|
||||
for width, height in ((3840, 1080), (3440, 1440), (1280, 800)):
|
||||
full = bytearray(original)
|
||||
ui.apply(full, members, width, height)
|
||||
expected = bytearray(original)
|
||||
baseline['apply'](expected, members, width, height)
|
||||
self.assertEqual(full, expected)
|
||||
for cap, extension in ((16 / 9, 0), (21 / 9, 300)):
|
||||
data = bytearray(original)
|
||||
ui.apply(data, members, 3840, 1080, cap)
|
||||
self.assertAlmostEqual(value(data, members, 'PlayerStatus_00', 'N_HeartPos_00', 'x'), -extension)
|
||||
self.assertAlmostEqual(value(data, members, 'SaveLoadIcon_00', 'RootPane', 'x'), -extension / 2)
|
||||
for name in ui.KEEP_ROOT:
|
||||
if name == 'AppMenuOverlay_00': continue
|
||||
lo, hi = members[f'blyt/{name}.bflyt']
|
||||
self.assertEqual(data[lo:hi], original[lo:hi])
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
+364
-3
@@ -18,6 +18,7 @@ ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from installer import ini, runner, screens, state, steps # noqa: E402
|
||||
from installer.events import Reporter # noqa: E402
|
||||
from installer import layout as layouts # noqa: E402
|
||||
from installer.layout import Layout # noqa: E402
|
||||
|
||||
|
||||
@@ -326,7 +327,7 @@ class LiftRunTest(unittest.TestCase):
|
||||
self.dest, temp = base / 'install', base / 'temp'
|
||||
self.dest.mkdir()
|
||||
temp.mkdir()
|
||||
layout = SimpleNamespace(recomp=ROOT / 'recomp', tools=ROOT / 'tools',
|
||||
layout = SimpleNamespace(dev=True, recomp=ROOT / 'recomp', tools=ROOT / 'tools',
|
||||
patches=lambda version: base / 'patches-v143.txt')
|
||||
self.ctx = SimpleNamespace(dest=self.dest, temp=temp, layout=layout, keys={'lift': 'k'},
|
||||
state={'version': '1.4.3'}, reporter=Reporter(out=io.StringIO()))
|
||||
@@ -383,6 +384,99 @@ class LiftRunTest(unittest.TestCase):
|
||||
self.assertEqual(self.outputs(), [False, False])
|
||||
self.assertIn('warn.exefs_skipped', self.ctx.reporter.out.getvalue())
|
||||
|
||||
def plugin_setup(self, kind, more=()):
|
||||
"""A mod with an exlaunch plugin (SQ), and one more mod per (name, kind) of more; the fake service run writes
|
||||
each plugin's status line of its kind."""
|
||||
kinds = {'SQ': kind, **dict(more)}
|
||||
for name in kinds:
|
||||
(self.dest / 'mods' / name / 'exefs').mkdir(parents=True, exist_ok=True)
|
||||
(self.dest / 'mods' / name / 'exefs' / 'subsdk9').write_bytes(b'NSO0' + name.encode())
|
||||
plugin = self.dest / 'mods' / 'SQ' / 'exefs' / 'subsdk9'
|
||||
dll = self.dest.parent / 'release-bin' / 'SDL3.dll'
|
||||
dll.parent.mkdir(exist_ok=True)
|
||||
dll.write_bytes(b'MZ')
|
||||
(self.ctx.temp / 'build').mkdir(parents=True, exist_ok=True)
|
||||
self.ctx.layout = SimpleNamespace(**vars(self.ctx.layout), llvm='llvm', runtime='runtime', ninja='ninja', dlls=[dll],
|
||||
deps=None, sysroot=None, runtime_lib_for=lambda cpu: None,
|
||||
pgo=lambda version: None, expected=lambda version: 'expected.json')
|
||||
saved = self.run_tool
|
||||
|
||||
def run_tool(ctx, step, script, args, parse=None, cwd=None):
|
||||
code, log = saved(ctx, step, script, args, parse, cwd)
|
||||
args = [str(a) for a in args]
|
||||
if Path(script).name == 'exefs_plugins.py':
|
||||
Path(args[args.index('--patches-out') + 1]).write_text('patches\n')
|
||||
status = Path(args[args.index('--status') + 1])
|
||||
status.parent.mkdir(parents=True, exist_ok=True)
|
||||
lines = []
|
||||
for name, k in kinds.items():
|
||||
h = 0x811C9DC5 # FNV-1a 32 of "<mod>/exefs/subsdk9", as tools/exefs_plugins.py keys it
|
||||
for b in f'{name}/exefs/subsdk9'.encode():
|
||||
h = ((h ^ b) * 0x01000193) & 0xFFFFFFFF
|
||||
lines.append(f'{h:08X}\t00000000\t{k}\t-\tnote\n')
|
||||
status.write_text(''.join(lines))
|
||||
return (1 if 'unsupported' in kinds.values() else 0), log
|
||||
return code, log
|
||||
steps.run_tool = run_tool
|
||||
return plugin
|
||||
|
||||
def test_plugin_stage(self):
|
||||
# the lift with the plugin, a totk.exe of it, the service run, then the lift with its hook sites
|
||||
plugin = self.plugin_setup('plugin')
|
||||
steps.Lift().run(self.ctx)
|
||||
self.assertEqual([c[0] for c in self.calls], ['exefs_patches.py', 'gen.py', 'build_game.py',
|
||||
'exefs_plugins.py', 'gen.py', 'exefs_patches.py --folded'])
|
||||
first, last = self.calls[1][1], self.calls[4][1]
|
||||
self.assertEqual(first[first.index('--plugins') + 1], str(plugin))
|
||||
self.assertEqual(last[last.index('--plugins') + 1], str(plugin))
|
||||
self.assertEqual(last[last.index('--patches') + 1], str(self.ctx.temp / 'patches-plugins.txt'))
|
||||
self.assertTrue(steps.plugins_status(self.ctx).is_file())
|
||||
# the service run's totk.exe finds its DLLs beside it
|
||||
self.assertTrue((self.ctx.temp / 'build' / 'SDL3.dll').is_file())
|
||||
|
||||
def test_refused_plugin_is_not_lifted(self):
|
||||
# a refused plugin: its status line stays (the Mods tab says why), the game is lifted without it
|
||||
self.plugin_setup('unsupported')
|
||||
steps.Lift().run(self.ctx)
|
||||
last = self.calls[4][1]
|
||||
self.assertNotIn('--plugins', last)
|
||||
self.assertTrue(steps.plugins_status(self.ctx).is_file())
|
||||
self.assertNotIn('warn.plugins_skipped', self.ctx.reporter.out.getvalue())
|
||||
|
||||
def test_refused_plugin_stays_in_the_layout_of_a_built_one(self):
|
||||
# one plugin built, one refused: the lift with the hook sites keeps both in the layout (the records hold the
|
||||
# addresses of the service runs' layout); the refused one has no patch set, its status line says why
|
||||
self.plugin_setup('plugin', [('ZZ', 'unsupported')])
|
||||
steps.Lift().run(self.ctx)
|
||||
last = self.calls[4][1]
|
||||
mods = self.dest / 'mods'
|
||||
self.assertEqual(last[last.index('--plugins') + 1],
|
||||
','.join(str(mods / n / 'exefs' / 'subsdk9') for n in ('SQ', 'ZZ')))
|
||||
self.assertIn('unsupported', steps.plugins_status(self.ctx).read_text())
|
||||
self.assertNotIn('warn.plugins_skipped', self.ctx.reporter.out.getvalue())
|
||||
|
||||
def test_failed_plugin_build_warns(self):
|
||||
self.plugin_setup('plugin')
|
||||
self.fail = {'build_game.py'}
|
||||
steps.Lift().run(self.ctx)
|
||||
self.assertNotIn('--plugins', self.calls[-2][1])
|
||||
self.assertFalse(steps.plugins_status(self.ctx).is_file())
|
||||
self.assertIn('warn.plugins_skipped', self.ctx.reporter.out.getvalue())
|
||||
|
||||
|
||||
class CompileKeyTest(unittest.TestCase):
|
||||
"""The compile key follows the release string: the exe carries the port version of the release that built it."""
|
||||
|
||||
def key(self, release):
|
||||
layout = SimpleNamespace(release=release, pgo=lambda version: None)
|
||||
ctx = SimpleNamespace(layout=layout, keys={'lift': 'L'}, state={'version': '1.4.3'})
|
||||
with mock.patch.object(steps, 'runtime_key', return_value='R'):
|
||||
return steps.Compile().key(ctx)
|
||||
|
||||
def test_new_release_compiles_again(self):
|
||||
self.assertEqual(self.key('0.4.2+abc'), self.key('0.4.2+abc'))
|
||||
self.assertNotEqual(self.key('0.4.2+abc'), self.key('0.4.3+def'))
|
||||
|
||||
|
||||
class CompileLockedTest(unittest.TestCase):
|
||||
"""Compile.run when the linker cannot write its totk.exe: another program holds the file (a game started from the
|
||||
@@ -398,7 +492,7 @@ class CompileLockedTest(unittest.TestCase):
|
||||
dest, temp = base / 'install', base / 'temp'
|
||||
dest.mkdir()
|
||||
temp.mkdir()
|
||||
layout = SimpleNamespace(tools=ROOT / 'tools', llvm=base / 'llvm', deps=None, sysroot=None, runtime=base,
|
||||
layout = SimpleNamespace(dev=True, tools=ROOT / 'tools', llvm=base / 'llvm', deps=None, sysroot=None, runtime=base,
|
||||
ninja=base / 'ninja', dlls=[], runtime_lib_for=lambda cpu: None,
|
||||
pgo=lambda version: None, expected=lambda version: base / 'expected.json')
|
||||
self.ctx = SimpleNamespace(dest=dest, temp=temp, layout=layout, state={'version': '1.4.3'},
|
||||
@@ -541,6 +635,21 @@ class CleanupTest(unittest.TestCase):
|
||||
lines = (self.dest / 'build-cache' / 'rebuild.txt').read_text(encoding='utf-8').splitlines()
|
||||
self.assertEqual(lines[1:3], ['-c', steps.REBUILD_BOOT])
|
||||
|
||||
def test_removes_only_stale_part_folders(self):
|
||||
# make_romfs_patches.py's unfinished folders: an hour-old one is a stopped run's, a fresh one a running one's
|
||||
old, fresh = self.dest / 'romfs-patches-2560x1080.part-41', self.dest / 'romfs-patches-pc.part-stale-42'
|
||||
for folder in (old, fresh):
|
||||
(folder / 'UI').mkdir(parents=True)
|
||||
(folder / 'UI' / 'a.zs').write_bytes(b'x')
|
||||
(self.dest / 'romfs-patches-2560x1080').mkdir()
|
||||
hour = steps.time.time() - steps.PART_STALE_S - 60
|
||||
for path in (old, old / 'UI', old / 'UI' / 'a.zs'):
|
||||
steps.os.utime(path, (hour, hour))
|
||||
self.assertEqual(self.run_cleanup(), 'ok')
|
||||
self.assertFalse(old.exists())
|
||||
self.assertTrue(fresh.is_dir() and (self.dest / 'romfs-patches-2560x1080').is_dir())
|
||||
self.assertIsNone(steps.SHAPED_FOLDER.match(old.name)) # the Shapes step's own clean-up leaves them
|
||||
|
||||
def test_emptied_romfs_fails(self):
|
||||
for p in (self.dest / 'romfs').iterdir():
|
||||
p.unlink()
|
||||
@@ -555,6 +664,137 @@ class CleanupTest(unittest.TestCase):
|
||||
self.assertEqual(self.run_cleanup(), 'cleanup.romfs_unreadable')
|
||||
|
||||
|
||||
def fake_release(root, version='1.0+abc'):
|
||||
"""A folder release_layout reads as a release: VERSION, the Python file and one file per other kit item."""
|
||||
for name in layouts.KIT_ITEMS:
|
||||
if '.' in name or name == 'VERSION':
|
||||
(root / name).parent.mkdir(parents=True, exist_ok=True)
|
||||
(root / name).write_text(version + '\n' if name == 'VERSION' else name)
|
||||
else:
|
||||
(root / name).mkdir(parents=True, exist_ok=True)
|
||||
(root / name / 'f.txt').write_text(name)
|
||||
layouts.release_python(root).parent.mkdir(parents=True, exist_ok=True)
|
||||
layouts.release_python(root).write_bytes(b'')
|
||||
(root / 'TotK-Setup.exe').write_bytes(b'launcher')
|
||||
(root / 'installer' / '__pycache__').mkdir()
|
||||
(root / 'installer' / '__pycache__' / 'x.pyc').write_bytes(b'')
|
||||
return layouts.release_layout(root)
|
||||
|
||||
|
||||
@unittest.skipUnless(steps.os.name == 'nt', 'the build kit is Windows-only')
|
||||
class KitTest(unittest.TestCase):
|
||||
"""The build kit: the setup's release folder copied into the install folder, the later steps and the rebuild
|
||||
command pointed at it, and an older setup's temp folder taken over."""
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
base = Path(self.tmp.name)
|
||||
self.setup, self.dest = base / 'TotK-Setup', base / 'game'
|
||||
self.dest.mkdir()
|
||||
self.layout = fake_release(self.setup)
|
||||
self.missing = mock.patch.object(Layout, 'missing', lambda self, cpu='v3': [])
|
||||
self.missing.start()
|
||||
|
||||
def tearDown(self):
|
||||
self.missing.stop()
|
||||
self.tmp.cleanup()
|
||||
|
||||
def ctx(self, layout):
|
||||
return SimpleNamespace(layout=layout, dest=self.dest, reporter=Reporter(out=io.StringIO()))
|
||||
|
||||
def install(self):
|
||||
ctx = self.ctx(self.layout)
|
||||
kit = steps.Kit()
|
||||
self.assertFalse(kit.current(ctx, {}))
|
||||
kit.run(ctx)
|
||||
kit.settle(ctx)
|
||||
return ctx, kit
|
||||
|
||||
def test_copies_the_release_and_the_next_steps_run_from_it(self):
|
||||
ctx, kit = self.install()
|
||||
folder = self.dest / 'build-kit'
|
||||
self.assertEqual(ctx.layout.root, folder.resolve())
|
||||
self.assertEqual(ctx.layout.release, '1.0+abc')
|
||||
self.assertEqual(sorted(p.name for p in folder.iterdir()), sorted(layouts.KIT_ITEMS))
|
||||
self.assertFalse((folder / 'installer' / '__pycache__').exists())
|
||||
self.assertFalse((self.dest / 'build-kit.new').exists() or (self.dest / 'build-kit.old').exists())
|
||||
self.assertTrue(kit.current(self.ctx(self.layout), {}))
|
||||
|
||||
def test_the_kits_own_rebuild_keeps_it(self):
|
||||
ctx, kit = self.install()
|
||||
(self.dest / 'build-kit' / 'tools' / 'mark').write_text('kept')
|
||||
self.assertTrue(kit.current(ctx, {}))
|
||||
kit.run(ctx)
|
||||
kit.settle(ctx)
|
||||
self.assertEqual((self.dest / 'build-kit' / 'tools' / 'mark').read_text(), 'kept')
|
||||
|
||||
def test_a_newer_setup_replaces_the_kit(self):
|
||||
self.install()
|
||||
(self.dest / 'build-kit' / 'tools' / 'old-only').write_text('old')
|
||||
self.layout = fake_release(Path(self.tmp.name) / 'TotK-Setup-2', '1.1+def')
|
||||
ctx, _ = self.install()
|
||||
self.assertEqual(ctx.layout.release, '1.1+def')
|
||||
self.assertFalse((self.dest / 'build-kit' / 'tools' / 'old-only').exists())
|
||||
|
||||
def test_rebuild_command_is_relative_to_the_install_folder(self):
|
||||
ctx, _ = self.install()
|
||||
cmd = steps.rebuild_command(ctx)
|
||||
self.assertEqual(cmd, [str(Path('build-kit', 'python', 'pythonw.exe' if (
|
||||
ctx.layout.python.with_name('pythonw.exe')).is_file() else 'python.exe')), '-c', steps.REBUILD_BOOT,
|
||||
'build-kit', '--root', 'build-kit', '--rebuild', '.'])
|
||||
self.assertFalse(any(str(self.dest) in a or str(self.setup) in a for a in cmd))
|
||||
|
||||
def test_the_kits_builds_are_portable(self):
|
||||
ctx, _ = self.install()
|
||||
ctx.temp, ctx.state = self.dest / 'build-cache' / 'work', {'version': '1.4.3'}
|
||||
self.assertIn('--portable', steps.build_args(ctx, ctx.temp / 'gen'))
|
||||
ctx.layout = Layout(root=ROOT, dev=True, release='x', python=Path('python'), tools=Path('tools'),
|
||||
recomp=Path('recomp'), llvm=Path('llvm'), deps=None, runtime=Path('rt'),
|
||||
runtime_lib=Path('lib'), ninja=Path('ninja'), hactool=Path('hactool'), xlate=Path('xlate'))
|
||||
self.assertNotIn('--portable', steps.build_args(ctx, ctx.temp / 'gen'))
|
||||
|
||||
def test_dev_mode_has_no_kit(self):
|
||||
ctx = self.ctx(SimpleNamespace(dev=True, release='x', root=ROOT))
|
||||
kit = steps.Kit()
|
||||
self.assertTrue(kit.current(ctx, {}))
|
||||
self.assertEqual(kit.run(ctx), {})
|
||||
kit.settle(ctx)
|
||||
self.assertFalse((self.dest / 'build-kit').exists())
|
||||
|
||||
def test_temp_folder_of_an_older_setup_moves_in(self):
|
||||
old = layouts.temp_folder(self.setup / 'temp', self.dest)
|
||||
(old / 'gen').mkdir(parents=True)
|
||||
(old / 'gen' / '.install-key').write_text('k')
|
||||
(self.dest / 'build-cache').mkdir()
|
||||
(self.dest / 'build-cache' / 'rebuild.txt').write_text(
|
||||
'\n'.join(['py', '-c', 'boot', str(self.setup), '--root', str(self.setup), '--rebuild', str(self.dest)]))
|
||||
temp = layouts.temp_for(self.layout, self.dest)
|
||||
self.assertEqual(temp, self.dest / 'build-cache' / 'work')
|
||||
self.assertIn('moved', steps.adopt_old_temp(self.layout, self.dest, temp))
|
||||
self.assertEqual((temp / 'gen' / '.install-key').read_text(), 'k')
|
||||
self.assertFalse(old.exists())
|
||||
self.assertIsNone(steps.adopt_old_temp(self.layout, self.dest, temp)) # once: the new one exists now
|
||||
|
||||
def test_no_temp_folder_to_take_over(self):
|
||||
temp = layouts.temp_for(self.layout, self.dest)
|
||||
self.assertIsNone(steps.adopt_old_temp(self.layout, self.dest, temp))
|
||||
(self.dest / 'build-cache').mkdir()
|
||||
(self.dest / 'build-cache' / 'rebuild.txt').write_text('build-kit\\python\\pythonw.exe\n-c\nboot\nbuild-kit\n')
|
||||
self.assertIsNone(steps.adopt_old_temp(self.layout, self.dest, temp))
|
||||
|
||||
|
||||
class RuntimeKeyTest(unittest.TestCase):
|
||||
def test_clangs_folder_is_not_in_the_key(self):
|
||||
layout = SimpleNamespace(clang=Path('clang'), tools=Path('tools'), runtime=Path('rt'), deps=None, sysroot=None,
|
||||
dlls=(), runtime_lib_for=lambda cpu: None)
|
||||
keys = []
|
||||
for where in ('C:/setup/llvm/bin', 'D:/game/build-kit/llvm/bin'):
|
||||
out = f'clang version 23\nTarget: x86_64-w64-windows-gnu\nInstalledDir: {where}\nConfiguration file: {where}/x.cfg\n'
|
||||
with mock.patch.object(steps.subprocess, 'run', return_value=SimpleNamespace(stdout=out)):
|
||||
keys.append(steps.runtime_key(SimpleNamespace(layout=layout)))
|
||||
self.assertEqual(keys[0], keys[1])
|
||||
|
||||
|
||||
class FreeSpaceTest(unittest.TestCase):
|
||||
def test_missing_folders_use_the_nearest_existing_parent(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
@@ -641,6 +881,24 @@ class ShapesTest(unittest.TestCase):
|
||||
'pad_layout = nintendo\nprompts = xbox',
|
||||
'pad_layout = xbox_prompts', 'prompts = nintendo')],
|
||||
[None, 'pc', 'xbox-label', 'xbox', 'xbox', None])
|
||||
self.assertEqual([screens.prompts_style(t) for t in ('prompts = playstation', 'prompts = PS',
|
||||
'pad_layout = nintendo\nprompts = playstation',
|
||||
'pad_layout = xbox\nprompts = playstation')],
|
||||
['playstation-xbox', 'playstation-xbox', 'playstation', 'playstation-xbox'])
|
||||
|
||||
def test_playstation_shapes_replace_every_older_shaped_folder(self):
|
||||
screens.displays = lambda: [(2560, 1080)]
|
||||
(self.dest / 'totk.ini').write_text('pad_layout = auto\nprompts = playstation\n')
|
||||
for old in ('romfs-patches-playstation-1280x800', 'romfs-patches-playstation-xbox-3440x1440-hud21x9',
|
||||
'romfs-patches-xbox-label-2560x1080', 'romfs-patches-playstation-xbox'):
|
||||
(self.dest / old).mkdir()
|
||||
(self.dest / 'romfs-patches-playstation-xbox' / 'manifest.tsv').write_text('#\n')
|
||||
record = steps.Shapes().run(self.ctx)
|
||||
self.assertEqual(record['folders'], ['romfs-patches-2560x1080', 'romfs-patches-playstation-xbox-2560x1080'])
|
||||
self.assertEqual(sorted(p.name for p in self.dest.iterdir() if p.is_dir()),
|
||||
['romfs-patches-2560x1080', 'romfs-patches-playstation-xbox',
|
||||
'romfs-patches-playstation-xbox-2560x1080'])
|
||||
self.assertEqual(self.calls[-1][self.calls[-1].index('--prompts') + 1], 'playstation-xbox')
|
||||
|
||||
def test_wanted_from_displays_and_ini(self):
|
||||
(self.dest / 'totk.ini').write_text('[display]\noutput_res = 3000x2000\n[input]\nprompts = pc\n')
|
||||
@@ -681,6 +939,108 @@ class ShapesTest(unittest.TestCase):
|
||||
str(self.dest / 'totk.ini')])
|
||||
self.assertNotIn('--binds', self.calls[0])
|
||||
|
||||
def test_selected_hud_only_for_needed_canonical_shapes(self):
|
||||
screens.displays = lambda: [(5120, 1440), (3840, 1080), (2560, 1600)]
|
||||
(self.dest / 'totk.ini').write_text('output_res = 5120x2160\nhud_width = 21:9\n')
|
||||
step = steps.Shapes()
|
||||
record = step.run(self.ctx)
|
||||
self.assertEqual(record['folders'], ['romfs-patches-2560x1080', 'romfs-patches-2560x1080-hud21x9',
|
||||
'romfs-patches-3840x1080', 'romfs-patches-3840x1080-hud21x9',
|
||||
'romfs-patches-1280x800'])
|
||||
caps = [c for c in self.calls if '--hud' in c]
|
||||
self.assertEqual(len(caps), 2)
|
||||
self.assertEqual(caps[0][-4:], ['--aspect', '2560x1080', '--hud', '21:9'])
|
||||
self.assertEqual(caps[1][-4:], ['--aspect', '3840x1080', '--hud', '21:9'])
|
||||
self.assertTrue(step.current(self.ctx, record))
|
||||
(self.dest / record['folders'][3] / 'manifest.tsv').unlink()
|
||||
self.assertFalse(step.current(self.ctx, record))
|
||||
|
||||
def test_hud_key_and_cleanup_follow_selection(self):
|
||||
screens.displays = lambda: [(2560, 1080)]
|
||||
ini = self.dest / 'totk.ini'
|
||||
ini.write_text('hud_width = full\n')
|
||||
step = steps.Shapes()
|
||||
full_key = step.key(self.ctx)
|
||||
for name in ('romfs-patches-3840x1080-hud21x9', 'romfs-patches-pc-2560x1080-hud16x9',
|
||||
'romfs-patches-player-custom'):
|
||||
(self.dest / name).mkdir()
|
||||
ini.write_text('TOTK_HUD_WIDTH = 16:9\n')
|
||||
self.assertNotEqual(step.key(self.ctx), full_key)
|
||||
record = step.run(self.ctx)
|
||||
self.assertEqual(record['folders'], ['romfs-patches-2560x1080', 'romfs-patches-2560x1080-hud16x9'])
|
||||
self.assertFalse((self.dest / 'romfs-patches-3840x1080-hud21x9').exists())
|
||||
self.assertFalse((self.dest / 'romfs-patches-pc-2560x1080-hud16x9').exists())
|
||||
self.assertTrue((self.dest / 'romfs-patches-player-custom').is_dir())
|
||||
self.calls.clear()
|
||||
ini.write_text('hud_width = full\n')
|
||||
record = step.run(self.ctx)
|
||||
self.assertEqual(record['folders'], ['romfs-patches-2560x1080'])
|
||||
self.assertTrue(all('--hud' not in c for c in self.calls))
|
||||
self.assertFalse((self.dest / 'romfs-patches-2560x1080-hud16x9').exists())
|
||||
|
||||
def test_full_hud_keeps_the_key_of_a_setup_before_hud_width(self):
|
||||
# An install that writes no capped folder keeps the Shapes key it had, so its next setup run prepares nothing
|
||||
screens.displays = lambda: [(2560, 1080), (2560, 1600)]
|
||||
step = steps.Shapes()
|
||||
sizes, style = step.wanted(self.ctx)
|
||||
old = steps.fingerprint('shapes-2', 'p', '', style or 'nintendo', *sizes)
|
||||
self.assertEqual(step.key(self.ctx), old)
|
||||
(self.dest / 'totk.ini').write_text('hud_width = full\n')
|
||||
self.assertEqual(step.key(self.ctx), old)
|
||||
# a cap no shape here is wider than writes nothing either
|
||||
screens.displays = lambda: [(2560, 1600)]
|
||||
del self.ctx.shapes_wanted
|
||||
(self.dest / 'totk.ini').write_text('hud_width = 16:9\n')
|
||||
sizes, style = step.wanted(self.ctx)
|
||||
self.assertEqual(step.key(self.ctx), steps.fingerprint('shapes-2', 'p', '', style or 'nintendo', *sizes))
|
||||
|
||||
def test_capped_pc_prompts_reuse_bindings(self):
|
||||
screens.displays = lambda: [(3840, 1080)]
|
||||
(self.dest / 'totk.ini').write_text('prompts = pc\nhud_width = 16:9\nbind_attack = key:f\n')
|
||||
(self.dest / 'romfs-patches-pc').mkdir()
|
||||
(self.dest / 'romfs-patches-pc' / 'manifest.tsv').write_text('#\n')
|
||||
record = steps.Shapes().run(self.ctx)
|
||||
self.assertEqual(record['folders'], ['romfs-patches-3840x1080', 'romfs-patches-pc-3840x1080',
|
||||
'romfs-patches-3840x1080-hud16x9',
|
||||
'romfs-patches-pc-3840x1080-hud16x9'])
|
||||
self.assertEqual(self.calls[-1][-6:], ['--hud', '16:9', '--reuse', str(self.dest / 'romfs-patches-pc'),
|
||||
'--binds', str(self.dest / 'totk.ini')])
|
||||
self.assertNotIn('--binds', self.calls[-2])
|
||||
|
||||
def test_hud_caps_ignore_equal_narrow_and_invalid_choices(self):
|
||||
# Common '21:9' modes are wider than exact 21/9: a manually selected cap is meaningful.
|
||||
self.assertEqual(steps.shape_hud('2560x1080', '21:9'), '21:9')
|
||||
self.assertEqual(steps.shape_hud('3440x1440', '21:9'), '21:9')
|
||||
self.assertIsNone(steps.shape_hud('2520x1080', '21:9'))
|
||||
self.assertIsNone(steps.shape_hud('1280x800', '16:9'))
|
||||
self.assertIsNone(steps.shape_hud('3840x1080', 'full'))
|
||||
self.assertEqual(steps.shape_hud('3440x1440', '16:9'), '16:9')
|
||||
(self.dest / 'totk.ini').write_text('hud_width = invalid\n')
|
||||
self.assertEqual(steps.hud_width(self.dest), 'full')
|
||||
|
||||
def test_failed_capped_prompts_are_retried(self):
|
||||
screens.displays = lambda: [(3840, 1080)]
|
||||
(self.dest / 'totk.ini').write_text('prompts = pc\nhud_width = 16:9\n')
|
||||
(self.dest / 'romfs-patches-pc').mkdir()
|
||||
(self.dest / 'romfs-patches-pc/manifest.tsv').write_text('#\n')
|
||||
successful = steps.run_tool
|
||||
|
||||
def fail_cap(ctx, step, script, args, **kwargs):
|
||||
if '--prompts' in args and '--hud' in args:
|
||||
return 7, self.dest / 'failed.log'
|
||||
return successful(ctx, step, script, args, **kwargs)
|
||||
|
||||
steps.run_tool = fail_cap
|
||||
step = steps.Shapes()
|
||||
record = step.run(self.ctx)
|
||||
self.assertTrue(record['failed'])
|
||||
self.assertFalse(step.current(self.ctx, record))
|
||||
steps.run_tool = successful
|
||||
record = step.run(self.ctx)
|
||||
self.assertFalse(record['failed'])
|
||||
self.assertTrue(step.current(self.ctx, record))
|
||||
self.assertIn('romfs-patches-pc-3840x1080-hud16x9', record['folders'])
|
||||
|
||||
def test_pc_prompts_writes_only_the_16_9_folder(self):
|
||||
(self.dest / 'totk.ini').write_text('[input]\nbind_attack = key:f\n')
|
||||
self.assertEqual(steps.PcPrompts().run(self.ctx), {})
|
||||
@@ -727,7 +1087,8 @@ class FontsTest(unittest.TestCase):
|
||||
|
||||
def test_all_steps_order(self):
|
||||
self.assertEqual([s.id for s in steps.all_steps()],
|
||||
['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss', 'cleanup'])
|
||||
['check', 'kit', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss',
|
||||
'cleanup'])
|
||||
|
||||
def test_extracts_into_the_install_folder(self):
|
||||
self.fake_tool()
|
||||
|
||||
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user