mirror of
https://github.com/valentderah/totk-pc-recomp.git
synced 2026-11-22 13:05:57 +00:00
Compare commits
No files matched your search
@@ -0,0 +1,100 @@
|
||||
name: Crash
|
||||
description: The game closes, freezes or shows a FATAL message.
|
||||
labels: [bug, crash]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Check the pinned issues at the top of the issue list first: they cover the known crashes and their workarounds.
|
||||
|
||||
Do not attach or link game files, keys, firmware or builds. Issues that do are closed.
|
||||
- type: checkboxes
|
||||
id: duplicates
|
||||
attributes:
|
||||
label: Existing issues
|
||||
options:
|
||||
- label: I read the pinned issues and [searched open and closed issues](https://github.com/valentderah/totk-pc-recomp/issues?q=is%3Aissue) for this crash.
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: The title line of the settings menu (F1), for example "TotK Recomp 0.1.0, game 1.4.3".
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: last-good
|
||||
attributes:
|
||||
label: Last version that worked
|
||||
description: If an earlier version did not crash at this point, which one.
|
||||
- type: textarea
|
||||
id: system
|
||||
attributes:
|
||||
label: System info
|
||||
description: Paste what Copy system info (F1, Advanced tab) puts on the clipboard. On a Steam Deck, add LCD or OLED.
|
||||
render: text
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: mods
|
||||
attributes:
|
||||
label: Mods and cheats
|
||||
description: The folders in mods/ with their download links, or "none". Say whether it also crashes without them.
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: when
|
||||
attributes:
|
||||
label: When does it crash?
|
||||
options:
|
||||
- At startup, before the Nintendo logo
|
||||
- Between the Nintendo logo and the title screen
|
||||
- While loading a save
|
||||
- In gameplay
|
||||
- In a cutscene
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: blocker
|
||||
attributes:
|
||||
label: Can you keep playing?
|
||||
options:
|
||||
- "Yes, it does not happen again after a restart, or I can avoid it"
|
||||
- "No, it happens every time at the same point"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: What you did before the crash
|
||||
validations:
|
||||
required: true
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
### The log
|
||||
|
||||
- The log of the run that crashed is `logs\totk.log` in the folder of `totk.exe` (F1, Advanced tab, Open log folder). Copy it before you start the game again: the next start renames it to `totk.1.log`, and after five starts it is gone.
|
||||
- Attach the whole file. Do not cut or edit it: the crash report is at the end, the GPU and driver lines are at the start.
|
||||
- The log says `device lost` or `VK_ERROR_DEVICE_LOST` and the GPU is an NVIDIA one: set GPU pass marks to On (F1, Advanced tab, Diagnostics), restart the game, make it crash again and attach that log. The `vk: pass marks` lines then name what the GPU was drawing.
|
||||
- type: textarea
|
||||
id: log
|
||||
attributes:
|
||||
label: Log
|
||||
description: Drag totk.log into this field.
|
||||
validations:
|
||||
required: true
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
### Save and input recording
|
||||
|
||||
When the crash comes back at one place in the game (an area, a shrine, a cutscene, a quest step), the save that gets there lets us crash it on our machine.
|
||||
|
||||
1. Zip the `profile` folder next to `totk.exe` and attach it. Say which slot you load, or that you use the autosave.
|
||||
2. If it takes more than walking a few steps from the save: turn on Input recording (F1, Advanced tab, Diagnostics), restart the game, load the save, make it crash, and attach `input-record.txt` from the logs folder together with the `totk.log` of that run.
|
||||
- type: textarea
|
||||
id: save
|
||||
attributes:
|
||||
label: Save and input recording
|
||||
description: Drag the zipped profile folder and input-record.txt into this field, when the crash comes back at one place.
|
||||
@@ -0,0 +1,74 @@
|
||||
name: Graphics glitch
|
||||
description: Artifacts, missing or broken textures, flicker, wrong colours or shadows.
|
||||
labels: [bug, graphics]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Check the pinned issues at the top of the issue list first: they cover the known glitches on each GPU.
|
||||
|
||||
Do not attach or link game files, keys, firmware or builds. Issues that do are closed.
|
||||
- type: checkboxes
|
||||
id: duplicates
|
||||
attributes:
|
||||
label: Existing issues
|
||||
options:
|
||||
- label: I read the pinned issues and [searched open and closed issues](https://github.com/valentderah/totk-pc-recomp/issues?q=is%3Aissue) for this glitch.
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: The title line of the settings menu (F1), for example "TotK Recomp 0.1.0, game 1.4.3".
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: last-good
|
||||
attributes:
|
||||
label: Last version that worked
|
||||
description: If an earlier version drew this correctly, which one.
|
||||
- type: textarea
|
||||
id: system
|
||||
attributes:
|
||||
label: System info
|
||||
description: Paste what Copy system info (F1, Advanced tab) puts on the clipboard. It lists the settings you changed too. On a Steam Deck, add LCD or OLED.
|
||||
render: text
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: mods
|
||||
attributes:
|
||||
label: Mods and cheats
|
||||
description: The folders in mods/ with their download links, or "none". Say whether the glitch also shows without them. Turn off ReShade and other overlays that draw into the game before you report.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: screenshot
|
||||
attributes:
|
||||
label: Screenshot or video
|
||||
description: Drag the file into this field. Say where in the game it was taken. Flicker needs a video.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: details
|
||||
attributes:
|
||||
label: What looks wrong and when
|
||||
description: Does it show all the time, in one place, or after some time in play? Does it go away after a restart, or when you change a setting?
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: blocker
|
||||
attributes:
|
||||
label: Can you keep playing?
|
||||
options:
|
||||
- "Yes"
|
||||
- "No, I cannot see enough to play"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: log
|
||||
attributes:
|
||||
label: Log
|
||||
description: Drag logs\totk.log from the folder of totk.exe into this field, from the run that showed the glitch. Copy it before you start the game again.
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,108 @@
|
||||
name: Performance
|
||||
description: Low frame rate, freezes, hitches, stutter or long loading.
|
||||
labels: [performance]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Check the pinned issues at the top of the issue list first.
|
||||
|
||||
Shaders the setup did not prepare are built the first time they are needed, so a short hitch the first time an area or effect shows is expected. Report it when it happens again in the same place.
|
||||
|
||||
Do not attach or link game files, keys, firmware or builds. Issues that do are closed.
|
||||
- type: checkboxes
|
||||
id: duplicates
|
||||
attributes:
|
||||
label: Existing issues
|
||||
options:
|
||||
- label: I read the pinned issues and [searched open and closed issues](https://github.com/valentderah/totk-pc-recomp/issues?q=is%3Aissue) for this problem.
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: The title line of the settings menu (F1), for example "TotK Recomp 0.1.0, game 1.4.3".
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: last-good
|
||||
attributes:
|
||||
label: Last version that ran better
|
||||
description: If an earlier version was faster in the same place, which one.
|
||||
- type: textarea
|
||||
id: system
|
||||
attributes:
|
||||
label: System info
|
||||
description: Paste what Copy system info (F1, Advanced tab) puts on the clipboard. It lists the settings you changed too. On a Steam Deck, add LCD or OLED.
|
||||
render: text
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: machine
|
||||
attributes:
|
||||
label: Machine
|
||||
options:
|
||||
- Desktop PC
|
||||
- Laptop, on mains power
|
||||
- Laptop, on battery
|
||||
- Steam Deck
|
||||
- Other handheld PC
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: mods
|
||||
attributes:
|
||||
label: Mods and cheats
|
||||
description: The folders in mods/ with their download links, or "none".
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: kind
|
||||
attributes:
|
||||
label: What kind of problem?
|
||||
options:
|
||||
- The frame rate is low all the time
|
||||
- Short freezes or hitches that come back in the same place
|
||||
- The frame rate is fine, but motion is not smooth
|
||||
- It gets slower the longer I play
|
||||
- Loading takes long
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: where
|
||||
attributes:
|
||||
label: Where and what you were doing
|
||||
description: For example "Lookout Landing, walking to the tower", "the Depths below Hyrule Castle", "fighting a Talus in the Sky". How long into the session it started.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: overlay
|
||||
attributes:
|
||||
label: Performance overlay
|
||||
description: Press F10 twice (or both stick clicks) for the full panel. Stay a minute in the place and write down the frame rate, the mean and the longest frame time, or attach a screenshot of the panel.
|
||||
validations:
|
||||
required: true
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
### Recording the log
|
||||
|
||||
1. In the settings menu (F1), Advanced tab, Diagnostics: turn on Performance log. For freezes and hitches, also turn on Flight recorder. Restart the game: both take effect at the next start.
|
||||
2. Play at least three minutes in the place where it happens. The log gets a frame-time summary every 60 s, and a line for every frame over 50 ms that names what the frame waited for.
|
||||
3. With the flight recorder on, press F8 right after a hitch. It also saves on its own after every frame longer than the freeze threshold (100 ms), at most once per 10 s.
|
||||
4. Close the game with Quit game in the menu or the window's close button. Do not end it from Task Manager: the last summary is written when the game exits.
|
||||
5. Copy `logs\totk.log` from the folder of `totk.exe` before you start the game again.
|
||||
6. Each flight recorder save is a folder; the log line `flight: dump` names it. Zip the folders and attach them.
|
||||
7. Turn both off again afterwards: they cost a little frame time.
|
||||
- type: textarea
|
||||
id: log
|
||||
attributes:
|
||||
label: Log
|
||||
description: Drag totk.log into this field.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: flight
|
||||
attributes:
|
||||
label: Flight recorder saves
|
||||
description: Drag the zipped folders into this field, for freezes and hitches.
|
||||
@@ -0,0 +1,94 @@
|
||||
name: Other bug
|
||||
description: Sound, controls, the settings menu, the installer, or game logic.
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Check the pinned issues at the top of the issue list first. Crashes, graphics glitches and performance have their own templates.
|
||||
|
||||
Do not attach or link game files, keys, firmware or builds. Issues that do are closed.
|
||||
- type: checkboxes
|
||||
id: duplicates
|
||||
attributes:
|
||||
label: Existing issues
|
||||
options:
|
||||
- label: I read the pinned issues and [searched open and closed issues](https://github.com/valentderah/totk-pc-recomp/issues?q=is%3Aissue) for this bug.
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area
|
||||
options:
|
||||
- Audio
|
||||
- Controls and input
|
||||
- Settings menu and overlay
|
||||
- Installer
|
||||
- Game logic and physics
|
||||
- Something else
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: The title line of the settings menu (F1), for example "TotK Recomp 0.1.0, game 1.4.3". For the installer, the version of TotK-Setup.
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: last-good
|
||||
attributes:
|
||||
label: Last version that worked
|
||||
description: If an earlier version did this correctly, which one.
|
||||
- type: textarea
|
||||
id: system
|
||||
attributes:
|
||||
label: System info
|
||||
description: Paste what Copy system info (F1, Advanced tab) puts on the clipboard. On a Steam Deck, add LCD or OLED. For the installer, write your OS and the install disk.
|
||||
render: text
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: mods
|
||||
attributes:
|
||||
label: Mods and cheats
|
||||
description: The folders in mods/ with their download links, or "none". Say whether it also happens without them.
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: blocker
|
||||
attributes:
|
||||
label: Can you keep playing?
|
||||
options:
|
||||
- "Yes"
|
||||
- "No, it stops the game or a quest"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: What happened and how to reproduce it
|
||||
description: What you expected, what happened instead, and the steps that lead there.
|
||||
validations:
|
||||
required: true
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
### What to attach for your area
|
||||
|
||||
Close the game with Quit game in the menu or the window's close button, then copy `logs\totk.log` from the folder of `totk.exe` before you start the game again.
|
||||
|
||||
**Audio.** Open `totk.ini` in the folder of `totk.exe` and add the line `trace = audio`; when the file already has `trace = perf` (Performance log on), change it to `trace = perf,audio`. Start the game, play at least two minutes where the sound goes wrong and close the game. The log then has an `audio:` line every 5 s with the buffer underruns. Name the output device and how it is connected (speakers, headphones, USB, Bluetooth, HDMI), and attach a short video with sound if you can. Remove the line afterwards.
|
||||
|
||||
**Controls and input.** Name the controller and how it is connected (USB, Bluetooth, Steam Input). Does it also happen with keyboard and mouse?
|
||||
|
||||
**Controls, game logic, anything you can trigger again.** Turn on Input recording (F1, Advanced tab, Diagnostics), restart the game, load a save, make the bug happen and close the game. Attach `input-record.txt` from the logs folder and a zip of the save you loaded: the `profile` folder next to `totk.exe`. The recording replays what you did, so we can see the bug on our machine.
|
||||
|
||||
**Installer.** Attach the newest `install-*.log` from `temp\logs` in the folder of `TotK-Setup.exe` (on Linux: `.setup-temp/logs` in the install folder), and the log file the error message names.
|
||||
- type: textarea
|
||||
id: log
|
||||
attributes:
|
||||
label: Log and other files
|
||||
description: Drag totk.log and the files your area asks for into this field.
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,17 @@
|
||||
name: Feature request
|
||||
description: A setting, option or support for something the port does not do yet.
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: duplicates
|
||||
attributes:
|
||||
label: Existing issues
|
||||
options:
|
||||
- label: I [searched open and closed issues](https://github.com/valentderah/totk-pc-recomp/issues?q=is%3Aissue) and the Planned section of the README for this request.
|
||||
required: true
|
||||
- type: textarea
|
||||
id: request
|
||||
attributes:
|
||||
label: What you want and why
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,32 +0,0 @@
|
||||
name: Bug report
|
||||
description: Something breaks, crashes or looks wrong.
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Do not attach or link game files, keys, firmware or builds. Issues that do are closed.
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: The title line of the settings menu (F1), for example "TotK Recomp 0.1.0, game 1.4.3".
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: system
|
||||
attributes:
|
||||
label: GPU, driver and Windows version
|
||||
description: Copy system info in the menu's Advanced tab puts them on the clipboard.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: What happened and how to reproduce it
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: log
|
||||
attributes:
|
||||
label: Log
|
||||
description: Attach logs\totk.log from the folder of totk.exe. After a crash, copy it before you start the game again.
|
||||
@@ -1 +1,5 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Question or help with setup
|
||||
url: https://github.com/valentderah/totk-pc-recomp/discussions
|
||||
about: Installing, updating and configuring the port. Ask in Discussions.
|
||||
@@ -0,0 +1,36 @@
|
||||
<!--
|
||||
Target branch: dev. Rules: CONTRIBUTING.md, "Pull requests". Write each section in your own words about this diff;
|
||||
delete the rows that do not apply. Never attach game files, keys, extracted data or logs that contain them.
|
||||
-->
|
||||
|
||||
## Problem
|
||||
|
||||
<!-- What the player sees or what is wrong in the code. Issue link if there is one. -->
|
||||
|
||||
## Change
|
||||
|
||||
<!-- What the diff does and why this way. Name the switch (totk.ini setting or TOTK_* variable) that turns it off. -->
|
||||
|
||||
## Where it reproduces
|
||||
|
||||
<!-- OS, CPU, GPU and driver, game update (1.2.1 / 1.4.3), settings. Hardware it cannot appear on, if known. -->
|
||||
|
||||
## Proof
|
||||
|
||||
<!-- Before and after on the same repro: screenshots, log lines, a test that failed and now passes. -->
|
||||
|
||||
## Checks run
|
||||
|
||||
<!-- The rows of CONTRIBUTING.md "Checks by what you changed" that match the diff, each with its result. -->
|
||||
|
||||
- [ ] `python tools/check_content.py --staged`
|
||||
- [ ] `totk.exe --selftest`
|
||||
|
||||
## Measurements
|
||||
|
||||
<!-- Frame path, timing or scheduling only. Per run, switch off and on, at least two each: average fps, 1% low or
|
||||
worst frame, `perf: slow frame` count. Scene, save, seconds, CPU, GPU, driver, resolution. -->
|
||||
|
||||
## Not run
|
||||
|
||||
<!-- Paths you could not run (Linux, HDR, a vendor you do not have) and how they are gated. -->
|
||||
@@ -42,6 +42,9 @@ __pycache__/
|
||||
*.o
|
||||
*.lib
|
||||
*.a
|
||||
*.so
|
||||
*.so.*
|
||||
*.AppImage
|
||||
|
||||
# .NET build output of the shader translator (tools/build_xlate.py)
|
||||
/tools/xlate/bin/
|
||||
|
||||
@@ -29,6 +29,15 @@ This repository is public. Game data lives outside it and every derived file sta
|
||||
- Graphics bugs: [docs/maxwell.md](docs/maxwell.md) lists the Maxwell behaviour the Vulkan path must match and the TotK bugs other ports fixed.
|
||||
- Comments say what the code does and why, in words that stand on their own. Cite our code by file plus function (a line number may follow as a hint) and upstream code by project, file and function: `refs/` moves, so its line numbers rot. Commit hashes belong to the attribution of copied code.
|
||||
|
||||
## Running and debugging
|
||||
|
||||
- Running the game, screenshots, frame dumps, timings: [docs/agents/running.md](docs/agents/running.md).
|
||||
- Investigating a bug, glitch or crash: search [docs/agents/symptoms.md](docs/agents/symptoms.md) by the player's words first, then follow [docs/agents/debugging.md](docs/agents/debugging.md). Read the code before running the game.
|
||||
|
||||
## Pull requests
|
||||
|
||||
Preparing a pull request: target `dev`; the checks by changed area, the proof and the performance runs it carries are in [CONTRIBUTING.md](CONTRIBUTING.md), "Pull requests". Reviewing one: [docs/pr-review-kit/](docs/pr-review-kit/).
|
||||
|
||||
## Writing
|
||||
|
||||
Code, comments, docs and commit messages are in English. Commit messages are plain sentences without type prefixes.
|
||||
+86
-7
@@ -29,14 +29,93 @@ Use the issue form. Include the port version and game update from the title line
|
||||
|
||||
## Pull requests
|
||||
|
||||
- One topic per pull request.
|
||||
- Describe the problem, then what changed.
|
||||
- Say how you tested it: which version, which scene, how long.
|
||||
- A change to the lifter (`recomp/`) or the CPU headers passes the differential tests in [docs/building.md](docs/building.md), "Checks".
|
||||
- Commit messages are plain sentences, without `feat:` or other prefixes.
|
||||
- AI-assisted code is welcome. You are responsible for having read and run it.
|
||||
### Branch
|
||||
|
||||
Open pull requests against `dev`. Branch from the current `dev` and rebase on it before you open the pull request. `main` receives `dev` at a release; a pull request against `main` is retargeted to `dev` before review.
|
||||
|
||||
### Before you start
|
||||
|
||||
- Search the open pull requests and issues on the topic. When another pull request already covers it, improve that one or say in yours how they differ.
|
||||
- Fixes are reviewed before features, in order of how many players the bug hits. A feature with a design in `docs/milestones/` (mods, cheats, the menu) follows that design. For a feature without one, open an issue first.
|
||||
- Find out where the bug reproduces: OS, GPU vendor and generation, driver, game update, settings. Put that in the description.
|
||||
|
||||
### What the change must keep
|
||||
|
||||
- **The default for everyone.** A fix for one setup (a GPU vendor, a memory size, a display) is gated on that setup. Players without the problem see no change.
|
||||
- **A switch.** New behaviour on the frame path or in rendering sits behind a `totk.ini` setting or a `TOTK_*` variable, so a player can turn it off and a reviewer can compare. A new setting is described in [totk.ini.example](totk.ini.example) and [docs/settings.md](docs/settings.md).
|
||||
- **The fix, not a disabled feature.** A crash that goes away with a feature off points at the bug in that feature. Turning the feature off for a vendor is not a fix.
|
||||
- **The frame time on weak hardware.** Game threads and the render thread do no file I/O, no GPU allocations, no per-draw state copies and no global atomic counters. Memory kept per frame or per object is freed. The full list with measured costs: [docs/pr-review-kit/02-performance.md](docs/pr-review-kit/02-performance.md), "What the hot path must not do".
|
||||
- **Other GPUs.** New Vulkan code queries each feature, extension, format and limit it uses and keeps a working path without it. Nothing is hardcoded from what one GPU reports.
|
||||
- **Text in the catalogs.** Text a player sees gets an id in `runtime/ui_text.h` and an entry in `runtime/ui_text.c` for every menu language (English, Russian, Brazilian Portuguese, Simplified Chinese); installer text goes into `installer/text/*.json`.
|
||||
- **The generator owns generated C.** Change `recomp/`, never `generated/`.
|
||||
|
||||
### Checks by what you changed
|
||||
|
||||
Run every row that matches your diff and list the results in the description. Commands and details: [docs/building.md](docs/building.md), "Checks".
|
||||
|
||||
| You changed | Run |
|
||||
|---|---|
|
||||
| anything | `python tools/check_content.py --staged`; `build\<ver>\totk.exe --selftest` |
|
||||
| `recomp/`, `runtime/cpu.h`, `runtime/simd.h` | the differential tests against Unicorn: `tests\diff\lift.py`, `simd.py`, `atomic.py`, `func.py`, `tests\flags_check.py`, `tests\excl_mt.py`; the same with a `--cpu v2` build |
|
||||
| `recomp/jumptables.py` | `tests\jumptables_check.py`: 0 disagreements on 1.2.1 and 1.4.3 |
|
||||
| `runtime/` | `--probe-kernel`, `--probe-vkexec`, `--probe-nvn-tex`, `--probe-shader`, plus the probe for the file you touched (list at the top of `runtime/main.c`) |
|
||||
| settings | `totk.exe --probe-cfg`; `python tests\settings_doc_check.py` |
|
||||
| button prompts | `.venv-py314\Scripts\python tests\romfs_prompts_test.py` |
|
||||
| mods, ExeFS patches | `.venv\Scripts\python tests\exefs_patches_test.py`; `totk.exe --probe-mods` |
|
||||
| `installer/` | `python tests\installer_test.py`; `python tests\installer_gui_test.py` |
|
||||
| shader translator | `tools\xlate_smoke.py`; `tools\shader_census.py --version <ver> --translate` with no new failure groups |
|
||||
| rendering | a run in a scene where the change acts, with `TOTK_VK_VALIDATION=1`: no new validation messages; screenshots before and after |
|
||||
| frame path, timing, scheduling | the measurements below |
|
||||
|
||||
Checks that need game files run on your own copy of the game. Results go into the pull request as text: pass or fail, counts, log lines. Never attach logs or dumps that contain game data.
|
||||
|
||||
### Proof
|
||||
|
||||
- **A bug fix** shows the bug before the change and gone after it, on the same repro: a screenshot pair, a log line, a probe or test that fails before and passes after. A scripted repro (`TOTK_INPUT_RECORD`, [docs/controls.md](docs/controls.md), "Scripted input") is the strongest. If the bug cannot be reproduced on your hardware, say so and point at the code that causes it.
|
||||
- **A crash fix** names the crash: the log's crash report, `vk: pass marks` lines for a lost device.
|
||||
- **Parts you could not run** (Linux-only code, HDR, vendor-only paths) are listed as unrun and gated away from everyone else.
|
||||
|
||||
### Performance measurements
|
||||
|
||||
A change on the frame path, in timing or in scheduling carries these numbers, or it waits until someone measures it.
|
||||
|
||||
1. **Ceiling first.** Before the work, estimate the share of the frame the changed code holds on the critical path (`TOTK_CRIT` + `tools/crit_path.py`). A ceiling of a few percent is not worth a hot-path change.
|
||||
2. **Build 1.4.3** with prepared shaders in that build folder (`tools/prepare_shaders.py`, [docs/building.md](docs/building.md) step 6). Caches copied from another build folder do not count.
|
||||
3. **A heavy scene** where the change acts: a fight with a large enemy and a crowd, or a town, with `TOTK_FPS_LIMIT=360`.
|
||||
4. **Whole runs, switch off and on, at least two each**, the same save and the same input script, timed by game seconds:
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python tools\run_game.py build\v143 --script <input.txt> --seconds 60 --quiet --env TOTK_TRACE=perf,sched --env TOTK_FPS_LIMIT=360 --env <SWITCH>=0
|
||||
```
|
||||
|
||||
`--quiet` waits until no other game or build runs. Close everything heavy on the machine. Before reading the numbers, check that each run reached the world and showed the same scene.
|
||||
5. **Report per run**: average fps, 1% low or worst frame, the number of `perf: slow frame` lines, VRAM; `tools/perf_summary.py` condenses the log. Add CPU, GPU, driver, RAM, resolution and the settings you changed.
|
||||
|
||||
A switch toggled inside one run on a moving scene gives false results: compare whole runs. Zero new slow frames is a hard bar; an fps gain does not buy back new hitches. Background and the reasons behind each rule: [docs/pr-review-kit/02-performance.md](docs/pr-review-kit/02-performance.md).
|
||||
|
||||
### Description and commits
|
||||
|
||||
Fill in the pull request template: problem, change, where it reproduces, checks, measurements, what stayed unrun. One topic per pull request.
|
||||
|
||||
Commit messages are plain English sentences, without `feat:`, `fix:` or other prefixes. A commit that works on an issue ends its subject with the issue numbers: `Render the handheld scene at the asked size on 1.4.3 (#998, #536)`.
|
||||
|
||||
### Review and merge
|
||||
|
||||
The maintainers review every pull request against [docs/pr-review-kit/](docs/pr-review-kit/): read it to see what gets a pull request rejected, which bug classes are already fixed and which invariants a change must keep. A good pull request that misses the project's conventions is fixed up while merging rather than sent back. Part of a pull request can be taken; the reason for what was left out or rejected is posted on the pull request.
|
||||
|
||||
Accepted work merges into `dev` and reaches players through test builds. `main` moves only at a release.
|
||||
|
||||
## Coding agents
|
||||
|
||||
AI-assisted code is welcome. You are responsible for having read and run it, and the pull request says which checks ran on your machine.
|
||||
|
||||
Point your agent at [AGENTS.md](AGENTS.md) (Claude Code reaches it through `CLAUDE.md`), this file and [docs/pr-review-kit/](docs/pr-review-kit/) before it writes code. [docs/agents/](docs/agents/) holds what it needs to run the game unattended, measure, and debug: the method, the bug classes of a recompiled Switch game, and a symptom catalog. The rules in them bind the agent as they bind you:
|
||||
|
||||
- Key values stay out of prompts, logs, commands and files. The agent passes the keys file path to the tools.
|
||||
- Results in the pull request come from runs that happened. A check the agent did not run is listed as not run.
|
||||
- The agent writes the description in its own words about this diff. A review kit checklist pasted in with every box ticked tells the reviewer nothing.
|
||||
|
||||
## Code and docs
|
||||
|
||||
- Code, comments, commit messages and documentation are in English.
|
||||
- Generated code is never edited by hand: change the generator.
|
||||
- Comments say what the code does and why. Cite our code by file and function, upstream code by project, file and function.
|
||||
@@ -1,46 +1,95 @@
|
||||
# TotK Recomp
|
||||
|
||||
**TotK Recomp** is a static recompilation of *The Legend of Zelda: Tears of the Kingdom* (Nintendo Switch, 2023) into a native Windows x86-64 application ([docs/architecture.md](docs/architecture.md)).
|
||||
**TotK Recomp** is a static recompilation of *The Legend of Zelda: Tears of the Kingdom* (Nintendo Switch, 2023) into a native x86-64 application for Windows and Linux ([docs/architecture.md](docs/architecture.md)).
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **No game files are included.** You need your own legally obtained copy of *Tears of the Kingdom*, dumped from your own console: the base game and the 1.2.1 or 1.4.3 update. Instructions for obtaining those files will not be provided.
|
||||
> **No game files are included.** You need your own legally obtained copy of *Tears of the Kingdom*, dumped from your own console: the base game and the 1.1.0, 1.2.1 or 1.4.3 update. Instructions for obtaining those files will not be provided.
|
||||
>
|
||||
> The game is built from your files on your machine, so the result contains the game. It is for your own use. Do not share it.
|
||||
|
||||
## Status
|
||||
|
||||
Early development. The game is playable on Windows; visual bugs and crashes are still expected.
|
||||
Early development. The game is playable on Windows and Linux; visual bugs and crashes are still expected.
|
||||
|
||||
Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
## Features
|
||||
|
||||
- Native code, not emulation
|
||||
- Game updates 1.2.1 and 1.4.3, with saves that carry over between them
|
||||
- Game updates 1.1.0, 1.2.1 and 1.4.3; 1.2.1 and 1.4.3 saves carry over between them
|
||||
- Takes NSP and XCI game files, and compressed NSZ and XCZ as they are: the setup unpacks them itself
|
||||
- 60 fps by default; up to 144 fps or the monitor's refresh rate (experimental)
|
||||
- Custom resolutions (1080p, 2k...), supersampling and AMD FSR 1 upscaling
|
||||
- NVIDIA DLSS / DLAA on RTX GPUs: the setup downloads `nvngx_dlss.dll` from NVIDIA's DLSS SDK repository
|
||||
(github.com/NVIDIA/DLSS, NVIDIA RTX SDK license) when it finds an RTX GPU; untick it in the setup to skip it
|
||||
- HDR10 output with peak, game and HUD brightness settings
|
||||
- 16:10 (Steam Deck, handhelds), 3:2 (Surface, Framework), 21:9 and 32:9 (ultrawide) game resolutions, with the camera and the interface in that shape
|
||||
- Anisotropic texture filtering up to 16x, for sharp ground into the distance
|
||||
- In-game settings menu (F1) and performance overlay (F10)
|
||||
- Play time across runs on the Game tab of the settings menu, kept in `playtime.txt` next to the saves
|
||||
- Discord Rich Presence ("Playing TotK Recomp" with the play time), off by default, own application id supported
|
||||
- Setup in 11 languages, in-game menu in 4 ([Languages](#languages))
|
||||
- Keyboard, mouse and gamepad with remapping, rumble and gyro
|
||||
- Xbox button prompts: a layout that keeps the Switch button positions and shows the Xbox labels
|
||||
- Stereo or 5.1 surround sound output
|
||||
- Xbox and PlayStation button prompts: Xbox's LB, RB, LT, RT, Menu, View and A, B, X, Y, or PlayStation's ○ × △ □, L1, R1, L2, R2, Options and Share, as labelled on the button to press, with either button layout
|
||||
- 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
|
||||
([docs/mods.md](docs/mods.md)). HD texture packs work: the port grows the texture heap a pack asks for by itself. Tested
|
||||
with the HDPacks.com 4K Texture Pack v1.0 on 1.4.3 and 1.2.1; other packs come with no guarantee
|
||||
- Atmosphère cheats: put a cheat file into a mod and switch its cheats in the menu ([docs/cheats.md](docs/cheats.md))
|
||||
|
||||
## Languages
|
||||
|
||||
The game keeps the text and voices of every language it shipped with. The port's own setup and in-game menu (F1) come
|
||||
in these; both follow the Windows display language, and the menu has its own choice on its Menu tab. A Traditional
|
||||
Chinese Windows gets the Simplified Chinese setup.
|
||||
|
||||
| Language | Setup | In-game menu |
|
||||
|---|:---:|:---:|
|
||||
| English | ✅ | ✅ |
|
||||
| Русский | ✅ | ✅ |
|
||||
| Português (Brasil) | ✅ | ✅ |
|
||||
| 简体中文 | ✅ | ✅ |
|
||||
| Deutsch | ✅ | English |
|
||||
| Français | ✅ | English |
|
||||
| Español | ✅ | English |
|
||||
| Italiano | ✅ | English |
|
||||
| Nederlands | ✅ | English |
|
||||
| 日本語 | ✅ | English |
|
||||
| 한국어 | ✅ | English |
|
||||
|
||||
Spotted a clumsy phrase, or want your language added? The setup texts are in `installer/text/<language>.json`, the
|
||||
menu texts in `runtime/ui_text.c`; open an issue or a pull request ([CONTRIBUTING.md](CONTRIBUTING.md)). Fixes from
|
||||
native speakers are welcome.
|
||||
|
||||
## Planned
|
||||
|
||||
- Linux and the Steam Deck
|
||||
- Mods made for emulators: unpack a mod into a `mods` folder
|
||||
- Ultrawide on 1.2.1 (1.4.3 has it for 2560x1080, 3440x1440, 3840x1600 and 5120x2160; other shapes get the wide camera with a 16:9 HUD)
|
||||
- VRR
|
||||
|
||||
## Installing
|
||||
|
||||
Requirements: Windows 10 or later, an x86-64 CPU with AVX2, a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`, about 36 GiB free during setup (20 GiB after).
|
||||
### Windows
|
||||
|
||||
Requirements: Windows 10 or later, an x86-64 CPU with SSE4.2 (AVX2/FMA machines get a faster build), a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`, about 36 GiB free during setup (20 GiB after).
|
||||
|
||||
1. Download `TotK-Setup-<version>-windows.zip` from [Releases](../../releases/latest) and unpack it.
|
||||
2. Start `TotK-Setup.exe`. If SmartScreen warns about an unsigned app, choose *More info*, then *Run anyway*.
|
||||
3. Pick your game files, the language and an install folder, and press *Start*. The setup builds the game once.
|
||||
3. Pick your game files, the language and an install folder, and press *Start*. The setup builds the game once. With
|
||||
an NVIDIA RTX GPU it also downloads NVIDIA DLSS, unless you untick *Download NVIDIA DLSS*; turn DLSS on in the
|
||||
menu (F1).
|
||||
4. Play `totk.exe` from the install folder.
|
||||
|
||||
To update, run a newer `TotK-Setup.exe` on the same folder; saves and settings are kept. Settings are in the in-game menu and in `totk.ini` ([totk.ini.example](totk.ini.example) lists every key). Controls: [docs/controls.md](docs/controls.md).
|
||||
### Linux
|
||||
|
||||
Requirements: as on Windows, plus Linux 6.7 or later and glibc 2.34 or later (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3).
|
||||
|
||||
1. Download `TotK-Setup-x86_64.AppImage` from [Releases](../../releases/latest), or build it ([docs/installer.md](docs/installer.md), "Linux release").
|
||||
2. Make it executable (`chmod +x TotK-Setup-x86_64.AppImage`) and start it. On a Steam Deck, do this in Desktop Mode.
|
||||
3. Pick your game files, the language and an install folder, and press *Start*.
|
||||
4. Play `totk` from the install folder.
|
||||
|
||||
To update, run a newer setup on the same folder; saves and settings are kept. Settings are in the in-game menu and in `totk.ini` ([totk.ini.example](totk.ini.example) lists every key). Controls: [docs/controls.md](docs/controls.md).
|
||||
|
||||
## Credits
|
||||
|
||||
|
||||
+39
-5
@@ -10,7 +10,10 @@ Code copied or adapted from another project is listed here with its source, the
|
||||
| MacNativeGames TotK host runtime: dynamic linking, identity check, module permissions, guest memory and SVCs, threads, IPC, audio renderer, system services, RomFS and save storage, boot sequence, the NVN proc name list | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/runtime/`, `games/totk/scripts/prepare_runtime.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/loader.c`, `runtime/memory.c`; `runtime/kernel.c`, `runtime/svc.c`, `runtime/ipc.c`, `runtime/ipc.h`, `runtime/audren.c`, `runtime/audren.h`, `runtime/audio_mixer.c`, `runtime/audio_effects.c`, `runtime/audio_effects.h`, `runtime/audio_reverb.c`, `runtime/audio_reverb.h` (SDL3 output replaces CoreAudio), `runtime/ov_system.c` (also `shared_font.c`: the BFTTF layout behind nn::pl), `runtime/ov_input.c` (also `hid_feedback.c`: vibration and six-axis handles and calls), `runtime/motion_fusion.c` (six-axis fusion of `motion_fusion.c`), `runtime/ov_media.c` (hardware Opus decoder over libopus), `runtime/swkbd_win.c` (`swkbd_host.c`: ShowKeyboardArg offsets, UTF-8/UTF-16 conversion, disabled-key filter, result codes; Win32 window replaces the macOS text bar), `runtime/ov_gfx.c`, `runtime/romfs.c`, `runtime/romfs_path.h`, `runtime/fs_host.c`, `runtime/fs.h`, `runtime/boot.c`; `runtime/gfx_window.c`; `tools/gen_nvn_procs.py`, `runtime/nvn_procs.inc` (`NVN/names.txt` and the `NVN_EXTRA` names of `totk_nvn_ext.c`) |
|
||||
| MacNativeGames TotK frame-rate patches: 60 fps present-interval controller, real-time frame step and its present sampling, hair and cloth clock, trampoline slow-motion check (instruction words and 1.2.1 sites), player position chain; quick-menu capture background RomFS overlay | https://github.com/ly05010419/MacNativeGames @ `ebe621de99bfc48f3c42f2d2aa73e04fbcc6eae2` (`games/totk/runtime/game_patches.c`, `game_version.h`, `world_survey.c`, `games/totk/scripts/make_romfs_patches.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/frame_rate.c`, `recomp/patches-v121.txt`, `tools/make_romfs_patches.py` |
|
||||
| MacNativeGames TotK 1.4.3 fade fix: the four distance / LOD and pre-actor fade sites, their instruction words and the floor of the fade step at 1 | https://github.com/ly05010419/MacNativeGames @ `3e9e7f67fdfdd3404134dcfa0f24969a9425a33f` (`games/totk/runtime/game_patches_v143.c` patch_fade_increment), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v143.txt` (set fade; the floor without flags, clz >> 5, as in pull request #78) |
|
||||
| MacNativeGames TotK aspect ratio: the camera and viewport sites that hand the perspective projection its aspect ratio, and the UI layout edits for a canvas wider than 16:9 | https://github.com/ly05010419/MacNativeGames @ `933b6a0d1438de160208a0a13eb5e8d7a2cb8094` (`games/totk/runtime/aspect_patch.h`, `aspect_math.h`, `game_patches_v143.c`, `games/totk/scripts/ultrawide_layout.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v143.txt` (set aspect), `tools/ultrawide_layout.py`, `tools/make_romfs_patches.py` (--aspect) |
|
||||
| MacNativeGames TotK 1.2.1 cursor and aim steps: the map cursor, vertical Ultrahand aim and vertical gyro aim sites, their instruction words and the step scaled by the frame ratio | https://github.com/ly05010419/MacNativeGames @ `363a6eb50434387f7d623349934bcf1e910be48f` (`games/totk/runtime/game_patches.c` patch_cursor_speed), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v121.txt`, `recomp/patches-v110.txt` (set cursor) |
|
||||
| MacNativeGames TotK aspect ratio: the camera and viewport sites that hand the perspective projection its aspect ratio, and the UI layout edits for a canvas wider than 16:9 | https://github.com/ly05010419/MacNativeGames @ `933b6a0d1438de160208a0a13eb5e8d7a2cb8094` (`games/totk/runtime/aspect_patch.h`, `aspect_math.h`, `game_patches_v143.c`, `games/totk/scripts/ultrawide_layout.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v110.txt`, `recomp/patches-v143.txt` (set aspect), `tools/ultrawide_layout.py`, `tools/make_romfs_patches.py` (--aspect) |
|
||||
| MacNativeGames TotK button icons: the Xbox controller's shoulder buttons, triggers, Menu, View and d-pad drawn with letters from the game's own text fonts, the .bfotf key, the button guide's images and their block-linear layout, the resource size table raised for the archives that grew | https://github.com/ly05010419/MacNativeGames @ `933b6a0d1438de160208a0a13eb5e8d7a2cb8094` (`games/totk/scripts/make_button_icons.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `tools/button_icons.py`, `tools/make_romfs_patches.py` (--prompts) |
|
||||
| RenoDX TotK mod (game mod by souperman9, tonemapper by Musa, RenoDX framework by ShortFuse, RenoVK fork by Ritsu): the HDR tonemap's colour reconstruction (the game's 1 - e^-x curve continued along its tangent above 0.18, the SDR result as hue and purity donor through MacLeod-Boynton in BT.2020, the saturation grade on a Neutwo-compressed colour, per-channel Neutwo to the peak in BT.2020, the sRGB to gamma 2.2 correction) adapted into GLSL, and the observation that the passes after the tonemap keep values above 1 | https://github.com/clshortfuse/renodx @ `43c067b755a6a741f6500b2b936570f1462dcfbe` (`src/games/totk/tonemap.slang`, `src/games/totk/macleod_boynton.hlsli`, `src/shaders/colorcorrect.hlsl`, `src/shaders/tonemap/neutwo.hlsl`), Copyright (c) 2025 Carlos Lopez Jr. | MIT | `runtime/shaders/hdr_tonemap.frag`, `runtime/vk_hdr.c` |
|
||||
| TOTK-Ultrawide, the community mod for emulators: the list of UI panes the ultrawide layout edits and the distances they move (data only, no code copied; the edit code is our own, and MacNativeGames' `ultrawide_layout.py` in the row above already carries the same values). The mod's repository URL and licence version are not recorded in this repository | TOTK-Ultrawide (community mod; URL not recorded here) | GPL (version not recorded here) | `tools/ultrawide_layout.py` (`KEEP_ROOT`, `edits`, `anim_edits`) |
|
||||
| MacNativeGames TotK virtual-core preemption: asynchronous preemption of an owner in top-level game code, priority inheritance through guest mutexes, the SDK's preemption-disable protocol (TLR+0x100/+0x102, SVC 0x36), the core-wait diagnostics | https://github.com/ly05010419/MacNativeGames @ `33e8fa83052ea1ae09a3583137008e9797e12950` (`games/totk/runtime/threads.c`, commits 8bf0893 and 19730cd), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/kernel.c` (SuspendThread and a register-saving stub replace SIGUSR2), `runtime/hostfn.c`, `runtime/svc.c` (host depth) |
|
||||
| MacNativeGames RomFS index builder (`TOTKRFS1` layout) | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/scripts/prepare_romfs_backend.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `tools/romfs_index.py` |
|
||||
@@ -24,10 +27,14 @@ Code copied or adapted from another project is listed here with its source, the
|
||||
| deko3d block-linear image layout, as ported in MacNativeGames' `nvn_tex.c` (Apple parts dropped, layout math unchanged; licence text in `games/totk/third_party/d2r_gfx/LICENSE.deko3d`, reproduced in the file header) | https://github.com/devkitPro/deko3d (`source/dk_image.cpp`), via MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/third_party/d2r_gfx/gfx/nvn/nvn_tex.c`, `nvn_tex.h`), Copyright (C) 2018-2020 fincs | zlib | `runtime/nvn_tex.c`, `runtime/nvn_tex.h` |
|
||||
| MacNativeGames texture auto-layout goldens (40 original-SDK size and block-height cases) | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/tests/texture_auto_layout/probe.c`), Copyright (c) 2026 jhaizhou | MIT | `runtime/nvn_tex_probe.c`; `runtime/nvn_probe.c` (four of the cases, through the procs) |
|
||||
| MacNativeGames block-linear deswizzler (address function; copy loop split out as `tex_bl_copy`) | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/third_party/d2r_gfx/gfx/tex/nvn_deswizzle.c`), Copyright (c) 2026 jhaizhou | MIT | `runtime/tex_deswizzle.c`, `runtime/tex.h` |
|
||||
| SDL 3.4.18, dynamic link, `SDL3.dll` copied next to `totk.exe`. Developer builds use the MSYS2 build (`mingw-w64-ucrt-x86_64-sdl3`, which imports `libiconv-2.dll`, LGPL-2.1, unmodified, copied beside it); the installer release ships the upstream release `SDL3-3.4.18-win32-x64.zip`, which imports no libiconv | https://libsdl.org, Copyright (c) 1997-2026 Sam Lantinga | zlib | `runtime/input_win.c` (gamepad input, rumble, gyro and accelerometer) |
|
||||
| SDL 3.4.20, dynamic link, `SDL3.dll` copied next to `totk.exe`. Developer builds use the MSYS2 build (`mingw-w64-ucrt-x86_64-sdl3`, which imports `libiconv-2.dll`, LGPL-2.1, unmodified, copied beside it); the installer release ships the upstream release `SDL3-3.4.20-win32-x64.zip`, which imports no libiconv | https://libsdl.org, Copyright (c) 1997-2026 Sam Lantinga | zlib | `runtime/input_win.c` (gamepad input, rumble, gyro and accelerometer) |
|
||||
| libopus (MSYS2 `mingw-w64-ucrt-x86_64-opus`), dynamic link, `libopus-0.dll` copied next to `totk.exe` | https://opus-codec.org, Copyright (c) 2001-2023 Xiph.Org, Skype Limited, Octasic, Jean-Marc Valin, Timothy B. Terriberry, CSIRO, Gregory Maxwell, Mark Borgerding, Erik de Castro Lopo, Mozilla, Amazon | BSD-3-Clause | `runtime/ov_media.c` (nn::codec hardware Opus decoder) |
|
||||
| Dear ImGui 1.91.9 (core and Vulkan back end, unmodified), as vendored by LAS Recomp | https://github.com/ocornut/imgui, via https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f` (`third_party/imgui/`), Copyright (c) 2014-2025 Omar Cornut | MIT | `runtime/third_party/imgui/` (compiled into `totk.exe` for the in-game menu, `runtime/ui/`) |
|
||||
| AMD FidelityFX SDK 1.1.4 subset (public host and shader headers, frame interpolation, optical flow and FSR 3 upscaler components, the Vulkan backend `ffx_vk.cpp` and its GLSL shaders, shared helpers), with four marked Savage Wind patches (64-byte aligned backend scratch arrays, doubled context size where `wchar_t` is 4 bytes, all six descriptor pool sizes, the upscaler's Catmull-Rom history reprojection) and one of ours (the upscaler's luma history declared `rgba16f`) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/tree/v1.1.4, Copyright (C) 2024 Advanced Micro Devices, Inc., via https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`third_party/FidelityFX/`) | MIT | `runtime/third_party/FidelityFX/` (compiled into `totk.exe`; licence text in `runtime/third_party/FidelityFX/LICENSE.txt`, shipped as `licenses/FidelityFX-SDK-LICENSE.txt`) |
|
||||
| SavageWindRecomp FidelityFX build support, frame generation and FSR 3 upscaler set-up: the SDK-to-clang compat header, the glslang SPIR-V shader generator with its resource reflection and its FSR 3 upscaler permutations, the blob lookup and the backend and context creation of `runtime/nvn/vulkan/framegen.cpp`, the upscaler context with its shared images and the dispatch parameters of `runtime/nvn/vulkan/fsr3.cpp`, the pair's present spacing of `runtime/nvn/vulkan/device.c` `present_wait_turn` | https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`third_party/FidelityFX/ffx_compat.h`, `tools/ffx_shaders.py`, `runtime/nvn/vulkan/framegen.cpp`, `runtime/nvn/vulkan/fsr3.cpp`, `runtime/nvn/vulkan/device.c`) | MIT | `runtime/third_party/FidelityFX/ffx_compat.h`, `runtime/third_party/FidelityFX/spirv/ffx_shaders_vk.h` and `ffx_fsr3upscaler_vk.h` (output of `tools/ffx_shaders.py`), `tools/ffx_shaders.py`, `runtime/vk_fg.cpp`, `runtime/vk_fsr3.cpp`, `runtime/vk_backend.c` (`present_pair`) |
|
||||
| SavageWindRecomp settings menu: two-pane option rows (row look, left / right stepping, hold speed-up, description pane), the menu style and tab bar | https://github.com/Revivedx/SavageWindRecomp @ `575ad88e02f9a89a9a885d90039d48af33c982f4` (`runtime/ui/option_rows.mm`, `runtime/ui/menu.mm`), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/ui/option_rows.cpp`, `runtime/ui/option_rows.h`, `runtime/ui/menu.cpp` |
|
||||
| SavageWindRecomp GPU overlap one-off readback rule: a target not read back within the last 16 frames (64-entry table) makes the frame wait wait up to the value that rendered it | https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`runtime/nvn/vulkan/exec.c` readback_schedule, renderer_wait_seq), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/vk_texture.c` (oneoff_streaming, vk_texture_oneshot) |
|
||||
| SavageWindRecomp descriptor sets allocated in growing batches per layout | https://github.com/Revivedx/SavageWindRecomp @ `740b18025fe11ba03c117dbb56668db304b5043e` (`runtime/nvn/vulkan/exec.c` vk_alloc_set), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/vk_exec_draw.c` (alloc_set_batched) |
|
||||
| SavageWindRecomp performance overlay: the frame ring and its one-second summary, the NVML calls, the sampling loop, the full panel's layout | https://github.com/Revivedx/SavageWindRecomp @ `575ad88e02f9a89a9a885d90039d48af33c982f4` (`runtime/perfmon.c`, `runtime/perfmon.h`, `perf_overlay_draw` in `runtime/ui/menu.mm`), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/perfmon.c`, `runtime/perfmon.h`, `runtime/ui/menu.cpp` |
|
||||
| Roboto Medium font (Dear ImGui's `misc/fonts/Roboto-Medium.ttf`, unmodified) | https://fonts.google.com/specimen/Roboto, via https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f` (`third_party/imgui/misc/fonts/`), Copyright 2011 Google Inc. | Apache-2.0 | `runtime/ui/fonts/Roboto-Medium.ttf` (licence text in `runtime/ui/fonts/LICENSE-Roboto.txt`), embedded by `runtime/ui/menu.cpp` |
|
||||
| Vulkan Memory Allocator 3.4.0 (MSYS2 `mingw-w64-ucrt-x86_64-vulkan-memory-allocator`), header-only, compiled into `totk.exe` | https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator, Copyright (c) 2017-2026 Advanced Micro Devices, Inc. | MIT | `runtime/vk_vma.cpp` (the allocator behind `runtime/vk_memory.c`) |
|
||||
@@ -37,6 +44,8 @@ Code copied or adapted from another project is listed here with its source, the
|
||||
| AMD FidelityFX Super Resolution 1.0 (`ffx_a.h`, `ffx_fsr1.h`, unmodified; licence text in `runtime/shaders/ffx/LICENSE.txt`) | https://github.com/GPUOpen-Effects/FidelityFX-FSR @ `a21ffb8f6c13233ba336352bdff293894c706575`, Copyright (c) 2021 Advanced Micro Devices, Inc. | MIT | `runtime/shaders/ffx/`, `runtime/shaders/fsr_easu.comp`, `runtime/shaders/fsr_rcas.comp` (compiled into `runtime/fsr_easu_spv.h`, `runtime/fsr_rcas_spv.h`) |
|
||||
| AMD Display Library (ADL) declarations: `AdapterInfo`, `ADLSingleSensorData`, `ADLPMLogDataOutput`, the `ADL_PMLOG_*` sensor numbers and the `ADL2_*` function signatures | https://github.com/GPUOpen-LibrariesAndSDKs/display-library @ `84c881cb2136f04287eb3af12de00a9e2867aa9e` (`include/adl_structures.h`, `include/adl_defines.h`, `include/adl_sdk.h`), Copyright (c) 2016 - 2022 Advanced Micro Devices, Inc. | MIT | `runtime/perfmon.c` |
|
||||
| Zstandard 1.5.7 (MSYS2 `mingw-w64-ucrt-x86_64-zstd`), static link | https://github.com/facebook/zstd, Copyright (c) Meta Platforms, Inc. and affiliates | BSD-3-Clause | `runtime/resolution.c` (the HeapDef table), `runtime/ov_zstd.c` (the game's zstd frames decoded on the host) |
|
||||
| musl `fma.c`, `fmaf.c` and `scalbn.c`, adapted into one file for the x86-64-v2 build | https://github.com/kraj/musl @ `5a56ad13e1e0790c06122978aad2a14d6b9efc1a` (mirror of https://git.musl-libc.org/cgit/musl), Copyright (c) 2005-2020 Rich Felker and contributors | MIT | `runtime/fma.c` (the correctly rounded fma/fmaf the FP lowering needs on CPUs without FMA3) |
|
||||
| MacNativeGames texture pool offset fix: widen the 32-bit texture storage and packaged-data offsets unsigned | https://github.com/ly05010419/MacNativeGames @ `ca311e2d` (`games/totk/runtime/game_patches.c` patch_pool_offset), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v110.txt` (set pooloff; sites located again in 1.1.0) |
|
||||
|
||||
## Compiler runtime in a source build
|
||||
|
||||
@@ -64,16 +73,41 @@ These tools run on the developer's or player's machine during the build. They ar
|
||||
|
||||
| Component | Source | License | Where in the release |
|
||||
|---|---|---|---|
|
||||
| Tcl/Tk 9.0.4, rebuilt with Xft for the Linux installer | https://github.com/tcltk/tcl and https://github.com/tcltk/tk, tag `core-9-0-4`; archives pinned by SHA-256 in `tools/make_release_linux.py` | Tcl/Tk licence (BSD-style) | `python/lib/`; licence texts in `licenses/tcl-license.terms` and `licenses/tk-license.terms` |
|
||||
| libXft 2 and libXrender 1, the sniper SDK sysroot's shared libraries, bundled beside the Xft Tk of the Linux installer; their Debian `copyright` files go into `licenses/` | https://repo.steampowered.com/steamrt-images-sniper/snapshots/3.0.20261021.266025/ | HPND (MIT-style) | `python/lib/`; `licenses/libXft-copyright.txt`, `licenses/libXrender-copyright.txt` |
|
||||
| CPython 3.14.9 embeddable package, with `tkinter` and Tcl/Tk 9.0.4 taken from the python.org 3.14.9 installer's component MSI (unpacked, never run); includes `vcruntime140*.dll` (Microsoft, redistributable with Python), OpenSSL, libffi, SQLite, zlib, libtommath | https://www.python.org/downloads/release/python-3149/ | PSF-2.0 (Tcl/Tk: Tcl/Tk licence, BSD-style) | `python/` |
|
||||
| numpy 2.5.4 (with its bundled OpenBLAS), lz4 4.4.5, cryptography 50.0.2 (with its bundled OpenSSL), cffi 2.1.1, pycparser 3.11 | PyPI binary wheels, pins in `tools/requirements-installer.txt` | BSD-3-Clause; lz4 BSD-3-Clause; cryptography Apache-2.0 OR BSD-3-Clause; cffi MIT; pycparser BSD-3-Clause | `python/Lib/site-packages/` |
|
||||
| Sun Valley ttk theme (sv-ttk 2.6.1): the light and dark themes, their sprite sheets and fonts, the look of the setup window | https://github.com/rdbende/Sun-Valley-ttk-theme @ `cefdf5d383073f29f04cb7254e24e195d8bda6a2` (tag v2.6.1, `sv_ttk/sv.tcl`, `sv_ttk/theme/`), Copyright (c) rdbende | MIT | `installer/vendor/sv_ttk/` (unmodified, licence in `installer/vendor/sv_ttk/LICENSE`), loaded by `installer/gui.py` use_sun_valley |
|
||||
| numpy 2.5.4 (with its bundled OpenBLAS), lz4 4.4.5, cryptography 50.0.2 (with its bundled OpenSSL), fontTools 4.68.0, cffi 2.1.1, pycparser 3.11 | PyPI binary wheels, pins in `tools/requirements-installer.txt` | BSD-3-Clause; lz4 BSD-3-Clause; cryptography Apache-2.0 OR BSD-3-Clause; fontTools MIT; cffi MIT; pycparser BSD-3-Clause | `python/Lib/site-packages/` |
|
||||
| llvm-mingw 20261020 (LLVM/Clang/LLD 23, mingw-w64, libc++, libunwind, compiler-rt), x86_64 subset | https://github.com/mstorsjo/llvm-mingw/releases/tag/20261020 | Apache-2.0 with LLVM exception; mingw-w64 ZPL-2.1/BSD/public domain; libc++ and libunwind Apache-2.0 with LLVM exception and MIT/UIUC; winpthreads MIT | `llvm/` |
|
||||
| SDL 3.4.18 upstream Windows release (`SDL3.dll`) and mingw development package (headers, `libSDL3.dll.a`) | https://github.com/libsdl-org/SDL/releases/tag/release-3.4.18 | zlib | `bin/SDL3.dll`, `runtime/deps/` |
|
||||
| SDL 3.4.20 upstream Windows release (`SDL3.dll`) and mingw development package (headers, `libSDL3.dll.a`) | https://github.com/libsdl-org/SDL/releases/tag/release-3.4.20 | zlib | `bin/SDL3.dll`, `runtime/deps/` |
|
||||
| libopus 1.6.1 (MSYS2 `mingw-w64-ucrt-x86_64-opus` 1.6.1-2; `libopus-0.dll` imports only KERNEL32 and the UCRT api-ms-win-crt DLLs), headers and import library | https://repo.msys2.org/mingw/ucrt64/ | BSD-3-Clause | `bin/libopus-0.dll`, `runtime/deps/` |
|
||||
| libvpx 1.17.0 (MSYS2 `mingw-w64-ucrt-x86_64-libvpx` 1.17.0-1), headers and static library compiled into `totk.exe`; `libvpx-LICENSE.txt` and `libvpx-PATENTS.txt` come from the v1.17.0 source tag | https://github.com/webmproject/libvpx | BSD-3-Clause with the WebM patent grant | `runtime/deps/`, `licenses/` |
|
||||
| Zstandard 1.5.7 (MSYS2 `mingw-w64-ucrt-x86_64-zstd` 1.5.7-2), headers and static library compiled into `totk.exe`; `zstd-LICENSE.txt` from the package | https://github.com/facebook/zstd | BSD-3-Clause | `runtime/deps/`, `licenses/` |
|
||||
| Vulkan-Headers and Vulkan-Loader 1.4.363.0 (MSYS2 packages; headers and `libvulkan-1.dll.a` only, no loader DLL) | https://github.com/KhronosGroup | Apache-2.0 OR MIT | `runtime/deps/` |
|
||||
| Vulkan Memory Allocator 3.4.0 (MSYS2 package), header | https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator | MIT | `runtime/deps/` |
|
||||
| Ninja 1.13.2 (`ninja-win.zip`) | https://github.com/ninja-build/ninja/releases/tag/v1.13.2 | Apache-2.0 | `bin/ninja.exe` |
|
||||
| hactool (SciresM @ `1d64a83450e025622f3468c28fc4164dad2c5ef6` plus `tools/hactool/portable.patch`, from MacNativeGames' `build_hactool()`: `MNG_TITLE_KEYS` and relaxed BKTR layout checks; our `tools/hactool/unicode.patch`: an embedded manifest that makes UTF-8 the process code page), built by `tools/build_hactool.py` with MSYS2 UCRT64 gcc; imports only KERNEL32 and the UCRT | https://github.com/SciresM/hactool | ISC | `bin/hactool.exe` |
|
||||
| hactool (SciresM @ `1d64a83450e025622f3468c28fc4164dad2c5ef6` plus `tools/hactool/portable.patch`, from MacNativeGames' `build_hactool()`: `MNG_TITLE_KEYS` and relaxed BKTR layout checks; our `tools/hactool/unicode.patch`: an embedded manifest that makes UTF-8 the process code page; our `tools/hactool/mbedtls-asm-clobbers.patch`: the clobbers the bundled mbedtls's x86-64 multiply asm lacks), built by `tools/build_hactool.py` with MSYS2 UCRT64 gcc; imports only KERNEL32 and the UCRT | https://github.com/SciresM/hactool | ISC | `bin/hactool.exe` |
|
||||
| `totk_xlate.exe` (Ryujinx shader translator, NativeAOT build of `tools/xlate/`, see the Ryujinx row above) | built by `tools/build_xlate.py` | MIT | `bin/totk_xlate.exe` |
|
||||
| MacNativeGames shader variant list | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/assets/shader_list.tsv`), Copyright (c) 2026 MacNativeGames contributors | MIT | `data/shader_list.tsv` |
|
||||
|
||||
## Distributed in the Linux release (AppImage)
|
||||
|
||||
`tools/make_release_linux.py` assembles these into the folder of `docs/installer.md` ("Linux release") and packs it as
|
||||
`TotK-Setup-x86_64.AppImage`. Versions and sha256 of every download are pinned in that script; licence texts are in the
|
||||
folder's `licenses/` and in each component's own folder.
|
||||
|
||||
| Component | Source | License | Where in the release |
|
||||
|---|---|---|---|
|
||||
| CPython 3.14.10, python-build-standalone 20261026 `install_only` build, with `tkinter` and the libraries it bundles (OpenSSL, libffi, SQLite, zlib, Tcl/Tk and others; their licences ship in the folder) | https://github.com/astral-sh/python-build-standalone/releases/tag/20261026 | PSF-2.0; bundled libraries under their own licences | `python/` |
|
||||
| numpy 2.5.4 (with the libraries its manylinux wheel bundles), lz4 4.4.5, cryptography 50.0.2, cffi 2.1.1, pycparser 3.11 | PyPI binary wheels, pins in `tools/requirements-installer.txt` | as in the installer release row above | `python/lib/python3.14/site-packages/` |
|
||||
| LLVM 23.1.4 official Linux X64 release: `clang`, `lld`, `llvm-ar`, `llvm-ranlib`, `llvm-objcopy`, `llvm-strip` and the clang resource headers; `llvm-LICENSE.txt` from the `llvmorg-23.1.4` source tag | https://github.com/llvm/llvm-project/releases/tag/llvmorg-23.1.4 | Apache-2.0 with LLVM exception | `llvm/` |
|
||||
| Steam Runtime 3 "sniper" SDK sysroot 3.0.20261021.266025 (Debian 11 based), only the headers, libraries and objects a game build reads: glibc 2.31 (headers, `crt*.o`, `libc_nonshared.a`, link libraries), GCC 10 `libstdc++.a` and `libgcc`, SDL 3.4.18, libopus, libvpx 1.9 (static), the Vulkan loader's link library; their Debian `copyright` files go into `licenses/` | https://repo.steampowered.com/steamrt-images-sniper/snapshots/3.0.20261021.266025/ | glibc LGPL-2.1+; libstdc++ and libgcc GPL-3.0 with the GCC Runtime Library Exception; SDL zlib; libopus BSD-3-Clause; libvpx BSD-3-Clause with the WebM patent grant (`libvpx-PATENTS.txt` from the v1.17.0 source tag); Vulkan loader Apache-2.0 | `llvm/sysroot/`, `bin/libSDL3.so.0` (the sysroot's, copied next to the game by the setup), `licenses/` |
|
||||
| Vulkan-Headers 1.4.363 (source tag) | https://github.com/KhronosGroup/Vulkan-Headers/tree/v1.4.363 | Apache-2.0 OR MIT | `runtime/deps/include/` |
|
||||
| Vulkan Memory Allocator 3.4.0, header (the licence text is its header comment) | https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator/tree/v3.4.0 | MIT | `runtime/deps/include/vma/` |
|
||||
| Zstandard 1.5.7, built from the release tarball into a static `libzstd.a` with the folder's clang and sysroot | https://github.com/facebook/zstd/releases/tag/v1.5.7 | BSD-3-Clause | `runtime/deps/` |
|
||||
| Ninja 1.13.2 (`ninja-linux.zip`) | https://github.com/ninja-build/ninja/releases/tag/v1.13.2 | Apache-2.0 | `bin/ninja` |
|
||||
| hactool (as in the installer release row above), built by `tools/build_hactool.py --cc` with the folder's clang and sysroot; includes its bundled mbedtls | https://github.com/SciresM/hactool | ISC; mbedtls Apache-2.0 | `bin/hactool` |
|
||||
| `totk_xlate` (NativeAOT linux-x64 build of `tools/xlate/`, linked with the folder's clang, lld and sysroot) | built by `tools/build_xlate.py --llvm --sysroot` | MIT | `bin/totk_xlate` |
|
||||
| AppImage type-2 runtime (static; includes libfuse and squashfuse), the AppImage's first part; appimagetool packs the folder and is not distributed | https://github.com/AppImage/type2-runtime | MIT; libfuse LGPL-2.1; squashfuse BSD-2-Clause | the AppImage header |
|
||||
| MacNativeGames shader variant list | as in the installer release row above | MIT | `data/shader_list.tsv` |
|
||||
| Weeping of the Empire menu cursor: eui's focus box read through ScreenMgr, BoxCursorMgr and the screens' node lists, AnimButton's hit test, the stale-hit-pane fallback to the parts panes, the three writes of moveBoxCursor, the structure offsets (1.0.0; the ScreenMgr instance placed in 1.4.3 by us) | https://github.com/daniel-madrid-07/weeping-of-the-empire @ `df0586cdc5702ca19bbebfa59697e0b6980f6237` (`engine/runtime/totk_menu_cursor.cpp`), Copyright (c) 2026 daniel-madrid-07 | MIT | `runtime/menu_cursor.c` |
|
||||
@@ -10,6 +10,7 @@ updates = ['C:\Games\TotK\update-1.4.3.nsp']
|
||||
keys = 'C:\Switch\prod.keys'
|
||||
# Optional: a firmware NCA directory (an unpacked firmware, or an emulator's installed registered/ directory).
|
||||
# tools/extract_fonts.py takes the system shared fonts from it; the game needs them only with Chinese or Korean text.
|
||||
# The installer asks for the same folder (--firmware) when the language needs those fonts.
|
||||
# firmware = 'C:\Switch\firmware'
|
||||
|
||||
[work]
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
# Debugging the port: method for agents
|
||||
|
||||
A game run costs minutes and a full rebuild costs several more, while reading code costs seconds. Order the work so the
|
||||
cheap steps decide as much as they can before the game starts. Each step ends on its stated condition.
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Evidence.** Hold one artifact that shows the symptom: the player's screenshot, log or input recording, a
|
||||
flight-recorder dump, a frame dump ([running.md](running.md), "Observing"). Done when you can point at the wrong
|
||||
pixel, line or frame.
|
||||
2. **Where it reproduces.** OS, GPU vendor and generation, driver, game update, settings, mods, the save. Done when you
|
||||
know whether your hardware can show the bug at all. NVIDIA bugs do not reproduce on AMD; RDNA1/2 bugs do not
|
||||
reproduce on RDNA3/4 (another driver branch); a Ryzen 7000 iGPU is RDNA2 and runs that branch. When your hardware
|
||||
cannot show it, say so and work from the code and the reporter's logs; runs that cannot decide anything are skipped.
|
||||
3. **Known already?** Search [symptoms.md](symptoms.md), [pr-review-kit/04-knowledge.md](../pr-review-kit/04-knowledge.md)
|
||||
and [maxwell.md](../maxwell.md) sections 6-7 with the words the player used (black, magenta, flicker, slow motion,
|
||||
missing, stale, streaks, stuck) and the object (sky, grass, shadow, fog, HUD, weapon). Then the upstream notes:
|
||||
`refs/nxnative/docs`, `refs/MacNativeGames/docs` and the SavageWindRecomp issue tracker (`tools/fetch_refs.sh`
|
||||
fetches `refs/`). Done when every hit is either ruled out or is your first hypothesis. A hit on a class we already
|
||||
fixed: confirm that fix still holds before deriving anything new.
|
||||
4. **Read the code.** The game's function in Ghidra ([building.md](../building.md), "Reverse engineering") or in
|
||||
`generated/<ver>/`, and our runtime path in `runtime/`. Done when the code either rules the hypothesis out or names
|
||||
the exact condition a run must show. A run confirms what the code could not rule out.
|
||||
5. **The cheapest falsifying check.** An existing switch (a `totk.ini` setting or a `TOTK_*` variable), a dump, a trace
|
||||
line, a probe. When it refutes the hypothesis, stop: write down what was checked and why it fell, and start again
|
||||
at step 3 with the next hypothesis. No build, no benchmark for a refuted idea.
|
||||
6. **Repro red, then green.** The same repro shows the bug before the fix and its absence after. A fix without a
|
||||
reproduced failure is a guess.
|
||||
7. **Fix the cause.** A crash that goes away with a feature off points at the bug in that feature; fix the feature.
|
||||
A fix that one setup needs is gated on that setup, and everyone else keeps today's behaviour.
|
||||
|
||||
## Traps
|
||||
|
||||
- **One-off failures.** A failure that happens once and not again: rerun before you debug it as a code bug. A crash or
|
||||
a forced shutdown leaves zero-filled cache files, and memory errors on the host flip bits in files and objects.
|
||||
- **Every build fails the same way at once.** Suspect the inputs and caches (game files, the OS file cache, shader and
|
||||
pipeline caches), not the code. Bisecting code is pointless when the old builds fail too.
|
||||
- **Compile errors in generated C** on a line the generator could not have written are a flipped bit. Regenerate and
|
||||
compare hashes; `recomp/` is fine.
|
||||
- **A crash that looks like a race.** Try the save first: some saves crash the same way on a real Switch.
|
||||
- **Theories about locks and threads.** Read the game's own protocol in Ghidra before running anything. Ten runs on
|
||||
lock theories once went where one read of the game's double-buffer code would have narrowed it.
|
||||
- **Numbers from a fast machine.** A change neutral on a fast desktop can matter on a weak laptop or the Steam Deck,
|
||||
in either direction. Say which hardware your numbers come from.
|
||||
|
||||
## Bug classes of a recompiled Switch game
|
||||
|
||||
The port runs the game's own code on another OS and another GPU. Most bugs come from places where the host differs
|
||||
from the console.
|
||||
|
||||
### Variable frame step and epsilon-gated timers
|
||||
|
||||
The console steps the game by whole 30 Hz units, so a countdown started at a whole value reaches exactly 0. With the
|
||||
real-time step (`realtime = 1`, the default) the step is a measured ratio, and the last step can leave a remainder of
|
||||
about 1e-8. Many of the game's updaters step a timer only while it is above `FLT_EPSILON`; a remainder in
|
||||
(0, `FLT_EPSILON`] is never stepped again. A consumer that tests the same field with `> 0` then sees it active
|
||||
forever, until a load reinitialises the object. Issue #18 (weapons locked after a Fuse) was this.
|
||||
|
||||
Symptom words: stuck until a reload, a teleport or a shrine; locked after an action; works sometimes; only above
|
||||
30 fps. To check a report: find the field the stuck behaviour reads, then compare the updater's threshold with the
|
||||
consumer's test. A change to the frame step, the pacer or the fps limit is checked for this class.
|
||||
|
||||
### Thread scheduling: Horizon is not a desktop OS
|
||||
|
||||
- Horizon runs a woken better-priority thread at once on its core, before the thread that woke it goes on. A host
|
||||
runs both in parallel, so state can be read one step early or freed while another thread still uses it.
|
||||
- Threads created with ideal core -2 start pinned to one core on Horizon. The game keys per-core data by
|
||||
`GetCurrentProcessorNumber` without locks and expects that pinning.
|
||||
- The game has hundreds of spin loops without a system call. On the console a spinning thread holds one core of three;
|
||||
on the host it burns a host core and can keep an equal-priority waiter out.
|
||||
- ARMv8 `stlr` followed by `ldar` is ordered (RCsc). C11 release/acquire lets x86 reorder that store and load. A
|
||||
two-thread flag handshake that loses a wake points here; lifter changes to barriers and atomics pass
|
||||
`tests\diff\atomic.py` and `tests\excl_mt.py`.
|
||||
- A scheduling change is judged by how long a ready, better thread waits for a core it may use, plus the slow-frame
|
||||
count. A check that made one bug rarer once added 50-75 ms hitches.
|
||||
|
||||
### Maxwell behaviour versus Vulkan defaults
|
||||
|
||||
The port must do what the Switch GPU does: last-vertex provoking, (0,0,0,1) for unwritten vertex outputs, colour
|
||||
targets outside the shader's output map keep their texels, the G-buffer pass samples its own targets. The full list
|
||||
with sources: [maxwell.md](../maxwell.md), section 7.
|
||||
|
||||
### Memory shared by the CPU and the GPU
|
||||
|
||||
- The game fills textures and buffers with the CPU and samples them on the GPU without the flush a desktop API needs.
|
||||
Missing uploads show as magenta, brown or stale textures.
|
||||
- The game reads GPU-rendered textures with the CPU (grass maps, cut and burn masks). Missing write-backs show as
|
||||
effects that never happen: cut grass stays up, fire does not spread.
|
||||
- Memory only the GPU writes looks idle to write-watch tracking: a store from a shader leaves no fault and no dirty bit.
|
||||
- Anything kept per texture, per frame or per object without a free grows host memory until a commit failure after
|
||||
hours. Watch private memory over a few idle minutes.
|
||||
|
||||
### Device lost and GPU hangs
|
||||
|
||||
- The `vk: pass marks` lines name the pass in flight. Validation names the misuse when there is one.
|
||||
- Submits and presents share one queue under one lock. A present from its own thread on a second queue gave device
|
||||
lost on NVIDIA before Turing in another port.
|
||||
- Caches from another driver or GPU (pipeline caches, translated shaders) gave black windows after driver updates;
|
||||
every cache is validated on load and dropped when vendor, device or `pipelineCacheUUID` change.
|
||||
- A first-time shader stall over 2 s on a slow GPU trips the Windows GPU timeout (display event 4101). Large one-shot
|
||||
submissions (a boot-time decode of every texture) do the same.
|
||||
- Point lists from vertex shaders that write no point size are undefined without `VK_KHR_maintenance5`.
|
||||
|
||||
### Windows and Wine host costs
|
||||
|
||||
What the hot path must not do, with measured costs: [pr-review-kit/02-performance.md](../pr-review-kit/02-performance.md),
|
||||
"What the hot path must not do". For debugging, also:
|
||||
|
||||
- `SuspendThread` returns at once, but `GetThreadContext` waits until the thread leaves the kernel. A sampler or a
|
||||
debugger stalls for as long as the stopped thread's file open or driver call runs.
|
||||
- A thread stopped between its `sub rsp` and its stack probe has its stack pointer inside the guard page. Check
|
||||
`PAGE_GUARD` with `VirtualQuery` before reading another thread's stack.
|
||||
- Paths go through the W APIs with UTF-8 to UTF-16 conversion. An A API call breaks on a path with non-Latin letters,
|
||||
such as a Windows user name in Cyrillic or Chinese.
|
||||
- Wine emulates `GetWriteWatch` with `mprotect` and one fault per first write. Anything relying on cheap OS memory
|
||||
tricks (write-watch, protection changes, fault handlers) costs more under Proton.
|
||||
- `win32u.dll` frames in a host stack are kernel graphics calls: memory allocation or submission.
|
||||
@@ -0,0 +1,93 @@
|
||||
# Running and observing the game as an agent
|
||||
|
||||
How an agent runs a build into gameplay without a person at the controls, captures what the game shows, and reads the
|
||||
results without flooding its context. Setting names and file formats live in [settings.md](../settings.md) and
|
||||
[controls.md](../controls.md); this page says which to use when. How to judge a performance change:
|
||||
[pr-review-kit/02-performance.md](../pr-review-kit/02-performance.md).
|
||||
|
||||
## Before the first run
|
||||
|
||||
- **A build dir per change.** Build into its own folder (`tools/build_game.py --out build/<ver>-<name>`) so a
|
||||
comparison has two exes side by side. After every build check the exe's modification time: a failed link leaves the
|
||||
old `totk.exe` in place and you test old code.
|
||||
- **Prepared shaders in that folder.** `tools/prepare_shaders.py build/<dir> --version <ver>` ([building.md](../building.md)
|
||||
step 6). Without it the game compiles shaders during play, and every timing and every "a draw is missing" shot of the
|
||||
first minutes says nothing about your change. Shader and pipeline caches are not copied between build folders.
|
||||
- **The same `totk.ini` on both sides** of any comparison. A folder without one runs at the defaults; check the log's
|
||||
`resolution:` line of each run before comparing them.
|
||||
- **Saves.** `tools/run_game.py` copies the profile `build/profile`, swaps in a save from `build/save-backup/<name>/`
|
||||
and deletes the copy afterwards, so the real profile is never written. To make a backup, copy the user folder from
|
||||
`build/profile/save/` into `build/save-backup/<name>/`. Pick a save that starts where the change acts.
|
||||
|
||||
## Running
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python tools\run_game.py build\<dir> --save <name> --seconds 30 [--script <input.txt>] [--shot out.png] [--env KEY=VALUE] [--quiet] [--tag <name>]
|
||||
```
|
||||
|
||||
- `--seconds` is game time since the world loaded (the log line `frame step: world clock starts` marks the start), at
|
||||
any frame rate. Measure and script by game time; a frame count at another fps is another scene.
|
||||
- `--script` replays input ([controls.md](../controls.md), "Scripted input"). A new script starts with every line of
|
||||
`tools/input/load_save.txt`, which loads the first save from the title: A every 2.5 s until the load ends, because a
|
||||
slow boot eats presses and a run left on a title dialog shows nothing. Its timed line stops those presses when the
|
||||
world clock starts; a script without a timed line would carry them into the world. `TOTK_INPUT_RECORD` turns a person's play into
|
||||
a script; ask the user to record the repro rather than guessing the button sequence.
|
||||
- `--shot` saves the last frame and builds pipelines synchronously: use it for pictures, never for timing.
|
||||
- `--quiet` waits until no other `totk.exe` or `ninja.exe` runs. Every timing you report comes from a `--quiet` run.
|
||||
- The log goes to `<dir>\logs\<tag>.log`; the tool prints `<log>: rc=<code>`.
|
||||
|
||||
Run one game at a time: two instances share the GPU's memory and the CPU, and both runs' numbers are void.
|
||||
|
||||
Running `totk.exe` yourself: set `TOTK_ASSUME_FOCUS=1` (an unfocused window otherwise pauses the game),
|
||||
`TOTK_INPUT=none` (the user's keyboard and pad stay out) and `TOTK_BACKGROUND_WINDOW=1`. Stop only the process you
|
||||
started, by PID: `taskkill /IM totk.exe` also closes the user's game.
|
||||
|
||||
**Check that the run reached the world** before trusting it: the world clock line is in the log and the shot shows the
|
||||
scene you expected. Title menus on a slow boot eat presses, and runs of one script drift apart after 10-15 game seconds
|
||||
(enemy AI, physics, weather). Two runs are comparable only when shots at the same game second show the same scene.
|
||||
|
||||
## Observing
|
||||
|
||||
| You need | Use |
|
||||
|---|---|
|
||||
| pictures over a time span | `TOTK_SHOTS=w<lo>-<hi>:<step>` (world seconds) and `TOTK_SHOTS_DIR`; 480x270 by default |
|
||||
| the frames around a hitch or a one-frame glitch | `TOTK_FLIGHT=1`: keeps the last 600 frames with timings and thumbnails, dumps on F8, on a frame over `TOTK_FLIGHT_SPIKE_MS` or at `TOTK_FLIGHT_AT=<frame>`; `python tools/flight_view.py <dump dir>` lists the worst frames and writes a contact sheet |
|
||||
| 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>` |
|
||||
|
||||
Frame dumps: a draw's argument lines come before its pass header. Pass numbers shift between runs, so find a pass by
|
||||
its draw count or its targets, not by its number. RenderDoc cannot capture this renderer ([controls.md](../controls.md),
|
||||
"RenderDoc capture").
|
||||
|
||||
## Measuring
|
||||
|
||||
| What | How |
|
||||
|---|---|
|
||||
| fps, worst frame, render-thread waits, GPU busy time, VRAM, `bound: gpu\|cpu\|pace` | `--env TOTK_TRACE=perf,sched`, then `python tools\perf_summary.py <log> <lo> <hi>` |
|
||||
| slow frames | count the `perf: slow frame` lines; each names what the render thread was blocked on (pipeline, translation, texture, fence, pacing) |
|
||||
| the frame's critical path, by thread and state | `TOTK_CRIT=w<lo>-<hi>` and `TOTK_CRIT_OUT=<absolute path>` with `sched` tracing, then `python tools\crit_path.py <file>` |
|
||||
| where CPU time goes | `TOTK_PROFILE=<path>` and `TOTK_PROFILE_FRAMES=w<lo>-<hi>`, then `python tools\prof_report.py <profile> <totk.map>`; `TOTK_PROFILE_RENDER=1` samples the render thread with call chains |
|
||||
| a switch on a static scene | a setting set to `ab` with `TOTK_AB=<seconds>` alternates the two sides in blocks of game time; `python tools\ab_summary.py <log> --skip <seconds>`. On a moving scene compare whole runs instead |
|
||||
|
||||
A single run proves little: runs of one script on one build spread by a third in their 1% lows. Compare medians of at
|
||||
least two whole runs per side, on a quiet machine.
|
||||
|
||||
## Probes
|
||||
|
||||
Each probe is a mode of `totk.exe`, run from the build folder; the list with what each covers is at the top of
|
||||
`runtime/main.c`. `--selftest` needs no game files. `--probe-kernel`, `--probe-vkexec`, `--probe-nvn-tex` and
|
||||
`--probe-shader` cover most runtime changes and run in seconds: run them before any game run.
|
||||
|
||||
## Reading output without filling the context
|
||||
|
||||
- Game logs run to megabytes. `grep` the lines you need, `tail` the end, pipe `perf_summary.py` through `grep SUMMARY`.
|
||||
- Generated C runs to hundreds of thousands of lines per file. `grep -n` the function, then print its line range.
|
||||
- Look at screenshots downscaled: paste several into one 1280x720 grid and read the grid once. Write down what it shows
|
||||
instead of opening it again.
|
||||
- Send long builds and runs to the background with their output in a file; read the last lines when they end.
|
||||
- Keep a notes file in the build folder from the first finding: what is ruled out, the leading hypothesis, the next
|
||||
step, temporary debug edits with file and line. A fresh session continues from it.
|
||||
@@ -0,0 +1,83 @@
|
||||
# Symptoms and their usual causes
|
||||
|
||||
What a player reports, the causes this port and other Switch ports (nxnative, MacNativeGames, SavageWindRecomp,
|
||||
LAS Recomp) found behind it, and the first check. Search by the player's words and by the object. Which of these are
|
||||
already fixed here, and where: [pr-review-kit/04-knowledge.md](../pr-review-kit/04-knowledge.md), "Fixed bug classes".
|
||||
GPU semantics behind the graphics rows: [maxwell.md](../maxwell.md). The method around this table:
|
||||
[debugging.md](debugging.md).
|
||||
|
||||
## Graphics
|
||||
|
||||
| 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 |
|
||||
| empty clouds or fog for the whole session | a one-shot draw skipped while its pipeline built, never drawn again | `perf: slow frame` lines naming pipeline waits; the draw's first frame |
|
||||
| fog that never parts, flicker in tile rows | driver constants (c0: dispatch size, point size, base instance) not filled | the c0 contents the translator expects for that stage |
|
||||
| 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
|
||||
|
||||
| Symptom | Usual causes | First check |
|
||||
|---|---|---|
|
||||
| stuck until a reload or teleport, locked after an action | a timer remainder below `FLT_EPSILON` with the real-time step ([debugging.md](debugging.md)) | `realtime = 0` in `totk.ini`; if the bug is gone, find the timer field |
|
||||
| slow motion in GPU-heavy scenes, dynamic resolution never drops | the engine's GPU time comes from report timestamps; wrong timestamps make the frame look free | what the engine reads as GPU time and what the report writes |
|
||||
| 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
|
||||
|
||||
| Symptom | Usual causes | First check |
|
||||
|---|---|---|
|
||||
| state read one step early, one frame of inconsistent data | a woken better-priority thread does not run before the waker goes on | sched trace around the handoff |
|
||||
| per-core data corrupted, rare crash in a container walk | threads the console pins to one core run on any host core | the thread's core mask from its creator; a run on one core |
|
||||
| rare hang or lost wake | address-arbiter signal values or wake order differ from Horizon | the arbiter path against mesosphere |
|
||||
| a flag handshake loses a wake | `stlr`/`ldar` ordering lost in x86 release/acquire | the guest code's barrier pattern |
|
||||
| a host core at 100% while the game waits | game spin loops without system calls | profile: which guest function spins |
|
||||
| crash on world load | sizes the game reads from the driver (command memory used) differ from the console's | the sizes the game asks for against the console's |
|
||||
| crash with one save only | the save itself; some crash on a real Switch | the same save on another build and, if possible, on hardware |
|
||||
| random crash after minutes to hours, access violation reading `0xffffffffffffffff` or a small address such as `0x90` in a game function (Windows reports any non-canonical address as `0xffffffffffffffff`) | an invalid value (-1, `0xffff0000ffffffff`) in an optional reference the game checks only for null; in main+0x1bd0138 (Recall / Ultrahand picking a target) also a reused holder whose actor points into other memory. Sets `optref` and `ability` in `recomp/patches-v143.txt` guard both there | the crash dump's faulting host instruction, the register it loads through and the field that register came from; `ability: target dropped` lines in the log |
|
||||
| crash while using Ultrahand or aiming, in the model scene's report loop (1.4.3 main+0xa22bc..0xa234c) | a report row index read from the report buffer with no bound (Weeping of the Empire #52, #73); set `report` sends a negative handle or an index from 0x8000 to the game's own reset | the faulting address against the report rows base (x12) |
|
||||
|
||||
## Device lost, hangs, black window
|
||||
|
||||
| Symptom | Usual causes | First check |
|
||||
|---|---|---|
|
||||
| device lost a few frames in, GPU writes to address 0 (older NVIDIA) | present from another thread or queue | every submit and present on one queue under one lock |
|
||||
| device lost or garbage on one AMD generation | views the driver branch mishandles (BC block views of 3D textures) | `vk: pass marks`, validation; the formats in the pass |
|
||||
| device lost on one scene, every run, one vendor | a shader or pass that driver cannot run | pass marks name the pass; skip shaders by hash to bisect |
|
||||
| GPU timeout after 1-2 min, single frames over 2 s | first-time shader stalls or a huge one-shot submission on a slow GPU | prepared shaders; submission sizes at boot |
|
||||
| GPU hang at boot with pipeline libraries | point lists without a point size | the shader writes point size or the device clamps it |
|
||||
| black window after a driver update | caches from another driver | the log line `vk_pipeline: ... written by another device or driver`; delete the caches next to `totk.exe` |
|
||||
|
||||
## Memory
|
||||
|
||||
| Symptom | Usual causes | First check |
|
||||
|---|---|---|
|
||||
| host memory grows in play until a commit failure after hours | state kept per texture init or per frame and never freed | private memory over a few idle minutes |
|
||||
| multi-GB peaks while travelling | upload staging grows inside one submission | staging bytes per submission |
|
||||
| out of memory after minutes | dead textures re-entering tables | live images and allocator bytes over time |
|
||||
| stutter as VRAM fills | new memory blocks allocated on the render thread (8-23 ms each) | profile the render thread over the hitch: `vkAllocateMemory` under the allocator's lock |
|
||||
+46
-8
@@ -40,6 +40,10 @@ MacNativeGames cannot run on x86-64 as is: its CPU path executes ARM64 code nati
|
||||
(`recomp/flags.py`, `recomp/regs.py`): registers are stored back where they changed, before calls, SVCs and
|
||||
exits, and reloaded after them. A call reloads only X0-X18 and X30, as AAPCS64 has the callee preserve X19-X29 and
|
||||
SP; `gen.py --no-callee-saved-trust` reloads those too.
|
||||
- `gen.py --v-locals K` keeps the K most used V registers of each function in a local `u128 vr[32]` that clang
|
||||
holds in XMM registers (`recomp/vlocals.py`, the `RT_VLOCALS` accessors of `runtime/simd.h`): loaded at entry,
|
||||
stored where they may have changed before calls and exits, reloaded after calls; `--v-trust` does not reload
|
||||
V8-V15, whose low halves AAPCS64 has the callee preserve. K is 8 by default; K = 0 keeps every V register in the `Cpu`.
|
||||
- Coverage oracle: MacNativeGames' NSO rewriter lists every site where game code touches the OS (SVCs, TLS reads, counter reads, `x18`, exclusive windows, jump tables): 68,968 sites in 1.4.3 `main`. The lifter must handle every one.
|
||||
- Memory: guest address equals host address, all below 2^39 (IPC encodes 39-bit addresses). The heap, stacks and the alias region are reserved with `MEM_WRITE_WATCH`, so the graphics back end can ask which pages the CPU wrote since the last upload (`runtime/memory.c`).
|
||||
- Indirect branches go through `rt_dispatch` (`runtime/dispatch.c`), which looks the target up in the address table and tail-calls it.
|
||||
@@ -54,7 +58,9 @@ MacNativeGames cannot run on x86-64 as is: its CPU path executes ARM64 code nati
|
||||
libzstd on the host (`ov_zstd.c`, `TOTK_ZSTD_NATIVE`); the lifted decoder took almost three times as long.
|
||||
- Settings and menu: every key with its default is in one table (`cfg.c`), read from `totk.ini` and `TOTK_*`
|
||||
variables and written back when the in-game menu changes it. The menu and the performance overlay are Dear ImGui,
|
||||
drawn into the swapchain image (`runtime/ui/`); their text is in `ui_text.c` (English, Russian).
|
||||
drawn into the swapchain image (`runtime/ui/`); their text is in `ui_text.c` (English, Russian, Brazilian Portuguese,
|
||||
Simplified Chinese). The Chinese glyphs come from a system font (Microsoft YaHei, `plat_font_path`) merged into the
|
||||
font atlas.
|
||||
- OS calls the host makes go through `runtime/platform/` (`platform.h`, `win32.c`), so a Linux or macOS host adds one file instead of touching the rest. The split is not finished: `tools/check_platform.py` lists the Win32 uses left in the other files.
|
||||
|
||||
#### Threads and cores
|
||||
@@ -74,19 +80,28 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app
|
||||
- Spin waits. Loops that only another thread can end (857 in 1.4.3, 864 in 1.2.1, found by `tools/spin_waits.py`, the
|
||||
nxnative search) send their back-edges through `rt_spin_gate`, which pauses the core once per pass and hands it to a
|
||||
waiter after 50 us of polling (`TOTK_SPIN`, `TOTK_SPIN_HANDOFF_US`).
|
||||
- `TOTK_FREE_CORES=1` turns the gate off, for experiments.
|
||||
- `free_cores = 1` (`TOTK_FREE_CORES=1`) turns the gate off, for experiments only: the game crashes or hangs, usually
|
||||
at start, because its job workers all report core 0 and share per-core memory (#212).
|
||||
|
||||
### 4. Graphics
|
||||
|
||||
- NVN front end from MacNativeGames (`nvn_api_*.c`, `nvn_obj.h`, texture layout and deswizzle). The game records command buffers through it; nothing reaches the GPU until the game submits.
|
||||
- Vulkan 1.3 back end in place of MacNativeGames' Metal one. At `QueueSubmitCommands` the recorded NVN commands are replayed into Vulkan command buffers (`vk_exec*.c`).
|
||||
- Memory pools. Apple's unified memory let MacNativeGames use the game's pools zero-copy. The back end imports the pools as host memory (`VK_EXT_external_memory_host`). On a discrete GPU, pools bound as buffers are mirrored in device-local memory and the pages the CPU wrote (write watch, above) are uploaded before a replay; idle pool regions are made read-only so the write-watch queries skip them (`vk_memory.c`). GPU-rendered textures are written back when the CPU reads them: on a pool invalidate, on a CPU copy, and for small targets once the CPU waits for a fence (`vk_texture.c`).
|
||||
- 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 because no timing has shown a gain yet.
|
||||
- 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. `TOTK_VK_RECORDER=0` makes every call on the submitting thread.
|
||||
- Replay thread. `TOTK_REPLAY_ASYNC=1` moves the replay off the submitting thread onto a queue at most one frame behind the game; reads of GPU results wait for the newest writer instead of draining the queue (`vk_backend.c`). It is off by default. Where the game waits for the GPU it overlaps the replay with the game threads (a GTX 1650 in the Depths, issue #88), a gain measured only there; while it was the default, a GTX 1660 Ti at the 60 fps cap with the GPU at 26 % reported uneven motion (#659). It adds up to a frame of latency; `replay_async = 1` turns it on.
|
||||
- Chunked replay. A large submission is recorded in chunks by several threads (`TOTK_REPLAY_WORKERS`, 0 by default: the sequential replay; 4 is a good value from 8 logical processors) and the chunks go to the queue in order (`vk_exec.c`). A sequential scan keeps a copy of the queue state where each chunk starts and lists what a chunk would otherwise learn from the chunks before it: inline uniform updates, conditions, contact shadow marches, uniform drops. It also makes render targets live in replay order and notes the op, since a chunk can sample a storage before the chunk that renders it got there or after the scan went past a later target there: a chunk's texture slots resolve as of its own op, and the chunks after a texture with no entry yet wait for the chunk that makes it. DLSS's decisions (the G-buffer, the light target, the end of the scene, the scaling pass) are the scan's too, and its copy of the lit scene and its evaluation are records of the chunk that holds the op; a chunk's draws are jittered while they come before the scan's end of the scene. The evaluation waits until the chunks before it are recorded, as it reads what their draws noted (the camera block, the jitter, the per-object motion list, which chunks add to under one lock), and the chunks after it wait for it, as they sample its output. `TOTK_REPLAY_STATE_CHECK=1` compares the state after the last chunk with the scan's.
|
||||
- Frame ahead. `TOTK_SYNC_AHEAD=1` (`sync_ahead`, off by default) makes the one `nvnSyncWait` per frame that waits for the frame presented last wait for the frame before it, so the game builds the next frame while the GPU still runs the previous one (`nvn_api_core.c`, `nvnSyncWait`). The game then writes memory that in-flight work still reads. Two forms guard that. With shadow storage (`vk_memory.c`, the CPU-visible pools are host-visible copies of guest memory, on by default on Linux and Wine, `shadow = 1` (`TOTK_SHADOW=1`) on native Windows) a CPU write reaches the GPU only through the shadow copy made before each submit (`vk_mem_shadow_sync`), and a copy that would overwrite bytes an unfinished submission reads is queued as a GPU copy in the prologue command buffer of the part submitted next (`vk_mem_shadow_prologue`, `TOTK_SHADOW_DEFER=1`, the default with the feature) or, with `=0`, waited for on the replay thread (`shadow_reader_wait`). Only that one wait lags (identified by its call site, known for 1.1.0, 1.2.1 and 1.4.3). GPU writes into pool storage come back with their fence, so a buffer the game reads back every frame after that wait holds the result of the frame before; a buffer it has not read lately holds none, and its `nvnMemoryPoolInvalidateMappedRange` waits for the write (`vk_mem_shadow_read`): TotK reads single pixels through a buffer per request, and in the Depths zeros in one of them put Link in gloom. The exit line `mem: the game waited for a GPU write it reads` counts these waits and their time. On 1.4.3 the patch set `qstamp` (`recomp/patches-v143.txt`) lets the game take its depth query results one frame older; it follows the switch and is off when the switch is refused. The fence write-back of small render targets (`vk_texture.c`, `write_back_n`) does not wait for the GPU with `TOTK_WB_EAGER=1` (`wb_eager`, the default, but only while frame-ahead is in effect: with `sync_ahead` off or refused the setting does nothing and the write-back reads the image when it runs): `vk_sync_submit` has `vk_texture_eager_record` copy the targets that value rendered into staging buffers inside the same command buffer, so once the value has passed the write-back only copies from staging into the target's storage. Only a target that was written back within the last 64 timeline values is copied (the first write-back of a target takes the blocking path), and the staging of a target past that window, no longer wanted or released goes through the deferred free (`vk_defer_buffer_until`). A snapshot is used only when its value is the one that last rendered the target, nothing recorded a write to the image since (`wr_fence`) and the GPU has finished it; otherwise the write-back reads the image as before, and the exit line `vk: wb_eager:` counts the reasons. With frame-ahead in effect the exit line `vk: fence write-backs waited for the GPU` counts the write-backs that waited for a copy and the time they waited, for every value of the setting. `check` also reads the old way and compares.
|
||||
- Frame ahead in place. Without shadow storage the GPU reads the game's own memory, as in Savage Wind's overlap, and `vk_ahead_init` (`runtime/vk_ahead.c`) turns on guards for what the GPU reads or writes there after the recording, each with a switch `TOTK_SYNC_AHEAD_<NAME>` (1 by default unless noted) for A/B runs. `MSYNC`: the VRAM mirrors' sync copies take the synced pages from a staging copy the replay thread makes at submit (`vk_memory.c` `stage_ranges`), not from guest memory when the GPU runs them; the frame wait returns only after the replay submitted the asked value, so those are that frame's bytes. A synced range that an earlier value still writes back into waits for that value first, or the copy would drop its GPU words. `WBMERGE`: every GPU write into a mirror goes back through the word merge (`wb_merge_record`), so a write-back that lands after the game wrote the range for the next frame puts back only the words the GPU changed. `DESWZ`: a texture the CPU rewrote after its last upload is deswizzled on the CPU (`upload_gpu`, reason `frame ahead`). `READS`: GPU writes into CPU-visible memory are listed with their value until it completes (bounded, `aw_add`), and an invalidate of a range not read lately waits for the writer's own value (`ahead_read`). `ONESHOT`: the frame wait waits up to the value that rendered a dirty small target not written back within the last 16 frames (Savage Wind's one-off rule, `vk_texture_oneshot`), so a photo or a pick reads its own frame, while targets read every frame or in turns get the frame before. `QUERIES` (0 by default): the same for samples-passed reports; TotK reads those two updates after it asks (1.2.1 `f_70010c3298`). With import memory (`TOTK_MEMORY=import`, the integrated-GPU mode) the GPU reads vertex, index and storage data in place, which no guard covers (a check run saw the game rewrite about 10 KiB of them a frame after the wait, particles mostly), so the switch is refused there without shadow storage. The exit lines `mem: sync-ahead in place` and `sync-ahead: frame waits made exact` give the guards' waits and copies. `TOTK_SYNC_AHEAD_CHECK=1` runs the detector below with the late wait itself.
|
||||
- Frame-ahead check. `TOTK_SYNC_AHEAD=check` keeps the frame wait exact and measures what a one-frame-late wait without shadow storage would race (`runtime/vk_ahead.c`). The replay notes, with each submission's value, every access of guest memory the GPU makes after the recording: in-place bindings of imported pools without a VRAM mirror (`VK_AHEAD_READ`), the mirror's sync copies (`vk_mem_mirror_prologue`), GPU deswizzle sources (`vk_texture.c` `upload_gpu`) and the mirror write-backs (`vk_mem_mirror_end`). At the frame wait for value A, whose late form would have waited for L, the notes of values in (L, A] form the frame's read set: merged per class, gap-joined into at most 512 write-watch queries that stamp the writes made so far into the shared page generations (`vk_mem_ahead_observe`). At the next frame-wait entry the queries run again, and every page of the set stamped since is a CPU write the late wait would have raced; memory without a write watch is compared by page hashes. GPU writes into CPU-visible memory and reports are listed with their value: an invalidate of a range written by a value in (L, A] of the last frame wait, and the fence write-back of a small target rendered by one, count as stale readbacks. One line `sync-ahead check:` per second of host time and a run summary with the largest offenders by pool at exit. `--probe-vkmem` checks the detector on a watched pool (`vk_ahead_selftest`); `tests/sync_ahead_check.py` checks that the wait stays exact.
|
||||
- Recorder thread. The Vulkan calls the replay makes into its command buffer are made by a thread of their own (`vk_rec.c`, after Savage Wind Recomp and LAS Recomp): each `vkCmd*` copies its arguments into a packet of a ring and the recorder makes the calls in order; calls into other command buffers are made at once; the recorder also ends the command buffer, and the submit waits until it has. In the town on an RX 9070 the replay takes 17% less time on the submitting thread. It is off by default on AMD GPUs, where the driver loses the device or hangs the GPU at startup with it (`TOTK_VK_RECORDER=1` forces it on, `=0` makes every call on the submitting thread).
|
||||
- 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
|
||||
binds from CPU-written pools is copied, and the draws bind the copy (`vk_usnap.c`, after MacNativeGames'
|
||||
`TOTK_UBO_SNAPSHOT`); without it, late draws read another object's matrix.
|
||||
- Uniform updates. `nvnCommandBufferUpdateUniformBuffer` between the draws of a pass is replayed as an overlay: the
|
||||
bytes go to scratch memory, later bindings of the range bind them, and the copies into the game's buffers are
|
||||
recorded behind one barrier when the pass ends (`vk_exec_draw.c` `op_update_ub`, `TOTK_UB_OVERLAY`). A copy at the
|
||||
update itself would end the pass with a full barrier, which the terrain paid before most of its draws.
|
||||
- Driver data. The NVN driver keeps a per-stage constant bank (c0) that shaders read for things like point size, dispatch size and base instance. The back end fills it the way the driver does.
|
||||
- Shaders: the Ryujinx translator 1.3.2 with MacNativeGames' patches and ours (`tools/xlate/patches/`), built with .NET 10 NativeAOT as `totk_xlate.exe` and run as a separate process. Its SPIR-V goes to Vulkan directly. `tools/prepare_shaders.py` and `totk.exe --prepare-shaders` translate and compile the variants of MacNativeGames' shared list ahead of play (29,587 for 1.4.3); the rest are translated on first use and cached on disk.
|
||||
- Pipelines: `VK_EXT_graphics_pipeline_library` where the driver has it. Shader stages are compiled ahead into libraries; a draw that meets a new state links them at once (fast link), and an optimised pipeline replaces the linked one when a background thread finishes it. Pipeline keys seen in play are saved and built at boot. A draw whose pipeline is not ready is skipped when one of its pass's targets was rendered in the previous frame, and waits otherwise, so one-shot passes are never lost; a full-screen draw is skipped as well rather than waiting (`TOTK_PIPE_SKIP`); the stage libraries a waiting draw needs are built on idle workers in parallel (`TOTK_PIPE_WAIT`). Without the extension, a missing pipeline is built on a worker and the draw waits or is skipped by the same rule.
|
||||
@@ -94,13 +109,36 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app
|
||||
(MacNativeGames' sites); `resolution.c` sets them from `output_res` and `render_scale` and grows the texture heap
|
||||
and the application pool to match. When the window is larger than the output, `vk_fsr.c` runs AMD FSR 1 (EASU,
|
||||
RCAS) on the present. An `output_res` that is not 16:9 (more than 1% off, `res_is_16x9`) also switches on the
|
||||
`aspect` patch set (1.4.3 only), which hands the output's ratio to the camera, and `romfs.c` `overlay_init` loads 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 four sizes: 2560x1080, 3440x1440, 3840x1600, 5120x2160). Other
|
||||
shapes, such as 16:10 or 32:9, get the wide camera and the 16:9 HUD stretched over it. 1.2.1 has no camera patch: a
|
||||
wide size there keeps the 16:9 view. 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
|
||||
into another float target, and a last draw copies that into the 8-bit sRGB window texture it presents. With HDR on,
|
||||
the tonemap's fragment shader (recognised by its constants and resource names, not a hash) runs as
|
||||
`shaders/hdr_tonemap.frag`, which keeps highlights up to the display's peak; the present reads the float target the
|
||||
window texture was copied from (any other last draw into it, such as a menu or a movie, leaves the window texture,
|
||||
shown at the HUD's white); a compute pass turns the picture into PQ code values in Rec. 2020 for an HDR10
|
||||
swapchain, which FSR 1 or the blit then scale; the in-game menu is drawn into an RGBA8 image and blended on at the
|
||||
HUD's white. Without an HDR10 surface format (Windows with "Use HDR" off, a compositor without colour management)
|
||||
the swapchain stays SDR. `TOTK_SHOTS` reads the window texture, so its pictures clip highlights in HDR.
|
||||
- DLAA (`vk_dlaa.c`, `dlaa`, off by default). NVIDIA DLSS at the scene's own size, through the driver's NGX core loaded
|
||||
at run time (no SDK code compiled in). It runs on the R11G11B10F light target right before the bloom chain's first
|
||||
pass, so post effects and the HUD read the anti-aliased picture. The scene's draws get a sub-pixel Halton viewport
|
||||
jitter; camera motion vectors are reprojected from the scene depth through this and last frame's view-projection of
|
||||
the scene camera block (constant bank c4), in double precision on the CPU. Per-object motion (`dlaa_objmv`,
|
||||
`vk_mvprev.c`, the per-object section of `vk_exec_draw.c`, translator patch 0015): solid scene draws whose position
|
||||
reads an object's own uniform blocks (bones c5, place c7, c6) are drawn a second time with a vertex shader variant
|
||||
that computes last frame's position from last frame's blocks (the game writes them into two copies that take turns;
|
||||
the uniform snapshot keeps both) and writes the difference into the motion image. `TOTK_MV_CHECK` measures the
|
||||
vectors against the picture, `TOTK_DLAA_TIMES` times the passes on the GPU. `fxaa` switches the game's own FXAA pass.
|
||||
- Occlusion queries never block the CPU; a result that is not ready counts as visible.
|
||||
- ASTC textures are uploaded as they are where the device reports `textureCompressionASTC_LDR`, and decoded by a compute shader everywhere else (`vk_astc.c`, `TOTK_ASTC`). The CPU decoder (`tex_astc*.c`) is the fallback and the test oracle.
|
||||
- Draw state. A draw whose program, bound state and textures repeat reuses the previous draw's shaders and skips rebuilding its descriptor sets; descriptor sets are written through update templates (`vk_exec_draw.c`, `vk_pipeline.c`).
|
||||
|
||||
+146
-13
@@ -1,7 +1,9 @@
|
||||
# Building from source
|
||||
|
||||
Windows 10 or later, an x86-64 CPU with AVX2, and a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`. Allow about
|
||||
60 GB for the work folder. Extraction wants about 55 GB free while it runs and keeps about 35 GB afterwards.
|
||||
Windows 10 or later, an x86-64 CPU with SSE4.2, and a GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`. The
|
||||
default build targets x86-64-v3 (AVX2/FMA); a CPU without them builds with `--cpu v2` instead and runs slower (see
|
||||
"Build"). Allow about 60 GB for the work folder. Extraction wants about 55 GB free while it runs and keeps about 35 GB
|
||||
afterwards.
|
||||
|
||||
Players who only want to play can use the [installer](installer.md) instead: it builds the game on their machine
|
||||
without this toolchain.
|
||||
@@ -37,20 +39,23 @@ PATH:
|
||||
|
||||
### hactool
|
||||
|
||||
`tools/build_hactool.py` fetches SciresM/hactool at `1d64a83` into `toolchain\src\hactool`, applies the two patches in
|
||||
`tools/build_hactool.py` fetches SciresM/hactool at `1d64a83` into `toolchain\src\hactool`, applies the three patches in
|
||||
`tools/hactool/` and builds a static `toolchain\hactool\hactool.exe` with MSYS2 UCRT64 gcc (a few seconds):
|
||||
|
||||
- `portable.patch`: the parts of MacNativeGames' `build_hactool()` that run on Windows, the `MNG_TITLE_KEYS` variable and
|
||||
the two BKTR fixes in `nca.c` for the subsection table padding and the subsection layout of newer cumulative updates;
|
||||
- `unicode.patch`: a manifest with `<activeCodePage>UTF-8</activeCodePage>`, so paths under a non-ASCII user profile
|
||||
reach it intact.
|
||||
reach it intact;
|
||||
- `mbedtls-asm-clobbers.patch`: the `memory` and `cc` clobbers the bundled mbedtls 2.6.1's x86-64 multiply asm lacks.
|
||||
Without them a clang build (the Linux release) fails every RSA signature check and the update merge stops.
|
||||
|
||||
hactool reads `-k <prod.keys>`; MSYS2 shells set `HOME`, which hides its default key location, so pass `-k` there.
|
||||
|
||||
## Build
|
||||
|
||||
From the repository root, in PowerShell. Every step that depends on the game version takes it as `<ver>`: `v143` for
|
||||
1.4.3 or `v121` for 1.2.1. The tools default to `v121` when `--version` is left out. Saves load on either version.
|
||||
1.4.3, `v121` for 1.2.1 or `v110` for 1.1.0. The tools default to `v121` when `--version` is left out. Saves load on any
|
||||
of them.
|
||||
|
||||
1. Python environments (once). `.venv` runs the lifter and the build; `.venv-py314` runs the extraction scripts, which
|
||||
need the stdlib `compression.zstd` of Python 3.14:
|
||||
@@ -66,19 +71,22 @@ From the repository root, in PowerShell. Every step that depends on the game ver
|
||||
keys file. `config.local.toml` is ignored by git. The tools read the keys file themselves.
|
||||
|
||||
3. Extract and verify. This writes `build\extracted\v0` (1.0.0) and `build\extracted\<ver>` for each update in
|
||||
`updates`, identified by its hash; a hash mismatch stops the run:
|
||||
`updates`, identified by its hash; a hash mismatch stops the run. With another `[work] dir` in `config.local.toml`,
|
||||
`extracted` goes there instead, and `build_game.py` reads the ExeFS and RomFS from there:
|
||||
|
||||
```powershell
|
||||
.venv-py314\Scripts\python tools\extract.py
|
||||
```
|
||||
|
||||
4. Shader translator (once; no game files). This publishes `build\xlate\totk_xlate.exe`:
|
||||
4. Shader translator (no game files; again after a change to its sources, and `tools\make_release.py` stops on an older
|
||||
one). This publishes `build\xlate\totk_xlate.exe`:
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python tools\build_xlate.py
|
||||
```
|
||||
|
||||
5. Lift the modules to C, write the RomFS half of the frame-rate patches, then compile and link `build\<ver>\totk.exe`:
|
||||
5. Lift the modules to C, write the RomFS overlay (the frame-rate fix), then compile and link
|
||||
`build\<ver>\totk.exe`:
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python recomp\gen.py --exefs build\extracted\<ver>\exefs --out generated\<ver> --patches recomp\patches-<ver>.txt
|
||||
@@ -86,12 +94,55 @@ From the repository root, in PowerShell. Every step that depends on the game ver
|
||||
.venv\Scripts\python tools\build_game.py --version <ver>
|
||||
```
|
||||
|
||||
`--cpu v2` targets x86-64-v2 (SSE4.2, no AVX2/FMA) for older CPUs; the default `v3` needs AVX2. The v2 build links
|
||||
`runtime/fma.c`, a correctly rounded software fma the FP lowering needs, and runs slower. Inline assembly,
|
||||
target attributes and intrinsics are not bound by `-march`, so a v2 build runs `tools/check_isa.py` over the runtime
|
||||
objects before it links: any AVX, BMI or other instruction above x86-64-v2 outside a function listed there as
|
||||
dispatched by a runtime CPU check stops the build.
|
||||
|
||||
`gen.py` sizes its emit pool from the CPU count and the free memory; `--jobs N` sets it, and so does the environment variable `TOTK_LIFT_JOBS=N`, which the installer's lift step honours too (it has no `--jobs`). When a worker runs out of memory, the pool restarts with half the workers (`emit: out of memory with N workers, retrying with M`), down to one; only an out-of-memory error with one worker fails the step. A later lift into the same `--out` lifts again only the chunks whose inputs changed (`<mod>/lift_cache.json`, see the top of `recomp/gen.py`); `--no-cache`, or `TOTK_LIFT_CACHE=0` (which the installer's lift step honours too), lifts every chunk.
|
||||
|
||||
Lifting takes about 15 s, a clean compile about 200 s on 24 threads; later builds recompile only what changed.
|
||||
A compiler cache in front of clang shortens it further: with `SCCACHE` set to an sccache executable, `build_game.py`
|
||||
writes it into the ninja file ahead of `cc`, and every lift rewrites the generated chunks with the same contents, so
|
||||
a second build of the same version hits all of their objects:
|
||||
|
||||
```powershell
|
||||
$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` once more with `--xbox-prompts`: it writes
|
||||
`build\<ver>\romfs-patches-xbox` ([controls.md](controls.md), "Xbox button prompts"); `build_game.py` copies it next
|
||||
to `totk.exe` like `romfs-patches`.
|
||||
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 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`)
|
||||
for the shared shader list:
|
||||
@@ -103,8 +154,14 @@ From the repository root, in PowerShell. Every step that depends on the game ver
|
||||
Without this step the first launch compiles shaders and pipelines during play and stutters until the caches fill.
|
||||
The AMD driver keeps its pipeline cache per exe path and holds a limited amount: preparing another build folder can
|
||||
evict this one's. `totk.exe --warm-shaders` rebuilds it from the shader cache.
|
||||
When the driver's shader compiler crashes on a variant (NVIDIA 615.78.08 on an RTX 5080 does, issue #30),
|
||||
`prepare_shaders.py` runs the driver step again with `--warm-shaders`, up to three times, without the variants the
|
||||
driver was building at the crash. `shader-prepare-skip.txt` next to the exe lists them with the GPU and driver
|
||||
version; they build at their first draw instead, another driver version builds them again, and so does deleting the
|
||||
file.
|
||||
|
||||
7. Run. Keep the window in the foreground; an unfocused window stalls the game.
|
||||
7. Run. The game keeps running when its window loses the focus (`assume_focus = 1` in `totk.ini`, the default; the
|
||||
Game tab switches it). With 0 it pauses, as it does on the Switch when Home is pressed.
|
||||
|
||||
```powershell
|
||||
build\<ver>\totk.exe
|
||||
@@ -120,6 +177,54 @@ your machines without MSYS2, Python or .NET. `romfs.bin` stays out unless you pa
|
||||
`romfs\` next to the exe or point `TOTK_ROMFS` at its folder. Run `totk.exe --prepare-shaders` once in the copied
|
||||
folder. The folder holds code and data derived from your game: for your own machines only.
|
||||
|
||||
### Profile-guided build
|
||||
|
||||
`build_game.py --pgo <file>.profdata` compiles the generated code and the runtime at -O2 with an execution
|
||||
profile, 6-12% shorter frames. Which build uses which profile, when to retrain, where and how to train and how to
|
||||
measure a new profile: [pgo.md](pgo.md).
|
||||
|
||||
## Linux (in progress)
|
||||
|
||||
The runtime builds and runs on x86-64 Linux with a window, input and menu on SDL3 (`*_sdl.c`) in place of the Win32
|
||||
files (`*_win.c`); `runtime/platform/linux.c` implements `platform.h`. Status: the selftest and the probes pass; 1.2.1
|
||||
plays at 60 fps on RADV (RX 7800 XT) and NVIDIA (RTX 3060); 1.4.3 builds, probes and plays on RADV (RX 6600, and the
|
||||
Vega 7 of a Ryzen 5 4600G at about 34 fps). Long play sessions and the Steam Deck itself are not verified yet.
|
||||
|
||||
Requirements:
|
||||
|
||||
- Linux 6.7 or later: the write watch uses userfaultfd write protection with `PAGEMAP_SCAN`. SteamOS 3.8 qualifies.
|
||||
- A Vulkan 1.3 driver with `VK_EXT_external_memory_host` (RADV, NVIDIA).
|
||||
- Packages on Arch:
|
||||
|
||||
```sh
|
||||
pacman -S --needed clang lld ninja make sdl3 opus libvpx zstd vulkan-headers vulkan-icd-loader \
|
||||
vulkan-validation-layers shaderc spirv-tools dotnet-sdk uv git
|
||||
```
|
||||
|
||||
Vulkan Memory Allocator is a single header (AUR `vulkan-memory-allocator`). Without it, `build_game.py` fetches the
|
||||
version the Windows release pins (3.4.0) into `toolchain/vma/` on first use and checks its hash.
|
||||
|
||||
The steps are the Windows ones with POSIX paths: `.venv/bin/python` in place of `.venv\Scripts\python`, and `totk` in
|
||||
place of `totk.exe`. `build_game.py` takes clang, lld and Ninja from PATH (or the ones in `<dir>/bin` with
|
||||
`--toolchain <dir>`) and links against the system libraries, with `libstdc++` static and an `$ORIGIN` rpath;
|
||||
`build_hactool.py` builds `hactool` with make. `tools/prepare_shaders.py` reads the shader list from
|
||||
`refs/MacNativeGames` at `origin/HEAD`, which must be the pinned commit with its history (the list format changed later).
|
||||
|
||||
The probes open a window, so from an SSH session they need the desktop session's display, or they stop at `gpu 0
|
||||
skipped: no graphics+compute+present queue family`: on Wayland `XDG_RUNTIME_DIR=/run/user/$(id -u)
|
||||
WAYLAND_DISPLAY=wayland-1 SDL_VIDEODRIVER=wayland` (the socket name is in `$XDG_RUNTIME_DIR`), on X11 `DISPLAY=:0`.
|
||||
|
||||
Memory: on Windows the GPU imports guest memory and `GetWriteWatch` tracks the CPU's writes to it. On Linux,
|
||||
re-protecting imported memory invalidates the driver's userptr buffer on every submit (about 1.3 ms per 16 MiB on
|
||||
amdgpu), and importing pins the pages, which drops their write protection. Each CPU-visible pool therefore gets a
|
||||
host-visible copy (shadow storage, `runtime/vk_memory.c`): the pages the CPU wrote go in before each submit, and the GPU's
|
||||
writes come back at its fence. In play that costs about 0.2 ms a frame and doubles the memory of those pools (about
|
||||
1.1 GB). `shadow = 1` in `totk.ini` (or `TOTK_SHADOW=1`) turns it on under Windows too. The Steam Deck's RADV has `VK_EXT_external_memory_host` as
|
||||
well: the shadow copies are chosen for the measured cost above, not for a missing extension.
|
||||
|
||||
The Deck's GPU (Van Gogh) has no native ASTC, so its textures go through the compute decoder (`runtime/vk_astc.c`,
|
||||
`TOTK_ASTC`) as on desktop AMD GPUs without it; frame times measured there include it.
|
||||
|
||||
## Checks
|
||||
|
||||
Before a commit:
|
||||
@@ -128,6 +233,29 @@ Before a commit:
|
||||
`git config core.hooksPath .githooks` runs it before each local commit.
|
||||
- `build\<ver>\totk.exe --selftest`: layout, dispatch table and host-function registry, without game files.
|
||||
|
||||
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).
|
||||
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
|
||||
(`runtime/cheats.c`, `tools/cheats.py`) passes `.venv\Scripts\python tests\cheats_vm_check.py`, which runs both on
|
||||
cheats of its own with clang from PATH (`--cc` names another). A change to what a generated chunk depends on, or to
|
||||
the lift cache of `recomp/gen.py` (`<mod>/lift_cache.json`), passes `.venv\Scripts\python tests\lift_cache_test.py`,
|
||||
which lifts a module it makes itself with and without the cache and compares the output (no game files); a new input
|
||||
of the chunk text goes into `chunk_key` with a case there. On game files, a lift with the cache into a used output
|
||||
folder and a `--no-cache` lift into an empty one give the same files apart from `manifest.json` and
|
||||
`lift_cache.json`.
|
||||
|
||||
The lifter (`recomp/`) and the CPU headers (`runtime/cpu.h`, `runtime/simd.h`) are checked against Unicorn. Every lifter
|
||||
change passes these, all run with `.venv`:
|
||||
|
||||
@@ -141,8 +269,13 @@ change passes these, all run with `.venv`:
|
||||
| `tests\excl_mt.py` | the exclusive monitor helpers under contention and ABA, on several threads | no |
|
||||
| `tests\jumptables_check.py` | `recomp/jumptables.py` against a Unicorn oracle; must report 0 disagreements, on 1.4.3 too | yes |
|
||||
|
||||
A `--cpu v2` build passes the same differential tests with `--cflags=-march=x86-64-v2`; they compile `runtime/fma.c`
|
||||
too, so they check the software fma the v2 build links rather than the C runtime's.
|
||||
|
||||
Runtime probes, each a mode of `totk.exe` (the list is at the top of `runtime/main.c`): `--probe-kernel`,
|
||||
`--probe-vkexec`, `--probe-nvn-tex` and `--probe-shader` cover most runtime changes.
|
||||
`--probe-vkexec`, `--probe-nvn-tex` and `--probe-shader` cover most runtime changes. `--probe-shader` and the draw
|
||||
part of `--probe-vkexec` translate shaders of the census below: they look for `build/<ver>/shaders/jobs.json` of the
|
||||
exe's own version first, then of the other one.
|
||||
|
||||
Shaders: `.venv-py314\Scripts\python tools\shader_census.py --version <ver> --translate` extracts every Maxwell shader
|
||||
to `build\<ver>\shaders\` and runs it through the translator and `spirv-val`; failure groups go to `failures.txt`.
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# Cheats
|
||||
|
||||
The port reads Atmosphère cheat files, the format Switch homebrew and the emulators use. It ships no cheat files: a cheat file goes into a mod in the `mods` folder next to `totk.exe`, like any other mod ([mods.md](mods.md)). Open the menu (F1) and switch the cheats on the Cheats tab. The switches are saved under `[cheats]` in `totk.ini`.
|
||||
|
||||
## Adding a cheat file
|
||||
|
||||
1. Find the cheat file for your update. Cheat sites and collections name it after the first 8 bytes of the game's build id:
|
||||
|
||||
| Update | File |
|
||||
|---|---|
|
||||
| 1.2.1 | `9B4E43650501A4D4.txt` |
|
||||
| 1.4.3 | `277178B7DBA1B6D4.txt` |
|
||||
|
||||
The Cheats tab names the file the installed game reads when no mod holds one, and `logs\totk.log` says `cheats: no enabled mod holds cheats/<id>.txt`.
|
||||
2. Put it in the `cheats` folder of a mod, a folder of its own under `mods`:
|
||||
|
||||
```
|
||||
mods\
|
||||
My cheats\
|
||||
cheats\
|
||||
277178B7DBA1B6D4.txt
|
||||
```
|
||||
|
||||
A download laid out for the Switch's SD card or an emulator works as it is: unpack it into a folder of its own under `mods`, and the port finds `atmosphere\contents\0100F2C0115B6000\cheats`, `contents\0100F2C0115B6000\cheats` or `0100F2C0115B6000\cheats` inside it. The file name's case does not matter.
|
||||
3. Start the game. Cheats that write the game's memory work now.
|
||||
4. Cheats that change the game's code need the game rebuilt with them. When the game starts and finds such cheats it did not build, it opens the setup's rebuild window, which builds them in (a few minutes; the shaders stay prepared) and starts the game again. Until then they are greyed out with "after the rebuild". When the rebuild fails or you cancel it, the game starts without them and does not try again for the same cheats; "Rebuild the game now" on the Cheats tab tries again. `mods_rebuild = off` under `[mods]` in `totk.ini` turns the automatic rebuild off; running `TotK-Setup.exe` on the same folder does the same job by hand. Saves and settings are kept.
|
||||
5. Switch the cheats on the Cheats tab of the menu.
|
||||
|
||||
The Cheats tab lists the cheats grouped by mod, in the order of the Mods tab. A mod switched off on the Mods tab, or one the port cannot use, contributes no cheats; the change applies at the next start. The Mods tab says how many cheats each mod brought.
|
||||
|
||||
## The file format
|
||||
|
||||
Standard Atmosphère: a `[name]` line starts a cheat, `{name}` a master cheat that is always on, and the cheat's opcodes follow as 8-digit hex words. A name with no opcodes is shown as a heading. The file's title line (the one with `TID=`) is not shown.
|
||||
|
||||
```
|
||||
[The Legend of Zelda: Tears of the Kingdom v1.4.3 TID=0100F2C0115B6000 BID=277178B7DBA1B6D4]
|
||||
|
||||
[Player]
|
||||
[A code cheat]
|
||||
040A0000 XXXXXXXX YYYYYYYY
|
||||
|
||||
[A data cheat (Hold ZL+X)]
|
||||
80000104
|
||||
580F0000 XXXXXXXX
|
||||
640F0000 00000000 YYYYYYYY
|
||||
20000000
|
||||
```
|
||||
|
||||
The words above are placeholders: `XXXXXXXX` an offset, `YYYYYYYY` a value.
|
||||
|
||||
Each cheat's switch is `cheat_<hash> = 1`, where the hash is FNV-1a 32 of `<mod folder name>/<cheat name>`. A name repeated in one file gets `#2`, `#3` and so on. The build names each code cheat the same way, so renaming a mod's folder resets its cheats' switches to off and makes the next start rebuild its code cheats. Rename the folder before you switch its cheats on.
|
||||
|
||||
## How cheats run
|
||||
|
||||
The game's code is compiled ahead of time, so a cheat cannot write new instructions into it while the game runs. The port sorts each cheat by what it writes (`tools/cheats.py` at setup, `runtime/cheats.c` in game):
|
||||
|
||||
| Kind | What the cheat does | How the port runs it |
|
||||
|---|---|---|
|
||||
| code | Opcode 0 writes into main's code | Built into the game at setup as a patch set (`recomp/patches.py`); switches at once. |
|
||||
| key | Code writes inside a button condition (`8` mask, writes, `21` else, the original words, `20`) | A patch set that is on while the cheat is on and the buttons are held. |
|
||||
| data | Writes data only: heap, main's data, pointer chains, button conditions | Runs in a cheat VM after dmnt's, opcodes 0 to A and C0 to C3, every presented frame while on. |
|
||||
| master | `{name}` with code writes | A patch set that is always on. |
|
||||
| restore | Writes back only the game's original instructions | Not needed: switching a cheat off restores them. Greyed out. |
|
||||
|
||||
A cheat whose code writes call or jump into a code cave the cheat writes itself (into main's zero padding) gets the cave inlined at the call site. The setup builds the code cheats of every mod in the `mods` folder, switched on or off, so switching a mod on later needs only a restart. A code cheat added or edited after the last build waits for the rebuild; a data cheat runs at the next start.
|
||||
|
||||
Not supported, and shown greyed out with the reason:
|
||||
|
||||
- opcode C4 (extended button condition) and the 0xF extensions (FF0 pause, FF1 resume, FFF debug log);
|
||||
- opcode 5 with a register offset;
|
||||
- code writes mixed with other opcodes, except the button pattern above;
|
||||
- code writes that change the CPU flags differently from the game's instruction, or code caves with branches or pc-relative instructions.
|
||||
|
||||
`build-cache\cheats.status` next to `totk.exe`, written by the setup, records which cheats were built and how; the log line `cheats: ...` sums them up at start. When the code cheats cannot be built, the setup warns and installs the game without them.
|
||||
+269
-18
@@ -7,15 +7,14 @@ Input comes from the first SDL3 gamepad, the keyboard and the mouse, merged into
|
||||
- `nintendo`: by position, as on a Switch (the table below).
|
||||
- `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.
|
||||
- `xbox_prompts`: the buttons as `nintendo`, and the game's prompts name the Xbox labels (see Xbox button prompts below).
|
||||
|
||||
The log names the layout in effect (`input: gamepad layout ...`); the menu shows it under *Automatic*. With `nintendo`, `xbox` and `auto` the game's button prompts stay Switch letters; `xbox_prompts` changes them.
|
||||
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 |
|
||||
|---|---|---|---|
|
||||
| Left stick | left stick | W A S D | move |
|
||||
| Right stick | right stick | mouse; arrow keys as a second source | camera |
|
||||
| Y | west | left mouse button | attack |
|
||||
| Y | west | left mouse button, T | attack |
|
||||
| ZL | left trigger (over 50%) | right mouse button, Z | shield, lock on |
|
||||
| ZR | right trigger (over 50%) | F, X | bow |
|
||||
| X | north | Space | jump |
|
||||
@@ -28,44 +27,98 @@ The log names the layout in effect (`input: gamepad layout ...`); the menu shows
|
||||
| D-pad left, up, right, down | D-pad | 1 2 3 4 | quick-select |
|
||||
| Plus | Start | Tab | menu, inventory |
|
||||
| Minus | Back | M | map |
|
||||
| Right stick shaken left and right | shake the right stick | G | detach a fused part from what Ultrahand holds |
|
||||
|
||||
Esc is unbound in the game; it opens the settings menu and releases the mouse cursor (see Mouse camera). Z and X duplicate ZL and ZR so menu pages turn with two neighbouring keys; the menu tabs (L, R) are Q and R. The mouse wheel is unbound. The bindings are the tables of `input_map` in `runtime/input_map.c`: the keys (platform-neutral key ids) and one gamepad table per layout (gamepad inputs by position); `runtime/input_win.c` translates Win32 virtual keys and SDL buttons.
|
||||
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
|
||||
|
||||
`pad_layout = xbox_prompts` (*Xbox prompts (A right)* on the Controls tab) is for an Xbox pad played by position. The buttons work as with `nintendo`: the right button, labelled B, does Switch A (interact, confirm), and the bottom one, labelled A, does Switch B (run, cancel). The letters the game shows are swapped to match the labels, A with B and X with Y, so each prompt names the button to press. The other layouts leave the prompts alone: with `xbox` the Switch letters already match the labels.
|
||||
`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).
|
||||
|
||||
The swapped letters are part of the game's textures, fonts 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 letter the game draws for it, and the prompt then names the wrong button. Use `xbox_prompts` with the default bindings.
|
||||
- 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.
|
||||
|
||||
The buttons change at once, but the game reads its UI archive and fonts once at boot, so the prompts change at the next start (the menu says *prompts change after restart*). `xbox_prompts` loads `romfs-patches-xbox` next to `romfs-index.bin` in place of `romfs-patches` (`runtime/romfs.c`, `overlay_init`): the same 60 fps patches, with the swap made from the game's own files by `tools/make_romfs_patches.py --xbox-prompts`, which the setup runs next to the plain one:
|
||||
| Switch | `nintendo` layout | `xbox` or `auto` layout |
|
||||
|---|---|---|
|
||||
| A, B, X, Y | B, A, Y, X | A, B, X, Y |
|
||||
| L, R | LB, RB | LB, RB |
|
||||
| ZL, ZR | LT, RT | LT, RT |
|
||||
| Plus, Minus | Menu, View | Menu, View |
|
||||
| D-pad | cross | cross |
|
||||
|
||||
- the action prompt (`DoCommand_00`) draws the letter images `Nt_KeyTexA/B/X/Y_00`, whose image data is swapped, in a diamond that names the other face buttons. 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); both are swapped. The diamond's shape shows the button's position and stays.
|
||||
- every other prompt is text in the button font (`scft/External.bfotf` in each `Font/Font*.Nin_NX_NVN.bfarc.zs`, glyphs U+E040 to U+E043); the A and B, X and Y glyphs are swapped.
|
||||
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).
|
||||
|
||||
Without the folder (an install made by an older setup, or one where the setup could not prepare it and showed a warning) the menu says the files are missing, the log has `RomFS overlay: pad_layout = xbox_prompts, but ...`, and the Switch prompts stay; running the setup again on the install folder writes it. In a source build, `.venv-py314\Scripts\python tools\make_romfs_patches.py --version <ver> --xbox-prompts` writes `build\<ver>\romfs-patches-xbox`.
|
||||
### 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.
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
`prompts = pc` (*PC* on the *Button prompts* row) shows the key or mouse button the default keyboard bindings press each Switch button with, whatever the pad layout. The game loads `romfs-patches-pc` in place of `romfs-patches`, written by `tools/make_romfs_patches.py --prompts pc` (`button_icons.py`, `pc_icons`), which the setup runs next to the Xbox ones:
|
||||
|
||||
| Switch | Prompt |
|
||||
|---|---|
|
||||
| A, B, X, Y | E, Shift, Space, left click (T in text prompts) |
|
||||
| L, R, ZL, ZR | Q, R, right click, F |
|
||||
| Plus, Minus | Tab, M |
|
||||
| D-pad | 1 (left), 2 (up), 3 (right), 4 (down), as a cross or the keys of the directions meant |
|
||||
| Left stick, its press | W A S D (or the keys of the directions meant), Ctrl |
|
||||
| Right stick, its press | the mouse, with an arrow for each direction meant, C |
|
||||
|
||||
- The glyphs keep the width of the game's own, so the right-aligned guides do not run into their text. A key is a rounded square with its label cut out in the game's own text fonts (Shift: an arrow over its name); a mouse button is a mouse with that button filled and the others hollow.
|
||||
- The button guide in play draws every button from images of the Common archive (`Nt_KeyTexA/B/X/Y/L/ZL_00`, `Nt_KeyTexLSt_00` and `_01`, the stick tilted and pressed): all of them are painted with the same icons. The letters of the action prompt's diamond are one character of the Normal font each: E, an arrow for Shift, a bar for Space, L and R for the mouse buttons.
|
||||
- Y has two keys, the left mouse button and T. The button guide in play and the action prompt show the left button, which attacks there; the prompts in text (the menus' guides such as *Sort*, the dialogue log's) show T, because while a menu has the pointer the left button is that menu's A, and T presses Y everywhere (`PC_TEXT_KEYS` in `tools/button_icons.py`). With a `bind_y` line, the text prompts take its first key that is not a mouse button (its only key when all are mouse buttons).
|
||||
- They follow the bindings of the install's `totk.ini` as the setup found them: its *Drawing the keyboard and mouse prompts* step passes the file as `--binds` (the first key of each `bind_` line), and the keyboard defaults without one. After a change on the Controls tab run the setup again: that step alone runs, since it is keyed by the `bind_` lines (`PcPrompts` in `installer/steps.py`). The Xbox prompts follow the defaults.
|
||||
- At a game resolution of another shape than 16:9 the game loads `romfs-patches-pc-<w>x<h>` in place of `romfs-patches-<w>x<h>`: the same prompts with that shape's UI layout, `make_romfs_patches.py --prompts pc --aspect <w>x<h> --reuse <install>\romfs-patches-pc --out <install>\romfs-patches-pc-<w>x<h>`. The setup writes one for each of the fifteen sizes it lays the UI out for, 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*).
|
||||
|
||||
## Window keys
|
||||
|
||||
| Key | Gamepad | Action |
|
||||
|---|---|---|
|
||||
| F1 or Esc | Minus and Plus together | open or close the settings menu; the game gets no input while it is open |
|
||||
| F10 | | performance overlay: off, frame rate, full panel |
|
||||
| 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).
|
||||
|
||||
## Remapping
|
||||
|
||||
The *Controls* tab of the settings menu lists, under the button layout, every Switch button and the eight stick directions the keys drive (movement and camera), each with two key cells and a controller cell. Select a cell, press A or Enter, then press the new key, mouse button or controller button; Esc or five seconds without a press cancel, and a controller button cancels a key cell. Delete, Backspace or X clears the selected cell. A key another action has moves to the new one (the description names the action it left); a controller button swaps with the one it replaces. A remapped controller button is physical: from then on the face buttons (A B X Y) stay where they are in both layouts, until the buttons are put back as the layout in use has them or *Reset all buttons* is chosen. F1, F8, F10, F11 and Esc cannot be bound (the menu, the flight recorder and the window keep them). Punctuation keys are named by their place on a US keyboard; the menu shows the character the keyboard layout in use puts there.
|
||||
The *Controls* tab of the settings menu lists, under the button layout, every Switch button, the eight stick directions the keys drive (movement and camera) and the shake key, each with two key cells and a controller cell. Select a cell, press A or Enter, then press the new key, mouse button or controller button; Esc or five seconds without a press cancel, and a controller button cancels a key cell. Delete, Backspace or X clears the selected cell. A key another action has moves to the new one (the description names the action it left); a controller button swaps with the one it replaces. A remapped controller button is physical: from then on the face buttons (A B X Y) stay where they are in both layouts, until the buttons are put back as the layout in use has them or *Reset all buttons* is chosen. F1, F8, F10, F11 and Esc cannot be bound (the menu, the flight recorder and the window keep them). Punctuation keys are named by their place on a US keyboard; the menu shows the character the keyboard layout in use puts there.
|
||||
|
||||
The tab writes `totk.ini` lines, one per Switch button or stick direction: `bind_<button> = <entry>, <entry>, ...`. The button is `A B X Y L R ZL ZR PLUS MINUS LEFT UP RIGHT DOWN LCLICK RCLICK`, or a stick direction `LSTICK_LEFT LSTICK_UP LSTICK_RIGHT LSTICK_DOWN` (movement, W A S D by default) and `RSTICK_...` (camera, the arrow keys). An entry is `pad:<name>` or `key:<name>`:
|
||||
The tab writes `totk.ini` lines, one per Switch button or stick direction: `bind_<button> = <entry>, <entry>, ...`. The button is `A B X Y L R ZL ZR PLUS MINUS LEFT UP RIGHT DOWN LCLICK RCLICK`, or a stick direction `LSTICK_LEFT LSTICK_UP LSTICK_RIGHT LSTICK_DOWN` (movement, W A S D by default) and `RSTICK_...` (camera, the arrow keys), or `SHAKE` (keys only, G by default). An entry is `pad:<name>` or `key:<name>`:
|
||||
|
||||
- pad names: `south east west north l r zl zr start back lstick rstick dpad_left dpad_up dpad_right dpad_down lpaddle1 rpaddle1 lpaddle2 rpaddle2` (`zl`, `zr` are the triggers; the paddles are the back buttons of an Xbox Elite, DualSense Edge or Steam Controller, upper pair 1, lower pair 2, and no Switch button has them by default)
|
||||
- pad names: `south east west north l r zl zr start back lstick rstick dpad_left dpad_up dpad_right dpad_down lpaddle1 rpaddle1 lpaddle2 rpaddle2 touchpad` (`zl`, `zr` are the triggers; the paddles are the back buttons of an Xbox Elite, DualSense Edge or Steam Controller, upper pair 1, lower pair 2; `touchpad` is the touchpad click of a DualSense or DualShock 4; no Switch button has the paddles or the touchpad by default)
|
||||
- key names: `a` to `z`, `0` to `9`, `f2` to `f7`, `f9`, `f12`, `num0` to `num9`, `space tab enter backspace lshift rshift lctrl rctrl lalt capslock insert delete home end pageup pagedown up down left right`, `num_add num_sub num_mul num_div num_decimal`, `minus equals lbracket rbracket semicolon apostrophe comma period slash backslash grave`, `mouse_l mouse_r mouse_m mouse_x1 mouse_x2`
|
||||
- `key:default` and `pad:default` keep that part's defaults (`pad:default` is each layout's own button).
|
||||
- `none` leaves the button unbound.
|
||||
|
||||
A line replaces every default of that button, pad and keyboard, so list the keys you still want or use `key:default`. Pad names are physical positions, so a line means the same in both layouts and replaces the layout's own button for that Switch button. Stick directions take keys only: the controller's sticks and the mouse camera always work. Buttons without a line keep the table above. Names are case-insensitive. An invalid entry logs one `input: bind ...` line and is skipped; a line without a valid entry changes nothing. The `TOTK_BIND_<button>` environment variables work like any other setting. A changed line applies at once (`runtime/input_win.c` builds the tables again at its next poll).
|
||||
A line replaces every default of that button, pad and keyboard, so list the keys you still want or use `key:default`. Pad names are physical positions, so a line means the same in both layouts and replaces the layout's own button for that Switch button. Stick directions take keys only: the controller's sticks and the mouse camera always work. Buttons without a line keep the table above, less any key a line binds: with `bind_X = key:t`, T presses X only, not also Y. Names are case-insensitive. An invalid entry logs one `input: bind ...` line and is skipped; a line without a valid entry changes nothing. The `TOTK_BIND_<button>` environment variables work like any other setting. A changed line applies at once (`runtime/input_win.c` builds the tables again at its next poll).
|
||||
|
||||
A pad that reports its face buttons swapped (A/B and X/Y, as some GuliKit models do) is fixed with:
|
||||
|
||||
@@ -76,16 +129,201 @@ bind_X = pad:west, key:space
|
||||
bind_Y = pad:north, key:mouse_l
|
||||
```
|
||||
|
||||
## Free camera
|
||||
|
||||
On game 1.4.3, a chosen gamepad combo or a key steps the free camera through three stages: move, lock, and off again.
|
||||
It is off by default: turn on *Free camera* on the Controls tab (`freecam_patch = 1`) and restart. Then pick the
|
||||
combo or the key, neither set by default, with `freecam_pad` and `freecam_key` in `totk.ini` or on the Controls tab
|
||||
(for example ZL+ZR+L3, LT+RT+L3 on an Xbox pad, and F2; `none` turns one off). An input script can press the combo as a
|
||||
gamepad would; the keys bound to its buttons do not. While the free camera moves, the world goes on but the game gets
|
||||
no input, so Link stands where he was.
|
||||
|
||||
Locked, the view stays where the flight left it and the game gets its input back. Link walks where the left stick
|
||||
points on screen, as the game steers him by the camera it draws. The right stick and the mouse turn the game camera,
|
||||
which still follows Link unseen.
|
||||
|
||||
| Gamepad | Keyboard and mouse (default bindings) | Free camera |
|
||||
|---|---|---|
|
||||
| Left stick | W A S D | forward and back along the view, and sideways |
|
||||
| ZR / ZL (RT / LT) | X / Z | straight up / down; a trigger by how far it is pressed |
|
||||
| Right stick | mouse, arrow keys | turn (yaw and pitch; pitch stops 5 degrees short of straight up or down) |
|
||||
| R / L (RB / LB) | R / Q | each press doubles / halves the speed, 0.25 to 512 m/s |
|
||||
|
||||
The keys are the ones bound to the left and right stick and to ZR, ZL, R and L (`bind_` lines), so remapped keys follow.
|
||||
The mouse turns the free camera at the game camera's rate (0.08 degrees a count at `mouse_sens = 1`) and the game's
|
||||
mouse camera gets none of it meanwhile. Each switch starts at the game camera's position and view at 8 m/s; the speed
|
||||
follows the clock, so it is the same at any frame rate and game speed. The horizon stays level.
|
||||
|
||||
How it works (`runtime/freecam.c`): the camera component update (main+0x628460) copies each component's eye, target
|
||||
and up into its sead camera. The site `freecam` (`recomp/patches-v143.txt`, main+0x6286d4) runs before that copy and
|
||||
writes the component's one-shot eye and target overrides (+0x180, +0x198), which the update takes in place of the pose
|
||||
and then clears, so the game camera's own state is never changed and resumes the frame the free camera ends. Locked,
|
||||
the site keeps writing the overrides without moving them. The up
|
||||
vector is levelled through the component's up offset (+0x200), which is kept and put back. Of the three components a
|
||||
frame updates, the free camera drives the two that share the player camera's eye and leaves the one at the default pose
|
||||
(eye 0, 0, 10). After a load replaced the components it picks the new ones and keeps its position.
|
||||
|
||||
## Mouse camera
|
||||
|
||||
Mouse motion (raw input) becomes right-stick deflection. Each presented frame takes the counts moved since the last frame, divides by the frame time and sets the deflection to `counts per second * TOTK_MOUSE_SENS / 3000` of full, held for that frame, so the turn rate does not depend on the frame rate. This is not mouselook: the game's stick curve and dead zone still apply, so very slow movements do nothing and a fast flick saturates. The mouse deflection competes with the gamepad and arrow keys by the larger-deflection rule.
|
||||
`mouse_mode = direct` (the default) turns the camera by the raw mouse motion on games 1.4.3 and 1.2.1, through hooks in the game's camera code (`runtime/mouse_direct.c`, the `mouse_direct` sites of `recomp/patches-v143.txt` and `recomp/patches-v121.txt`). None of them changes a step of the gamepad alone. The free-orbit camera receives raw-count
|
||||
angular increments at its final spherical-angle output: 0.08 degrees per count on both axes at sensitivity 1 (about
|
||||
14.3 cm a turn at 800 DPI), with no time multiplier, curve or carry into later frames. The controller's persistent pitch/yaw move with
|
||||
the output. Mouse input is removed from its stick path first, so the camera's later vertical signed-square curve and
|
||||
velocity filters cannot process it a second time.
|
||||
The aiming camera (bow, throwing), the Purah Pad camera, the scope, the ability camera (Ultrahand, Fuse, Ascend,
|
||||
Recall, Autobuild), the horse camera, lock-on, the bow drawn while locked on, climbing (walls and objects), the
|
||||
waterfall's turn, shield surfing, the wakeboard and the dialogue cameras take the mouse the same way, at the same
|
||||
degrees per count: each turns by
|
||||
the stick times its own speeds and the frame time and adds that to a base angle, so the load of the stick it turns by
|
||||
gets the gamepad's part only and the load of that base angle gets the mouse's degrees (`camera_load`, two sites per
|
||||
axis per camera). Their speeds, time step, slow motion (bullet time) and, for the Purah Pad camera and the abilities,
|
||||
the eased curve their pitch moves along do not touch the mouse; their own limits, collision and blends apply to the
|
||||
result. Past the pitch limit of the scope or the ability camera the stick moves the camera's distance; the mouse's
|
||||
motion past the limit keeps doing that through the stick. Recall's cursor is the ability camera's offset mode: the
|
||||
camera keeps a direction, the stick moves the cursor across the screen (ReverseRecorderCursorSpeed, within
|
||||
ReverseRecorderCursorRange) and the camera follows it by up to ReverseRecorderCameraRange (10 degrees across, 7.8 up).
|
||||
The mouse moves the cursor so that its aim, the camera's follow plus the cursor's angle from the screen's centre (the
|
||||
offset taken as the screen's half width or height at the camera's 50 degree view and aspect ratio), turns as many
|
||||
degrees a count as the camera does elsewhere. The follow range is read from the game each step (until it has been read
|
||||
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.
|
||||
Shield surfing and the wakeboard turn their pitch by the square of the stick's y and move a second camera parameter
|
||||
with it: their stick y keeps the mouse (that parameter and the camera's state follow it as before), the pitch gets
|
||||
the degrees, and the pitch turn the game made from y is cut to the gamepad's share (p |p| / t |t|). Their stick x, and
|
||||
the dialogue camera's (which is also its test for input), give a tiny value in the mouse's direction when the
|
||||
gamepad's axis is at rest, so the camera still sees input without a stick turn.
|
||||
Two inputs stay stick input: the waterfall's vertical axis moves the camera's height, not an angle, and the horse's
|
||||
lock-on without a target (HorseLockOnEmpty) turns the stick's position into an offset that returns when the stick
|
||||
does, which a mouse has no position for.
|
||||
Those receive input after
|
||||
the radial dead zone, unit-circle clamp and stick response exponent: x is 0.0343 stick units a count over the frame
|
||||
ratio (the stick turns yaw 70 x / 30 degrees a step) and y 70 / 51 times that, linear like their pitch (51 y / 30
|
||||
degrees a step), so both axes turn by the same amount for the same motion. `stick_sens` (which scales the game's
|
||||
stick turn rates) is divided out. While the player uses an ability and the ability camera's hooks do not take the
|
||||
mouse, its part is scaled by 1 / 0.8 and 70 / (1.5 x 51), the ability camera's own stick scales.
|
||||
The player's verbs are read every 50 ms from the player actor (the player root's GOT slot main+0x3969918, the
|
||||
component array +0x228, its AS component +0x158 and the verbs of its five slots). Ultrahand has a separate hook after
|
||||
its manipulation input's power curves; it gets 0.01 stick units a count over the frame ratio, at most three full tilts
|
||||
a step.
|
||||
`mouse_aim_scale` (0.1 to 3, default 1) multiplies the mouse's motion while the bow is drawn (the verb UseBow or
|
||||
DrawnBow with ZR held). The game's camera inversion and gamepad response remain in effect. `mouse_sens` scales raw
|
||||
counts, with the same meaning as in 0.3.10 (the free camera turns 0.08 degrees a count at 1, and now every other camera
|
||||
does too); its scale differs from the stick-emulation mode.
|
||||
The Controls tab switches between *Direct* and *Stick emulation* (`mouse_mode = stick`).
|
||||
The orbit camera keeps its desired pitch at the final angular output, including stationary frames, so a later game
|
||||
filter cannot recenter it. The persistent filter state accounts for the camera's current vertical offset instead of
|
||||
accumulating corrections. A gamepad vertical input releases that mouse target to the game's own. The game's
|
||||
lock-on, recenter and override (aiming) drive the camera themselves: the mouse stops holding without restoring its
|
||||
earlier target, and when they end (or after the camera went 100 ms without a step) it holds the pitch the camera has
|
||||
then, so the camera does not spring back to a pitch from before the aim or to the game's default after a shot.
|
||||
While the ability wheel is open (L held and its screen, ShortCutMainItem_00 or ShortCut_00, has the focus), mouse
|
||||
counts move its virtual cursor, which stays where it was when the mouse stops. L or the D-pad held with no wheel or
|
||||
strip on screen (L soothes the horse, turns menu tabs) leaves the mouse on the camera; with the menu cursor off
|
||||
(`menu_cursor = 0`) the screens are not read and the buttons alone decide.
|
||||
The horizontal quick lists (D-pad up/left/right: materials, shields and weapons) use separate 32 ms right-stick steps,
|
||||
with at least 32 ms of neutral between them. At sensitivity 1, 32 horizontal counts request a step; a large flick
|
||||
cannot queue continued scrolling after the mouse stops. Vertical movement is ignored in these lists. Switching or
|
||||
releasing a selector resets its cursor/step state without sending the last movement to the camera. Selector input is
|
||||
not consumed by the direct camera or Ultrahand hooks. The scroll wheel steps these lists too: each notch is one step,
|
||||
away from you to the left, towards you to the right.
|
||||
To detach a fused part from what Ultrahand holds, shake the mouse left and right, or press G (`bind_SHAKE`). A press
|
||||
swings the right stick left and right for 0.8 s, holding the key keeps it swinging. With `mouse_mode = direct` a shake
|
||||
of the mouse while Ultrahand holds an object swings the right stick with it: once the swings (10 degrees of camera turn
|
||||
or more each, 125 counts at sensitivity 1) change direction twice within 0.35 s, the stick goes full tilt the
|
||||
way the mouse moves, each side held at least two frames so the game reads it, and goes neutral as soon as the mouse
|
||||
rests. Only your own swings reach the stick, so nothing keeps swinging after you stop; shake until the part comes off.
|
||||
The camera hooks ignore that swing (the mouse turns the camera in degrees already). Turning a held object back and
|
||||
forth at an ordinary pace is slower and does not count. The arrow keys or the gamepad's right stick shaken by hand
|
||||
work too.
|
||||
A step of the gamepad alone, with no mouse motion and no pitch the mouse holds, reaches the camera exactly as without
|
||||
the hooks.
|
||||
The mapping below is still used when the camera-input hook is unavailable or the game disables camera input.
|
||||
Game 1.1.0 has no hooks and keeps stick emulation whatever `mouse_mode` says. On 1.2.1 `mouse_aim_scale` has no effect (the bow-in-hand state is not read there).
|
||||
|
||||
In stick-emulation mode, mouse motion (raw input) becomes right-stick deflection. Each presented frame takes the counts moved since the last frame, divides by the frame time and sets the deflection to `counts per second * TOTK_MOUSE_SENS / 3000` of full, held for that frame, so the turn rate does not depend on the frame rate. This is not mouselook: the game's stick curve and dead zone still apply, so very slow movements do nothing and a fast flick saturates. The mouse deflection competes with the gamepad and arrow keys by the larger-deflection rule.
|
||||
|
||||
`TOTK_MOUSE_SENS` (0 to 10, default 1; higher turns faster, 0 turns the mouse camera and the cursor capture off). While the window is the foreground window the cursor is hidden and confined to the client area. It is released on focus loss, minimise, while F11 changes the window, during a size or move loop and while a text entry is open. Esc releases it by hand: the cursor shows, the mouse camera and mouse buttons stop, and the window can be moved, minimised or closed. A mouse click inside the client area captures it again; that click does not reach the game. Activating the window by a click on its title bar or border does not capture, so it can be dragged or closed right away; Alt+Tab or a click in the client area captures as before. `TOTK_INPUT=none` disables the capture too.
|
||||
|
||||
`TOTK_STICK_DEADZONE` (0 to 50, default 8) is the gamepad stick dead zone in percent of full deflection, the same for both sticks. It is round: a stick inside the circle reads centred, and the rest of its travel is scaled to start at 0 at the edge, so full deflection still reaches full. Raise it for a stick that drifts. The game's own dead zone applies after it.
|
||||
`TOTK_STICK_DEADZONE` (0 to 50, default 8) is the gamepad stick dead zone in percent of full deflection, the same for both sticks. It is round: a stick inside the circle reads centred, and the rest of its travel is scaled to start at 0 at the edge, so full deflection still reaches full. Raise it for a stick that drifts. The game's own dead zone applies after it. `TOTK_LSTICK_DEADZONE` and `TOTK_RSTICK_DEADZONE` (the *Left/Right stick dead zone* rows under *Analog sticks* on the Controls tab) set one stick each and fall back to `TOTK_STICK_DEADZONE` while unset, so a worn stick can get a larger zone than the other. With a gamepad connected each row shows its stick's deflection now, before the dead zone (*stick now*): let go of the stick and set the row a few percent above the value it rests at.
|
||||
|
||||
The stick direction bits (`StickLLeft` to `StickRDown`) are derived from the sticks at 50% deflection. A gamepad plugged in later is picked up within one second; with none connected the log says `input: no gamepad`.
|
||||
|
||||
## Mouse in the game's menus
|
||||
|
||||
On game 1.4.3, while one of the game's menus has its focus box (the frame the d-pad moves: the title, the save list, the inventory and its System tab, Options, shops, dialogue choices), the cursor is released from the mouse camera and shown in the middle of the window. A focus gap of up to 300 ms (a tab switch, a popup opening: the game drops the focus box for a frame or two) keeps the pointer where it is instead of capturing and centring it again. The item under the pointer takes the focus as if the d-pad had moved there, with the game's highlight, sound and description; a left click is A on it, a right click is B. The middle and side mouse buttons keep their bindings (bound to L and R they turn the tabs), and T presses Y (sort). The scroll wheel moves the focus up and down, one step a notch (a full-tilt push of the left stick for 70 ms with 50 ms of neutral after it, up for a turn away from you), so a long list of items scrolls without moving the pointer; `menu_cursor = 0` turns this off with the pointer. The keys and the pad keep working, and the focus moves with the pointer only when the pointer moves: after the wheel, a key or the pad moved the focus off the pointer's item, the pointer takes it back once it has moved 6 layout units (the menus' 1280 x 720: about 9 window pixels at 1080p, 18 at 4K) from where it was then (`DEAD_ZONE` in `runtime/menu_cursor.c`), so a hand resting on the mouse does not undo a scroll; a click acts at once. With `pointer_image = 1` (off by default) the game window shows a pointer of its own while the cursor is not captured, a gold arrowhead drawn at the window's DPI (`runtime/cursor_art.c`), in place of the system arrow. This happens only while the keyboard and mouse are the device used last: after a gamepad button press or a stick pushed past half way the menus are as on the console, with no pointer, until the mouse moves or a key is pressed (`input_kbm_last` in `runtime/input.c`). The ability wheel, the d-pad strips, Autobuild and the Purah Pad's camera stay gameplay: the mouse keeps the camera there. The map has no focus box; it is found in `eui::ScreenMgr`'s list of open screens (every 100 ms: the Purah Pad's frame `AppMenuOverlay_00` with `AppMap_00` and the menu background `AppMenuBG_00`), and there the mouse moves the map's cursor as the left stick does, with the cursor still captured, and the scroll wheel zooms: each notch is a full-tilt push of the right stick (the map's zoom) for 100 ms with 50 ms of neutral after it, up (in) for a turn away from you; a fast scroll's notches wait their turn (at most four), a turn the other way drops them. The Scope opens the same map screen without the menu background and keeps the mouse camera. The Purah Pad's camera (the ability wheel's camera) opens the frame and its pointer `CameraPointer_00` without `AppMap_00` (the Scope has it); there the scroll wheel zooms as the camera's guide shows: each notch is a press of the d-pad's up (in, for a turn away from you) or down for 100 ms with 50 ms of release after it (`menu_cursor_camera`). The Scope itself has no zoom; the wheel does nothing there. When the menu closes the cursor is captured again.
|
||||
|
||||
`runtime/menu_cursor.c` reads eui's screens at each pad read and moves the focus with the writes `eui::BoxCursorMgr::moveBoxCursor` makes, so no game code is called. `menu_cursor = 0` (`TOTK_MENU_CURSOR=0`, live; the *Mouse in the game's menus* row of the Controls tab) turns it off; `TOTK_MENU_CURSOR_LOG=1` logs every screen it reads (by default the first six), with the layout size, the node count and the hit panes it uses.
|
||||
|
||||
### Left click on the map
|
||||
|
||||
With `map_click = 1` (off by default, so each key presses one controller button as everywhere else), on game 1.4.3, while the Purah Pad's map is open (found as above; the Scope is not the map), the left mouse button presses A at the map's cursor instead of the button it is bound to (Y by default). A press is A or the binding from the moment the button goes down until it is released, so a button held as the map opens or closes keeps what it pressed (`poll_merged` in `runtime/input.c`). `map_click = 1` (`TOTK_MAP_CLICK=1`, live; the *Left click on the map* row of the Controls tab) turns it on and `0`, the default, leaves the left button on its binding there. The map is found only while `menu_cursor` is on.
|
||||
|
||||
### Clicks in dialogue
|
||||
|
||||
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:
|
||||
|
||||
- **Ultrahand object rotation**: turning the mouse wheel while Ultrahand holds an object rotates it directly without holding R or pressing the D-pad (`gameplay_ultrahand_rotate = 1`, sensitivity `gameplay_rotation_sensitivity = 1`). Holding C while scrolling rotates around the alternate axis (`gameplay_ultrahand_c_axis = 1`).
|
||||
- **Ultrahand distance**: holding the right mouse button while scrolling pushes or pulls the held object closer or farther (`gameplay_ultrahand_distance = 1`, sensitivity `gameplay_distance_sensitivity = 1`).
|
||||
- **Free-roam weapon switching**: scrolling the mouse wheel in free roam steps through equipped weapons (`gameplay_weapon_wheel = 1`, sensitivity `gameplay_weapon_sensitivity = 1`). Press E to confirm the chosen weapon; right click or pressing B cancels.
|
||||
- **Quick-selection menus**: scrolling the mouse wheel browses items while a quick-selection menu (weapons, bows, shields, materials) is open (`gameplay_item_wheel = 1`, sensitivity `gameplay_item_sensitivity = 1`). A and D keys step left and right through the strip (`gameplay_item_ad = 1`).
|
||||
- **Smooth map zoom**: the mouse wheel performs continuous inertial zooming on the Purah Pad map (`gameplay_map_zoom = 1`, sensitivity `gameplay_map_zoom_sensitivity = 1`).
|
||||
|
||||
All sub-toggles default to 1 and sensitivities to 1 (range 0.25 to 4.0), so enabling `gameplay_tweaks_enabled` activates the full suite immediately while allowing individual features to be toggled or tuned.
|
||||
|
||||
## Nintendo Switch 2 controllers
|
||||
|
||||
Windows does not present the Switch 2 Pro Controller as a gamepad SDL can open (the log says `input: no gamepad`), so it needs a bridge program that wakes it and creates a virtual gamepad. The DS4Windows fork by hbashton ([github.com/hbashton/DS4Windows](https://github.com/hbashton/DS4Windows), tested with release VIIPERRC4.5.1, a pre-release) with the output set to an emulated DualSense gives buttons, rumble, gyro and accelerometer, and reads the sticks through the controller's calibration (they rest at 0 to 2%). The game reads its virtual DualSense directly; the log then shows `input: gamepad "DualSense Wireless Controller" (rumble, gyro and accelerometer, ...)` and `input: motion sensors on`. Its release notes also list Joy-Con 2 support, which is untested here.
|
||||
|
||||
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:
|
||||
@@ -93,14 +331,27 @@ The stick direction bits (`StickLLeft` to `StickRDown`) are derived from the sti
|
||||
```
|
||||
<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> # 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.
|
||||
|
||||
`TOTK_INPUT_RECORD=<file>` (`input_record` in `totk.ini`, or Input recording in the menu) writes the merged input in the same format, one line per button press and per stick segment: events before the world clock starts by tick, the rest timed; a button or stick held when the world clock starts is cut there and goes on as a timed event. The file replays as a script, which makes it the repro to attach to a bug report.
|
||||
|
||||
In direct mouse mode the recording also writes one `MOUSE` event per consumed raw displacement. These are one-shot
|
||||
displacements rather than held stick segments. They replay without cursor capture, including with `input = none`;
|
||||
the game must be accepting camera input when the event reaches its camera update. 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.
|
||||
|
||||
## RenderDoc capture (blocked)
|
||||
|
||||
+210
-36
@@ -1,73 +1,173 @@
|
||||
# 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
|
||||
|
||||
1. Downloads `TotK-Setup-<version>-windows.zip` from GitHub Releases (none is published yet), unpacks it anywhere and
|
||||
starts `TotK-Setup.exe`.
|
||||
2. Picks:
|
||||
- the base game (XCI or NSP) and the 1.2.1 or 1.4.3 update (NSP);
|
||||
- the base game (XCI or NSP) and the 1.1.0, 1.2.1 or 1.4.3 update (NSP); an NSZ or XCZ (compressed by the nsz
|
||||
tool) works as it is, the setup unpacks it itself;
|
||||
- their `prod.keys`;
|
||||
- optionally the firmware folder (`system/Contents/registered` of an unpacked firmware or an emulator's install),
|
||||
needed for Chinese, Korean and Traditional Chinese text;
|
||||
- the game language and the install folder.
|
||||
3. Waits for the setup, one time. The window shows each step and its progress.
|
||||
4. Plays `totk.exe` from the install folder. The installer and the source NSP or XCI can be deleted.
|
||||
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):
|
||||
|
||||
```
|
||||
<install folder>/
|
||||
totk.exe, SDL3.dll, libopus-0.dll, totk_xlate.exe
|
||||
nvngx_dlss.dll NVIDIA DLSS, downloaded by the setup's DLSS step when the player keeps it ticked
|
||||
totk.ini language; the other keys as commented defaults (totk.ini.example)
|
||||
exefs/, romfs/ extracted from the player's files
|
||||
shared-fonts/ the Switch system fonts, with Chinese, Korean or Traditional Chinese text
|
||||
profile/ saves
|
||||
mods/ the player's mods, one folder per mod (created by the menu's "Open mods folder")
|
||||
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/`,
|
||||
`profile/` and `totk.ini` after checking their hashes, rebuilds `totk.exe` and re-prepares the shaders. A newer
|
||||
release that changes nothing game-derived skips the rebuild.
|
||||
`shared-fonts/`, `profile/` and `totk.ini` after checking their hashes, 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 another update file than the recorded one (1.2.1, then 1.4.3), the installer extracts and builds again from it and
|
||||
keeps `profile/`. Saves carry over both ways: 1.4.3 converts a 1.2.1 save on load, and 1.2.1 loads the saves 1.4.3 wrote.
|
||||
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
|
||||
loads the saves 1.4.3 wrote.
|
||||
|
||||
## Setup steps
|
||||
|
||||
1. **Check** before writing anything: the files open with the keys, the update is 1.2.1 or 1.4.3 (by hash, as
|
||||
1. **Check** before writing anything: an NSZ or XCZ input is unpacked first (below), the files open with the keys, the update is 1.1.0, 1.2.1 or 1.4.3 (by hash, as
|
||||
`tools/extract.py`), the keys are new enough for the update, enough space is free on the target disk (about 36 GiB at the peak of a
|
||||
first install, 20 GiB after it), the CPU has
|
||||
AVX2 (`-march=x86-64-v3`), a Vulkan 1.3 GPU exists. Each failure is one clear message.
|
||||
2. **Extract** ExeFS and RomFS into the install folder and verify the hashes.
|
||||
3. **Lift** the ExeFS to C (`recomp/gen.py`, `recomp/patches-v121.txt` or `patches-v143.txt`) into a temp folder next
|
||||
to the installer.
|
||||
4. **Compile** the generated C, `modules.c`, `romfs.c`, `patches.c` and `ov_zstd.c` (they bake the per-install layout, RomFS
|
||||
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. **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.
|
||||
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 into `totk.exe` (`build_game.py --runtime-lib`; about 3 min on 24 cores).
|
||||
5. **Prepare** the RomFS patches and the shaders (`tools/make_romfs_patches.py`, `tools/prepare_shaders.py`,
|
||||
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).
|
||||
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 twice: `romfs-patches` and `romfs-patches-xbox` (`--xbox-prompts`, the A/B and X/Y prompts
|
||||
swapped for `pad_layout = xbox_prompts`).
|
||||
6. **Clean up** the temp folder (generated C and objects, about 1.3 GB).
|
||||
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`), `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 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.
|
||||
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:
|
||||
`xrandr`, else the DRM connectors), of the `output_res` the game defaults to on each, and of the `totk.ini`
|
||||
`output_res` (`installer/screens.py`). One folder per shape, named after the shape's size in `ASPECT_SIZES` (the
|
||||
closest within 1%; `5120x2160` uses `2560x1080`); `runtime/romfs.c` `overlay_init` maps the game resolution the
|
||||
same way, and a folder of the exact size from an older setup still wins. A 16:9 player gets none. The step runs
|
||||
again when the displays, the prompts or the patches change. At a game resolution whose shape has no folder the
|
||||
game draws 16:9 with bars and starts the generator itself, in the background, for the next start: at start and
|
||||
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.
|
||||
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, 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. 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
|
||||
|
||||
`installer/` (stdlib only; `installer/layout.py` maps the release folder and, in a repository, the dev toolchain):
|
||||
|
||||
```
|
||||
python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--root DIR] [--temp DIR] [--verify]
|
||||
python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--firmware DIR] [--root DIR] [--temp DIR] [--verify]
|
||||
```
|
||||
|
||||
- On a folder with `totk-install.json` only `--dest` is needed; the game files only when the extraction must run again.
|
||||
- `--firmware DIR` is the folder holding the firmware NCAs: an unpacked firmware, or the emulators' installed
|
||||
`Contents/registered` (the parent `Contents` folder works too). It is read only with Chinese, Korean or Traditional
|
||||
Chinese text, and only when `shared-fonts/` is not already in the install folder.
|
||||
- stdout: one JSON event per line, types `start`, `plan`, `step` (started, done, skipped), `progress` (step, phase,
|
||||
done/total/unit), `space` (bytes needed and free on the install disk and the temp disk), `warning`, `error`, `end` (`installer/events.py`). Messages are ids with parameters;
|
||||
`installer/text/en.json` holds their English text. The human-readable log goes to `<temp>/logs/`.
|
||||
@@ -77,13 +177,23 @@ python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR
|
||||
resume and update are one rule; output kept from another release is re-hashed first.
|
||||
- Peak space on the install disk is about 36 GiB, not 22: the extraction copies both Program NCAs (16.3 GiB) next to
|
||||
the merged RomFS (15.9 GiB) before it deletes them. The check computes the exact figure.
|
||||
- Window (`python -m installer.gui`, `installer/gui.py` draws, `installer/guilogic.py` decides): form, step list with
|
||||
progress, space line, collapsible log, Cancel (Ctrl+Break to the CLI's process group, then it waits for the exit),
|
||||
finish screen with Open folder. English or Russian, chosen from the Windows display language, switchable in the
|
||||
window; every sentence is an id in `installer/text/<en|ru>.json`. A folder with `totk-install.json` needs only the
|
||||
folder. `--selftest [--shots DIR]` builds every screen in both languages and closes itself.
|
||||
- `tests/installer_gui_test.py`: event model, form, catalogs, cancel, the self-closing window and one end-to-end run
|
||||
of the CLI in `--verify` mode (needs `build/install-test` and `build/extracted/v121`; see its docstring).
|
||||
- Window (`python -m installer.gui`, `installer/gui.py` draws, `installer/guilogic.py` decides): form (game files and
|
||||
install sections, the explanations under More details, the share notice next to Start) in the Sun Valley ttk theme
|
||||
(`installer/vendor/sv_ttk/`, the platform theme when it does not load), step list with progress, space line,
|
||||
collapsible log, Cancel (Ctrl+Break to the CLI's process group, then it waits for the exit), finish screen with Open
|
||||
folder. English, Russian, Brazilian Portuguese, Simplified Chinese, German, French, Spanish, Italian, Dutch, Japanese
|
||||
or Korean (`guilogic.UI_LANGUAGES`), chosen from the Windows display language (every Chinese, zh-TW and zh-HK
|
||||
included, gives Simplified Chinese; pt-PT and languages without a catalog give English), switchable in the window;
|
||||
every sentence is an id in `installer/text/<lang>.json`. The game language starts as the window's when the game has
|
||||
it; a Chinese or Korean window still starts with English, because that game text needs the Switch shared fonts,
|
||||
which the setup extracts only from a firmware folder. A folder with
|
||||
`totk-install.json` needs only the folder. `--selftest [--shots DIR]` builds every screen in every language and
|
||||
closes itself. The window is not stretched on a display whose scale is the system DPI: `installer/dpi.py` makes the
|
||||
process system DPI aware before Tk starts, Tk then draws the fonts at the display's scale and `dpi.px` sizes the
|
||||
paddings and wrap widths with it; the launcher does the same for its error box.
|
||||
- `tests/installer_gui_test.py`: event model, form, catalogs, cancel, the display scale, the self-closing window and
|
||||
one end-to-end run of the CLI in `--verify` mode (needs `build/install-test` and `build/extracted/v121`; see its
|
||||
docstring).
|
||||
- `tests/installer_test.py`: bookkeeping with fake steps. `tests/installer_e2e.py`: a dev-mode run with the files of
|
||||
`config.local.toml`.
|
||||
|
||||
@@ -92,26 +202,81 @@ 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)
|
||||
installer/ the installer: steps, CLI, window, en/ru text catalog
|
||||
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, text catalogs (text/<lang>.json), Sun Valley theme (vendor/)
|
||||
python/ Python 3.14.9 embeddable + numpy, lz4, cryptography, cffi, pycparser (+ tkinter for the window)
|
||||
recomp/, tools/ the lifter and the build, extraction and shader scripts the steps run (copied from the repo)
|
||||
llvm/ llvm-mingw, x86_64-only subset (Apache-2.0 with LLVM exception; mingw-w64 parts permissive)
|
||||
runtime/ libtotkrt.a and the headers the generated code and modules.c/romfs.c/patches.c include
|
||||
runtime/ libtotkrt.a, libtotkrt-v2.a and the headers the generated code and modules.c/romfs.c/patches.c
|
||||
include
|
||||
bin/ totk_xlate.exe, hactool.exe, SDL3.dll, libopus-0.dll, ninja.exe
|
||||
data/ shader_list.tsv (MacNativeGames, MIT)
|
||||
data/ shader_list.tsv (MacNativeGames, MIT); pgo-<ver>.profdata + .json, the execution profile an
|
||||
update's code and the runtime libraries compile with (pgo.md)
|
||||
THIRD_PARTY_NOTICES.md
|
||||
totk.ini.example, VERSION the default ini; the release string (the repository's VERSION plus the commit)
|
||||
```
|
||||
|
||||
- SDL3 comes from the upstream release, not MSYS2: MSYS2's DLL imports the LGPL libiconv.
|
||||
- Every bundled third-party piece gets a row in `THIRD_PARTY_NOTICES.md`.
|
||||
- The release contains nothing game-derived; `make_release.py` runs `tools/check_content.py` over the folder before it
|
||||
finishes.
|
||||
- The release contains no code, data, text or assets of the game; `make_release.py` runs `tools/check_content.py` over
|
||||
the folder before it finishes. The execution profiles name lifted functions by address (`f_<address>`) and hold
|
||||
branch counts and control-flow hashes of the generated C.
|
||||
|
||||
## Switch system fonts
|
||||
|
||||
Simplified Chinese, Traditional Chinese and Korean text needs the Switch system fonts (`0-standard.bfttf` and the other
|
||||
nn::pl shared fonts). The game does not ship them. Without them it exits before its first frame in those languages
|
||||
(`rt_fatal` in `runtime/ov_system.c`). Supply them from your own console, in either way:
|
||||
|
||||
- Give the setup the firmware folder (`--firmware DIR`, or the window's firmware field); the Fonts step extracts them to
|
||||
`shared-fonts/` in the install folder.
|
||||
- Run `python tools/extract_fonts.py --firmware <dir>` with `.venv-py314` and the keys from `config.local.toml`, or
|
||||
point `TOTK_SHARED_FONTS` at a folder that holds the extracted fonts.
|
||||
|
||||
## Linux release
|
||||
|
||||
`tools/make_release_linux.py` builds the same setup for Linux and packs it as `TotK-Setup-x86_64.AppImage` (the static
|
||||
type-2 runtime: no libfuse2 needed on the host). The player makes it executable and starts it; on a Steam Deck, from
|
||||
Desktop Mode. The command-line setup needs the desktop session's display (`DISPLAY` or `WAYLAND_DISPLAY`) because preparing the
|
||||
shaders opens a window; the check step fails at once without it. Building the release also needs `make` and `pkg-config`. The bundled Tcl/Tk 9.0.4 is rebuilt with
|
||||
Xft against the sniper sysroot so Russian text uses system TrueType fonts. The setup builds the game into the folder they pick, as on Windows, and the game is `totk` there with
|
||||
`libSDL3.so.0` beside it. The folder inside the AppImage:
|
||||
|
||||
```
|
||||
AppRun starts python/bin/python3 -m installer.gui (no bytecode written into the read-only mount)
|
||||
totk-setup.desktop, totk-setup.png
|
||||
installer/, recomp/, tools/, data/, licenses/, THIRD_PARTY_NOTICES.md, totk.ini.example, VERSION as on Windows
|
||||
python/ python-build-standalone 3.14 (with tkinter) + the installer's packages; a .pth puts the folder,
|
||||
tools/ and recomp/ on sys.path
|
||||
llvm/ LLVM 23 (clang, lld, llvm-ar) and llvm/sysroot: the files of the Steam Runtime 3 "sniper" SDK the
|
||||
game's compile and link read (about 130 files)
|
||||
runtime/ libtotkrt.a, libtotkrt-v2.a, headers, the install-side sources, totk.png; deps/ with the Vulkan
|
||||
headers, VMA and a static zstd
|
||||
bin/ totk_xlate, hactool, ninja, libSDL3.so.0
|
||||
```
|
||||
|
||||
- What we compile is built against the sniper sysroot (glibc 2.31): the game, hostcheck, hactool and the translator
|
||||
need no newer glibc. The game links Opus, libvpx, zstd and libstdc++ statically and needs only glibc, the system's
|
||||
Vulkan loader and the SDL3 beside it. The setup itself needs glibc 2.34 (Ubuntu 22.04, Debian 12, Fedora 35,
|
||||
SteamOS 3): the official LLVM binaries and the `cryptography` wheel are built against it. `make_release_linux.py`
|
||||
checks every ELF file in the folder against that floor (`check_glibc`), and the setup's check step stops with one
|
||||
message on an older system.
|
||||
- The setup's temp folder is `.setup-temp` inside the install folder (`--temp` changes it): the AppImage is mounted
|
||||
read-only, and a Steam Deck's `/home` is often too full for the generated C while the game goes to the SD card.
|
||||
- The game keeps Mesa's shader cache in `mesa-cache` beside `totk` unless `MESA_SHADER_CACHE_DIR` is set, for the
|
||||
same reason: RADV fills its default folder in `~/.cache` up to 1 GB.
|
||||
- The window follows `LANG` for English or Russian, cancels through SIGTERM to the CLI's process group (the CLI handles
|
||||
it as Ctrl+Break on Windows) and opens the finished folder with `xdg-open`.
|
||||
- Requirements beyond Windows': Linux 6.7 or later (the write watch, `docs/building.md`) and glibc 2.34.
|
||||
- Building the release needs one game version extracted and lifted (`tools/extract.py`, `recomp/gen.py`, either
|
||||
version): the runtime library includes the generated `layout.h`, whose shared part (`MOD_COUNT`, `MOD_MAIN_BASE`)
|
||||
is the same for both. `tools/make_release.py` takes `generated/v121`, else `generated/v143`.
|
||||
|
||||
## Constraints
|
||||
|
||||
- The installer steps contain no Win32 calls: Linux follows with its own compiler and the same steps.
|
||||
- The installer steps contain no Win32 calls; only the window's DPI awareness (`installer/dpi.py`) is Windows-only, and
|
||||
it does nothing elsewhere. Linux runs the same steps with its own compiler ("Linux release").
|
||||
- The keys file path is passed to the tools; key values never appear in the UI, logs or files.
|
||||
- The window is a front end over the CLI (`python -m installer --base ... --update ... --keys ... --lang ... --dest
|
||||
...`), which prints one JSON progress event per line. Tests and CI use the CLI.
|
||||
@@ -123,8 +288,17 @@ totk.ini.example, VERSION the default ini; the release string (the repository's
|
||||
the file and asks to copy it again (`extract.DamagedFile`). A failed merge checks the base Program NCA alone to tell
|
||||
which file is damaged.
|
||||
- Unsigned exe: SmartScreen warns on first start.
|
||||
- NSZ and XCZ input (game files compressed by the nsz tool: NCAs stored as NCZ, their sections decrypted and
|
||||
compressed with zstd): the check step tells them by their content, not their name (an NSP or XCI holding NCZ files),
|
||||
so the file dialog has one filter for all four. It unpacks each into `<temp>/unpacked/<base|update>.nsp`
|
||||
(`tools/ncz.py`), an NSP of the NSZ's files or of the XCZ's secure partition, and the extraction reads that.
|
||||
Unpacking encrypts the sections again, so every NCA comes back byte for byte, and checks each against the hash its
|
||||
name carries; a mismatch is `check.input_damaged`. It needs the unpacked size free in the temp folder (checked
|
||||
first), runs at about 500 MB/s, and an interrupted setup reuses a finished NSP of the same file. The extract step
|
||||
deletes the folder when it is done. An XCZ update is refused like an XCI one.
|
||||
|
||||
## Later
|
||||
|
||||
- Re-warm the driver cache on start after a move, GPU or driver change.
|
||||
- NSZ and XCZ input. Linux release.
|
||||
- Per-monitor DPI in the setup window: Tk 9 has none, so a display whose scale differs from the primary one still gets
|
||||
the window stretched.
|
||||
+9
-3
@@ -35,7 +35,7 @@ Source shorthands:
|
||||
|---|---|---|---|---|
|
||||
| 1.1 | **Colour target the fragment shader does not write keeps its old texel**, even with blending enabled. | Undefined value written/blended. | NXN: zero write mask and no blend for unwritten outputs (`reflection colors`). Already fixed here. | NXN; MNG `games/totk/tests/metal_semantics/probe.m:5` |
|
||||
| 1.2 | **Unwritten vertex outputs read as (0, 0, 0, 1)** in the next stage, including the unwritten components of a partly written output (VS writes xyz, FS divides by w). | FS input with no VS output: interface mismatch, value undefined; an unwritten component of a written output is undefined (AMD: whatever the register holds, often 0). | Ryujinx initialises exactly the components the next stage reads, but only when stages are linked (`Translation/Translator.cs:212-227`, `NextInputAttributesComponents`); position starts (0,0,0,1) (`:259`). NXN Link's Awakening: sun shadow lookups divided by w = 0, scene dim, no shadows. Ours: missing outputs padded with (0, 0, 0, 1), unlinked outputs initialised by translator patch 0006 (section 7, check 2). | NXN |
|
||||
| 1.3 | **Clears honour the scissor and the clear's own channel / stencil write mask**, and may come between draws inside a pass. `SET_CLEAR_SURFACE_CONTROL` (0x10f8) has `RESPECT_STENCIL_MASK`, `USE_CLEAR_RECT`, `USE_SCISSOR0`, `USE_VIEWPORT_CLIP0`. | `vkCmdClearAttachments` takes a rect but **ignores the colour write mask**; load-op clears are whole-attachment. | NXN/MNG draw a triangle with the clear's mask (`clear_color_tri`, `clear_ds_tri`); TotK uses mid-pass, partial-mask and partial-scissor clears (NXN). yuzu: "red dot" was clears hitting the wrong RT index (YZ-2305, PR 10243). Hardware recipe (DK3D): `CLEAR_BUFFERS` (`0x674` = 0x19d0) carries the colour channel mask (bits 2-5), depth (0), stencil (1), target id (6-9) and layer (10-20) in one word; `ClearBufferFlags` (`0x43E` = 0x10f8) is set once to `StencilMask | Scissor` (`maxwell/gpu_3d_base.cpp:69`), so every clear is cut by scissor 0 and its stencil bits by the stencil front write mask register, and DK3D's colour clear does not program `ColorWriteMask` (`0x680`). A stencil clear writes `StencilFrontMask` (`0x4E7`) and `ClearStencil` (`0x368`) just before the clear and restores the shadowed state after (`gpu_3d_base.cpp:497-510`). Multisample raster is switched off around a colour clear (`:459, :465`). Arrays: an MME macro repeats the clear for every layer (`maxwell/clear_buffers.mme:5-22`). No pass concept: clears sit between draws. Ours: masked colour and stencil clears are **skipped** (check 3). | OGD 0x10f8; NXN; DK3D `maxwell/gpu_3d_base.cpp:444-512`, `engine_3d.def:305, 644` |
|
||||
| 1.3 | **Clears honour the scissor and the clear's own channel / stencil write mask**, and may come between draws inside a pass. `SET_CLEAR_SURFACE_CONTROL` (0x10f8) has `RESPECT_STENCIL_MASK`, `USE_CLEAR_RECT`, `USE_SCISSOR0`, `USE_VIEWPORT_CLIP0`. | `vkCmdClearAttachments` takes a rect but **ignores the colour write mask**; load-op clears are whole-attachment. | NXN/MNG draw a triangle with the clear's mask (`clear_color_tri`, `clear_ds_tri`); TotK uses mid-pass, partial-mask and partial-scissor clears (NXN). yuzu: "red dot" was clears hitting the wrong RT index (YZ-2305, PR 10243). Hardware recipe (DK3D): `CLEAR_BUFFERS` (`0x674` = 0x19d0) carries the colour channel mask (bits 2-5), depth (0), stencil (1), target id (6-9) and layer (10-20) in one word; `ClearBufferFlags` (`0x43E` = 0x10f8) is set once to `StencilMask \| Scissor` (`maxwell/gpu_3d_base.cpp:69`), so every clear is cut by scissor 0 and its stencil bits by the stencil front write mask register, and DK3D's colour clear does not program `ColorWriteMask` (`0x680`). A stencil clear writes `StencilFrontMask` (`0x4E7`) and `ClearStencil` (`0x368`) just before the clear and restores the shadowed state after (`gpu_3d_base.cpp:497-510`). Multisample raster is switched off around a colour clear (`:459, :465`). Arrays: an MME macro repeats the clear for every layer (`maxwell/clear_buffers.mme:5-22`). No pass concept: clears sit between draws. Ours: masked colour and stencil clears are **skipped** (check 3). | OGD 0x10f8; NXN; DK3D `maxwell/gpu_3d_base.cpp:444-512`, `engine_3d.def:305, 644` |
|
||||
| 1.4 | **Conditional rendering** (`SET_RENDER_ENABLE_A..C` 0x1550-0x1558, NVN `SetRenderEnableConditional`) compares two 64-bit counters at `addr` and `addr+16` on the GPU, in command order. TotK wraps nearly every clear in it. A `TIMESTAMP` report writes 0 to the counter field. | `VK_EXT_conditional_rendering` tests one 32-bit word against zero. | NXN: honouring it fixed the black 3D scene (light-volume depth never cleared). deko3d has no conditional rendering at all (no `SET_RENDER_ENABLE` in `engine_3d.def`), so it cannot settle the compare rule. Ours: evaluated on the CPU at record time; a report from an unfinished submission counts as 0 (check 5). | OGD; NXN |
|
||||
| 1.5 | **Depth mode** is runtime state: `nvnDeviceSetDepthMode` near = -w (GL, NVN default) or 0. Register `SET_VIEWPORT_Z_CLIP` (0x0d7c) `NEGATIVE_W_TO_POSITIVE_W` / `ZERO_TO_POSITIVE_W`. | Vulkan clips z < 0 unless `VK_EXT_depth_clip_control` `negativeOneToOne`. | Ryujinx infers the mode from the viewport transform, falling back to the register (`GetDepthMode`, RYU-SU). NXN: wrong mode either clips everything (black window) or puts all depth in 0.5..1 (DOF blurs the screen). Ours: `negativeOneToOne` from NVN state. DK3D programs both halves: `SetDepthMode` (`0x35F` = 0xd7c) selects the pre-transform clip range, and the viewport transform maps z to [near, far] itself: scale z = `0.5 * (far - near)` and offset z = `0.5 * (near + far)` for -1..1, scale `far - near` and offset `near` for 0..1 (`maxwell/gpu_3d_base.cpp:143-147, 336-343`). Same maths as Vulkan `negativeOneToOne`. | OGD 0x0d7c; NXN-64, NXN; DK3D `maxwell/gpu_3d_base.cpp:136-147, 321-362` |
|
||||
| 1.6 | **Depth clamp / clip**: `SET_VIEWPORT_CLIP_CONTROL` (0x193c) has separate `PIXEL_MIN_Z`/`PIXEL_MAX_Z` CLIP or CLAMP and geometry-clip modes. | `depthClampEnable` also disables z clipping (unless `VK_EXT_depth_clip_enable`). RADV had a dynamic depth clamp driver bug causing TotK vertex explosions. | Ryujinx: clamp = `!(clip & DepthClampDisabled)` (RYU-SU `UpdateDepthClampState`). yuzu disabled dynamic depth clamp on affected RADV (YZ-2305, PR 10262). DK3D has one switch, `depthClampEnable`, and writes `VIEW_VOLUME_CLIP_CONTROL` (`0x64F` = 0x193c) with `0x101A` when on and `0x181D` when off (default at setup is `0x181D`); it labels the bits "todo: figure out what this actually does". Bits 3-4 (`DepthClampNear/Far`) are set in both values, bits 0-2 and 11 differ. There is no separate depth-clip toggle. The viewport near/far registers (`Viewport` array words 2-3) carry the clamp range and are swapped when far < near (`:349-350`). Vulkan clamp to [min, max] of the viewport depth matches. | OGD 0x193c; DK3D `maxwell/gpu_3d_state.cpp:42`, `gpu_3d_base.cpp:135-139, 349-350`, `engine_3d.def:621` |
|
||||
@@ -66,8 +66,9 @@ Source shorthands:
|
||||
| 2.7 | **Swizzles** per texture and per view (`TextureBuilderSetSwizzle`, `TextureViewSetSwizzle`); BotW layout captures rebuild a texture on the same storage with (1, 1, 1, R) or alpha 1. Default per-format mapping R8 → (R, 0, 0, 1). | `VkComponentMapping` on the view. | NXN: font atlas white boxes, HUD dark boxes without it. Ours: mapped (`vk_exec_draw.c` `get_view`). | NXN |
|
||||
| 2.8 | **Sample dimension comes from the instruction**: a non-array sample of an array texture reads layer 0; 1,512 BotW shaders sample a cube as a cube array. | View type must match the declared type. | NXN: 2D array bound as 2D gave one pale colour (washed-out scene); cubes created as 6-layer arrays with cube / cube-array views. Ours: views per resource type (`get_view`). | NXN |
|
||||
| 2.9 | **LOD**: TSC min/max LOD clamp, LOD bias, `TWO_D_NO_MIPMAP` texture type, a min filter without mips stays on the base level; TIC carries its own max anisotropy and aniso quality fields. | `minLod`/`maxLod`, `mipLodBias` limited by `maxSamplerLodBias`. | yuzu: anisotropy heuristics for mods forcing trilinear (YZ-2306, PR 10744). Ours: non-mip filter → `maxLod = minLod + 0.25`, bias clamped (`vk_texture.c` `make_sampler`). | G80TEX |
|
||||
| 2.10 | **Texture gather rounding**: Maxwell sub-texel precision differs from AMD/Intel; edge texels picked by TLD4 differ by one. | Implementation-defined `subTexelPrecisionBits`. | yuzu adds a sub-pixel offset to gathers on non-NVIDIA hosts: fixed BotW shadow artifacts at object edges ("shader_recompiler: Add subpixel offset for correct rounding at ImageGather", <https://git.openpunk.com/OpenPunk/yuzu/src/commit/780240e6979b198e7bd10feaad5399b8b4b63762>, title only). | — |
|
||||
| 2.10 | **Texture gather rounding**: Maxwell sub-texel precision differs from AMD/Intel; edge texels picked by TLD4 differ by one. | Implementation-defined `subTexelPrecisionBits`. | yuzu adds a sub-pixel offset to gathers on non-NVIDIA hosts: fixed BotW shadow artifacts at object edges ("shader_recompiler: Add subpixel offset for correct rounding at ImageGather", <https://git.openpunk.com/OpenPunk/yuzu/src/commit/780240e6979b198e7bd10feaad5399b8b4b63762>, title only). Ours: the translator biases gather coordinates by the host's `subTexelPrecisionBits` on every non-NVIDIA GPU (`vk_caps.c` → job `gather_bias` → Ryujinx `TexturePass.InsertCoordGatherBias`); TotK on RADV drew dashed dark lines along wall and floor edges in the prologue caves without it. `TOTK_GATHER_BIAS=0` turns it off. | — |
|
||||
| 2.11 | **Gather offsets**: `TLD4.PTP` takes four per-texel offsets, possibly from registers. | `ConstOffsets` must be constant. | Ours: `QueryHostSupportsNonConstantTextureOffset() => false` makes Ryujinx emulate register offsets (`tools/xlate/Program.cs`). | RYU-SH `Translation/Optimizations` (TexturePass) |
|
||||
| 2.13 | **TXD gradient register order**: TotK's terrain shaders fill the gradient registers of a `TXD` per coordinate (du/dx, du/dy, dv/dx, dv/dy). | Vulkan's `Grad` takes dPdx (du/dx, dv/dx) and dPdy (du/dy, dv/dy). | Ryujinx's `EmitTxd` takes the first two registers as dPdx and the last two as dPdy, so the mip level came from the wrong derivatives and was too sharp on terrain faces turned across the screen: patches that followed the faces crawled when the camera moved (1.4.3, the Depths; found by the user from their F9 frame, a gradient sample's coordinate and gradients traced back to `DPdx` and `DPdy` of the interpolants). Ours: `gfx_shader.c` `patch_txd_transpose` swaps the two inner components of every two-component gradient pair in the loaded SPIR-V (the shader cache is untouched). `TOTK_TXD_TRANSPOSE=0` turns it off. Only 2D gradients are handled; 3D and cube ones are left as translated. | — |
|
||||
| 2.12 | **Depth compare** (`TSC` depth compare + `TIC_4_DEPTH_TEXTURE`), min/max reduction filtering. | `compareEnable`; reduction mode needs `samplerFilterMinmax` and is not allowed with compare. | Ours: reduction dropped when compare is on (`vk_texture.c` `make_sampler`). | G80TEX |
|
||||
| 2.13 | **ASTC / BC**: native ASTC; zero ASTC block = error colour on hosts. | AMD and NVIDIA desktop GPUs lack ASTC: decode to RGBA8. yuzu offered ASTC recompression to BC1/BC3 for low VRAM (YZ-2305, PR 10398). | Ours: native upload where the device samples ASTC, else a compute-shader decode (`vk_astc.c`, `TOTK_ASTC`), CPU decode (`tex_astc.c`) as the fallback. | `runtime/vk_astc.c` |
|
||||
| 2.14 | **Linear CPU-written textures** (`FLAGS_LINEAR`, small ramps, glyph caches): CPU writes visible to the GPU directly. | Must re-upload or use linear images over host memory. | NXN Mario: sky black without its 64×1 RGBA16F ramps. | NXN |
|
||||
@@ -80,11 +81,14 @@ Source shorthands:
|
||||
| 3.2 | **FMZ multiply mode** (`FMUL/FFMA/...` field `Fmz`, `.FMZ`): 0 × anything = 0, including Inf/NaN (DX9 rule). | IEEE: 0 × Inf = NaN. | Ryujinx decodes `Fmz` (`Decoders/InstDecoders.cs:306-309, 1901`) but no emitter reads it. Ours: same. Census needed (check 13). | RYU-SH |
|
||||
| 3.3 | **Denormals**: per-instruction `.FTZ`. | AMD flushes fp32 denormals by default; `VK_KHR_shader_float_controls` sets it per shader. | Ryujinx ignores `.FTZ`. Low risk. | RYU-SH (no `Ftz` use in `Instructions/`) |
|
||||
| 3.4 | **Warp size 32**: `SHFL`, `VOTE`, `S2R LANEID`, ballots are 32-bit. | AMD RDNA runs wave32 or wave64 per shader (the driver chooses; RADV fragment default wave64); `VK_EXT_subgroup_size_control` `requiredSubgroupSize = 32` fixes it. | Ryujinx adapts lane masks to `QueryHostSubgroupSize()` (default 32, `IGpuAccessor.cs:218`; `Instructions/InstEmitWarp.cs:72, 106`, `InstEmitMove.cs:175-185`). Ours: not overridden, no required size (check 6). | <https://docs.mesa3d.org/envvars.html> (`RADV_PERFTEST=pswave32`) |
|
||||
| 3.5 | **Discard (`KIL`)** keeps the quad's derivatives valid (demote semantics). | `OpKill` terminates; later derivatives in the quad undefined. | Ryujinx emits `OpKill` (`CodeGen/Spirv/Instructions.cs:508`). | — |
|
||||
| 3.5 | **Discard (`KIL`)** keeps the quad's derivatives valid (demote semantics). | `OpKill` terminates; later derivatives in the quad undefined. | Ryujinx emits `OpKill` (`CodeGen/Spirv/Instructions.cs:508`). Ours: on AMD's own drivers (`vk_caps.amd` without `mesa`) `vk_pipeline.c` `spirv_demote` turns each `OpKill` that a selection header branches to into `OpDemoteToHelperInvocation` plus a branch to the selection's merge block; `TOTK_DEMOTE` overrides. TotK's cloud shader discards and then takes `OpImageQueryLod`: with `OpKill` AMD's Windows driver lost fog in the fragments sharing a quad with a discarded one (#164). | <https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/EXT/SPV_EXT_demote_to_helper_invocation.asciidoc> |
|
||||
| 3.6 | **Implicit-LOD sampling in divergent control flow** works on Maxwell (TEX unit uses quad neighbours). | Undefined in non-uniform control flow; AMD whole-quad mode usually works. | — | VKSPEC (derivatives) |
|
||||
| 3.7 | **Integer division** does not exist (compiled to `XMAD`/`IMAD` sequences); MUFU.RCP(0) = +Inf, LG2(0) = -Inf. | Same IEEE edge cases through `1/x`, `Log2`. | Low risk. | — |
|
||||
| 3.8 | **FP64** in some TotK cutscene shaders. | No FP64 on some hosts. | yuzu FP64 → FP32 (YZ-2306, PR 10693); ours: `softfloat64` job flag (`tools/xlate/Program.cs` `QueryHostSupportsShaderFloat64`). | — |
|
||||
| 3.9 | **Integer vertex inputs read as raw bits** (bone indices `R8UI`). | Float-declared inputs convert integers. | NXN Mario: stretched characters; re-translated with `uint` inputs. Ours: attribute types passed to `QueryGraphicsState` (`Program.cs`). | NXN |
|
||||
| 3.10 | **BFE / BFI fields past bit 31** (as PTX `bfe` / `bfi`): a field that runs past bit 31 is cut there; one that starts past it extracts 0 (signed: bit 31 repeated) and inserts nothing. TotK 1.4.3's Depths terrain vertex shaders (42 variants) take the position from a register, `((2y + x) * 8) & 0xff` with 5-bit x and y, so up to 248. | `OpBitField*Extract` / `OpBitFieldInsert` undefined when offset or offset + count exceeds 32; AMD's bitfield instructions take offset and width modulo 32. | Ryujinx passes the fields through. UltraTears saw the Depths walls and ground missing on the Steam Deck and a Linux RX 570 (RADV). Ours: clamped where the field is not a constant inside the word (translator patch 0012). RX 9070 on Windows drew the Depths the same before and after. | PTX ISA `bfe`, `bfi` |
|
||||
| 3.11 | **SHF by 0** gives the unshifted word (C for `SHF.L`, A for `SHF.R`). | Ryujinx's funnel shifts the other word by 32: undefined in SPIR-V; AMD shifts take the low 5 bits and give A \| C. | yuzu fixed Depths terrain gaps in its funnel shift (PR 10459). Ours: a select on a zero amount (translator patch 0013). In 1.4.3 every register SHF pairs its word with 0, so the result was right already. | — |
|
||||
| 3.12 | **Registers read before any write** on a path (paths the structurizer adds included) have no defined value in the game's code; UltraTears reports 0 from the NVIDIA driver. | An `OpVariable` without an initializer loads an undefined value; Mesa folds undefined values freely. | Ours: on Mesa drivers (RADV, ANV, NVK; `vk_caps_driver`) every function-local variable starts at 0 (`OpConstantNull`, job flag `zero_locals`, translator patch 0016; `TOTK_ZERO_LOCALS` overrides). Elsewhere the load stays undefined: a zero start on every driver (the old patch 0014) made the whole picture shake by about 0.9 output pixels a frame with DLSS or DLAA on an RTX 4080 SUPER (#612). It also moved the SPIR-V hash of the game's FXAA shader out of `FXAA_FS` (`vk_dlaa.c` `vk_dlaa_skip_draw`), the likely cause of the shake; that path is not traced. | — |
|
||||
|
||||
## 4. Memory model
|
||||
|
||||
@@ -141,6 +145,8 @@ Source shorthands:
|
||||
| TotK | AO broken above 1008p mods | rescale thresholds | YZ-2306 PR 10675 |
|
||||
| TotK | "detective mode" Link on AMD | AMD EDS3 colour-blend driver regression | YZ-2306 PR 10946 |
|
||||
| BotW | shadow artifacts at object edges (AMD) | gather rounding | yuzu commit 780240e (2.10) |
|
||||
| TotK | dashed dark lines along wall and floor edges, changing with the camera angle (AMD, RADV) | gather rounding | gather bias (2.10) |
|
||||
| TotK | blocky foliage shadows that jump instead of sliding | not a GPU difference: the engine sizes its sun shadow map to the area it covers, down to about 400 near the ground, and each change of size moves the shadow texels | fixed size, `shadow_res` (the shadow set of `recomp/patches-v121.txt`; the community mods force 1024 the same way) |
|
||||
| BotW | black textures on GCN | HTILE (depth compression) | `AMD_DEBUG=nohyperz` wiki (1.9) |
|
||||
| BotW | 3D scene black | deferred texture handles | NXN |
|
||||
| BotW | albedo scattered squares | duplicate colour attachments | NXN |
|
||||
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
# Mods
|
||||
|
||||
TotK Recomp loads the mods players make for the Switch emulators (Ryujinx, yuzu and its forks): texture and model
|
||||
packs, gameplay and text changes from GameBanana and similar sites, TKMM's merged output, code patches (`.ips`,
|
||||
`.pchtxt`) and Atmosphère cheat files. No mod or cheat file ships with the port.
|
||||
|
||||
## Install a mod
|
||||
|
||||
1. Open the settings menu (F1, Esc, or Minus and Plus together on a controller), go to the Mods tab and choose
|
||||
**Open mods folder**. That is the `mods` folder next to `totk.exe`; the menu creates it when it is missing.
|
||||
2. Make one folder per mod in it and unpack the mod's archive into that folder. The mod's own folders (`romfs`,
|
||||
`exefs`, `cheats`) must sit directly inside the mod's folder:
|
||||
|
||||
```
|
||||
mods\
|
||||
Better Grass\
|
||||
romfs\
|
||||
...
|
||||
Fast Travel Anywhere\
|
||||
exefs\
|
||||
patch.pchtxt
|
||||
My cheats\
|
||||
cheats\
|
||||
277178B7DBA1B6D4.txt
|
||||
```
|
||||
|
||||
An archive laid out for a Switch SD card or an emulator works as it is. Inside the mod's folder the port also finds
|
||||
`atmosphere\contents\0100F2C0115B6000\romfs`, `contents\0100F2C0115B6000\romfs` and `0100F2C0115B6000\romfs`, the
|
||||
same places for `exefs` and `cheats`, and `atmosphere\exefs_patches\<name>\` for code patches.
|
||||
3. Start the game. A mod that patches the game's code makes the game rebuild itself first (see Code patches below).
|
||||
4. Open the Mods tab to check the mod. Each row says how many game files the mod replaces and adds, how many cheats it
|
||||
brings, and why a part of it is not used.
|
||||
|
||||
## 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. Changes apply after a restart.
|
||||
|
||||
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
|
||||
|
||||
Two mods that edit the same game file do not combine: the higher one wins the whole file. Merge such mods with
|
||||
[TKMM](https://github.com/TKMM-Team/Tkmm) (TotK Mod Manager) and set its export location to an empty folder inside
|
||||
`mods`, for example `mods\TKMM`. The exported folder then counts as one mod here. Mods packaged for TKMM only
|
||||
(`.tkcl` files) go the same way.
|
||||
|
||||
The port merges the resource size table on its own: at every start with mods on, it combines the tables the mods ship
|
||||
and raises the entries for files a mod made larger or added, the files inside a mod's packs (`Pack\**\*.pack.zs`)
|
||||
included. A separate RESTBL mod is not needed. The table tells the game how much memory each file needs: a file that
|
||||
outgrew its entry crashes the game when it loads, which can be long after the start, when the game first needs it. The
|
||||
log line `RomFS: resource size table: ...` says how many entries were raised and names the first files inside packs.
|
||||
|
||||
## Code patches (ExeFS)
|
||||
|
||||
A mod with `.ips` or `.pchtxt` files patches the game's code. A patch is for one game update: an `.ips` file is named
|
||||
after the build id of the update's code, a `.pchtxt` file names it on its `@nsobid` line. The game's code is compiled
|
||||
ahead of time, so these patches are built into `totk.exe`:
|
||||
|
||||
1. The first start after such a mod is added closes the game and opens the setup's rebuild window. The rebuild takes
|
||||
a few minutes (the shaders stay prepared), then the game starts again. Saves and settings are kept.
|
||||
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 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
|
||||
that change the game's code need the same rebuild as code patches. [cheats.md](cheats.md) explains the file names for
|
||||
each game update, the rebuild and which cheats cannot run.
|
||||
|
||||
## Renaming a mod folder
|
||||
|
||||
The port keys a mod by its folder name. A renamed folder counts as a new mod:
|
||||
|
||||
- it moves below the mods the list names, and comes back switched on;
|
||||
- its cheats come back switched off;
|
||||
- its code patches and code cheats are built again, so the next start runs the rebuild.
|
||||
|
||||
Rename mod folders before you set them up in the menu, not after.
|
||||
|
||||
## HD texture packs
|
||||
|
||||
Texture packs made for the emulators replace the game's textures with larger ones, so the heap the world's textures
|
||||
stream into must grow. Such a pack grows it in its own `System/HeapSize/Product.Nin_NX_NVN.HeapDef.byml.zs`, sized for
|
||||
the emulators' 8 GB memory option. The port reads that file at start: the texture heap and the game's memory pool grow
|
||||
by the pack's amount, and the game gets the port's own heap table with that growth (the log says
|
||||
`resolution: mod <name> ships a HeapDef with TextureHeap ...`). Nothing needs to be set. For a pack without such a file
|
||||
that still loops the panic Blood Moon, set `tex_heap_extra_mb` under `[mods]` in `totk.ini` (0 to 4096 MiB).
|
||||
|
||||
Tested: **HDPacks.com Tears of the Kingdom 4K Texture Pack v1.0** (`4kTextures`, 10,407 textures, 6.5 GB) on game 1.4.3
|
||||
and 1.2.1, RTX 4080 SUPER: it loads into the game from a save and runs at the same frame rate, with about 3.3 GB more of
|
||||
textures in memory (4.5 GB of game memory pools against 1.2 GB without it). Other packs are not tested and come with no
|
||||
guarantee. Such a pack needs a lot of video memory; on a GPU with less than 8 GB, `astc_bc = 1` under `[performance]`
|
||||
keeps its textures at a quarter of the size.
|
||||
|
||||
## What does not work
|
||||
|
||||
| On the Mods tab | Why | What to do |
|
||||
|---|---|---|
|
||||
| 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). | 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.
|
||||
|
||||
## When something looks wrong
|
||||
|
||||
1. Switch the newest mod off on the Mods tab and restart. If the problem goes away, check that the mod is made for your
|
||||
game update and does not fight another mod over the same files.
|
||||
2. `logs\totk.log` next to `totk.exe` names every mod at the start (lines starting with `mods:`), the cheats
|
||||
(`cheats:`) and the resource size table (`RomFS: resource size table:`). Open log folder on the Advanced tab of
|
||||
the menu shows the logs.
|
||||
3. When reporting a problem, attach `totk.log` and list your mods with the links you downloaded them from.
|
||||
@@ -0,0 +1,67 @@
|
||||
# Game 1.1.0 patch coverage
|
||||
|
||||
The built-in table is [recomp/patches-v110.txt](../recomp/patches-v110.txt). These sites were located in the local 1.1.0 main and checked against its original instruction words, rather than applying a version-wide address shift. The generator rejects a different word or an invalid spin back-edge.
|
||||
|
||||
## Added coverage
|
||||
|
||||
| Set | Sites added | Runtime control |
|
||||
| --- | ---: | --- |
|
||||
| realtime | 1 | Equipment-switch cooldown: step every positive remainder, including values below FLT_EPSILON. Follows the existing real-time clock switch. |
|
||||
| cursor | 3 | Scale map panning, vertical ability aim and vertical gyro aim by the 30 Hz ratio; follows `TOTK_HIGHFPS_FIX`. |
|
||||
| aspect | 4 | The two camera and two viewport projections read page +56. The resolution code enables it for non-16:9 output. |
|
||||
| fov | 2 | The two camera projections multiply their vertical angle by page +60. The field-of-view setting is live; 100 leaves the original path. |
|
||||
| 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 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.
|
||||
|
||||
## Deliberately separate
|
||||
|
||||
- Direct mouse: 1.1.0 continues to use stick emulation. Porting the complete camera hook set also needs the runtime layout and load-site table; matching an individual store or one camera mode is not sufficient. No partial set is enabled here.
|
||||
- Fade: the four 1.4.3 sites are not presumed to exist in 1.1.0. An equivalent zero-increment path has not been established.
|
||||
- Native Zstandard: the existing host bridge calls back to hard-coded 1.4.3 decoder entry points on fallback. Adding only the BL patches to 1.1.0 would be incorrect.
|
||||
- Live DLSS scene sizing and game-menu mouse input retain their existing version restrictions. They are not patch-table parity work.
|
||||
|
||||
## Validation
|
||||
|
||||
Run with Python's numpy, lz4, capstone and unicorn dependencies and a runtime-supported Clang:
|
||||
|
||||
```sh
|
||||
# CC selects the Clang used by the differential harness.
|
||||
python tests/patches_v110_check.py
|
||||
python tests/patches_v110_check.py --cflags=-march=x86-64-v2
|
||||
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.
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
# Profile-guided build
|
||||
|
||||
A profile-guided build compiles the generated code and the runtime at -O2 with an execution profile: a record of
|
||||
which functions and branches ran while someone played. Hot paths are laid out straight, hot calls are inlined, and code
|
||||
that never ran is compiled for size. On 1.4.3 a trained fight ran 12% faster per frame and an untrained fight about
|
||||
6%; on 1.2.1 the trained fight ran 11% faster.
|
||||
|
||||
Each game version has its own profile, `pgo-v121.profdata` and `pgo-v143.profdata`, trained on that version's code.
|
||||
|
||||
## How a build uses a profile
|
||||
|
||||
- `build_game.py --pgo <file>.profdata` compiles with that profile. Every compile depends on the file, so a new
|
||||
profile rebuilds everything.
|
||||
- `tools/pgo.py merge` writes the profile to `build\pgo\pgo-<ver>.profdata`, next to its record `pgo-<ver>.json`. The
|
||||
record holds the git tree of `recomp/` it was trained on and the digests of the runtime headers the generated C
|
||||
includes (`cpu.h`, `simd.h`, `simd_fp.h`).
|
||||
- `make_release.py` ships every profile in `build\pgo` in the release's `data\` folder. It warns when a record names
|
||||
another `recomp/` tree than the one released, or a header digest differs. The runtime libraries of the release
|
||||
compile with the newest version's profile.
|
||||
- The installer builds a player's game with `data\pgo-<ver>.profdata` when the release has one for that version, and
|
||||
at -O1 without it.
|
||||
|
||||
A profile only fits the code it was trained on. clang matches each function by name and control-flow hash, and a
|
||||
function whose code changed loses its counts without a warning (`build_game.py` passes `-Wno-backend-plugin`, which
|
||||
hides the "hash mismatch" messages). The inline helpers of `cpu.h`, `simd.h` and `simd_fp.h` become part of every
|
||||
lifted function, so a change to them invalidates the profile as surely as a generator change: one change to the
|
||||
floating-point helpers left a profile with a fifth of its weight and 2% of its gain.
|
||||
|
||||
## When to retrain
|
||||
|
||||
- After a change to the lifter or the generator (`recomp/`) that changes the generated C. Patch table changes
|
||||
(`recomp/patches-<ver>.txt`) touch only the patched functions and can wait for the next retrain.
|
||||
- After a change to `runtime/cpu.h`, `runtime/simd.h` or `runtime/simd_fp.h`.
|
||||
- Before a release whose `make_release.py` run warns about a profile.
|
||||
|
||||
Train both versions from the same commit, from a clean `recomp/`.
|
||||
|
||||
## Train
|
||||
|
||||
### 1. Instrumented build
|
||||
|
||||
MSYS2's clang has no profile runtime, so the instrumented build uses llvm-mingw (unpack it under `toolchain\`):
|
||||
|
||||
```powershell
|
||||
$llvm = "toolchain\llvm-mingw-<date>\llvm-mingw-<date>-ucrt-x86_64"
|
||||
.venv\Scripts\python tools\build_game.py --version v143 --out build\v143-pgogen --toolchain $llvm --pgo gen
|
||||
```
|
||||
|
||||
Regenerate `generated\<ver>` first if it is older than the commit you train on. If `totk.exe` stops at start with
|
||||
`0xc000007b`, copy `libiconv-2.dll` from `C:\msys64\ucrt64\bin` next to it.
|
||||
|
||||
`totk.exe` writes `build\v143-pgogen\pgo\default_<id>.profraw` every minute and at exit. Each run of the same exe adds
|
||||
to that file.
|
||||
|
||||
### 2. Shaders
|
||||
|
||||
Copy your `totk.ini` into the build folder and prepare the shaders (`tools\prepare_shaders.py build\v143-pgogen
|
||||
--version v143`). Shader preparation runs `totk.exe` too, so move `pgo\*.profraw` out of the build folder afterwards:
|
||||
its counts describe shader building, not play.
|
||||
|
||||
Keep the default settings, with the GPU command recorder on (`vk_recorder = 1`, the default).
|
||||
|
||||
### 3. Training scenes
|
||||
|
||||
The instrumented build runs slower than a normal one. Count each scene's time by the game clock, not by the wall
|
||||
clock. Spend 90 to 120 seconds on each of the first four scenes, where most frames are spent, and about 60 seconds on
|
||||
each of the others, which cover code the first four do not reach.
|
||||
|
||||
| Place | What to do | Time |
|
||||
| --- | --- | --- |
|
||||
| Lookout Landing | Stand in the middle of the town and turn the camera slowly all the way round, then walk through the crowd. | 120 s |
|
||||
| Kakariko Village | The same: a slow camera turn, then walk between the houses. | 100 s |
|
||||
| A fight with a Battle Talus | Fight it with weapons and the bow. | 110 s |
|
||||
| The Depths, near a Lightroot | Turn the camera over the lit area, throw a Brightbloom Seed. | 90 s |
|
||||
| The Depths, away from any light | Walk and turn the camera in the dark. | 60 s |
|
||||
| The edge of a sky island | Run off the edge, skydive, open the paraglider. | 60 s |
|
||||
| Outdoors in the rain | Walk and look around while it rains. | 60 s |
|
||||
| A cave with Brightbloom plants | Walk in and fight the Moblins and Bokoblins inside. | 60 s |
|
||||
| Inside a shrine | Walk through the first rooms. | 60 s |
|
||||
| A Moblin camp | Fight several Moblins at once. | 60 s |
|
||||
| Next to Yunobo | Use his ability: roll him into something. | 60 s |
|
||||
| Hyrule Field, by the standing stone pillars | Run across the field, also backwards past the pillars. | 60 s |
|
||||
|
||||
Keep two scenes out of the training, so that you can measure on scenes the profile has not seen: Hyrule Field in tall
|
||||
grass, and a fight with Moblins and Zonai constructs at once.
|
||||
|
||||
With a save at a scene, `tools\run_game.py` plays it without you: `--save <backup> --script <input file> --seconds
|
||||
<game time>` ([agents/running.md](agents/running.md)). Without a save, play the scenes by hand.
|
||||
|
||||
### 4. Free play
|
||||
|
||||
Then play for 15 to 25 minutes and touch every kind of thing the game does, so that no common path is left without
|
||||
counts:
|
||||
|
||||
- Run, sprint, climb, swim and glide; ride a horse; jump from a tower and skydive.
|
||||
- Fight with one-handed and two-handed weapons, a spear and the bow; shield parry, flurry rush, fused arrows.
|
||||
- Use every ability: Ultrahand (build a vehicle with a fan and wheels and drive it), Fuse, Ascend, Recall, Autobuild.
|
||||
- Call the sages and use their abilities: Tulin, Riju, Sidon, Yunobo, Mineru.
|
||||
- Open the inventory, the map and the camera; cook at a pot; talk to people in a town.
|
||||
- Travel quickly to a few places, so that areas load; enter and leave a shrine and the Depths.
|
||||
- Play in daytime and at night, in clear weather and in rain or snow.
|
||||
|
||||
### 5. Merge
|
||||
|
||||
```powershell
|
||||
.venv\Scripts\python tools\pgo.py merge build\v143-pgogen --version v143
|
||||
```
|
||||
|
||||
writes `build\pgo\pgo-v143.profdata` and its record. Merge right after the training, from the checkout and commit the
|
||||
instrumented build was made in: the record reads the `recomp/` tree from git and the header digests from the build's
|
||||
Ninja deps log.
|
||||
|
||||
Repeat steps 1 to 5 with `v121` for 1.2.1.
|
||||
|
||||
## Measure
|
||||
|
||||
Build the same code three ways in three folders with llvm-mingw, as the installer does: with the new profile, with
|
||||
the old one and with none. Prepare the shaders in each folder. Then run the held-out scenes and one trained scene
|
||||
in the order new, old, none, none, old, new, and compare the mean frame time over the same stretch of game time. One
|
||||
run of a fight can vary by up to 15% from the next, so a profile counts as better only when it wins both pairs.
|
||||
@@ -0,0 +1,91 @@
|
||||
# Rules for taking a PR
|
||||
|
||||
## 1. What to review first
|
||||
|
||||
1. Fixes before features. A PR that fixes a bug, a glitch or a crash goes first; feature PRs wait.
|
||||
2. Order fixes by reach: how many players the bug hits and how badly. Windows and default settings first, rare
|
||||
hardware and unusual setups later.
|
||||
3. Scale the depth of the checks to the reach. A crash many players hit and anything on the frame path get the full
|
||||
checks. A rare case (a CPU without AVX, an unusual setup) gets the minimal fix, one targeted check and a short
|
||||
note. A crash fix on rare hardware is still worth taking: cut the checks around it, not the fix.
|
||||
4. Before testing, find out where the bug reproduces: OS, GPU vendor and generation, game version, settings. If the
|
||||
symptom cannot appear on the hardware at hand (an NVIDIA paging bug on an AMD machine), say so and do not run
|
||||
tests that cannot decide it.
|
||||
5. Check a feature PR against the designs in `docs/milestones/`. A feature with a design (mods, cheats) goes in as
|
||||
part of that design.
|
||||
6. Several PRs on one topic: compare them before taking either. Another PR may already do it right.
|
||||
|
||||
## 2. How to read the diff
|
||||
|
||||
- The author's claim is a hypothesis. Read the whole diff: races, wrong semantics, edge cases, leaks, lock order.
|
||||
- Check the behaviour against evidence: how yuzu, Ryujinx, LAS Recomp, SavageWindRecomp, nxnative and MacNativeGames
|
||||
do the same thing in `refs/` (`tools/fetch_refs.sh` recreates it); the Vulkan spec; hardware docs
|
||||
([docs/maxwell.md](../../docs/maxwell.md)); upstream issues.
|
||||
- Weigh two things for every change: its cost on the hot path, and how it fails (device lost, hang, stale data, weak
|
||||
or non-AVX CPUs, other GPU vendors, Wine/Proton).
|
||||
- Read the code a hypothesis depends on before running the game: the game's functions in Ghidra or
|
||||
`generated/<ver>`, our path in `runtime/`. A run confirms what the code could not rule out. It is one run, not a
|
||||
series of variants.
|
||||
- Order the work so the cheapest check that could refute the PR's idea runs first. Refuted: stop, write down why,
|
||||
no build, no benches.
|
||||
|
||||
## 3. What a PR needs
|
||||
|
||||
- **Proof.** The bug reproduced before the fix, the same repro after, both results side by side: a screenshot, a log
|
||||
line, a probe, a differential test. A fix without a reproduced failure is not proof. Where a repro is impossible
|
||||
on the hardware at hand, say so; the fix is then taken only on strong static evidence in the code. Where a repro is
|
||||
risky (device lost or a TDR can hang the machine), write the recipe and let the owner decide.
|
||||
- **Frame-path changes** get whole runs of the heavy scene with the switch off and on, at least two each
|
||||
([02-performance.md](02-performance.md)). Zero new slow frames is a hard bar.
|
||||
- **A switch.** A change on the hot path or in rendering sits behind an env or `totk.ini` switch, so a player can turn
|
||||
it off and we can compare.
|
||||
- **Nothing changes for players outside the feature.** The DLSS PRs touched shared code; they went in once every
|
||||
path that runs without DLSS was gated on DLSS being on.
|
||||
- **A fix for one setup keeps the default for everyone.** The PRs that raised the low memory block from 6 to 10 GiB for
|
||||
all players were rejected; the right shape is 6 GiB plus the extra where it is needed.
|
||||
- **Parts we cannot run** (Linux-only code, an HDR display, RTX-only paths) are gated so they cannot touch anyone
|
||||
else, or wait for a report from someone with that hardware. Note them as unrun.
|
||||
- **Project tests** from [03-correctness.md](03-correctness.md): lifter differential tests, probes, `--selftest`,
|
||||
`tools/check_content.py --staged`.
|
||||
- **Text the player sees** goes into the catalog: `runtime/ui_text.h` ids and `runtime/ui_text.c` entries in every
|
||||
language the menu has (English, Russian, Brazilian Portuguese, Simplified Chinese), and `installer/text/*.json` for
|
||||
the installer. No hardcoded sentences, no second string table.
|
||||
- **A new setting** is described in `totk.ini.example` and [docs/settings.md](../../docs/settings.md).
|
||||
- **Licences.** MIT, BSD, ISC, zlib and Apache-2.0 code may be copied, with its header and a row in
|
||||
`THIRD_PARTY_NOTICES.md`. yuzu, suyu and other GPL code is read for behaviour only; we write our own.
|
||||
|
||||
## 4. Reasons to reject or rework
|
||||
|
||||
- No test or repro for a change that is not trivial.
|
||||
- Slow: a state copy per draw, a global atomic counter on the hot path, synchronous file I/O or a GPU allocation on a
|
||||
game or render thread, new slow frames.
|
||||
- Changes behaviour for everyone to serve one setup, or is on by default without a run in a scene where it acts.
|
||||
- "Fixes" a crash by turning a feature off for a vendor. A crash that goes away with a feature off points at the bug;
|
||||
the feature gets fixed.
|
||||
- Breaks another feature (a preview that loses anti-aliasing).
|
||||
- Fake features: labelled FSR4 or frame generation, and not that.
|
||||
- Wrong measurements: percentiles over window means, counters over the wrong set.
|
||||
- Generated C edited by hand instead of the generator (`recomp/`).
|
||||
- A disallowed licence or pasted GPL code.
|
||||
|
||||
## 5. Finishing a good PR
|
||||
|
||||
A good PR that misses the project's scheme (hardcoded text, conflicts, layout, comment style) is brought to it while
|
||||
merging, not sent back to the author for another round. When only part of a PR is good, take that part and note what
|
||||
was left out and why.
|
||||
|
||||
A bug found outside the PR under review is not fixed on the spot: search the open PRs on that topic, report the bug
|
||||
with them, and let the owner decide.
|
||||
|
||||
## 6. Merging, branches, commits
|
||||
|
||||
- Each PR or wave of PRs gets its own branch `task/<tag>` from a fresh `dev` and its own build dir. It merges into
|
||||
`dev`.
|
||||
- Once the review is done, the symptom is gone on one paired shot and the probes pass, merge into `dev` and hand the
|
||||
build to players: they test in game faster and wider than our routes. The wider checks (other routes, validation,
|
||||
fps cost) follow as a separate diff. Speed never skips the review of the diff itself.
|
||||
- `main` only with the owner's explicit yes. Push only when told to.
|
||||
- A commit message is a plain English sentence, no `feat:`/`fix:` prefixes.
|
||||
- The version lives in the repo-root `VERSION` file; the owner decides when it moves.
|
||||
- After a merge, record which PRs went in, what was reworked, what was rejected and why. The reason for a rejection
|
||||
goes into the PR as a plain English comment.
|
||||
@@ -0,0 +1,97 @@
|
||||
# Performance: no lost frames on weak hardware
|
||||
|
||||
## Who we tune for
|
||||
|
||||
- The goal is many more fps on modest hardware, and Steam Deck later (Zen 2 4c/8t APU, shared LPDDR5, the exe runs
|
||||
through Proton/Wine).
|
||||
- The developer's machine (Ryzen 9 7900X + RX 9070) is fast and its numbers do not carry over. A laptop with an
|
||||
i7-9750H and a GTX 1050 Ti is a sample of a weak machine, not the target to fit constants to.
|
||||
- What weak hardware measured:
|
||||
- GTX 1050 Ti (4 GiB, 214 MiB BAR, no ReBAR): the GPU read imported host pools over PCIe, 110-120 ms a frame
|
||||
against 4.3 ms on the RX 9070. The VRAM mirror brought it to 10-11 ms; that machine is now CPU-bound at 25-45 fps,
|
||||
replay 25-30 ms a frame.
|
||||
- The same write-watch scan costs about 3x the CPU time there.
|
||||
- NVIDIA and desktop AMD GPUs have no ASTC: textures decode in a compute shader. CPU decodes before that made
|
||||
0.4-0.7 s load frames on the 1050 Ti.
|
||||
- Wine emulates `GetWriteWatch` with `mprotect` and a fault per first write. Anything relying on cheap OS memory
|
||||
tricks (write-watch, `VirtualProtect` freezing, fault handlers) is checked against Wine's implementation.
|
||||
- The port uses about half of even a weak CPU, so the frame's critical path is the limit, not throughput. TotK keys
|
||||
per-core data by `GetCurrentProcessorNumber` without locks, so the game's threads share three virtual cores on any
|
||||
host. In a fight the main thread and five job workers keep 2.6 of the 3 busy: guest code speed sets the fps.
|
||||
- Perf work builds and measures 1.4.3. A 1.2.1 build is for a change about to merge with a large gain.
|
||||
|
||||
## Gain ceiling first
|
||||
|
||||
Before writing or taking a perf change, compute its ceiling: the share of the code it removes times the share of the
|
||||
frame that code holds on the critical path, on weak hardware. A ceiling of a few percent or less is not worth it.
|
||||
|
||||
- Use the critical path (`TOTK_CRIT` + `tools/crit_path.py`, heavy frames only), not one thread's profile. On the weak
|
||||
laptop the submit thread is 55% replay, yet the critical path of heavy frames is 67% guest code, 15%
|
||||
`nvnSyncWait`, 13% core waits and wake latency.
|
||||
- Changes that can move the frame by 10% or more are usually design changes. Polishing a hot function from a flat
|
||||
profile almost always gives zero.
|
||||
|
||||
## A neutral safe change stays
|
||||
|
||||
An optimization that measures neutral on the fast machine stays on by default when:
|
||||
|
||||
- upstream (`refs/`, other ports) reports a gain for it, especially on weak CPUs or GPUs;
|
||||
- the static read leaves no hazard, and the probe or differential test passes;
|
||||
- whole heavy-scene runs off/on x2 show no fps loss and no new slow frames;
|
||||
- a switch turns it off.
|
||||
|
||||
"No gain here" is not a reason to drop a safe change with upstream evidence. A regression or a hazard nobody ruled
|
||||
out is.
|
||||
|
||||
## How to measure
|
||||
|
||||
- **By game time, never by frame counts.** Run length, analysis windows, A/B blocks and input scripts go by the world
|
||||
clock (`--seconds`, `TOTK_CRIT=w<lo>-<hi>`, `TOTK_PROFILE_FRAMES=w<lo>-<hi>`, `TOTK_SHOTS=w<lo>-<hi>:<step>`). The
|
||||
same frame count at another fps is another scene.
|
||||
- **Check a scripted run reached the world.** Title menus on a slow boot eat button presses; confirm the run is in the
|
||||
world before trusting its numbers.
|
||||
- **Whole runs off and on, two each at least.** An in-run A/B on a moving scene lies: the A and B blocks land on the
|
||||
same game seconds every run, so a content difference repeats. One in-run A/B showed "-11% replay"; whole runs gave
|
||||
5.84/5.73 against 5.76/5.73 ms, nothing. In-run A/B only on a static scene (standing still).
|
||||
- **Spread.** One script on near-identical builds gave 1% lows from 31.5 to 50 fps. Compare medians of three runs,
|
||||
never one run against one run.
|
||||
- **A quiet machine.** `tools/run_game.py --quiet` takes the machine-wide lock; no other `totk.exe`, build or test runs
|
||||
meanwhile. One game at a time.
|
||||
- **A warm shader cache, prepared properly.** Shader and pipeline caches are not copied between build dirs:
|
||||
`totk.exe --prepare-shaders` or `--warm-shaders` in that dir. The AMD driver cache is keyed to the exe path and
|
||||
limited in size: preparing another build dir can evict this one's libraries (40-220 ms per new effect in play).
|
||||
- **A heavy scene.** A fight with a large enemy and a crowd, fps limit at the maximum (`TOTK_FPS_LIMIT=360`). Compare
|
||||
one shot with the scene's reference before trusting numbers.
|
||||
- **No base runs by habit.** Run the candidate alone and judge it against the targets: max fps, zero slow frames
|
||||
(`perf: slow frame`), no black or flat frames, no new validation errors. Glitches are found by looking at shots and
|
||||
frame dumps, not by diffing metrics. Run a base build only when a specific question needs a side-by-side.
|
||||
|
||||
| What | How |
|
||||
|---|---|
|
||||
| fps, worst frame, render-thread buckets, GPU busy, VRAM | `--env TOTK_TRACE=perf,sched`, then `python tools/perf_summary.py <log> <lo> <hi>` |
|
||||
| the frame's critical path | `TOTK_CRIT=w<lo>-<hi>` + `TOTK_CRIT_OUT=<path>`, then `python tools/crit_path.py <file>` |
|
||||
| sampling profiler | `TOTK_PROFILE=<path>` + `TOTK_PROFILE_FRAMES=w<lo>-<hi>`, then `tools/prof_report.py <profile> <totk.map>` |
|
||||
| A/B on a static scene | `TOTK_AB=<seconds>`, then `tools/ab_summary.py --skip <seconds>` |
|
||||
| VRAM pressure on a large card | `TOTK_VRAM_LIMIT_MIB=<MiB>` caps the budget the port sees |
|
||||
|
||||
## What the hot path must not do (Windows host)
|
||||
|
||||
- **Files.** The game threads (main, job workers) and the render thread never open, read, write or flush a file, and
|
||||
never wait for a thread that does. Opening a 20-byte file in a 139k-file folder: 0.1 ms idle, 11-40 ms in play while
|
||||
the translator, the pipeline cache and the save wrote to the same volume. A save's `FlushFileBuffers` and
|
||||
`MOVEFILE_WRITE_THROUGH`: 93-135 ms. Saving the pipeline cache under its lock on the present thread froze the replay
|
||||
every 20 s. File I/O goes to a background thread; results come back in memory.
|
||||
- **Waits.** Short waits spin on the counter; waits over 1 ms use the high-resolution timer. A waitable timer wakes
|
||||
0.3-0.5 ms late; the SDK's 20 us sleeps took 460-515 us. A 1 ms timer thread does not help: it gave more slow frames.
|
||||
- **GPU allocations.** VMA's `vkAllocateMemory` of a 256 MiB block under its lock: 8-23 ms. A new block on the render
|
||||
thread is a hitch.
|
||||
- **128-bit division.** `(unsigned __int128)t * num / den` compiles to the library call `__udivti3`; counter
|
||||
conversions that way took a tenth of the game threads' time in a fight. Use the precomputed scale (`platform.h`
|
||||
`PlatScale`).
|
||||
- **Per-draw copies and counters.** A pipeline-state copy per draw, a global atomic counter, a scan of every page each
|
||||
frame: on a weak CPU each is frames.
|
||||
- **Memory kept per frame.** Anything allocated per texture initialization or per frame must be freed. One copy kept
|
||||
per texture init grew host memory by ~44 MiB a game minute until a commit failure after hours (#670). Check private
|
||||
memory over a few idle minutes for a PR that stores per-object state.
|
||||
- **Scheduling.** Any timing or scheduling change is checked for slow frames. A preempt check at every host call made
|
||||
one bug rarer but added 50-75 ms CPU hitches and was reverted.
|
||||
@@ -0,0 +1,92 @@
|
||||
# Correctness: checks that keep behaviour intact
|
||||
|
||||
## Lifter and generated C
|
||||
|
||||
- Generated C is never edited by hand: change the generator in `recomp/`.
|
||||
- `recomp/layout.py` alone decides module bases.
|
||||
- Every change to the lifter or the CPU headers (`runtime/cpu.h`, `runtime/simd.h`) passes the differential tests
|
||||
against Unicorn, all run with `.venv`:
|
||||
|
||||
| Test | Checks |
|
||||
|---|---|
|
||||
| `tests\diff\lift.py` | instructions sampled from the modules; `--coverage` lists the words the lifter rejects |
|
||||
| `tests\diff\simd.py` | the whole FP/SIMD encoding space |
|
||||
| `tests\diff\atomic.py` | exclusive load/store and ARMv8.1 atomics |
|
||||
| `tests\diff\func.py` | whole functions as the generator emits them: loops, jump tables, calls |
|
||||
| `tests\flags_check.py` | the function-local flag helpers against the packed ones |
|
||||
| `tests\excl_mt.py` | the exclusive monitor under contention and ABA, on several threads |
|
||||
| `tests\jumptables_check.py` | `recomp/jumptables.py` against Unicorn: 0 disagreements on 1.2.1 and 1.4.3 |
|
||||
|
||||
- A `--cpu v2` build (no AVX2) passes the same tests with `--cflags=-march=x86-64-v2`. Players without AVX exist.
|
||||
- A compile error in generated C on a line the generator could not have written is a bit flip on disk or in memory.
|
||||
Regenerate and compare hashes; leave `recomp/` alone.
|
||||
|
||||
## Runtime
|
||||
|
||||
- From the build dir: `totk.exe --selftest`, `--probe-kernel`, `--probe-vkexec`, `--probe-nvn-tex`, `--probe-shader`
|
||||
pass.
|
||||
- Settings: `totk.exe --probe-cfg` and `python tests\settings_doc_check.py`.
|
||||
- Button prompts: `.venv-py314\Scripts\python tests\romfs_prompts_test.py`. Build dirs carry only `romfs-patches`; to
|
||||
test PC or Xbox prompts in game, generate the overlay first:
|
||||
`.venv-py314\Scripts\python tools\make_romfs_patches.py --version <ver> --prompts pc --out build\<dir>\romfs-patches-pc`,
|
||||
then restart the game.
|
||||
- Installer: `tests\installer_gui_test.py` (event model, form, catalogs, cancel, display scale).
|
||||
- Shaders: `tools\shader_census.py --version <ver> --translate`, `tools\xlate_smoke.py`. A translator patch
|
||||
(`tools/xlate/patches/`) needs `build/xlate` rebuilt and changes shader hashes: anything keyed to a shader hash
|
||||
breaks with it.
|
||||
|
||||
## GPU portability
|
||||
|
||||
- New Vulkan code queries the feature, extension, format or limit it uses and keeps a working path or a logged
|
||||
fallback without it (provoking vertex and subgroup size pinning in `vk_pipeline.c` are examples).
|
||||
- Never hardcode what one GPU reports: alignments, subgroup size (RDNA4 may run wave64, old AMD Vega is wave64 only),
|
||||
depth formats, `maxPushDescriptors`.
|
||||
- One queue: every submit and present takes `vk_queue_lock`. Presenting from its own thread on a second queue gave
|
||||
device lost on GTX 10-series in another port.
|
||||
- RDNA1/2 bugs do not reproduce on RDNA4 (another driver branch); NVIDIA bugs do not reproduce on AMD. A Ryzen 7000
|
||||
iGPU is RDNA2 and runs the RDNA1/2 driver branch: a cheap testbed for those reports.
|
||||
- Validation: a `--validation` run in the world shows no new messages.
|
||||
|
||||
## Maxwell / NVN behaviour
|
||||
|
||||
The port must do what the Switch GPU does, not what Vulkan does by default. The full list with sources:
|
||||
[docs/maxwell.md](../../docs/maxwell.md), section 7. The traps a PR breaks most easily:
|
||||
|
||||
- Provoking vertex: Vulkan takes the first vertex, NVN the last.
|
||||
- Unwritten vertex outputs read (0, 0, 0, 1).
|
||||
- A colour target outside the fragment shader's output map keeps its texel (write mask 0). AMD writes garbage there.
|
||||
- Feedback loops: the G-buffer pass reads its own targets. It needs the feedback layout and a by-region barrier.
|
||||
- Depth bias argument order, depth mode, depth clamp: checked against deko3d.
|
||||
- Report timestamps: the engine's GPU time comes from them, and dynamic resolution and game speed follow it.
|
||||
|
||||
## Timers and the real-time step
|
||||
|
||||
- With `realtime` set, the game steps by a measured ratio, not whole 30 Hz units. A countdown remainder in
|
||||
(0, FLT_EPSILON] is never stepped again, and a consumer testing `> 0` sees it active forever. That was "weapons
|
||||
cannot be changed after a Fuse until a reload" (#18).
|
||||
- Symptoms of this class: stuck until a reload or teleport, locked after an action, works sometimes.
|
||||
- A PR touching the frame step, the pacer or the fps limit is checked for this class.
|
||||
|
||||
## Threads and scheduling
|
||||
|
||||
- ARMv8 `stlr` then `ldar` is ordered (RCsc); C11 release/acquire lets x86 reorder that store and load. Changes to
|
||||
the lifter's barriers or atomics pass `tests\diff\atomic.py` and `tests\excl_mt.py`.
|
||||
- A scheduler change is judged from one `TOTK_TRACE=sched` run by how long a ready, better thread waits for a core it
|
||||
may use, plus the slow-frame count. Not by statistics over many runs.
|
||||
- A crash that looks like a race: rule out the save first. One reported crash was the save itself; it crashed the
|
||||
same way on a real Switch.
|
||||
|
||||
## Files and caches
|
||||
|
||||
- A crash leaves zero-filled files. Caches are validated on load, not trusted because they exist.
|
||||
- The pipeline cache is dropped when vendor, device or `pipelineCacheUUID` change.
|
||||
- Unicode paths: W APIs with UTF-8 to UTF-16 conversion.
|
||||
- A failure that happens once and does not come back: rerun before debugging it as a code bug. Broken caches and bit
|
||||
flips happen.
|
||||
|
||||
## Game content boundary
|
||||
|
||||
- The repository is public. No game files, and nothing extracted or generated outside `build/` and `generated/`.
|
||||
- Keys never appear in logs, commands, files, issues or comments.
|
||||
- Every file the generator emits carries the `GENERATED_MARKER` defined in `tools/check_content.py`.
|
||||
- `python tools/check_content.py --staged` before every commit. CI runs the same check.
|
||||
@@ -0,0 +1,98 @@
|
||||
# Knowledge base
|
||||
|
||||
Before investigating a symptom, or trusting a PR that "fixes" it, look for it here. Search by what the player sees
|
||||
(black, magenta, flicker, slow motion, missing, stale, streaks) and by the object (sky, grass, shadow, fog, HUD).
|
||||
|
||||
## Invariants of recent changes
|
||||
|
||||
A PR that touches these areas must keep them.
|
||||
|
||||
- **Queue order.** When anything is submitted, every earlier part is already on the queue. Present, uploads, readbacks
|
||||
from guest threads and the `vkDeviceWaitIdle` sites rely on it. The recorder thread now begins, ends and submits
|
||||
the parts it records; the submitting thread still waits for that submission, so the order holds.
|
||||
`TOTK_REC_END=0` restores the old split.
|
||||
- **GPU-written memory is never frozen.** Storage-buffer stores, copies and fills land in imported guest memory
|
||||
without a fault or a write-watch bit, so a region only the GPU writes looks idle. Such regions are never frozen
|
||||
read-only, and a frozen region is thawed before a GPU write. LAS Recomp never changes the protection of imported
|
||||
memory because of NVIDIA. A suspected cause of NVIDIA "write invalid" device faults (#788, #802), not proven.
|
||||
- **VRAM pressure.** Under pressure, released textures whose storage the game has given to another texture go first:
|
||||
30 s after release and once no finalized slot has bound them for 600 submits. Clean mirrored entries wait 5 s.
|
||||
Both stop once use is back under the line. A PR touching texture lifetime is tested with `TOTK_VRAM_LIMIT_MIB`.
|
||||
- **Texture pins are freed.** Each pin counts the recording copies naming it and is freed 1200 submits after its last
|
||||
use unless the replay holds it as a render target. Before that, pins leaked ~44 MiB a game minute (#670).
|
||||
|
||||
## Fixed bug classes
|
||||
|
||||
If a PR touches this code, confirm the fix still holds.
|
||||
|
||||
| Symptom | Cause | Where the fix is |
|
||||
|---|---|---|
|
||||
| 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` |
|
||||
| streaks on cliffs | primitive restart ignored | `vk_exec_draw.c` `restart_for` |
|
||||
| streaky map screen | the newest texture picked at shared storage | `vk_texture.c` `vk_texture_by_id` |
|
||||
| dark 16x16 blocks on the ground, sage spirit not drawn | G-buffer feedback loop | `vk_exec_draw.c`, `TOTK_FEEDBACK` |
|
||||
| magenta cave walls, brown sky | CPU-filled textures without a flush | write-watched mirrors, `vk_memory.c`, `vk_texture.c` |
|
||||
| black 3D scene | deferred texture binds | `nvn_api_cmd.c` `Bind*Deferred` |
|
||||
| HUD prompt boxes, black stamina wheel | `nvnTextureCompare` ignored the channel mapping | `nvn_api_obj.c` |
|
||||
| crash on world load | `GetCommandMemoryUsed` did not follow the driver's sizes; the game sizes model heaps from it | `nvn_api_cmd.c` |
|
||||
| 20 fps | a yield back-off starting before 2 ms | `kernel.c` SVC 0x0B: no back-off |
|
||||
| weapons locked after a Fuse (#18) | timer remainder in (0, FLT_EPSILON] with the real-time step | patch under the `realtime` setting |
|
||||
| magenta/blue garbage or device lost on RDNA1/2 (#5) | writes into 3D BC block views | in `dev` |
|
||||
| black window after a driver update | a pipeline cache from another driver | `vk_pipeline.c` drops the cache by UUID |
|
||||
|
||||
## Known open risks
|
||||
|
||||
A PR touching these needs stronger proof.
|
||||
|
||||
- Buffer textures are not replayed and bind a stand-in: light and decal lists may read 0.
|
||||
- New GPU-only colour images start undefined; feedback effects may show garbage.
|
||||
- Clears with a partial channel or stencil mask are skipped (`W_CLEAR_MASK`, `W_STENCIL_MASK`).
|
||||
- 8-bit indices are widened on the CPU at record time; a copy in the same submission gives stale indices.
|
||||
- `UpdateUniformBuffer` is a copy between full barriers and ends the render pass (fps outdoors).
|
||||
- Report timestamps carry host time at fence completion: the engine's GPU time is wrong.
|
||||
- The game's SVC-free spin loops burn a host core (843 in `main`).
|
||||
- Images aliased onto one GPU-only pool allocation do not see each other's data on AMD.
|
||||
|
||||
## Past PR decisions
|
||||
|
||||
| PR | Decision | Why |
|
||||
|---|---|---|
|
||||
| #690 shrine snapshots | rejected | a pass restart per copy, a `VkPipeState` copy per draw, broken `bind_sig` skip; fps loss |
|
||||
| #674 | rejected | a global STXR counter on the hot path |
|
||||
| #660 | rejected | the preview loses anti-aliasing |
|
||||
| #713, #576 | rejected | low memory block 10 GiB for everyone; should be 6 GiB plus the extra where needed |
|
||||
| #573 | rejected | dynamic resolution off by default for everyone, the 1.4.3 site never run |
|
||||
| #568, #569 | rejected | fake FSR4 and frame generation |
|
||||
| #487 | rejected | wrong metrics: percentiles over window means, counters over the wrong set |
|
||||
| #451, #380 | rejected | not painless to take |
|
||||
| #566, #594, #534 DLSS | taken with changes | #594's shared paths gated on DLSS being on; nothing changes without DLSS |
|
||||
| #489 | partly taken | the runtime part checked by a frame dump; the installer's DLL download was the owner's call, its pinned hash re-checked |
|
||||
| #519, #582 amiibo | rewritten by us | took the data-format fixes; left out the features and the Linux event rework |
|
||||
| #483 vs #585 | #585's mapping kept | #483's stick glyph mapping was rewritten unasked while #585 already had it right |
|
||||
| #528 rain | taken after a check | code review fine, merged only after a run on a rain save |
|
||||
| #767 | taken with our fix | the default was skipped with `prompts = xbox\|pc` when those folders did not exist |
|
||||
| #625 frame queue | taken, off by default | a new frame queue, one field run with it on |
|
||||
| #743 UB overlay | waiting | +25% in a Depths fight on an RTX 4080; needs review, fight runs x2 and shots on AMD |
|
||||
|
||||
## Our mistakes, not to repeat
|
||||
|
||||
- **"-11%" was an A/B artifact** of a moving scene. Whole runs off/on showed zero.
|
||||
- **Micro-optimizations from a flat profile** (1-3% of samples each) gave 26.2 against 26.4 ms on the weak laptop:
|
||||
nothing. Nobody had computed a ceiling.
|
||||
- **A scheduler patch merged on run statistics** added 50-75 ms hitches. Slow frames are a hard bar.
|
||||
- **Ten game runs on lock theories** where one Ghidra read of the game's code narrowed it at once.
|
||||
- **45 minutes of builds and benches** on an idea its own first thread census had refuted: the game pins 53 of 56
|
||||
threads itself. The cheapest refuting check goes first; when it refutes, stop and write the idea down.
|
||||
- **Tests of a bug that could not appear on the hardware at hand** (NVIDIA paging on an AMD machine): 245k tokens and
|
||||
37 minutes for nothing. Ask first where the bug reproduces.
|
||||
- **Turning the recorder off for a vendor** instead of finding its bug. Stopped: the feature gets fixed, not silenced.
|
||||
- **Bisecting code when every build crashed the same way at once.** The cause was a bad page of a game file in the OS
|
||||
file cache. When all builds fail identically, suspect inputs and caches first.
|
||||
- **A duplicate issue closed with a bare "Same as #N"** lost the logs and links. Move everything useful to the issue
|
||||
that stays open first: hardware, driver, version, when it happens, workarounds, links from comments.
|
||||
@@ -0,0 +1,49 @@
|
||||
# Per-PR checklist
|
||||
|
||||
## Before reading
|
||||
|
||||
- [ ] Fix or feature? Fixes first, ordered by how many players they reach.
|
||||
- [ ] Where does the bug reproduce: OS, GPU vendor and generation, game version, settings? Can the hardware at hand
|
||||
show it?
|
||||
- [ ] Is the symptom in [04-knowledge.md](04-knowledge.md) or `docs/maxwell.md`?
|
||||
- [ ] Another open PR on the same topic? Compare them.
|
||||
- [ ] Feature: is there a design in `docs/milestones/`?
|
||||
|
||||
## Reading the diff
|
||||
|
||||
- [ ] The whole diff read, not the description: races, edge cases, lock order, leaks.
|
||||
- [ ] Behaviour checked against `refs/` (Ryujinx, yuzu, LAS, SavageWind, nxnative, MacNativeGames), the Vulkan spec,
|
||||
`docs/maxwell.md`.
|
||||
- [ ] Hot-path cost: no file I/O, GPU allocations, waits, per-draw copies or global atomics on game or render threads.
|
||||
- [ ] No memory kept per frame or per object without a free.
|
||||
- [ ] Failure modes: device lost, hang, stale data, CPUs without AVX, NVIDIA/Intel/old AMD, Wine/Proton.
|
||||
- [ ] New Vulkan code queries the feature and has a fallback; nothing hardcoded for one GPU.
|
||||
- [ ] Invariants kept: queue order, GPU-written memory never frozen, VRAM pressure path, pins freed.
|
||||
- [ ] Players without the feature see no change. The default for everyone stays for one setup's sake.
|
||||
- [ ] New behaviour behind a switch. A new setting described in `totk.ini.example` and `docs/settings.md`.
|
||||
- [ ] Player-visible text in the catalogs, in every menu language (`runtime/ui_text.c`, `installer/text/*.json`).
|
||||
- [ ] Copied code: allowed licence, header kept, row in `THIRD_PARTY_NOTICES.md`. No GPL code.
|
||||
- [ ] Generated C not edited by hand.
|
||||
- [ ] Parts we cannot run (Linux, HDR, RTX-only) gated away from everyone else and noted as unrun.
|
||||
|
||||
## Proof
|
||||
|
||||
- [ ] Repro before the fix and the same repro after, side by side.
|
||||
- [ ] Lifter or CPU headers: differential tests against Unicorn; `jumptables_check.py` 0 disagreements.
|
||||
- [ ] Runtime: `--selftest` and the four probes pass.
|
||||
- [ ] Settings: `--probe-cfg` and `tests\settings_doc_check.py`. Prompts: `romfs_prompts_test.py`, overlay generated
|
||||
for a game check.
|
||||
- [ ] Frame path: whole heavy-scene runs off/on, two each at least, by game time, quiet machine, warm cache prepared
|
||||
in that build dir. No fps loss, zero new slow frames.
|
||||
- [ ] Rendering: shots or a frame dump in a scene where the change acts; no black or flat frames; no new validation
|
||||
errors.
|
||||
- [ ] Perf PR: gain ceiling computed for weak hardware.
|
||||
|
||||
## Decision
|
||||
|
||||
- [ ] Taken, partly taken or rejected, with the reason written down and posted to the PR.
|
||||
- [ ] What missed the project's scheme brought to it while merging.
|
||||
- [ ] Bugs found outside the PR reported, not fixed on the spot.
|
||||
- [ ] Merged into `dev` from `task/<tag>`. `main` only with the owner's yes.
|
||||
- [ ] `python tools/check_content.py --staged` before the commit.
|
||||
- [ ] Commit message: a plain English sentence, no `feat:`/`fix:`.
|
||||
@@ -0,0 +1,32 @@
|
||||
# PR review kit
|
||||
|
||||
Rules and background for a tester or reviewer who takes community PRs into `dev`. One goal: no PR breaks the
|
||||
game's behaviour or costs frames on weak hardware.
|
||||
|
||||
## The short version
|
||||
|
||||
1. A PR description and "works for me" prove nothing. Read the diff yourself and check it against `refs/`, the
|
||||
Vulkan spec and upstream issues.
|
||||
2. Almost every change needs a test: a repro before and after, a probe, a differential test, or whole runs with the
|
||||
switch off and on.
|
||||
3. The developer's machine is fast; players run weak machines. "Neutral here" says nothing about them, in either
|
||||
direction.
|
||||
4. A player without the problem sees no change: the new path sits behind a switch and the old path stays as it was.
|
||||
5. Nothing goes into `main` without the project owner's explicit yes. Accepted work lives in `dev` first.
|
||||
|
||||
## Files
|
||||
|
||||
| File | Covers |
|
||||
|---|---|
|
||||
| [01-rules.md](01-rules.md) | triage order, what a PR needs, reasons to reject, merging and commits |
|
||||
| [02-performance.md](02-performance.md) | target hardware, gain ceiling, how to measure, what the hot path must not do |
|
||||
| [03-correctness.md](03-correctness.md) | lifter, tests and probes, GPU portability, Maxwell behaviour, timers, threads, game content |
|
||||
| [04-knowledge.md](04-knowledge.md) | invariants of recent changes, fixed bug classes, open risks, past PR decisions, our mistakes |
|
||||
| [05-checklist.md](05-checklist.md) | the per-PR checklist |
|
||||
|
||||
The public docs this kit builds on: [docs/architecture.md](../../docs/architecture.md),
|
||||
[docs/building.md](../../docs/building.md) ("Checks"), [docs/maxwell.md](../../docs/maxwell.md),
|
||||
[docs/settings.md](../../docs/settings.md), [docs/tester-guide.md](../../docs/tester-guide.md), `AGENTS.md`.
|
||||
Working with a coding agent: give it this folder and `AGENTS.md` before the first review.
|
||||
|
||||
State as of 2026-11-06. The code and `docs/` win over this text where they differ.
|
||||
@@ -0,0 +1,252 @@
|
||||
# Settings reference
|
||||
|
||||
`totk.ini.example` describes the settings for players. This page lists the rest: diagnostics, test hooks, paths and experiments. Set one as `name = value` in `totk.ini`, or as the environment variable `TOTK_NAME`, which wins over the file. Remove the line to go back to the default.
|
||||
|
||||
## Safety
|
||||
|
||||
- **Safe**: changes only what the row says, with no effect on stability or saves.
|
||||
- **Caution**: can slow the game, grow files, or change the picture, and undoes cleanly when removed.
|
||||
- **Risky**: can crash or hang the game, or break the picture or game logic, while it is set.
|
||||
- **Save risk**: can damage or lose saves, or point the game at other game or save files.
|
||||
- **Unknown**: the code did not settle it.
|
||||
|
||||
Many rows below are developer tools that only act together with another setting or a command-line mode (for example a trace mode or the DLSS path). The row says so where the code does. The rows come from reading the code, and most effects have not been checked in a run.
|
||||
|
||||
`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; `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_census` (default `1`) | With `TOTK_TRACE=perf` and the import memory mode (`TOTK_MEMORY=import`, the automatic mode on an integrated GPU; the mirror mode of a discrete GPU has its own `mem:` lines instead of the census), `0` turns off the dirty census: the `mem: dirty` lines that count, at every submit, the pages the CPU wrote in the pools the replay binds as buffers. | The census queries the write watch at every submit, 3.5-5 ms of the replay thread a frame on a Steam Deck; with `0` a perf trace measures the frame without that cost, and `tools/perf_summary.py` prints no dirty lines. | 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 |
|
||||
| `speed_probe` | `1` adds the player's position and ground speed to the frame-rate line that `TOTK_TRACE=perf` prints every 120 presents. | Only adds log text; has no effect without `TOTK_TRACE=perf`. | Safe |
|
||||
|
||||
## Profiling and measurement
|
||||
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `ab` | Splits game time into blocks of this many seconds in the order A B B A and lets settings written as `ab` take effect only in the B blocks. | Settings that accept `ab` flip on and off every few seconds, so frame times and the picture change with the block; without such a setting it does nothing. | Caution |
|
||||
| `crit` | `<first>-<last>` frame range (with `TOTK_TRACE=sched`) that records every state change and wake of the guest threads, then writes a file at the last frame. | Recording adds overhead to every thread switch in the range and writes one file; `tools/crit_path.py` reads it. | Caution |
|
||||
| `crit_out` (default `crit.bin`) | Path of the file that `crit` writes. | Only moves the file; nothing is written without `crit`. | Safe |
|
||||
| `profile` | Path of a sampling profile file; the profiler suspends threads to unwind their stacks. | Frames get slower while it samples and the profile file grows; `tools/prof_report.py` reads it. | Caution |
|
||||
| `profile_chains` | `1` keeps call chains of every thread in the profile. | Larger profile file and more work per sample; has no effect without `profile`. | Caution |
|
||||
| `profile_frames` | `<lo>-<hi>` samples only while presents lo to hi-1 are pending; `w<lo>-<hi>` uses world-clock seconds. | Limits the profile to a window; has no effect without `profile`. | Safe |
|
||||
| `profile_main` | `1` samples only the guest main thread. | Narrows the profile; has no effect without `profile`. | Safe |
|
||||
| `profile_render` | `1` samples only the render thread and keeps its call chains. | Narrows the profile and makes it larger; has no effect without `profile`. | Caution |
|
||||
|
||||
## Capture and frame dumps
|
||||
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `dump` | Frame number to dump: every render pass target and storage image of that frame is copied out as PNG, with `passes.txt` and `images.txt`. | Writes many PNG files and shader hashes to disk and slows the dumped frame; size is capped by the dump code. | Caution |
|
||||
| `dump_buf` | `<addr>:<size>[:<off>:<stride>:<w>:<h>]` snapshots one GPU buffer range after every logged pass of a dump. | Writes `buf_<pass>.bin` files and `bufs.txt`; has no effect without `dump`. | Caution |
|
||||
| `dump_dir` (default `dump`) | Folder that receives the frame dump files. | Only moves the output. | Safe |
|
||||
| `dump_log` | Frame number; logs the frames from there up to the dumped frame into `passes.txt`, with PNGs only of targets up to 64K texels. | Writes a longer `passes.txt` and more PNGs; has no effect without `dump`. | Caution |
|
||||
| `flight_at` | Comma-separated frame numbers that trigger a flight-recorder dump. | Writes a dump folder when each frame is reached; has no effect unless the flight recorder (`TOTK_FLIGHT=1`) is on. | Caution |
|
||||
| `flight_dir` | Folder for flight-recorder dumps; the default is `flight` beside the folder of `totk.exe`. | Only moves the output. | Safe |
|
||||
| `flight_frames` (default `600`) | Number of presents the flight recorder keeps. | A larger ring keeps more history and more thumbnails in memory; has no effect unless `TOTK_FLIGHT=1`. | Caution |
|
||||
| `flight_thumbs` (default `1`) | `0` turns off the 320x180 thumbnail the flight recorder saves for each present. | Dumps hold only `frames.tsv`; thumbnails cost a GPU blit per present when on. | Safe |
|
||||
| `rdoc` | Comma-separated frame numbers to capture with RenderDoc, which is loaded before Vulkan starts. | The game runs under RenderDoc, with its capture options set to keep `VK_EXT_external_memory_host` available and to reference all resources, and captures are written to disk. | Caution |
|
||||
| `rdoc_dir` | Output folder for RenderDoc captures (the default is `build/captures`). | Only moves the output. | Safe |
|
||||
| `rdoc_dll` | Path of the RenderDoc library, for when it is not found by default. | A wrong path logs that the library cannot be loaded and no capture is taken. | Safe |
|
||||
| `shots` | `<lo>-<hi>:<step>` saves every step-th present in the range as `f<n>.png`, scaled to 480x270; `w<lo>-<hi>:<step>` takes them by world-clock seconds. | Writes one PNG per step and adds a readback of the window texture; the pictures clip highlights in HDR. | Caution |
|
||||
| `shots_dir` (default `.`) | Folder for the `shots` pictures; it is created when needed. | Only moves the output. | Safe |
|
||||
| `shots_full` | Set to any value to save `shots` at full size instead of 480x270. | Files get far larger and writing them takes longer; has no effect without `shots`. | Caution |
|
||||
|
||||
## Automated tests and test hooks
|
||||
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `vram_limit_mib` | Pretends the device-local memory budget is at most this many MiB, for the paths that react to the budget (`tex_vram_pressure`, mirror refusal); the driver knows nothing of it. | Lets a large card drive those paths; a low value drops released textures and refuses mirrors that would have fit. | Caution |
|
||||
| `background_window` | `1` keeps the window behind the user's windows, never fullscreen at start, and F11 keeps its place; SDL windows ignore it. | The window does not come to the front or flash, so it is easy to miss; meant for unattended runs. | Caution |
|
||||
| `gpu` | `vulkan` or `null`: the graphics back end; `null` has no GPU, completes every submit at once and returns zeros for texture reads. | `null` shows no picture; any other value stops the start with an error. | Caution |
|
||||
| `input` | `none` reports no input from the keyboard, mouse or controllers. | The game gets no controller input and the menu cursor stops following the mouse; `input_script` still applies. | Caution |
|
||||
| `input_script` | Path of a file with lines `<frame> <button> [hold]` or `<frame> LSTICK or RSTICK <x> <y> [hold]` that are ORed into the real input. | The game presses those buttons by itself; a file that cannot be opened is logged and ignored. | Caution |
|
||||
| `menu_test` | `<frame>[:<frames per page>]` opens the menu at that frame, shows each tab for 30 frames (or the given count), saves one screenshot per tab and closes the menu. | The menu opens by itself and screenshots are written. | Caution |
|
||||
| `menu_test_dir` | Folder for the `menu_test` screenshots; the default is the working directory. | Only moves the output. | Safe |
|
||||
| `menu_test_set` | `<frame>:<key>=<value>[,...][;...]` changes settings live at that frame, with or without the menu open; `SAVE=1` also writes `totk.ini`. | Settings change during play without input, and `SAVE=1` rewrites the file. | Caution |
|
||||
| `probe_movie` | Text that picks the movie for `totk.exe --probe-movie`: the first file whose path contains it. | Only used by the movie decoder probe; ignored in normal play. | Safe |
|
||||
| `probe_movie_shot` | Path of a `.ppm` file that the movie probe writes the middle frame to. | Only used by the movie decoder probe. | Safe |
|
||||
| `probe_movie_bench` | `1` makes the movie probe also time the resampler that fits a movie to a game resolution of another shape, and print the time per frame. | Only used by the movie decoder probe. | Safe |
|
||||
| `swkbd_answer` | `<text>`, `<cancel>` or `<initial>`: answers the on-screen keyboard (for example a horse name) without opening a window. | The game gets that answer every time it asks for text. | Caution |
|
||||
| `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
|
||||
|
||||
| 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
|
||||
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `amiibo_dir` | Folder the Amiibo tab starts in; the tab saves the folder you last browsed here. | Only changes which folder the tab lists first. | Safe |
|
||||
| `exefs` | Folder of the game's ExeFS (with `main.npdm`); a relative path is relative to `totk.exe`'s folder. | Without it, an `exefs` folder next to `totk.exe` is used, else the path set at build time. The game code is compiled into `totk.exe`, and the loader checks the files here by SHA-256, so files from another build or game version stop the start with a message. | Caution |
|
||||
| `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_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 |
|
||||
| `romfs_index` | Path of `romfs-index.bin`, which `tools/romfs_index.py` wrote; the default is beside `totk.exe`. | The index is checked against the image by SHA-256 and size; a mismatch stops the start. | Caution |
|
||||
| `romfs_mmap` | `1` maps the RomFS image into memory instead of reading it with positional reads. | Changes how the image is read; the log reports when the mapped path is on. | Caution |
|
||||
| `romfs_mods` | Folder of an overlay with a `manifest.tsv` of sizes and SHA-256 hashes; its files are served in place of the originals. | A missing file, size or hash mismatch, or a changed original stops the start; player mods win over this overlay. | Save risk |
|
||||
| `romfs_patches` | Folder of an overlay with a `manifest.tsv`, served in place of the original files; the default is `romfs-patches` beside the index. | Same checks as `romfs_mods`; while it is set the Xbox and PC button prompts are off, and the menu says so. | Save risk |
|
||||
| `romfs_proof_dir` | Folder for the `.romfs-verified-v1` proof file of a full verification; the default is beside the index. | Only moves one small file. | Safe |
|
||||
| `romfs_verify` | `full` hashes the whole RomFS image at start; `force` hashes it again even when a proof file exists. | Start takes many minutes for a 17 GB image; a proof file is written so later starts skip the hash. | Caution |
|
||||
| `shader_cache` | Folder of the translated shader cache (default `shader-cache` beside `totk.exe`). | A new folder starts empty, so shaders are translated again during play. | Caution |
|
||||
| `shared_fonts` | Folder of the extracted system fonts; the default is `shared-fonts` beside `totk.exe`, else beside the RomFS. | Simplified Chinese, Traditional Chinese and Korean need these fonts: without them the game exits before its first frame in those languages. Other languages do not use them. | Caution |
|
||||
|
||||
## Shader translation
|
||||
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `xlate` | Path of the shader translator program; the default is `totk_xlate` beside `totk.exe`, else under `build/xlate`. | Shaders are translated by that program; if it is missing the log says so and graphics shaders cannot be translated. | Risky |
|
||||
| `xlate_id` | Text or 64 hex digits that identify the translator build in shader cache keys; the default comes from an `.id` file beside the translator, else a hash of the program. | A value that two different builds share lets the cache serve shaders translated by the other build. | Caution |
|
||||
| `xlate_keep` (default `0`) | `1` keeps the translation job of a last-frame variant as `<key>.job` with its code. | Writes extra files to the shader cache folder; meant for running the translator by hand. | Caution |
|
||||
| `xlate_procs` (default `2`) | Number of translator processes allowed during play. | More processes translate new shaders sooner and use more CPU and memory; values below 1 count as 1. | Caution |
|
||||
|
||||
## Graphics experiments
|
||||
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `bind_inc` (default `0`) | `1` (or `on`) prepares a draw from what changed since the draw before (the bind ops mark the slots whose bytes they changed) instead of from the whole bound state; `check` prepares every draw as before, takes every decision of `on` beside it, logs each kind of difference once and counts them in a `bind_inc:` line every 300 frames; `0` or `off`: as before. `check` also counts what changed between draws in that line. | Less work per draw on the render thread; a change the marks missed would leave a stale descriptor, a wrong picture or a lost device, which `check` would show first. Off by default: with it on, a GTX 1050 Ti lost the device at one place, after the validation layer reported a descriptor pool reset while a command buffer still used its sets; the cause is not found yet. | Caution |
|
||||
| `block_views_3d` (default `0`) | `1` gives 3D block-compressed images block views too. | On some AMD cards a GPU write past the end of the image's memory loses the Vulkan device, and the game stops. | Risky |
|
||||
| `deswizzle` (default `auto`) | Where block-linear textures are deswizzled: `auto` or `gpu` uses a compute pass where the texture's storage is an imported pool and the CPU elsewhere, `cpu` always uses the CPU, `check` uses the GPU and also deswizzles every upload on the CPU and compares the two. | `cpu` brings back the long frames on entering new areas (the replay thread deswizzles every texture); `check` waits for the GPU at every upload and is for testing only. The log names the mode in use. | Caution |
|
||||
| `dyn_delta` (default `1`) | Records only the pipeline dynamic states (cull mode, depth and stencil tests, vertex input, blend enables, equations and write masks, ...) whose values changed since the last draw in the command buffer, also across pipeline changes; `0` records the full set at every change of pipeline state, as before; `ab` alternates with the `ab` blocks. | Fewer commands per pipeline change on the render and recorder threads; a driver that loses dynamic state across pipeline binds would draw with stale state. `TOTK_TRACE=perf` prints the calls and commands per submission. | Caution |
|
||||
| `feedback` | `0` samples a target that an earlier draw of the same pass wrote with no barrier; `restart` ends and restarts the pass behind a full barrier; otherwise the feedback-loop layout is used when the GPU supports it. | `0` brings back the old behaviour that the barrier fixed, so the picture can break in passes that read a target they draw into; `restart` costs extra passes. | Risky |
|
||||
| `flush_span` (default `0`) | `1` copies one span from the lowest to the highest flushed address of a pool, as an older version did. | Copies far more data to the GPU in crowded towns: an estimated 30-50 ms of GPU time per large copy over PCIe 3.0 x8. | Caution |
|
||||
| `frame_gen` (default `off`) | The frame generator: `off`, or `fsr3`, which brings up AMD FSR 3 frame interpolation and optical flow (FidelityFX SDK 1.1.4) at start; with DLSS off the replay follows the scene and records the motion vectors (the camera's and the moving objects', `fg_objects`), the picture before the HUD and the interpolation of a frame between each two the game draws (`runtime/vk_fg.cpp`). Each frame then goes out as two presents: the generated picture once the GPU has drawn the frame (a timeline wait, not before the pacer's time), the game's half the smoothed interval later (`runtime/vk_backend.c` `present_pair`); `fps_limit` counts the pictures shown and the game draws half, 30 at least (`runtime/frame_rate.c` `frame_step_cap_ns`). Off with DLSS or FSR 3.1 (`scene_upscaler`), `replay_workers` above 0, `sync_ahead = 1` or HDR output, and while a menu background or a loading or event fade is open; the game then draws at the whole limit. The swapchain gets one image more. Applies at once: turned on in the menu, the contexts are made at the next frame (a hitch of about 0.1 s once); turned off, they stay until exit. | The controls answer at the drawn rate, about half a frame later. Costs about 1.5 ms of GPU and 0.6 ms of the replay thread per drawn frame at 1080p (RX 9070, 7900X on 4 cores: 94 drawn without it, 86 drawn and 169 shown with it, no limit). For displays of 120 Hz and more. | Caution |
|
||||
| `fg_test` | Frame generation checks: `1` presents the generated frame in place of the game's, `2` the picture before the HUD. Read at start. | Shows the frames out of their order: for checks only. | Caution |
|
||||
| `fg_debug` | `1`: the generated frames hold the SDK's debug view (motion fields, optical flow, disocclusion). Read at start. | For checks only. | Caution |
|
||||
| `fg_objects` (default `1`) | Frame generation's motion vectors get the per-object pass DLSS uses over the camera's: the moving scene draws (characters, enemies, objects) are drawn again with last frame's blocks (`runtime/vk_exec_draw.c` `vk_mvobj_execute`, `runtime/vk_mvprev.c`). `0`: the camera's motion alone; Link, whom the camera follows, then carries the world's motion and the generated pictures show him twice. Read at start. `dlaa_objmv = 0` also turns the object pass off. | About 0.04 ms of GPU and 0.8 ms of the replay thread per drawn frame (RX 9070, 7900X on 4 cores, field, 1080p: 85.6 drawn with `0`, 80.0 with `1`), half of it the host copy of the uniform snapshot the object pass reads. | Safe |
|
||||
| `fg_shot` | Frame generation shots: a present number, or `w<seconds>` of world time; the window texture, the generated frame and the picture before the HUD of three frames from there go to `fg_shot_dir` as `fg_<present>_<real\|gen\|hudless>.png`. | Writes PNGs. | Safe |
|
||||
| `fg_shot_dir` | Folder for the `fg_shot` PNGs (default the working folder). | Only moves the output. | Safe |
|
||||
| `fg_times` (default `1`) | `0` turns off the GPU timestamps of frame generation's steps; every 600 generated frames a log line gives their GPU times and the replay thread's recording time (median, p99). | Timestamps cost next to nothing. | Safe |
|
||||
| `shadow_snap` (default `1`) | Shadow storage (Linux, Wine): `1` syncs the pools from per-submission write-watch snapshots, each 2 MiB region queried at most once per submission and shared with the texture checks; `0` queries each pool at every part of a submission, as before. | `1` cut the replay thread's write tracking from about 4.4 to 1.3 ms a frame on a Steam Deck; `0` is for comparison runs. Under Wine/Proton the default is `0` until it has been measured there; `1` turns it on. No effect where shadow storage is off (Windows by default). | Caution |
|
||||
| `freeze_idle` (default `60`) | Number of submissions a 2 MiB region stays unwritten before it is made read-only; `0` turns the freeze off. | A larger value keeps more regions writable and costs more write tracking; a write to a frozen region costs about 60 microseconds. | Caution |
|
||||
| `gpl_draw_build` (default `1`) | `0` leaves the missing shader libraries of a waiting draw to its background job instead of building them in parallel at once. | Draws whose pipeline is not ready are skipped meanwhile, until the job finishes. | Caution |
|
||||
| `lib_prebuild_keep` (default `0`) | Number of recorded graphics shader library variants that stay in memory after the boot prebuild. | Each kept library costs 140-460 KB of memory; the driver cache already makes a rebuild cheap. | Caution |
|
||||
| `minimal_layout` (default `1`) | `0` skips the compare against one-block tiles when a texture's memory layout is chosen. | The code calls it a negative control for fresh sessions; the comment does not say what the picture does. | Unknown |
|
||||
| `mirror_gap` (default `2`) | Hot pools at most this many 2 MiB regions apart share one write-watch query. | Changes the number of queries per submission; negative values count as 0. | Caution |
|
||||
| `movie_host` (default `1`) | `0` leaves every movie decoder to the game's own library. | The code comment says that library aborts at the first movie, so the game stops at the first cutscene. | Risky |
|
||||
| `movie_pace` (default `1`) | `0` hands every decoded movie frame over at the next present instead of when it is due. | Movies play at the game's frame rate rather than their own, so their speed no longer matches the sound. | Caution |
|
||||
| `pcss_k` (default `0.5`) | Depth-to-penumbra factor of soft shadows at 100 percent, for tuning. | Changes how wide soft shadows blur; has no effect while `pcss` is `0`. | Caution |
|
||||
| `pipe_sync` | Any value other than `0` or empty stops graphics pipelines from being built in the background. | Pipelines are built on the render path, which causes stutter when new effects appear. | Caution |
|
||||
| `push_stage` | `fs` pushes the descriptor set from the fragment stage instead of the vertex stage. | The log names the stage in use; the code does not say what changes in the picture. | Unknown |
|
||||
| `rec_async` (default `1`) | `0` makes the submitting thread wait until the recorder thread has recorded and submitted each part; `ab` alternates with the `ab` blocks. | With `0` the submitting thread waits for every part (about 0.3 ms a frame in a town on a Ryzen 7900X). | Caution |
|
||||
| `rec_end` (default `1`) | `0` lets the submitting thread begin, end and submit a recorded part again, as older versions did. | On some AMD cards the GPU hangs or the scene turns green and then white when a submission is split. | Risky |
|
||||
| `rec_spin_us` (default `60`) | Microseconds the recorder thread polls for the next packets before it sleeps; `0` polls 4096 pauses instead; `ab` polls only in the B blocks of `ab`. With fewer than 6 logical processors it always polls 4096 pauses. | A longer poll saves an OS wake-up per packet and takes more CPU time; a shorter one sleeps sooner. | Caution |
|
||||
| `tex_vram_pressure` (default `90`) | Percent of the device-local memory budget above which released textures are dropped, 0 to 100; `0` is off. First those the game has overwritten with a later texture and left alone for 30 s, then those that can be uploaded again. | A low value drops textures sooner and re-uploads them; `0` keeps them and lets the card spill into system memory. Also a slider in the menu. | Caution |
|
||||
| `txd_transpose` (default `1`) | `0` turns off the swap of gradient components for gradient texture samples. | Terrain textures turned across the screen show crawling patches again. | Caution |
|
||||
| `ub_overlay` (default `1`) | `0` copies each uniform update inside a pass into its buffer at once, ending the pass with a full barrier; `ab` alternates with the `ab` blocks. | With `0` scenes with many updated blocks (the terrain, the sky islands) take longer on the GPU; `TOTK_TRACE=perf` prints how many updates stayed in their pass. | Caution |
|
||||
| `ub_overlay_out` (default `1`) | `0` copies each uniform update between passes into its buffer at once, behind a full barrier of its own; `ab` alternates with the `ab` blocks. Needs `ub_overlay`. | With `0` a run of updates before a pass costs a full GPU barrier each; `TOTK_TRACE=perf` prints how many updates between passes were overlaid. | Caution |
|
||||
| `ubo_snapshot` (default `1`) | `0` binds live memory for uniform blocks; `ab` alternates with the `ab` blocks. | Without snapshots late draws read another object's matrix, so objects can be drawn in the wrong place. | Risky |
|
||||
| `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; 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 |
|
||||
| `dlaa_mvdebug` (default `0`) | `1` shows the motion vectors in place of the picture, x in red and y in green. | The frame shows a debug image while it is set. | Caution |
|
||||
| `dlaa_survey` (default `0`) | `1` logs what is drawn into the light target that DLSS reads. | Adds log output and per-draw work. | Caution |
|
||||
| `dlaa_times` (default `0`) | `1` times the DLSS passes on the GPU. | Adds GPU timestamps and log lines. | Caution |
|
||||
| `dlss_reactive` (default `0`) | `1` builds a reactive mask for DLSS where it ran. | Changes how DLSS blends moving areas; a test setting. | Caution |
|
||||
| `fsr3_debug` (default `0`) | With `scene_upscaler = fsr3`: `1` creates the FSR 3.1 context with the SDK's input checks, whose warnings go to the log (the first 32). | Adds checks to every FSR 3.1 dispatch and log lines. | Caution |
|
||||
| `fsr3_view` (default `0`) | With `scene_upscaler = fsr3`: `1` shows FSR 3.1's own debug view of its inputs and state in place of the picture. | The frame shows a debug image while it is set. | Caution |
|
||||
| `mv_check` | Frame interval; every that many DLSS frames copies the light target and motion images to host memory and logs how well the vectors explain the picture. | Costs a GPU-to-host copy and a comparison on the completion thread at each interval. | Caution |
|
||||
| `mv_survey` (default `0`) | `1` notes the uniform blocks of each scene draw and compares them with those of earlier frames. | Adds per-draw work and log output. | Caution |
|
||||
| `mvobj_all` (default `0`) | `1` also lists draws for object motion that read no object blocks (terrain and grass). | More draws are checked and listed, which costs time. | Caution |
|
||||
| `mvobj_banks` (default `0`) | `1` logs which words of the other uniform banks changed for each scene draw. | Adds log output and per-draw work. | Caution |
|
||||
| `mvobj_equal` (default `0`) | `1` uses an EQUAL depth compare for the object motion pass, for comparison. | Changes which pixels get object vectors; the code comment names the default as the one that hides objects behind nearer geometry. | Caution |
|
||||
| `mvobj_exact` | Hex bank mask; only draws whose position uses exactly these banks get object motion. | Fewer draws get object vectors, so their motion falls back to the camera's. | Caution |
|
||||
| `mvobj_exec` (default `1`) | `0` lists object motion draws but never records them. | Objects get camera motion only. | Caution |
|
||||
| `mvobj_noc4` (default `0`) | `1` draws again positions that have no scene camera bank. | Those draws get this frame's view, so they can show wrong motion. | Caution |
|
||||
| `mvobj_only` | Hex bank mask; only draws whose position reads no bank outside the mask get object motion. | Fewer draws get object vectors. | Caution |
|
||||
| `mvobj_times` (default `0`) | `1` adds timings to the object-motion summary. | The clock reads themselves cost frame time. | Caution |
|
||||
| `mvprev_check` (default `0`) | `1` verifies the stored first bytes of each previous-frame table entry. | The code comment measures 3.6 ms per frame. | Caution |
|
||||
| `mvprev_grow` (default `1`) | `0` keeps only three banks in the previous-frame tables. | Object motion that depends on the other banks is no longer tracked. | Caution |
|
||||
| `mvprev_skip` | Hex bank mask of banks left out of the previous-frame copy, replacing the default. | Different banks are tracked, which changes object motion. | Caution |
|
||||
| `mvprev_trust` | Hex bank mask of banks whose found previous-frame copy is taken without the check. | A copy that does not match is used anyway, which can give wrong motion. | Caution |
|
||||
| `reflex` (default `off`) | `off`, `on`, or `boost`; enables NVIDIA Reflex Low Latency (`VK_NV_low_latency2`) to reduce system input latency. Read at start. | On NVIDIA GPUs supporting the extension, coordinates simulation and presentation cadence to lower latency, holding frames to the frame limit the pacer uses (`fps_limit`, the monitor's rate for `display`); `boost` keeps GPU clocks high in CPU-bound scenes. Has no effect on non-NVIDIA GPUs. | Safe |
|
||||
|
||||
## Scheduling and host
|
||||
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `app_pool` | Size in bytes of the guest application memory pool; accepts decimal or `0x` hex. | The default depends on the resolution settings; `0` stops the start with a message, and too small a pool leaves the game without memory. | Risky |
|
||||
| `audio_off` | Any value mixes audio without opening an output device. | The game runs in silence and reports two channels; same as `audio = none`. | Caution |
|
||||
| `kspin_us` (default `20`) | Microseconds a guest wait or a wait for a virtual core polls before it sleeps; `0` turns the poll off; `ab` polls only in the B blocks of `ab`. Off with fewer than 6 logical processors. | A wake within the poll costs no OS wake-up; a longer poll takes more CPU time from other threads. | Caution |
|
||||
| `mem_reserve_mib` (default `1536`) | MiB of system memory kept free for Windows, other programs and the game's own heap when the renderer sizes what it keeps in device memory, where device memory takes system memory (integrated GPUs, and discrete GPUs whose driver charges it to the process). | A larger value keeps fewer released textures and spare blocks when the system runs short; a smaller one lets the game use more before it holds back. | Caution |
|
||||
| `one_per_core` (default `0`) | `1` keeps the process on the first logical processor of each physical core; `ab` switches it with the `ab` blocks. | Busy threads stop sharing a core with a sibling thread, which can help or hurt on the CPU; it only applies when the CPU has hyperthreads. | Caution |
|
||||
| `pcore` (default `1`) | On a hybrid CPU (performance and efficiency cores), the game's main and render threads and the replay, recorder and present threads prefer the performance cores; `0` turns that off. | With `0` Windows may run those threads on efficiency cores; no effect on a CPU with one kind of core. The log says which cores were found. | Caution |
|
||||
| `reexec` | Counter of address-space retries that the runtime sets itself when it starts the process again. | The counter is cleared when the window is recreated; a value of 20 or more stops the start with a fatal error. | Risky |
|
||||
| `replay_chunks` (default `0`) | Most chunks a submission is cut into when `replay_workers` is set; `0` uses twice the number of recording threads. | Fewer chunks leave threads idle at the end of a submission, more add scan and submit work per chunk; no effect while `replay_workers` is `0`. | Caution |
|
||||
| `replay_chunk_draws` (default `128`) | Least draws a chunk of the chunked replay holds before it may end at a pass. | Small values make many short chunks, large ones leave big submissions on few threads; no effect while `replay_workers` is `0`. | Caution |
|
||||
| `replay_state_check` (default `0`) | `1` compares the replay state after the last chunk of a chunked submission with the state of the scan and logs differences. | Adds a comparison per submission and log lines on a mismatch; no effect while `replay_workers` is `0`. | Caution |
|
||||
| `replay_skew_us` (default `0`) | Debug: the even chunks of a chunked submission wait this many microseconds before they record, so the chunk after each one records first. | Shows a recording that depends on which thread gets to a chunk first in every submission; slows the replay; no effect with fewer than 2 `replay_workers`. | Caution |
|
||||
| `restart_wait` | Set by the runtime when it restarts itself; names the old process by id and creation time so the new process waits for it to exit. | Meant for the runtime's own use; the code does not describe a manual value. | Unknown |
|
||||
| `spin` (default `1`) | `0` makes a guest thread that polls memory keep its virtual core. | Polling threads can starve the thread whose item they wait for, so frames can stall. | Caution |
|
||||
| `spin_handoff_us` (default `50`) | Microseconds a polling wait lasts before it gives its virtual core to a waiting thread. | A shorter value hands cores over sooner; a longer one keeps them longer. | Caution |
|
||||
| `tex_block_mib` (default `64`) | Block size in MiB of the pool that holds the game's textures; images of a quarter block or more get memory of their own. `0` puts textures in the default pools with the buffers. | Larger blocks hold more memory that no texture uses; smaller ones mean more allocations from the driver. | Caution |
|
||||
| `tex_released_mib` (default `256`) | MiB of textures the game released that are kept for reuse; older ones beyond it are dropped. `0` keeps up to 2048 of them, whatever their size. | A larger value keeps more device memory and process commit; a smaller one makes the game create more textures again. | Caution |
|
||||
| `vma_block_mib` (default `64`) | Block size in MiB that the Vulkan memory allocator takes from the driver for buffers and other images on heaps over 1 GiB; larger allocations than half a block get memory of their own. `0` uses the allocator's 256. | Larger blocks hold more memory that nothing uses; smaller ones mean more allocations from the driver. | Caution |
|
||||
|
||||
## Generated-code patches
|
||||
|
||||
These names are code patch sets built into the generated game code (`recomp/patches-*.txt`). `rt_patches_init` reads the environment name at start, then the resolution and mouse code switches some sets itself.
|
||||
|
||||
| Setting | What it does | Effect of changing it | Safety |
|
||||
| --- | --- | --- | --- |
|
||||
| `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 |
|
||||
| `freecam_patch` (default `0`) | Patch set of the hook in the camera component update behind the free camera (`freecam_pad`, `freecam_key`) on game 1.4.3; the *Free camera* row of the Controls tab. Read at start. | `1` puts the hook in the camera update: while the free camera is off it runs the game's own load and one compare. `0` runs the game's code as shipped: the combo and the key do nothing and the game gets the combo's buttons. | Safe |
|
||||
| `fov_patch` (default `0`) | Patch set that scales the camera's vertical view angle by the field-of-view setting. | The resolution code switches this set itself whenever the field of view is not 100 percent; a manual value is replaced. | Unknown |
|
||||
| `mouse_direct_patch` (default `1`) | Patch set of the hooks in the game's camera code behind `mouse_mode = direct` on game 1.4.3. | `0` stops `mouse_mode = direct` from taking effect; other mouse modes are unaffected. | Safe |
|
||||
| `optref_guard` (default `1`) | Patch set that treats a negative value in the optional reference at object +0x6b0 (1.4.3 main+0x1bd01c0, 1.2.1 main+0x1622bec) as absent instead of loading through it (#1005). | `0` runs the game's code as shipped: the random crash reading `0xffffffffffffffff` after minutes to hours of play can return. | Risky |
|
||||
| `patch_output` (default `0`) | Patch set that makes the game use the configured output size for its swapchain and display configuration. | The resolution code switches this set whenever the output differs from the base size; a manual value is replaced. | Unknown |
|
||||
| `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 |
|
||||
+38
-3
@@ -6,9 +6,10 @@ from it may be shared.
|
||||
|
||||
## What you need
|
||||
|
||||
- Windows 10 or later, an x86-64 CPU with AVX2, about 60 GB free.
|
||||
- Windows 10 or later, an x86-64 CPU with SSE4.2 (AVX2/FMA recommended: they build the default, faster version), about
|
||||
60 GB free.
|
||||
- A GPU with Vulkan 1.3 and `VK_EXT_external_memory_host`, with a current driver.
|
||||
- *Tears of the Kingdom* base game (1.0.0) and the 1.2.1 or 1.4.3 update, dumped from your own Switch as NSP or XCI.
|
||||
- *Tears of the Kingdom* base game (1.0.0) and the 1.1.0, 1.2.1 or 1.4.3 update, dumped from your own Switch as NSP or XCI.
|
||||
- `prod.keys` dumped from your own Switch. Never send it to anyone, and never paste it into a log or an issue.
|
||||
|
||||
## Build
|
||||
@@ -38,7 +39,13 @@ build\<ver>\totk.exe
|
||||
`TOTK_VK_VALIDATION=1` turns on the Vulkan validation layer (it comes with the Vulkan SDK). It makes the game slower;
|
||||
do one run with it and one without (`set TOTK_VK_VALIDATION=`).
|
||||
|
||||
Keep the window in the foreground: an unfocused window stalls the game. Shaders the preparation did not cover compile on first use, so
|
||||
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.
|
||||
Play into the open field (load a save, walk around for a minute, fight something if you can), then close the window.
|
||||
|
||||
@@ -51,6 +58,13 @@ A laptop with an iGPU and a discrete GPU, or two cards, lists every GPU at the t
|
||||
|
||||
The line `vk: using gpu N: <name>` says which one ran.
|
||||
|
||||
## Mods
|
||||
|
||||
Mods and cheats made for the emulators go into `mods/` next to `totk.exe`, one folder per mod. [mods.md](mods.md) covers
|
||||
installing them, their order, code patches, what does not work and what to check when something looks wrong;
|
||||
[cheats.md](cheats.md) covers cheat files. The log names every mod at the start (`mods: <name>: ...`); when you
|
||||
report a problem with mods, list them with their download links.
|
||||
|
||||
## What to send back
|
||||
|
||||
1. `logs\totk.log` from each run. It contains no keys and no game files. The lines that matter most start with
|
||||
@@ -63,6 +77,27 @@ The line `vk: using gpu N: <name>` says which one ran.
|
||||
5. For a bug you can trigger again: a recording of your input (`set TOTK_INPUT_RECORD=input.txt`, see
|
||||
[controls.md](controls.md), "Scripted input") and the save you started from.
|
||||
|
||||
## Steam Deck
|
||||
|
||||
Build or install on Linux ([installer.md](installer.md), "Linux release"), in Desktop Mode. The game then runs in either
|
||||
mode; for Game Mode, add `totk` from the install folder to Steam as a non-Steam game.
|
||||
|
||||
The game recognises the Deck (LCD and OLED) and uses its device profile for every setting `totk.ini` does not set:
|
||||
fullscreen, the screen's own 1280x800 (16:10: the camera and interface take that shape), the game's own 3D scale,
|
||||
vsync and a 40 fps limit. These are starting points, not measurements. What helps most:
|
||||
|
||||
1. The performance overlay (F10, or both stick clicks L3 + R3) in full mode: the frame rate, mean and longest frame
|
||||
time over a minute in Lookout Landing, in the Depths and in the Sky, with the settings named.
|
||||
2. The same with `fps_limit` 30, 45 and 60 and `render_scale` 50, 67 and game, so the defaults can be picked from
|
||||
measurements. Steam's own performance overlay (the ... button) adds power draw and temperatures.
|
||||
3. LCD or OLED, SteamOS version (`uname -r` in Desktop Mode's terminal), and the game update.
|
||||
4. Anything that looks stretched, squeezed or cut off, with a screenshot. At 16:10 the menus keep their 16:9
|
||||
proportions in the middle of the taller screen, the HUD sits at the top and bottom edges, and full-screen
|
||||
backgrounds reach them; pre-rendered cutscenes play stretched.
|
||||
|
||||
`device_profile = desktop` in `totk.ini` turns the profile off; `deck` turns it on elsewhere, to try the Deck's
|
||||
settings on a PC.
|
||||
|
||||
## Switches for the developer's questions
|
||||
|
||||
Only set these when asked; each forces a fallback the build picks by itself on GPUs that need it.
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""The TotK installer: builds a playable folder from the player's own game files (docs/installer.md).
|
||||
|
||||
python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--root DIR] [--temp DIR]
|
||||
python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--firmware DIR] [--root DIR]
|
||||
[--temp DIR]
|
||||
|
||||
Modules: layout (where the bundled tools are, release or repository), events (JSON progress on stdout and the log
|
||||
file), state (totk-install.json), runner (which steps run: resume and update), steps (the six steps), ini (totk.ini),
|
||||
file), state (totk-install.json), runner (which steps run: resume and update), steps (the eight steps), ini (totk.ini),
|
||||
cli (the command line). text/en.json holds the English text of every message id the events carry.
|
||||
|
||||
Standard library only, apart from what the extraction tools import (cryptography). Runs on Python 3.14.
|
||||
|
||||
+25
-19
@@ -1,13 +1,17 @@
|
||||
"""Command line: python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--root DIR]
|
||||
[--temp DIR] [--verify]
|
||||
"""Command line: python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--firmware DIR]
|
||||
[--root DIR] [--temp DIR] [--verify] [--dlss]
|
||||
|
||||
A first install needs every option. On a folder with totk-install.json (resume after a cancel or failure, or update
|
||||
with a newer release) only --dest is needed: --lang defaults to the recorded language, and the game files are needed
|
||||
only when the extraction has to run again. Prints JSON events on stdout (events.py). Exit code: 0 done, 1 failed,
|
||||
2 bad command line, 3 cancelled (Ctrl+C or Ctrl+Break).
|
||||
A first install needs every option. --firmware names the Switch firmware folder (an unpacked firmware or an emulator's
|
||||
Contents/registered); the setup extracts the system shared fonts from it when the language is Chinese, Korean or
|
||||
Traditional Chinese. On a folder with totk-install.json (resume after a cancel or failure, or update with a newer
|
||||
release) only --dest is needed: --lang defaults to the recorded language, and the game files are needed only when the
|
||||
extraction has to run again. Prints JSON events on stdout (events.py). Exit code: 0 done, 1 failed, 2 bad command
|
||||
line, 3 cancelled (Ctrl+C or Ctrl+Break).
|
||||
|
||||
--dlss downloads NVIDIA's DLSS library (nvngx_dlss.dll) from NVIDIA's DLSS SDK repository into the install folder on
|
||||
Windows with an NVIDIA RTX GPU (steps.py, Dlss).
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
@@ -17,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
|
||||
from .steps import adopt_old_temp, all_steps, migrate_state
|
||||
|
||||
EXIT = {'ok': 0, 'failed': 1, 'cancelled': 3}
|
||||
|
||||
@@ -28,27 +32,25 @@ class Parser(argparse.ArgumentParser):
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = Parser(prog='python -m installer', description=__doc__.splitlines()[0])
|
||||
ap.add_argument('--base', type=Path, help='base game, XCI or NSP')
|
||||
ap.add_argument('--update', type=Path, help='1.2.1 or 1.4.3 update NSP')
|
||||
ap.add_argument('--base', type=Path, help='base game, XCI or NSP (or NSZ, XCZ: unpacked first)')
|
||||
ap.add_argument('--update', type=Path, help='the update NSP or NSZ: 1.1.0, 1.2.1 or 1.4.3')
|
||||
ap.add_argument('--keys', type=Path, help='prod.keys')
|
||||
ap.add_argument('--firmware', type=Path, help='Switch firmware folder (Contents/registered) for the shared fonts '
|
||||
'of Chinese, Korean and Traditional Chinese text')
|
||||
ap.add_argument('--lang', help='game language, a Switch language code (en-US, en-GB, ja, de, ru, ...)')
|
||||
ap.add_argument('--dest', type=Path, required=True, help='install folder')
|
||||
ap.add_argument('--root', type=Path, help='release folder or repository (default: the folder above installer/)')
|
||||
ap.add_argument('--temp', type=Path, help='temp folder (default: temp/ of the release, 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')
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
# The window cancels with Ctrl+Break to the installer's process group (CREATE_NEW_PROCESS_GROUP), which also reaches
|
||||
@@ -58,9 +60,12 @@ def main(argv=None):
|
||||
signal.signal(getattr(signal, name), cancel)
|
||||
layout = layouts.find(args.root)
|
||||
dest = args.dest.resolve()
|
||||
temp = temp_folder((args.temp or layout.temp).resolve(), 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)
|
||||
@@ -69,6 +74,7 @@ def main(argv=None):
|
||||
rep.emit('end', result='failed', seconds=0)
|
||||
return 1
|
||||
ctx = Context(layout, dest, temp, rep, args, state=state, verify=args.verify)
|
||||
migrate_state(ctx)
|
||||
steps = all_steps()
|
||||
rep.emit('start', release=layout.release, mode=ctx.mode, dev=layout.dev, dest=str(dest), log=str(log),
|
||||
steps=[s.id for s in steps])
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""The display scale of the installer window: process DPI awareness and the pixel sizes that follow it.
|
||||
|
||||
Windows draws a DPI-unaware process at 96 DPI and stretches its windows to the display's scale, which is what made the
|
||||
setup window blurry at 125% and above. gui.py calls enable() before it imports tkinter, so the process is system DPI
|
||||
aware before its first window exists; Tk then reads the display's DPI when it starts (`tk scaling` is 2.667 at 200%)
|
||||
and every font size in points comes out at the right size. The pixel sizes of the layout have no such scaling of their
|
||||
own, so gui.py passes them through px().
|
||||
|
||||
System DPI awareness, not per-monitor: Tk 9.0.4, the one the release bundles, has no per-monitor support (its DLL
|
||||
imports no DPI-awareness function), so it draws everything at the system DPI. Per-monitor awareness would leave the
|
||||
window crisp on a display at another scale but with the primary display's font sizes; system awareness draws the
|
||||
primary display exactly and lets Windows stretch the window only on a display whose scale differs from it, as before.
|
||||
|
||||
On Linux the window stays 1:1 (px returns n as it is): Tk and the desktop scale what they draw.
|
||||
"""
|
||||
import ctypes
|
||||
import os
|
||||
|
||||
DPI_96 = 96 # the scale Windows calls 100%
|
||||
DPI_AWARENESS_CONTEXT_SYSTEM_AWARE = -2
|
||||
PROCESS_SYSTEM_DPI_AWARE = 1 # SetProcessDpiAwareness' value for the same thing (Windows 8.1)
|
||||
LOGPIXELSX = 88 # GetDeviceCaps' horizontal DPI, the only source before Windows 10 1607
|
||||
LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800 # ctypes.WinDLL's winmode: System32 only, never the installer's folder
|
||||
|
||||
_scale = None
|
||||
|
||||
|
||||
def enable():
|
||||
"""Make the process system DPI aware, then return the display scale (1.0 at 96 DPI). Must run before the first
|
||||
window; a later call only returns the scale."""
|
||||
global _scale
|
||||
if _scale is None:
|
||||
dpi = _system_dpi() if os.name == 'nt' else DPI_96
|
||||
_scale = dpi / DPI_96
|
||||
return _scale
|
||||
|
||||
|
||||
def scale():
|
||||
"""The display scale: 1.0 at 100%, 2.0 at 200%."""
|
||||
return enable()
|
||||
|
||||
|
||||
def px(n):
|
||||
"""n pixels at 100% as this display's pixels: 14 stays 14 at 100% and becomes 28 at 200%."""
|
||||
return int(round(n * enable()))
|
||||
|
||||
|
||||
def awareness():
|
||||
"""What Windows says the process is: 0 unaware, 1 system aware, 2 per-monitor aware."""
|
||||
if os.name != 'nt':
|
||||
return 0
|
||||
try: # Windows 10 1607
|
||||
user32 = ctypes.WinDLL('user32')
|
||||
user32.GetThreadDpiAwarenessContext.restype = ctypes.c_void_p
|
||||
user32.GetAwarenessFromDpiAwarenessContext.argtypes = [ctypes.c_void_p]
|
||||
return int(user32.GetAwarenessFromDpiAwarenessContext(user32.GetThreadDpiAwarenessContext()))
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
try: # Windows 8.1
|
||||
value = ctypes.c_int()
|
||||
shcore = ctypes.WinDLL('shcore', winmode=LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||
shcore.GetProcessDpiAwareness.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)]
|
||||
if shcore.GetProcessDpiAwareness(None, ctypes.byref(value)) == 0:
|
||||
return value.value
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
try: # Windows Vista
|
||||
return 1 if ctypes.WinDLL('user32').IsProcessDPIAware() else 0
|
||||
except (AttributeError, OSError):
|
||||
return 0
|
||||
|
||||
|
||||
def _system_dpi():
|
||||
"""Make the process system DPI aware and return the display DPI. Each call that this Windows version has is tried;
|
||||
one failing means the process already is aware (a manifest, or the call before it) and changes nothing."""
|
||||
try:
|
||||
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||
except OSError:
|
||||
return DPI_96
|
||||
try: # Windows 10 1607, and the only way to ask for the system context explicitly
|
||||
user32.SetProcessDpiAwarenessContext.argtypes = [ctypes.c_void_p]
|
||||
user32.SetProcessDpiAwarenessContext.restype = ctypes.c_bool
|
||||
user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(DPI_AWARENESS_CONTEXT_SYSTEM_AWARE))
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
try: # Windows 8.1
|
||||
ctypes.WinDLL('shcore', winmode=LOAD_LIBRARY_SEARCH_SYSTEM32).SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE)
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
try: # Windows Vista
|
||||
user32.SetProcessDPIAware()
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
try: # Windows 10 1607
|
||||
return int(user32.GetDpiForSystem()) or DPI_96
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
try: # before that
|
||||
gdi32 = ctypes.WinDLL('gdi32')
|
||||
user32.GetDC.restype = ctypes.c_void_p
|
||||
user32.GetDC.argtypes = [ctypes.c_void_p]
|
||||
user32.ReleaseDC.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
|
||||
gdi32.GetDeviceCaps.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
||||
dc = user32.GetDC(None)
|
||||
dpi = gdi32.GetDeviceCaps(ctypes.c_void_p(dc), LOGPIXELSX)
|
||||
user32.ReleaseDC(None, ctypes.c_void_p(dc))
|
||||
return dpi or DPI_96
|
||||
except (AttributeError, OSError):
|
||||
return DPI_96
|
||||
+5
-1
@@ -15,6 +15,7 @@ Text is never the payload: ids name a step ("step.<id>"), a phase ("phase.<step>
|
||||
and installer/text/en.json holds their English text with {param} placeholders. The log renders events with it.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
@@ -28,11 +29,14 @@ def load_catalog(path=CATALOG):
|
||||
return json.loads(path.read_text(encoding='utf-8'))
|
||||
|
||||
|
||||
GAME_EXE = 'totk.exe' if os.name == 'nt' else 'totk' # {game_exe} in the catalogs
|
||||
|
||||
|
||||
def render(catalog, id, params=None):
|
||||
"""The English text of id, or the id itself when the catalog lacks it."""
|
||||
text = catalog.get(id, id)
|
||||
try:
|
||||
return text.format(**(params or {}))
|
||||
return text.format(**{'game_exe': GAME_EXE, **(params or {})})
|
||||
except (KeyError, IndexError, ValueError):
|
||||
return f'{text} {params}'
|
||||
|
||||
|
||||
+323
-87
@@ -1,19 +1,34 @@
|
||||
"""The installer window: python -m installer.gui
|
||||
|
||||
A front end over the CLI (docs/installer.md): it collects the game files, the keys file path, the game language and the
|
||||
install folder, runs `python -m installer ...` as a subprocess and shows its JSON events. Decisions live in guilogic.py;
|
||||
this file only draws. The window text is in installer/text/<en|ru>.json under "ui.*" and "launcher.*" ids.
|
||||
A front end over the CLI (docs/installer.md): it collects the game files, the keys file path, the optional firmware
|
||||
folder, the game language and the install folder, runs `python -m installer ...` as a subprocess and shows its JSON
|
||||
events. Decisions live in guilogic.py; this file only draws. The window text is in
|
||||
installer/text/<lang>.json under "ui.*" and "launcher.*" ids. On Windows the window follows the
|
||||
display's DPI (installer/dpi.py): fonts and paddings grow with the scale, so Windows does not stretch it.
|
||||
|
||||
--selftest [--shots DIR] build every screen in both languages and close by itself (PNG per screen with --shots)
|
||||
--lang en|ru window language (default: the Windows display language)
|
||||
--selftest [--shots DIR] build every screen in every language and close by itself (PNG per screen with --shots)
|
||||
--lang en|ru|pt-BR|zh-Hans|de|fr|es|it|nl|ja|ko window language (default: the Windows display language)
|
||||
--rebuild DIR rebuild the install folder DIR for its mods (totk.exe starts this, build-cache/rebuild.txt):
|
||||
the run starts at once with that folder, and the game starts again when it succeeds
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tkinter as tk
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from tkinter import filedialog, messagebox, ttk
|
||||
|
||||
from . import dpi
|
||||
|
||||
# Windows fixes the DPI awareness of a process when its first window is created, and Tk reads the display's DPI when it
|
||||
# starts: both happen inside the first tkinter.Tk(), so this call comes before tkinter is imported at all.
|
||||
dpi.enable()
|
||||
|
||||
import tkinter as tk # noqa: E402 (after dpi.enable, see above)
|
||||
from tkinter import filedialog, messagebox, ttk # noqa: E402
|
||||
from tkinter import font as tkfont # noqa: E402
|
||||
|
||||
try:
|
||||
from PIL import ImageGrab # only the screenshots of --selftest --shots need it; the release has no PIL
|
||||
@@ -22,13 +37,32 @@ except ImportError:
|
||||
|
||||
from . import ini
|
||||
from . import layout as layouts
|
||||
from .guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGES, Catalog, Form, Model, Process,
|
||||
amount, default_game_language, describe_event, parse_line, windows_ui_language)
|
||||
from . import recent
|
||||
from .guilogic import (DONE, FAILED, PENDING, RUNNING, SKIPPED, UI_LANGUAGE_LABELS, UI_LANGUAGES, Catalog, Form, Model,
|
||||
Process, amount, default_game_language, describe_event, parse_line, windows_ui_language)
|
||||
|
||||
POLL_MS = 100
|
||||
GLYPH = {PENDING: '\u25cb', RUNNING: '\u25b6', DONE: '\u2714', SKIPPED: '\u2013', FAILED: '\u2716'}
|
||||
COLOR = {PENDING: '#808080', RUNNING: '#1a5fb4', DONE: '#26a269', SKIPPED: '#808080', FAILED: '#c01c28'}
|
||||
PAD = 14
|
||||
HEADING = '#303030' # section titles, the details link and the update line: dark grey, no accent colour
|
||||
MUTED = '#6b6b6b' # secondary text: the details and the footer notice
|
||||
# The window's pixels at 100%: Tk scales the fonts by itself (tk scaling), these through installer/dpi.py.
|
||||
PAD = dpi.px(14) # padding of the window and its frames
|
||||
WRAP = dpi.px(620) # wrap width of the long labels
|
||||
|
||||
RECENT_WAIT = 1.5 # seconds the window waits for the recorded paths
|
||||
# Sun Valley, the Windows 11 look for ttk (sv-ttk 2.6.1, MIT, unmodified; THIRD_PARTY_NOTICES.md)
|
||||
SUN_VALLEY = Path(__file__).resolve().parent / 'vendor' / 'sv_ttk' / 'sv.tcl'
|
||||
|
||||
|
||||
def load_recent(wait=RECENT_WAIT):
|
||||
"""recent.load() in a daemon thread, waited for at most `wait` seconds: a recorded path on a disconnected network
|
||||
share can block its stat call for a long time. Nothing is prefilled when it has not returned by then."""
|
||||
out = {}
|
||||
thread = threading.Thread(target=lambda: out.update(recent.load()), daemon=True)
|
||||
thread.start()
|
||||
thread.join(wait)
|
||||
return {} if thread.is_alive() else out
|
||||
|
||||
|
||||
def fix_tcl_paths():
|
||||
@@ -40,9 +74,50 @@ def fix_tcl_paths():
|
||||
os.environ[var] = str(tcl / lib)
|
||||
|
||||
|
||||
def use_sun_valley(root, ui_font):
|
||||
"""Switch the window to the light Sun Valley theme; False leaves the platform theme when it does not load.
|
||||
|
||||
The theme sizes its fonts in pixels, which Tk does not scale with the display; they are turned into points (96 DPI
|
||||
pixels * 0.75) so they grow with tk scaling like the rest of the window. Its Segoe UI Variable families exist on
|
||||
Windows 11 only; elsewhere the fonts take `ui_font`, bold where the theme asked for Semibold. The theme's images
|
||||
(check boxes, button and field borders) stay at their 100% pixel size.
|
||||
|
||||
sv.tcl answers <<ThemeChanged>> with configure_colors, whose tk_setPalette writes the theme's text and background
|
||||
colour into every widget and into the option database, over the colours of our label styles (errors, notices,
|
||||
muted text). The binding is dropped before the switch and the ttk half of configure_colors is done here."""
|
||||
try:
|
||||
root.tk.call('source', str(SUN_VALLEY))
|
||||
root.bind_class('Tk', '<<ThemeChanged>>', '')
|
||||
style = ttk.Style(root)
|
||||
style.theme_use('sun-valley-light')
|
||||
c = {k: root.tk.call('set', f'ttk::theme::sv_light::colors(-{k})') for k in ('fg', 'bg', 'disfg', 'selfg', 'selbg')}
|
||||
style.configure('.', background=c['bg'], foreground=c['fg'], troughcolor=c['bg'], focuscolor=c['selbg'],
|
||||
selectbackground=c['selbg'], selectforeground=c['selfg'], insertwidth=1, insertcolor=c['fg'],
|
||||
fieldbackground=c['bg'], font='SunValleyBodyFont', borderwidth=0, relief='flat')
|
||||
style.map('.', foreground=[('disabled', c['disfg'])])
|
||||
root.configure(background=c['bg'])
|
||||
for cls in ('TEntry', 'TCombobox'): # config_entry_font sets this only on fields that exist at the switch
|
||||
root.option_add(f'*{cls}.font', 'SunValleyBodyFont')
|
||||
except (tk.TclError, OSError):
|
||||
return False
|
||||
families = set(root.tk.splitlist(root.tk.call('font', 'families')))
|
||||
for name in root.tk.splitlist(root.tk.call('font', 'names')):
|
||||
if not str(name).startswith('SunValley'):
|
||||
continue
|
||||
f = tkfont.nametofont(str(name), root=root)
|
||||
size = int(f.cget('size'))
|
||||
if size < 0:
|
||||
f.configure(size=round(-size * 0.75))
|
||||
family = f.cget('family')
|
||||
if family not in families:
|
||||
f.configure(family=ui_font, weight='bold' if 'Semibold' in family else 'normal')
|
||||
return True
|
||||
|
||||
|
||||
class App:
|
||||
def __init__(self, root, ui_lang, layout, run_args=None):
|
||||
def __init__(self, root, ui_lang, layout, run_args=None, rebuild=None):
|
||||
self.root, self.layout = root, layout
|
||||
self.rebuild = rebuild # the install folder of --rebuild, or None
|
||||
self.cat = Catalog(ui_lang)
|
||||
self.model = Model()
|
||||
self.process = None
|
||||
@@ -50,22 +125,43 @@ class App:
|
||||
self.run_args = run_args or {} # extra CLI options for tests: temp, verify
|
||||
self.log_entries = [] # events and raw lines of the run, rendered by render_log
|
||||
self.bound = [] # (widget, option, id, params) retranslated on a language switch
|
||||
self.vars = {n: tk.StringVar() for n in ('base', 'update', 'keys', 'dest')}
|
||||
self.vars = {n: tk.StringVar() for n in ('base', 'update', 'keys', 'firmware', 'dest')}
|
||||
self.vars['lang'] = tk.StringVar()
|
||||
self.recorded = {} # base/update paths prefilled from the recorded ones, by field
|
||||
self.touched = set() # fields the user picked or typed
|
||||
self.programmatic = False
|
||||
for name in ('base', 'update'):
|
||||
self.vars[name].trace_add('write', lambda *_, n=name: self.touched.add(n) if not self.programmatic else None)
|
||||
self.lang_code = default_game_language(ui_lang)
|
||||
self.screen = None
|
||||
self.fitted = None # the (width, height) fit last gave the window
|
||||
|
||||
root.title(self.cat('ui.title'))
|
||||
icon = layout.runtime / 'totk.ico'
|
||||
png = layout.runtime / 'totk.png' # Tk loads no .ico off Windows; the Linux release converts it
|
||||
if os.name == 'nt' and icon.is_file():
|
||||
root.iconbitmap(default=str(icon))
|
||||
elif png.is_file():
|
||||
self.icon = tk.PhotoImage(file=str(png))
|
||||
root.iconphoto(True, self.icon)
|
||||
root.protocol('WM_DELETE_WINDOW', self.on_close)
|
||||
self.ui_font = 'Segoe UI' if os.name == 'nt' else 'DejaVu Sans'
|
||||
self.mono_font = 'Consolas' if os.name == 'nt' else 'DejaVu Sans Mono'
|
||||
self.sun_valley = use_sun_valley(root, self.ui_font)
|
||||
# A read-only combobox selects its text when a value is picked (ttk::combobox::SelectEntry), which draws the
|
||||
# value as highlighted text; the pick clears that selection once ttk has made it
|
||||
root.bind_class('TCombobox', '<<ComboboxSelected>>',
|
||||
lambda e: e.widget.after_idle(e.widget.selection_clear), add='+')
|
||||
style = ttk.Style(root)
|
||||
style.configure('Title.TLabel', font=('Segoe UI', 15, 'bold'))
|
||||
style.configure('Notice.TLabel', background='#fff3cd', foreground='#664d03', padding=8)
|
||||
style.configure('Title.TLabel', font=(self.ui_font, 15, 'bold'))
|
||||
style.configure('Notice.TLabel', background='#fff3cd', foreground='#664d03', padding=dpi.px(8))
|
||||
style.configure('Err.TLabel', foreground='#c01c28')
|
||||
style.configure('Version.TLabel', foreground='#808080')
|
||||
style.configure('Section.TLabel', foreground=HEADING, font=(self.ui_font, 10, 'bold'))
|
||||
style.configure('Muted.TLabel', foreground=MUTED)
|
||||
style.configure('Link.TLabel', foreground=HEADING)
|
||||
style.configure('Status.TLabel', foreground=HEADING)
|
||||
style.configure('Main.TButton', padding=(dpi.px(16), dpi.px(4))) # Start: the native button, larger
|
||||
|
||||
top = ttk.Frame(root, padding=(PAD, PAD, PAD, 0))
|
||||
top.pack(fill='x')
|
||||
@@ -73,19 +169,34 @@ class App:
|
||||
self.title.pack(side='left')
|
||||
version = ttk.Label(top, style='Version.TLabel')
|
||||
self.bind_text(version, 'text', 'ui.version', version=layout.release)
|
||||
version.pack(side='left', padx=(10, 0), pady=(6, 0))
|
||||
version.pack(side='left', padx=(dpi.px(10), 0), pady=(dpi.px(6), 0))
|
||||
sw = ttk.Frame(top)
|
||||
sw.pack(side='right')
|
||||
self.ui_var = tk.StringVar(value=self.cat.lang)
|
||||
for code in UI_LANGUAGES:
|
||||
ttk.Radiobutton(sw, text=code.upper(), value=code, variable=self.ui_var, style='Toolbutton',
|
||||
command=self.switch_language).pack(side='left', padx=1)
|
||||
self.ui_var = tk.StringVar(value=self.cat.lang) # the window language code; the box shows its name
|
||||
labels = [UI_LANGUAGE_LABELS[c] for c in UI_LANGUAGES]
|
||||
self.ui_box = ttk.Combobox(sw, values=labels, state='readonly', width=max(map(len, labels)) + 1)
|
||||
self.ui_box.set(UI_LANGUAGE_LABELS[self.cat.lang])
|
||||
self.ui_box.bind('<<ComboboxSelected>>', self.pick_language)
|
||||
self.ui_box.pack(side='left')
|
||||
self.body = ttk.Frame(root, padding=PAD)
|
||||
self.body.pack(fill='both', expand=True)
|
||||
self.frames = {'form': self.build_form(), 'run': self.build_run(), 'finish': self.build_finish()}
|
||||
self.vars['lang'].set(self.lang_label(self.lang_code))
|
||||
self.vars['dest'].trace_add('write', lambda *_: self.refresh_form())
|
||||
self.show('form')
|
||||
if rebuild:
|
||||
self.bind_text(self.title, 'text', 'ui.rebuild_title')
|
||||
self.vars['dest'].set(str(rebuild))
|
||||
root.after(POLL_MS, self.start)
|
||||
else:
|
||||
# recorded sources fill only empty fields; dest goes last, its trace runs refresh_form (update hint and
|
||||
# recorded language). In update mode filled files are harmless: Extract.current hashes one only when its
|
||||
# size or mtime differ from the recorded ones.
|
||||
last = load_recent()
|
||||
self.recorded = {n: last[n] for n in ('base', 'update') if n in last and not self.vars[n].get().strip()}
|
||||
for name in ('base', 'update', 'keys', 'firmware', 'dest'):
|
||||
if name in last and not self.vars[name].get().strip():
|
||||
self.set_prefill(name, last[name])
|
||||
|
||||
# ---- text -----------------------------------------------------------------------------------------------------
|
||||
|
||||
@@ -113,12 +224,17 @@ class App:
|
||||
self.refresh_finish()
|
||||
self.render_log()
|
||||
|
||||
def pick_language(self, _event=None):
|
||||
self.ui_var.set(UI_LANGUAGES[self.ui_box.current()])
|
||||
self.switch_language()
|
||||
|
||||
def switch_language(self):
|
||||
self.cat.set_language(self.ui_var.get())
|
||||
self.ui_box.set(UI_LANGUAGE_LABELS[self.ui_var.get()])
|
||||
code = self.selected_lang()
|
||||
self.retext()
|
||||
self.vars['lang'].set(self.lang_label(code))
|
||||
self.fit()
|
||||
self.fit(shrink=True)
|
||||
|
||||
def lang_label(self, code):
|
||||
return self.cat('lang.' + code)
|
||||
@@ -144,91 +260,148 @@ class App:
|
||||
f.pack_forget()
|
||||
self.frames[name].pack(fill='both', expand=True)
|
||||
self.screen = name
|
||||
self.fit()
|
||||
self.fit(shrink=True)
|
||||
|
||||
def fit(self):
|
||||
"""Size the window to its largest screen (an unpacked frame still reports the size its children ask for), so
|
||||
a screen or language switch neither cuts text nor moves the buttons. The window only grows: opening the log
|
||||
makes it taller, and a size the user dragged it to stays. Every text change that can add lines calls it again,
|
||||
or pack takes the missing height from the button bars."""
|
||||
def fit(self, shrink=False):
|
||||
"""Size the window: the width of the widest screen (an unpacked frame still reports the size its children ask
|
||||
for), so a screen or language switch does not move the buttons sideways, and the height of the shown screen,
|
||||
so no screen carries the empty band of a taller one. Every text change that can add lines calls it again, or
|
||||
pack takes the missing height from the button bars. Without `shrink` the window only grows and a size the user
|
||||
dragged it to stays; a screen or language switch and closing the details or the log shrink it to fit."""
|
||||
self.root.update_idletasks()
|
||||
sizes = [(f.winfo_reqwidth(), f.winfo_reqheight()) for f in self.frames.values()]
|
||||
widths = [f.winfo_reqwidth() for f in self.frames.values()]
|
||||
shown = self.frames[self.screen] if self.screen else max(self.frames.values(), key=lambda f: f.winfo_reqheight())
|
||||
chrome = self.root.winfo_reqheight() - self.body.winfo_reqheight() # the title row above the body
|
||||
w = max(self.root.winfo_reqwidth(), max(s[0] for s in sizes) + 2 * PAD)
|
||||
h = chrome + max(s[1] for s in sizes) + 2 * PAD
|
||||
if (w, h) == self.fitted: # refresh_run calls it on every poll: leave the window alone while nothing grew
|
||||
w = max(self.root.winfo_reqwidth(), max(widths) + 2 * PAD)
|
||||
h = chrome + shown.winfo_reqheight() + 2 * PAD
|
||||
# refresh_run calls it on every poll: leave the window alone while nothing grew
|
||||
if (w, h) == self.fitted and (not shrink or self.root.winfo_height() == h):
|
||||
return
|
||||
self.fitted = (w, h)
|
||||
self.root.minsize(w, h)
|
||||
self.root.geometry(f'{max(w, self.root.winfo_width())}x{max(h, self.root.winfo_height())}')
|
||||
self.root.geometry(f'{max(w, self.root.winfo_width())}x{h if shrink else max(h, self.root.winfo_height())}')
|
||||
|
||||
def notice(self, parent):
|
||||
w = ttk.Label(parent, style='Notice.TLabel', wraplength=620, justify='left')
|
||||
w = ttk.Label(parent, style='Notice.TLabel', wraplength=WRAP, justify='left')
|
||||
self.bind_text(w, 'text', 'ui.notice')
|
||||
return w
|
||||
|
||||
def section(self, grid, row, id, top):
|
||||
"""A section title across the form grid with a rule after it."""
|
||||
head = ttk.Frame(grid)
|
||||
head.grid(row=row, column=0, columnspan=3, sticky='ew', pady=(top, dpi.px(2)))
|
||||
self.label(head, id, style='Section.TLabel').pack(side='left')
|
||||
ttk.Separator(head).pack(side='left', fill='x', expand=True, padx=(dpi.px(8), 0), pady=(dpi.px(2), 0))
|
||||
|
||||
def build_form(self):
|
||||
f = ttk.Frame(self.body)
|
||||
bar = ttk.Frame(f) # packed first so pack shrinks the text above it, never the buttons
|
||||
bar.pack(side='bottom', fill='x', pady=(12, 0))
|
||||
self.start_button = self.button(bar, 'ui.start', self.start)
|
||||
self.start_button.pack(side='right')
|
||||
self.form_intro = self.label(f, 'ui.intro', wraplength=620, justify='left')
|
||||
self.form_intro.pack(anchor='w', pady=(0, 8))
|
||||
self.notice(f).pack(fill='x', pady=(0, 10))
|
||||
gap = dpi.px(4) # between the form's rows
|
||||
# The footer goes first so pack shrinks the text above it, never the button. The notice sits next to Start,
|
||||
# where the player looks before the build begins, in quiet text instead of a banner over the form.
|
||||
bar = ttk.Frame(f)
|
||||
bar.pack(side='bottom', fill='x', pady=(dpi.px(12), 0))
|
||||
self.start_button = self.button(bar, 'ui.start', self.start, style='Main.TButton')
|
||||
self.start_button.pack(side='right', anchor='s')
|
||||
self.label(bar, 'ui.notice', style='Muted.TLabel', wraplength=dpi.px(470),
|
||||
justify='left').pack(side='left', anchor='w', padx=(0, dpi.px(12)))
|
||||
ttk.Separator(f).pack(side='bottom', fill='x', pady=(dpi.px(10), 0))
|
||||
# The status lines sit on the footer: a window taller than the form leaves its spare height above them
|
||||
self.form_error = ttk.Label(f, style='Err.TLabel', wraplength=WRAP, justify='left')
|
||||
self.form_error.pack(side='bottom', anchor='w', pady=(dpi.px(4), 0))
|
||||
self.update_hint = ttk.Label(f, style='Status.TLabel', wraplength=WRAP, justify='left')
|
||||
self.update_hint.pack(side='bottom', anchor='w', pady=(dpi.px(8), 0))
|
||||
self.form_intro = self.label(f, 'ui.intro', wraplength=WRAP, justify='left')
|
||||
self.form_intro.pack(anchor='w', pady=(0, dpi.px(4)))
|
||||
grid = ttk.Frame(f)
|
||||
grid.pack(fill='x')
|
||||
grid.columnconfigure(1, weight=1)
|
||||
self.section(grid, 0, 'ui.section_files', dpi.px(6))
|
||||
rows = (('base', 'ui.base', 'ui.pick_game'), ('update', 'ui.update', 'ui.pick_update'),
|
||||
('keys', 'ui.keys', 'ui.pick_keys'))
|
||||
self.form_rows = {}
|
||||
for i, (name, label_id, pick_id) in enumerate(rows):
|
||||
for i, (name, label_id, pick_id) in enumerate(rows, start=1):
|
||||
lab = self.label(grid, label_id)
|
||||
lab.grid(row=i, column=0, sticky='w', pady=4, padx=(0, 10))
|
||||
ttk.Entry(grid, textvariable=self.vars[name]).grid(row=i, column=1, sticky='ew', pady=4)
|
||||
lab.grid(row=i, column=0, sticky='w', pady=gap, padx=(0, dpi.px(12)))
|
||||
ttk.Entry(grid, textvariable=self.vars[name]).grid(row=i, column=1, sticky='ew', pady=gap)
|
||||
b = self.button(grid, 'ui.browse', lambda n=name, p=pick_id: self.pick_file(n, p))
|
||||
b.grid(row=i, column=2, padx=(8, 0))
|
||||
b.grid(row=i, column=2, padx=(dpi.px(8), 0))
|
||||
self.form_rows[name] = lab
|
||||
i = len(rows)
|
||||
self.label(grid, 'ui.game_language').grid(row=i, column=0, sticky='w', pady=4)
|
||||
i = len(rows) + 1
|
||||
self.label(grid, 'ui.firmware').grid(row=i, column=0, sticky='w', pady=gap, padx=(0, dpi.px(12)))
|
||||
ttk.Entry(grid, textvariable=self.vars['firmware']).grid(row=i, column=1, sticky='ew', pady=gap)
|
||||
self.button(grid, 'ui.browse', self.pick_firmware).grid(row=i, column=2, padx=(dpi.px(8), 0))
|
||||
self.section(grid, i + 1, 'ui.section_install', dpi.px(12))
|
||||
i += 2
|
||||
self.label(grid, 'ui.game_language').grid(row=i, column=0, sticky='w', pady=gap, padx=(0, dpi.px(12)))
|
||||
self.lang_box = ttk.Combobox(grid, textvariable=self.vars['lang'], state='readonly', width=30)
|
||||
self.lang_box.grid(row=i, column=1, sticky='w', pady=4)
|
||||
self.lang_box.grid(row=i, column=1, sticky='w', pady=gap)
|
||||
self.lang_touched = False
|
||||
self.lang_box.bind('<<ComboboxSelected>>', lambda _e: setattr(self, 'lang_touched', True))
|
||||
self.fill_languages()
|
||||
self.label(grid, 'ui.dest').grid(row=i + 1, column=0, sticky='w', pady=4)
|
||||
ttk.Entry(grid, textvariable=self.vars['dest']).grid(row=i + 1, column=1, sticky='ew', pady=4)
|
||||
self.button(grid, 'ui.browse', self.pick_dest).grid(row=i + 1, column=2, padx=(8, 0))
|
||||
self.update_hint = ttk.Label(f, wraplength=620, justify='left')
|
||||
self.update_hint.pack(anchor='w', pady=(8, 0))
|
||||
self.form_error = ttk.Label(f, style='Err.TLabel', wraplength=620, justify='left')
|
||||
self.form_error.pack(anchor='w', pady=(8, 0))
|
||||
self.label(f, 'ui.keys_private', wraplength=620, justify='left').pack(anchor='w', pady=(8, 0))
|
||||
self.label(grid, 'ui.dest').grid(row=i + 1, column=0, sticky='w', pady=gap, padx=(0, dpi.px(12)))
|
||||
ttk.Entry(grid, textvariable=self.vars['dest']).grid(row=i + 1, column=1, sticky='ew', pady=gap)
|
||||
self.button(grid, 'ui.browse', self.pick_dest).grid(row=i + 1, column=2, padx=(dpi.px(8), 0))
|
||||
# On by default and named with its source and licence: the player sees what is downloaded and can untick it.
|
||||
# The source and licence line is the first one under More details.
|
||||
self.dlss_var = tk.BooleanVar(value=True)
|
||||
dlss = ttk.Checkbutton(f, variable=self.dlss_var)
|
||||
self.bind_text(dlss, 'text', 'ui.dlss')
|
||||
dlss.pack(anchor='w', pady=(dpi.px(12), 0))
|
||||
# The explanations stay out of the way until asked for: a link opens them under it
|
||||
self.details_toggle = ttk.Label(f, style='Link.TLabel', cursor='hand2', takefocus=True)
|
||||
self.bind_text(self.details_toggle, 'text', 'ui.more_details')
|
||||
for seq in ('<Button-1>', '<Return>', '<space>'):
|
||||
self.details_toggle.bind(seq, lambda _e: self.toggle_details())
|
||||
self.details_toggle.pack(anchor='w', pady=(dpi.px(8), 0))
|
||||
self.details = ttk.Frame(f) # packed after the link when open; no holder frame, as an emptied Tk frame keeps
|
||||
# the height its last child gave it
|
||||
for id in ('ui.dlss_help', 'ui.formats_help', 'ui.compressed_help', 'ui.firmware_help', 'ui.keys_private'):
|
||||
self.label(self.details, id, style='Muted.TLabel', wraplength=WRAP - dpi.px(16),
|
||||
justify='left').pack(anchor='w', pady=(dpi.px(6), 0))
|
||||
self.details_open = False
|
||||
return f
|
||||
|
||||
def toggle_details(self):
|
||||
self.details_open = not self.details_open
|
||||
if self.details_open:
|
||||
self.details.pack(after=self.details_toggle, fill='x', padx=(dpi.px(16), 0))
|
||||
else:
|
||||
self.details.pack_forget()
|
||||
self.bound = [b for b in self.bound if b[0] is not self.details_toggle]
|
||||
self.bind_text(self.details_toggle, 'text', 'ui.fewer_details' if self.details_open else 'ui.more_details')
|
||||
self.fit(shrink=not self.details_open)
|
||||
|
||||
def build_run(self):
|
||||
f = ttk.Frame(self.body)
|
||||
bar = ttk.Frame(f)
|
||||
bar.pack(side='bottom', fill='x', pady=(8, 0))
|
||||
bar.pack(side='bottom', fill='x', pady=(dpi.px(8), 0))
|
||||
self.cancel_button = self.button(bar, 'ui.cancel', self.cancel)
|
||||
self.cancel_button.pack(side='right')
|
||||
self.log_toggle = self.button(bar, 'ui.show_log', self.toggle_log)
|
||||
self.log_toggle.pack(side='left')
|
||||
self.run_header = ttk.Label(f, font=('Segoe UI', 11, 'bold'))
|
||||
self.run_header = ttk.Label(f, font=(self.ui_font, 11, 'bold'))
|
||||
self.run_header.pack(anchor='w')
|
||||
self.step_rows = {}
|
||||
self.steps_box = ttk.Frame(f)
|
||||
self.steps_box.pack(fill='x', pady=(8, 8))
|
||||
self.phase_label = ttk.Label(f, wraplength=620, justify='left')
|
||||
self.steps_box.pack(fill='x', pady=dpi.px(8))
|
||||
self.phase_label = ttk.Label(f, wraplength=WRAP, justify='left')
|
||||
self.phase_label.pack(anchor='w')
|
||||
self.bar = ttk.Progressbar(f, mode='determinate', maximum=1000)
|
||||
self.bar.pack(fill='x', pady=(4, 6))
|
||||
self.space_label = ttk.Label(f, wraplength=620, justify='left')
|
||||
bar_holder = ttk.Frame(f)
|
||||
bar_holder.pack(fill='x', pady=(dpi.px(4), dpi.px(6)))
|
||||
self.bar = ttk.Progressbar(bar_holder, mode='determinate', maximum=1000)
|
||||
self.bar.pack(fill='both', expand=True)
|
||||
if os.name == 'nt' and ttk.Style(f).theme_use() == 'vista':
|
||||
# The vista theme draws the bar 22 px high at every DPI and has no thickness option: the holder gives it the
|
||||
# height it would have at 100%, scaled with the display. Every other theme draws its own height, and the
|
||||
# holder follows it.
|
||||
bar_holder.pack_propagate(False)
|
||||
bar_holder.configure(height=dpi.px(22))
|
||||
self.space_label = ttk.Label(f, wraplength=WRAP, justify='left')
|
||||
self.space_label.pack(anchor='w')
|
||||
self.warn_label = ttk.Label(f, wraplength=620, justify='left', foreground='#9a6700')
|
||||
self.warn_label = ttk.Label(f, wraplength=WRAP, justify='left', foreground='#9a6700')
|
||||
self.warn_label.pack(anchor='w')
|
||||
self.log_frame = ttk.Frame(f)
|
||||
self.log = tk.Text(self.log_frame, height=10, wrap='word', state='disabled', font=('Consolas', 9))
|
||||
self.log = tk.Text(self.log_frame, height=10, wrap='word', state='disabled', font=(self.mono_font, 9))
|
||||
scroll = ttk.Scrollbar(self.log_frame, command=self.log.yview)
|
||||
self.log.configure(yscrollcommand=scroll.set)
|
||||
scroll.pack(side='right', fill='y')
|
||||
@@ -239,31 +412,60 @@ class App:
|
||||
def build_finish(self):
|
||||
f = ttk.Frame(self.body)
|
||||
bar = ttk.Frame(f)
|
||||
bar.pack(side='bottom', fill='x', pady=(12, 0))
|
||||
bar.pack(side='bottom', fill='x', pady=(dpi.px(12), 0))
|
||||
self.button(bar, 'ui.close', self.on_close).pack(side='right')
|
||||
self.open_button = self.button(bar, 'ui.open_folder', self.open_folder)
|
||||
self.open_button.pack(side='right', padx=(0, 8))
|
||||
self.open_button.pack(side='right', padx=(0, dpi.px(8)))
|
||||
self.back_button = self.button(bar, 'ui.back', lambda: self.show('form'))
|
||||
self.back_button.pack(side='left')
|
||||
self.finish_title = ttk.Label(f, style='Title.TLabel', wraplength=620, justify='left')
|
||||
if self.rebuild: # a failed or cancelled rebuild: the game starts with the code it has
|
||||
self.button(bar, 'ui.start_game', self.start_game).pack(side='right', padx=(0, dpi.px(8)))
|
||||
self.finish_title = ttk.Label(f, style='Title.TLabel', wraplength=WRAP, justify='left')
|
||||
self.finish_title.pack(anchor='w')
|
||||
self.finish_text = ttk.Label(f, wraplength=620, justify='left')
|
||||
self.finish_text.pack(anchor='w', pady=(8, 8))
|
||||
self.finish_text = ttk.Label(f, wraplength=WRAP, justify='left')
|
||||
self.finish_text.pack(anchor='w', pady=dpi.px(8))
|
||||
self.finish_steps = ttk.Frame(f)
|
||||
self.finish_steps.pack(fill='x', pady=(0, 8))
|
||||
self.finish_steps.pack(fill='x', pady=(0, dpi.px(8)))
|
||||
self.finish_notice = self.notice(f)
|
||||
self.finish_notice.pack(fill='x', pady=(8, 0))
|
||||
self.finish_notice.pack(fill='x', pady=(dpi.px(8), 0))
|
||||
return f
|
||||
|
||||
# ---- form -----------------------------------------------------------------------------------------------------
|
||||
|
||||
def form(self):
|
||||
return Form(base=self.vars['base'].get(), update=self.vars['update'].get(), keys=self.vars['keys'].get(),
|
||||
lang=self.selected_lang(), dest=self.vars['dest'].get())
|
||||
firmware=self.vars['firmware'].get(), lang=self.selected_lang(), dest=self.vars['dest'].get(),
|
||||
dlss=self.dlss_var.get())
|
||||
|
||||
def set_prefill(self, name, value):
|
||||
self.programmatic = True
|
||||
try:
|
||||
self.vars[name].set(value)
|
||||
finally:
|
||||
self.programmatic = False
|
||||
|
||||
def match_prefill(self, state):
|
||||
"""Prefilled base/update stay only while the chosen install recorded the same file (name and size, one stat);
|
||||
another install would otherwise extract again from them. Fields the user touched are left alone."""
|
||||
for name, value in self.recorded.items():
|
||||
if name in self.touched:
|
||||
continue
|
||||
keep = True
|
||||
if state is not None:
|
||||
known = (state.get('inputs') or {}).get(name)
|
||||
try:
|
||||
keep = (isinstance(known, dict) and Path(value).name == known.get('name')
|
||||
and Path(value).stat().st_size == known.get('size'))
|
||||
except (OSError, ValueError):
|
||||
keep = False
|
||||
want = value if keep else ''
|
||||
if self.vars[name].get() != want:
|
||||
self.set_prefill(name, want)
|
||||
|
||||
def refresh_form(self):
|
||||
form = self.form()
|
||||
state = form.installed_state()
|
||||
self.match_prefill(state)
|
||||
if state is not None:
|
||||
self.update_hint.configure(text=self.cat('ui.update_mode'))
|
||||
recorded = ini.canonical_language(state.get('lang'))
|
||||
@@ -274,15 +476,19 @@ class App:
|
||||
self.fit()
|
||||
|
||||
def pick_file(self, name, pick_id):
|
||||
types = [(self.cat('ui.type_game'), '*.nsp *.xci'), (self.cat('ui.type_all'), '*.*')]
|
||||
if name == 'update':
|
||||
types = [(self.cat('ui.type_nsp'), '*.nsp'), (self.cat('ui.type_all'), '*.*')]
|
||||
# One filter for every game file: the setup tells an NSZ or XCZ from a plain file by its content (Check.unpack)
|
||||
types = [(self.cat('ui.type_game'), '*.nsp *.xci *.nsz *.xcz'), (self.cat('ui.type_all'), '*.*')]
|
||||
if name == 'keys':
|
||||
types = [(self.cat('ui.type_keys'), '*.keys'), (self.cat('ui.type_all'), '*.*')]
|
||||
path = filedialog.askopenfilename(title=self.cat(pick_id), filetypes=types)
|
||||
if path:
|
||||
self.vars[name].set(os.path.normpath(path))
|
||||
|
||||
def pick_firmware(self):
|
||||
path = filedialog.askdirectory(title=self.cat('ui.pick_firmware'), mustexist=True)
|
||||
if path:
|
||||
self.vars['firmware'].set(os.path.normpath(path))
|
||||
|
||||
def pick_dest(self):
|
||||
path = filedialog.askdirectory(title=self.cat('ui.pick_dest'), mustexist=False)
|
||||
if path:
|
||||
@@ -298,8 +504,12 @@ class App:
|
||||
self.fit()
|
||||
return
|
||||
self.form_error.configure(text='')
|
||||
command = form.command(self.layout.python, root=self.layout.root if self.layout.dev else None,
|
||||
temp=self.run_args.get('temp'), verify=self.run_args.get('verify', False))
|
||||
recent.save(form.dest, {name: getattr(form, name) for name in recent.SOURCES})
|
||||
# in a repository the Python running this window: the tools' embeddable Python there has no ._pth entry for
|
||||
# the repository, so `-m installer` would not find the package
|
||||
python = Path(sys.executable) if self.layout.dev else self.layout.python
|
||||
command = form.command(python, root=self.layout.root if self.layout.dev else None,
|
||||
temp=self.run_args.get('temp'), verify_hashes=self.run_args.get('verify', False))
|
||||
self.begin(command, self.layout.root)
|
||||
|
||||
def begin(self, command, cwd):
|
||||
@@ -321,7 +531,7 @@ class App:
|
||||
self.step_rows = {}
|
||||
for s in steps:
|
||||
row = ttk.Frame(self.steps_box)
|
||||
row.pack(fill='x', pady=1)
|
||||
row.pack(fill='x', pady=dpi.px(1))
|
||||
glyph = ttk.Label(row, width=3)
|
||||
glyph.pack(side='left')
|
||||
name = ttk.Label(row)
|
||||
@@ -345,6 +555,9 @@ class App:
|
||||
return
|
||||
self.model.finish(code)
|
||||
self.process = None
|
||||
if self.rebuild and self.model.result == 'ok' and not self.closing:
|
||||
self.start_game()
|
||||
return
|
||||
self.refresh_run()
|
||||
self.refresh_finish()
|
||||
self.show('finish')
|
||||
@@ -373,7 +586,7 @@ class App:
|
||||
glyph.configure(text=GLYPH[state], foreground=COLOR[state])
|
||||
name.configure(text=self.cat('step.' + s) + (f' ({self.cat("ui.state_" + state)})'
|
||||
if state in (SKIPPED, FAILED) else ''),
|
||||
font=('Segoe UI', 10, 'bold') if state == RUNNING else ('Segoe UI', 10))
|
||||
font=(self.ui_font, 10, 'bold') if state == RUNNING else (self.ui_font, 10))
|
||||
mode = m.mode or 'install'
|
||||
self.run_header.configure(text=self.cat('ui.running_' + mode if mode in ('install', 'resume', 'update')
|
||||
else 'ui.running_install'))
|
||||
@@ -403,12 +616,12 @@ class App:
|
||||
def toggle_log(self):
|
||||
self.log_open = not self.log_open
|
||||
if self.log_open:
|
||||
self.log_frame.pack(fill='both', expand=True, pady=(8, 0))
|
||||
self.log_frame.pack(fill='both', expand=True, pady=(dpi.px(8), 0))
|
||||
else:
|
||||
self.log_frame.pack_forget()
|
||||
self.bound = [b for b in self.bound if b[0] is not self.log_toggle]
|
||||
self.bind_text(self.log_toggle, 'text', 'ui.hide_log' if self.log_open else 'ui.show_log')
|
||||
self.fit()
|
||||
self.fit(shrink=not self.log_open)
|
||||
|
||||
def clear_log(self):
|
||||
self.log_entries = []
|
||||
@@ -474,20 +687,34 @@ class App:
|
||||
self.open_button.state(['!disabled'])
|
||||
else:
|
||||
self.open_button.state(['disabled' if not Path(m.dest or '.').is_dir() else '!disabled'])
|
||||
self.fit() # an error text can be longer than the screen it replaces
|
||||
|
||||
def start_game(self):
|
||||
"""Starts the game of the install folder and closes the window."""
|
||||
dest = Path(self.vars['dest'].get().strip())
|
||||
exe = dest / ('totk.exe' if os.name == 'nt' else 'totk')
|
||||
flags = subprocess.DETACHED_PROCESS if os.name == 'nt' else 0
|
||||
if exe.is_file():
|
||||
subprocess.Popen([str(exe)], cwd=str(dest), creationflags=flags, close_fds=True)
|
||||
self.root.destroy()
|
||||
|
||||
def open_folder(self):
|
||||
dest = self.model.dest
|
||||
if dest and Path(dest).is_dir():
|
||||
os.startfile(dest)
|
||||
if os.name == 'nt':
|
||||
os.startfile(dest)
|
||||
else:
|
||||
subprocess.Popen(['xdg-open', dest], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
start_new_session=True)
|
||||
|
||||
|
||||
# ---- self test ---------------------------------------------------------------------------------------------------
|
||||
|
||||
SAMPLE_START = {'type': 'start', 'release': 'selftest', 'mode': 'install', 'dest': 'Z:/selftest/TotK', 'log': 'D:\\log.txt',
|
||||
'steps': ['check', 'extract', 'lift', 'compile', 'prepare', 'cleanup']}
|
||||
'steps': ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'pc_prompts', 'shapes', 'dlss', 'cleanup']}
|
||||
SAMPLE_RUN = [
|
||||
SAMPLE_START,
|
||||
{'type': 'plan', 'run': ['check', 'extract'], 'skip': {}},
|
||||
{'type': 'plan', 'run': ['check', 'fonts', 'extract'], 'skip': {}},
|
||||
{'type': 'step', 'step': 'check', 'state': 'started'},
|
||||
{'type': 'progress', 'step': 'check', 'phase': 'inputs'},
|
||||
{'type': 'space', 'dest': 'Z:/selftest/TotK', 'need': 36_400_000_000, 'free': 210_000_000_000, 'temp': 'C:\\t',
|
||||
@@ -500,12 +727,14 @@ SAMPLE_RUN = [
|
||||
]
|
||||
|
||||
|
||||
SAMPLE_OK = [SAMPLE_START, {'type': 'plan', 'run': ['check', 'extract'], 'skip': {'lift': 'current', 'compile': 'current',
|
||||
'prepare': 'current', 'cleanup': 'not_needed'}},
|
||||
SAMPLE_OK = [SAMPLE_START, {'type': 'plan', 'run': ['check', 'extract'], 'skip': {'fonts': 'current', 'lift': 'current',
|
||||
'compile': 'current', 'prepare': 'current',
|
||||
'cleanup': 'not_needed'}},
|
||||
{'type': 'step', 'step': 'check', 'state': 'started'},
|
||||
{'type': 'step', 'step': 'check', 'state': 'done', 'seconds': 1.0},
|
||||
{'type': 'step', 'step': 'extract', 'state': 'started'},
|
||||
{'type': 'step', 'step': 'extract', 'state': 'done', 'seconds': 1.0},
|
||||
{'type': 'step', 'step': 'fonts', 'state': 'skipped', 'reason': 'current'},
|
||||
{'type': 'step', 'step': 'lift', 'state': 'skipped', 'reason': 'current'},
|
||||
{'type': 'step', 'step': 'compile', 'state': 'skipped', 'reason': 'current'},
|
||||
{'type': 'step', 'step': 'prepare', 'state': 'skipped', 'reason': 'current'},
|
||||
@@ -523,8 +752,9 @@ def grab(root, path):
|
||||
|
||||
|
||||
def selftest(layout, shots=None):
|
||||
"""Every screen in both languages; the window closes itself. Returns 0 when nothing raised."""
|
||||
"""Every screen in every language; the window closes itself. Returns 0 when nothing raised."""
|
||||
fix_tcl_paths()
|
||||
os.environ[recent.ENV] = os.path.join(tempfile.mkdtemp(prefix='totk-selftest-'), 'setup.json')
|
||||
root = tk.Tk()
|
||||
root.geometry('+60+40')
|
||||
app = App(root, 'en', layout)
|
||||
@@ -549,6 +779,9 @@ def selftest(layout, shots=None):
|
||||
app.start() # missing files: shows the problems
|
||||
steps.append(app.form_error.cget('text'))
|
||||
shot(f'form-{tag}')
|
||||
app.toggle_details()
|
||||
shot(f'form-details-{tag}')
|
||||
app.toggle_details()
|
||||
app.model = Model()
|
||||
app.clear_log()
|
||||
app.build_step_rows(app.model.steps)
|
||||
@@ -601,13 +834,16 @@ def main(argv=None):
|
||||
ap.add_argument('--shots', type=Path)
|
||||
ap.add_argument('--lang', choices=UI_LANGUAGES)
|
||||
ap.add_argument('--root', type=Path)
|
||||
ap.add_argument('--rebuild', type=Path)
|
||||
args = ap.parse_args(argv)
|
||||
layout = layouts.find(args.root)
|
||||
if args.selftest:
|
||||
return selftest(layout, args.shots)
|
||||
fix_tcl_paths()
|
||||
root = tk.Tk()
|
||||
App(root, args.lang or windows_ui_language(), layout)
|
||||
# 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
|
||||
|
||||
|
||||
+69
-12
@@ -11,6 +11,7 @@ import ctypes
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
@@ -23,11 +24,22 @@ from . import state as statefile
|
||||
from .events import render
|
||||
|
||||
TEXT = Path(__file__).resolve().parent / 'text'
|
||||
UI_LANGUAGES = ('en', 'ru')
|
||||
STEP_ORDER = ('check', 'extract', 'lift', 'compile', 'prepare', 'cleanup')
|
||||
UI_LANGUAGES = ('en', 'ru', 'pt-BR', 'zh-Hans', 'de', 'fr', 'es', 'it', 'nl', 'ja', 'ko')
|
||||
# what the language switch in the window's corner shows for each
|
||||
UI_LANGUAGE_LABELS = {'en': 'English', 'ru': 'Русский', 'pt-BR': 'Português (Brasil)', 'zh-Hans': '简体中文',
|
||||
'de': 'Deutsch', 'fr': 'Français', 'es': 'Español', 'it': 'Italiano', 'nl': 'Nederlands',
|
||||
'ja': '日本語', 'ko': '한국어'}
|
||||
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
|
||||
LANG_PT_BR = 0x0416 # Portuguese (Brazil), the whole LANGID: Portugal's Portuguese stays English
|
||||
# primary language id in a Windows LANGID -> window language, for the languages whose every region gets the same text.
|
||||
# Every Chinese gets Simplified Chinese: the setup has no Traditional Chinese text, as the in-game menu has none.
|
||||
PRIMARY_LANGS = {0x04: 'zh-Hans', 0x19: 'ru', 0x07: 'de', 0x0c: 'fr', 0x0a: 'es', 0x10: 'it', 0x13: 'nl', 0x11: 'ja',
|
||||
0x12: 'ko'}
|
||||
# window language -> the game language the form starts with (default_game_language)
|
||||
GAME_LANGUAGE_FOR_UI = {'ru': 'ru', 'de': 'de', 'fr': 'fr', 'es': 'es', 'it': 'it', 'nl': 'nl', 'ja': 'ja'}
|
||||
|
||||
|
||||
def load_texts(lang):
|
||||
@@ -75,16 +87,44 @@ def flat(value):
|
||||
|
||||
|
||||
def windows_ui_language():
|
||||
"""'ru' when the Windows display language is Russian, else 'en'."""
|
||||
"""The window language for the display language: the Windows one (ui_language_for_langid); elsewhere LC_ALL,
|
||||
LC_MESSAGES or LANG (ui_language_for_locale)."""
|
||||
if os.name != 'nt':
|
||||
return ui_language_for_locale(os.environ.get('LC_ALL') or os.environ.get('LC_MESSAGES')
|
||||
or os.environ.get('LANG') or '')
|
||||
try:
|
||||
langid = ctypes.windll.kernel32.GetUserDefaultUILanguage()
|
||||
except (AttributeError, OSError):
|
||||
return 'en'
|
||||
return 'ru' if langid & 0x3ff == LANG_RU else 'en'
|
||||
return ui_language_for_langid(langid)
|
||||
|
||||
|
||||
def ui_language_for_locale(loc):
|
||||
"""The window language for a POSIX locale such as 'de_AT.UTF-8': its language, Brazilian Portuguese only for
|
||||
pt_BR, Simplified Chinese for every Chinese, else English."""
|
||||
loc = loc.lower().replace('-', '_')
|
||||
if loc.startswith('pt_br'):
|
||||
return 'pt-BR'
|
||||
lang = loc.split('_')[0].split('.')[0]
|
||||
if lang == 'zh':
|
||||
return 'zh-Hans'
|
||||
return lang if lang in PRIMARY_LANGS.values() else 'en'
|
||||
|
||||
|
||||
def ui_language_for_langid(langid):
|
||||
"""The window language for a Windows LANGID: by its primary language (PRIMARY_LANGS), Brazilian Portuguese only
|
||||
for pt-BR (Portugal's stays English), else 'en'."""
|
||||
if langid == LANG_PT_BR:
|
||||
return 'pt-BR'
|
||||
return PRIMARY_LANGS.get(langid & 0x3ff, 'en')
|
||||
|
||||
|
||||
def default_game_language(ui):
|
||||
return 'ru' if ui == 'ru' else 'en-US'
|
||||
"""The game language the form starts with: the window's own when the game has it. A Chinese or Korean window
|
||||
still starts with English: that game text needs the Switch shared fonts (ini.NEED_SHARED_FONTS), which the setup
|
||||
extracts only from a firmware folder, and the game stops when they are missing; the player can still pick it.
|
||||
The game has no Brazilian Portuguese, so that window starts with English too."""
|
||||
return GAME_LANGUAGE_FOR_UI.get(ui, 'en-US')
|
||||
|
||||
|
||||
def gib(n):
|
||||
@@ -107,8 +147,10 @@ class Form:
|
||||
base: str = ''
|
||||
update: str = ''
|
||||
keys: str = ''
|
||||
firmware: str = ''
|
||||
lang: str = ''
|
||||
dest: str = ''
|
||||
dlss: bool = False
|
||||
|
||||
def installed_state(self):
|
||||
"""The recorded state of the install folder (totk-install.json), or None. Never raises."""
|
||||
@@ -143,20 +185,24 @@ class Form:
|
||||
value = getattr(self, name).strip()
|
||||
if value and not Path(value).is_file():
|
||||
found.append(f'ui.missing_{name}')
|
||||
if self.firmware.strip() and not Path(self.firmware.strip()).is_dir():
|
||||
found.append('ui.missing_firmware')
|
||||
return found
|
||||
|
||||
def command(self, python, root=None, temp=None, verify=False):
|
||||
def command(self, python, root=None, temp=None, verify_hashes=False):
|
||||
cmd = [str(python), '-m', 'installer']
|
||||
for flag, value in (('--base', self.base), ('--update', self.update), ('--keys', self.keys),
|
||||
('--lang', self.lang), ('--dest', self.dest)):
|
||||
('--firmware', self.firmware), ('--lang', self.lang), ('--dest', self.dest)):
|
||||
if value.strip():
|
||||
cmd += [flag, value.strip()]
|
||||
if root:
|
||||
cmd += ['--root', str(root)]
|
||||
if temp:
|
||||
cmd += ['--temp', str(temp)]
|
||||
if verify:
|
||||
if verify_hashes:
|
||||
cmd.append('--verify')
|
||||
if self.dlss:
|
||||
cmd.append('--dlss')
|
||||
return cmd
|
||||
|
||||
|
||||
@@ -316,7 +362,14 @@ else:
|
||||
|
||||
def send_break(proc, python=None):
|
||||
"""Ctrl+Break to the process group of proc (started with CREATE_NEW_PROCESS_GROUP). The window itself may have no
|
||||
console (pythonw), so a short helper process attaches to the child's console and sends it."""
|
||||
console (pythonw), so a short helper process attaches to the child's console and sends it. Elsewhere SIGTERM to
|
||||
proc's session (Process starts it in one of its own), which installer/cli.py handles as Ctrl+Break."""
|
||||
if os.name != 'nt':
|
||||
try:
|
||||
os.killpg(proc.pid, signal.SIGTERM)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
helper = [str(python or sys.executable), '-c', _BREAK, str(proc.pid)]
|
||||
flags = CREATE_NO_WINDOW if os.name == 'nt' else 0
|
||||
r = subprocess.run(helper, creationflags=flags, capture_output=True)
|
||||
@@ -332,10 +385,14 @@ class Process:
|
||||
self.command = command
|
||||
self.helper_python = helper_python
|
||||
self.lines = queue.Queue()
|
||||
flags = (CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW) if creationflags is None else creationflags
|
||||
env = dict(os.environ, PYTHONIOENCODING='utf-8', PYTHONUTF8='1', PYTHONUNBUFFERED='1')
|
||||
if os.name == 'nt':
|
||||
flags = (CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW) if creationflags is None else creationflags
|
||||
group = {'creationflags': flags}
|
||||
else:
|
||||
group = {'start_new_session': True}
|
||||
self.proc = subprocess.Popen(command, cwd=cwd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, creationflags=flags)
|
||||
stderr=subprocess.STDOUT, **group)
|
||||
self.cancelled_at = None
|
||||
self.reader = threading.Thread(target=self.read, daemon=True)
|
||||
self.reader.start()
|
||||
|
||||
+36
-3
@@ -1,6 +1,7 @@
|
||||
// Host check of the installer's first step, compiled with the bundled clang at install time: does the CPU run
|
||||
// -march=x86-64-v3 code, and does a Vulkan 1.3 device exist. Prints one JSON object on stdout.
|
||||
// -march=x86-64-v3 code (or only x86-64-v2), and does a Vulkan 1.3 device exist. Prints one JSON object on stdout.
|
||||
// The Vulkan loader is opened at run time, so a machine without one gets "loader": false instead of a failed start.
|
||||
#include <cpuid.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <vulkan/vulkan.h>
|
||||
@@ -24,9 +25,41 @@ static void json_string(const char *s) {
|
||||
putchar('"');
|
||||
}
|
||||
|
||||
// The x86-64-v2 level from CPUID: SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CMPXCHG16B and LAHF/SAHF. Every CPU with
|
||||
// SSE4.2 has the others, but the level is what the v2 build is compiled for, so check them all.
|
||||
static int x86_64_v2(void) {
|
||||
unsigned a, b, c, d;
|
||||
if (!__get_cpuid(1, &a, &b, &c, &d)) return 0;
|
||||
const unsigned sse3 = 1u << 0, ssse3 = 1u << 9, cx16 = 1u << 13, sse41 = 1u << 19, sse42 = 1u << 20,
|
||||
popcnt = 1u << 23;
|
||||
if ((c & (sse3 | ssse3 | cx16 | sse41 | sse42 | popcnt)) != (sse3 | ssse3 | cx16 | sse41 | sse42 | popcnt))
|
||||
return 0;
|
||||
if (!__get_cpuid(0x80000001, &a, &b, &c, &d)) return 0;
|
||||
return (c & (1u << 0)) != 0; // LAHF/SAHF
|
||||
}
|
||||
|
||||
// The x86-64-v3 level from CPUID: AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT and MOVBE, with the OS saving the YMM state.
|
||||
// Not __builtin_cpu_supports("x86-64-v3"): clang reads that from the C runtime's CPU model, and libgcc before GCC 12
|
||||
// (the Linux release's sysroot has GCC 10) has no level bits, so it answers false on every CPU.
|
||||
static int x86_64_v3(void) {
|
||||
if (!x86_64_v2()) return 0;
|
||||
unsigned a, b, c, d;
|
||||
if (!__get_cpuid(1, &a, &b, &c, &d)) return 0;
|
||||
const unsigned fma = 1u << 12, movbe = 1u << 22, osxsave = 1u << 27, avx = 1u << 28, f16c = 1u << 29;
|
||||
if ((c & (fma | movbe | osxsave | avx | f16c)) != (fma | movbe | osxsave | avx | f16c)) return 0;
|
||||
unsigned lo, hi;
|
||||
__asm__("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
|
||||
if ((lo & 6) != 6) return 0; // XMM and YMM state enabled by the OS
|
||||
if (!__get_cpuid_count(7, 0, &a, &b, &c, &d)) return 0;
|
||||
const unsigned bmi1 = 1u << 3, avx2 = 1u << 5, bmi2 = 1u << 8;
|
||||
if ((b & (bmi1 | avx2 | bmi2)) != (bmi1 | avx2 | bmi2)) return 0;
|
||||
if (!__get_cpuid(0x80000001, &a, &b, &c, &d)) return 0;
|
||||
return (c & (1u << 5)) != 0; // LZCNT (ABM)
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
__builtin_cpu_init();
|
||||
printf("{\"x86_64_v3\": %s, ", __builtin_cpu_supports("x86-64-v3") ? "true" : "false");
|
||||
printf("{\"x86_64_v2\": %s, \"x86_64_v3\": %s, ", x86_64_v2() ? "true" : "false",
|
||||
x86_64_v3() ? "true" : "false");
|
||||
void *lib = open_lib();
|
||||
PFN_vkGetInstanceProcAddr gipa = lib ? (PFN_vkGetInstanceProcAddr)lib_sym(lib, "vkGetInstanceProcAddr") : NULL;
|
||||
if (!gipa) {
|
||||
|
||||
+2
-1
@@ -14,7 +14,8 @@ LANGUAGES = ('ja', 'en-US', 'en-GB', 'fr', 'fr-CA', 'de', 'it', 'es', 'es-419',
|
||||
'zh-Hans', 'zh-Hant')
|
||||
# Older installer builds wrote these two codes; they are read as the canonical ones and rewritten on the next install.
|
||||
ALIASES = {'zh-CN': 'zh-Hans', 'zh-TW': 'zh-Hant'}
|
||||
# Their text falls back to the Switch shared fonts (runtime/ov_system.c), which the installer does not extract.
|
||||
# Their text falls back to the Switch shared fonts (runtime/ov_system.c), which the fonts step extracts from the
|
||||
# firmware folder when the player gives one.
|
||||
NEED_SHARED_FONTS = ('ko', 'zh-Hans', 'zh-Hant')
|
||||
|
||||
ACTIVE = re.compile(r'^(\s*)(?:totk_)?lang(\s*=\s*)(.*?)(\s*)$', re.IGNORECASE)
|
||||
|
||||
@@ -3,20 +3,42 @@
|
||||
No console window. The two message strings come from the catalog (installer/text/<lang>.json, ids launcher.title and
|
||||
launcher.python_missing); tools/make_release.py writes them into launcher_text.h before it compiles this file.
|
||||
Build: llvm/bin/llvm-windres -I runtime -O coff launcher.rc -o launcher_rc.o, then
|
||||
llvm/bin/clang -O2 -mwindows launcher.c launcher_rc.o -o TotK-Setup.exe */
|
||||
llvm/bin/clang -O2 -mwindows launcher.c launcher_rc.o -o TotK-Setup.exe
|
||||
|
||||
System DPI aware, like the window's Python process (installer/dpi.py): Windows draws the error box of fail() at the
|
||||
display's scale instead of stretching it, which it would at 125% and above. */
|
||||
#include <windows.h>
|
||||
#include <wchar.h>
|
||||
|
||||
#include "launcher_text.h"
|
||||
|
||||
#define LANGID_RUSSIAN 0x19
|
||||
#define LANGID_PT_BR 0x0416 /* the whole LANGID: Portugal's Portuguese stays English */
|
||||
#define PATH_CHARS (MAX_PATH * 2)
|
||||
|
||||
/* The language of the window (installer/guilogic.py ui_language_for_langid): Brazilian Portuguese by the whole LANGID,
|
||||
the rest by the primary language (every Chinese gets Simplified Chinese), else English. */
|
||||
static void fail(void)
|
||||
{
|
||||
int russian = (GetUserDefaultUILanguage() & 0x3ff) == LANGID_RUSSIAN;
|
||||
MessageBoxW(NULL, russian ? LAUNCHER_PYTHON_MISSING_RU : LAUNCHER_PYTHON_MISSING_EN,
|
||||
russian ? LAUNCHER_TITLE_RU : LAUNCHER_TITLE_EN, MB_OK | MB_ICONERROR);
|
||||
static const struct { WORD primary; const wchar_t *title, *text; } by_primary[] = {
|
||||
{ LANG_RUSSIAN, LAUNCHER_TITLE_RU, LAUNCHER_PYTHON_MISSING_RU },
|
||||
{ LANG_GERMAN, LAUNCHER_TITLE_DE, LAUNCHER_PYTHON_MISSING_DE },
|
||||
{ LANG_FRENCH, LAUNCHER_TITLE_FR, LAUNCHER_PYTHON_MISSING_FR },
|
||||
{ LANG_SPANISH, LAUNCHER_TITLE_ES, LAUNCHER_PYTHON_MISSING_ES },
|
||||
{ LANG_ITALIAN, LAUNCHER_TITLE_IT, LAUNCHER_PYTHON_MISSING_IT },
|
||||
{ LANG_DUTCH, LAUNCHER_TITLE_NL, LAUNCHER_PYTHON_MISSING_NL },
|
||||
{ LANG_JAPANESE, LAUNCHER_TITLE_JA, LAUNCHER_PYTHON_MISSING_JA },
|
||||
{ LANG_KOREAN, LAUNCHER_TITLE_KO, LAUNCHER_PYTHON_MISSING_KO },
|
||||
{ LANG_CHINESE, LAUNCHER_TITLE_ZH_HANS, LAUNCHER_PYTHON_MISSING_ZH_HANS },
|
||||
};
|
||||
LANGID ui = GetUserDefaultUILanguage();
|
||||
const wchar_t *title = LAUNCHER_TITLE_EN, *text = LAUNCHER_PYTHON_MISSING_EN;
|
||||
if (ui == LANGID_PT_BR) {
|
||||
title = LAUNCHER_TITLE_PT_BR; text = LAUNCHER_PYTHON_MISSING_PT_BR;
|
||||
} else {
|
||||
for (size_t i = 0; i < sizeof by_primary / sizeof by_primary[0]; i++)
|
||||
if (PRIMARYLANGID(ui) == by_primary[i].primary) { title = by_primary[i].title; text = by_primary[i].text; }
|
||||
}
|
||||
MessageBoxW(NULL, text, title, MB_OK | MB_ICONERROR);
|
||||
}
|
||||
|
||||
int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line, int show)
|
||||
@@ -26,6 +48,7 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line, i
|
||||
STARTUPINFOW si = { sizeof si };
|
||||
PROCESS_INFORMATION pi;
|
||||
(void)instance; (void)previous; (void)command_line; (void)show;
|
||||
SetProcessDPIAware(); /* before the message box exists; the call fails harmlessly when a manifest set it */
|
||||
if (n == 0 || n >= PATH_CHARS) { fail(); return 1; }
|
||||
while (n > 0 && folder[n - 1] != L'\\') n--;
|
||||
folder[n > 0 ? n - 1 : 0] = 0;
|
||||
|
||||
+124
-17
@@ -7,29 +7,55 @@ Release (docs/installer.md "Release layout"), root = the unpacked folder:
|
||||
recomp/, tools/ the lifter and the scripts; recomp/patches-<v>.txt, tools/data/expected-v<version>.json for
|
||||
each supported update (SUPPORTED)
|
||||
llvm/ llvm-mingw (bin/clang.exe)
|
||||
runtime/ libtotkrt.a, the headers, install-side sources (romfs.c, patches.c, ov_zstd.c) and totk.ico; runtime/deps/ holds
|
||||
runtime/ libtotkrt.a and libtotkrt-v2.a (x86-64-v3 / v2), the headers, install-side sources (romfs.c,
|
||||
patches.c, ov_zstd.c) and totk.ico; runtime/deps/ holds
|
||||
include/ + lib/ of Vulkan, SDL3, Opus, libvpx and VMA (build_game.py --deps)
|
||||
bin/ totk_xlate.exe (+ totk_xlate.id), hactool.exe, ninja.exe, SDL3.dll, libopus-0.dll
|
||||
data/shader_list.tsv the MacNativeGames shader list
|
||||
data/pgo-<v>.profdata the execution profile the update's code is compiled with (tools/pgo.py; Windows only);
|
||||
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
|
||||
against), runtime/deps/ with include/ and the static Opus, libvpx and zstd, bin/ without .exe and with libSDL3.so.0.
|
||||
|
||||
Dev mode, root = a repository checkout (no python/python.exe): build/py314-embed/py/python.exe (the embeddable
|
||||
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 (tools/build_game.py --make-runtime-lib --out
|
||||
build/install-rtlib); MSYS2 UCRT64 ninja.exe; toolchain/hactool; build/xlate/totk_xlate.exe; the shader list from
|
||||
refs/MacNativeGames; build/install-temp. The version is VERSION with -dev and the commit: 0.1.0-dev+973c626.
|
||||
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/<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
|
||||
import sys
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
EXE = '.exe' if os.name == 'nt' else ''
|
||||
WIN = os.name == 'nt'
|
||||
EXE = '.exe' if WIN else ''
|
||||
UCRT = Path(r'C:\msys64\ucrt64\bin')
|
||||
SUPPORTED = ('1.2.1', '1.4.3') # updates the installer builds; the check identifies the player's by hash
|
||||
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):
|
||||
@@ -45,8 +71,8 @@ class Layout:
|
||||
python: Path # runs the tools
|
||||
tools: Path
|
||||
recomp: Path
|
||||
llvm: Path # llvm-mingw tree
|
||||
deps: Path # include/ and lib/ for the link
|
||||
llvm: Path # llvm-mingw tree; on Linux the tree with bin/clang (a release's, or the system's /usr)
|
||||
deps: Path | None # include/ and lib/ for the link; None: the system's (Linux dev mode)
|
||||
runtime: Path # runtime headers and install-side sources
|
||||
runtime_lib: Path # libtotkrt.a
|
||||
ninja: Path
|
||||
@@ -56,11 +82,28 @@ class Layout:
|
||||
shader_list: Path | None = None # None: dev, read from refs/MacNativeGames through git
|
||||
ini_example: Path | None = None
|
||||
temp: Path | None = None
|
||||
sysroot: Path | None = None # Linux release: what the game links against, instead of the host's
|
||||
runtime_lib_v2: Path | None = None # libtotkrt-v2.a: the runtime for CPUs without AVX2 (build_game.py --cpu v2)
|
||||
pgo_dir: Path | None = None # pgo-<v>.profdata (tools/pgo.py); None: no profiles (Linux)
|
||||
|
||||
@property
|
||||
def clang(self):
|
||||
return self.llvm / 'bin' / ('clang' + EXE)
|
||||
|
||||
def runtime_lib_for(self, cpu):
|
||||
"""The prebuilt runtime library for cpu (v2 or v3). None in dev mode when it was not built: the runtime is
|
||||
then compiled from the sources in runtime/ instead."""
|
||||
lib = self.runtime_lib_v2 if cpu == 'v2' else self.runtime_lib
|
||||
if lib and lib.is_file():
|
||||
return lib
|
||||
return None if self.dev else lib
|
||||
|
||||
def pgo(self, version):
|
||||
"""The execution profile build_game.py --pgo compiles the update's code with, None without one (the game is
|
||||
then built at -O1)."""
|
||||
p = self.pgo_dir / f'pgo-{version_tag(version)}.profdata' if self.pgo_dir else None
|
||||
return p if p and p.is_file() else None
|
||||
|
||||
def patches(self, version):
|
||||
"""The code patch table for recomp/gen.py."""
|
||||
return self.recomp / f'patches-{version_tag(version)}.txt'
|
||||
@@ -69,21 +112,32 @@ class Layout:
|
||||
"""The expected hashes of the update."""
|
||||
return self.tools / 'data' / f'expected-v{version}.json'
|
||||
|
||||
def missing(self):
|
||||
"""Paths the steps need that do not exist."""
|
||||
need = [self.python, self.tools / 'extract.py', self.tools / 'build_game.py', self.tools / 'prepare_shaders.py',
|
||||
def missing(self, cpu='v3'):
|
||||
"""Paths the steps need that do not exist. cpu picks the runtime library the host will use."""
|
||||
lib = self.runtime_lib_for(cpu)
|
||||
need = [self.python, self.tools / 'extract.py', self.tools / 'ncz.py', self.tools / 'build_game.py',
|
||||
self.tools / 'prepare_shaders.py',
|
||||
self.tools / 'pack_shader_cache.py', self.tools / 'make_romfs_patches.py', self.tools / 'ultrawide_layout.py',
|
||||
self.tools / 'button_icons.py',
|
||||
self.tools / 'vendor' / 'macnativegames' / 'extract_shared_fonts.py',
|
||||
self.recomp / 'gen.py',
|
||||
self.clang,
|
||||
self.deps / 'include', self.deps / 'lib', self.runtime, self.runtime_lib, self.ninja, self.hactool,
|
||||
*((self.deps / 'include', self.deps / 'lib') if self.deps else ()), self.runtime, *([lib] if lib else ()),
|
||||
self.ninja, self.hactool,
|
||||
self.xlate, *self.dlls, *(f(v) for v in SUPPORTED for f in (self.patches, self.expected))]
|
||||
if self.shader_list:
|
||||
need.append(self.shader_list)
|
||||
if self.sysroot:
|
||||
need.append(self.sysroot)
|
||||
return [str(p) for p in need if not p.exists()]
|
||||
|
||||
|
||||
def release_python(root):
|
||||
return root / 'python' / ('python.exe' if WIN else 'bin/python3')
|
||||
|
||||
|
||||
def is_release(root):
|
||||
return (root / 'python' / ('python' + EXE)).is_file()
|
||||
return release_python(root).is_file()
|
||||
|
||||
|
||||
def release_layout(root):
|
||||
@@ -91,17 +145,26 @@ def release_layout(root):
|
||||
return Layout(
|
||||
root=root, dev=False,
|
||||
release=version.read_text(encoding='utf-8').strip() if version.is_file() else 'unknown',
|
||||
python=root / 'python' / ('python' + EXE),
|
||||
python=release_python(root),
|
||||
tools=root / 'tools', recomp=root / 'recomp',
|
||||
llvm=root / 'llvm', deps=root / 'runtime' / 'deps', runtime=root / 'runtime',
|
||||
runtime_lib=root / 'runtime' / 'libtotkrt.a',
|
||||
runtime_lib_v2=root / 'runtime' / 'libtotkrt-v2.a',
|
||||
ninja=root / 'bin' / ('ninja' + EXE), hactool=root / 'bin' / ('hactool' + EXE),
|
||||
xlate=root / 'bin' / ('totk_xlate' + EXE),
|
||||
dlls=(root / 'bin' / 'SDL3.dll', root / 'bin' / 'libopus-0.dll'),
|
||||
shader_list=root / 'data' / 'shader_list.tsv', ini_example=root / 'totk.ini.example', temp=root / 'temp')
|
||||
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,
|
||||
# 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')
|
||||
|
||||
|
||||
def dev_layout(root):
|
||||
if not WIN:
|
||||
return dev_layout_posix(root)
|
||||
commit = subprocess.run(['git', '-C', str(root), 'rev-parse', '--short', 'HEAD'], capture_output=True,
|
||||
text=True).stdout.strip()
|
||||
embed = root / 'build' / 'py314-embed' / 'py' / ('python' + EXE)
|
||||
@@ -114,9 +177,30 @@ def dev_layout(root):
|
||||
tools=root / 'tools', recomp=root / 'recomp',
|
||||
llvm=trees[-1] if trees else root / 'toolchain' / 'llvm-mingw-missing', deps=deps,
|
||||
runtime=root / 'runtime', runtime_lib=root / 'build' / 'install-rtlib' / 'libtotkrt.a',
|
||||
runtime_lib_v2=root / 'build' / 'install-rtlib' / 'libtotkrt-v2.a',
|
||||
ninja=UCRT / ('ninja' + EXE), hactool=root / 'toolchain' / 'hactool' / ('hactool' + EXE),
|
||||
xlate=root / 'build' / 'xlate' / ('totk_xlate' + EXE),
|
||||
dlls=tuple(sorted((deps / 'bin').glob('*.dll'))),
|
||||
shader_list=None, ini_example=root / 'totk.ini.example', temp=root / 'build' / 'install-temp',
|
||||
pgo_dir=root / 'build' / 'pgo')
|
||||
|
||||
|
||||
def dev_commit(root):
|
||||
return subprocess.run(['git', '-C', str(root), 'rev-parse', '--short', 'HEAD'], capture_output=True,
|
||||
text=True).stdout.strip()
|
||||
|
||||
|
||||
def dev_layout_posix(root):
|
||||
clang, ninja = shutil.which('clang'), shutil.which('ninja')
|
||||
semver = (root / 'VERSION').read_text(encoding='utf-8').strip()
|
||||
return Layout(
|
||||
root=root, dev=True, release=f'{semver}-dev+{dev_commit(root) or "unknown"}',
|
||||
python=Path(sys.executable), tools=root / 'tools', recomp=root / 'recomp',
|
||||
llvm=Path(clang).parent.parent if clang else root / 'toolchain' / 'clang-missing', deps=None,
|
||||
runtime=root / 'runtime', runtime_lib=root / 'build' / 'install-rtlib' / 'libtotkrt.a',
|
||||
runtime_lib_v2=root / 'build' / 'install-rtlib' / 'libtotkrt-v2.a',
|
||||
ninja=Path(ninja) if ninja else root / 'toolchain' / 'ninja-missing',
|
||||
hactool=root / 'toolchain' / 'hactool' / 'hactool', xlate=root / 'build' / 'xlate' / 'totk_xlate',
|
||||
shader_list=None, ini_example=root / 'totk.ini.example', temp=root / 'build' / 'install-temp')
|
||||
|
||||
|
||||
@@ -124,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
|
||||
@@ -0,0 +1,86 @@
|
||||
"""The last install folder and source paths, in a per-user file, so an update, a reinstall or a switch to another game
|
||||
version starts with the form filled in.
|
||||
|
||||
{"format": 1, "dest": ..., "base": ..., "update": ..., "keys": ..., "firmware": ...}
|
||||
|
||||
Absolute paths only. The keys entry is the path of the keys file, never its contents.
|
||||
|
||||
Windows: %LOCALAPPDATA%\TotK Recomp\setup.json; elsewhere $XDG_STATE_HOME/totk-recomp/setup.json (default
|
||||
~/.local/state/totk-recomp/setup.json). TOTK_SETUP_RECENT names another file (tests, --selftest). Nothing else is
|
||||
stored: the language comes from the install's own totk-install.json. A file of format 0 (only "dest") still loads.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from . import state
|
||||
|
||||
FORMAT = 1
|
||||
ENV = 'TOTK_SETUP_RECENT'
|
||||
FILES = ('base', 'update', 'keys') # recorded when they are files
|
||||
SOURCES = FILES + ('firmware',)
|
||||
FIELDS = ('dest',) + SOURCES
|
||||
|
||||
|
||||
def path():
|
||||
override = os.environ.get(ENV)
|
||||
if override:
|
||||
return Path(override)
|
||||
if sys.platform == 'win32':
|
||||
base = os.environ.get('LOCALAPPDATA') or str(Path.home() / 'AppData' / 'Local')
|
||||
return Path(base) / 'TotK Recomp' / 'setup.json'
|
||||
base = os.environ.get('XDG_STATE_HOME') or str(Path.home() / '.local' / 'state')
|
||||
return Path(base) / 'totk-recomp' / 'setup.json'
|
||||
|
||||
|
||||
def usable(name, value):
|
||||
"""value when it is a non-empty absolute path of the right kind for the field, else None. One stat call per
|
||||
path, no file is opened or hashed; a path the OS rejects (embedded NUL, unreachable share) counts as missing."""
|
||||
if not isinstance(value, str) or not value or not os.path.isabs(value):
|
||||
return None
|
||||
try:
|
||||
p = Path(value)
|
||||
if name == 'dest':
|
||||
ok = (p / state.NAME).is_file()
|
||||
elif name == 'firmware':
|
||||
ok = p.is_dir()
|
||||
else:
|
||||
ok = p.is_file()
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return value if ok else None
|
||||
|
||||
|
||||
def read():
|
||||
try:
|
||||
data = json.loads(path().read_text(encoding='utf-8'))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def load():
|
||||
"""The recorded entries that still exist, by field name. Never raises."""
|
||||
data = read()
|
||||
return {name: data[name] for name in FIELDS if usable(name, data.get(name))}
|
||||
|
||||
|
||||
def save(dest, sources=None):
|
||||
"""Records dest and the non-empty, existing entries of sources (base, update, keys, firmware); an entry left out
|
||||
or empty keeps its saved value. Atomic; a failure to write is ignored, the window works without it."""
|
||||
target = path()
|
||||
tmp = target.with_name(target.name + '.tmp')
|
||||
data = {name: v for name, v in read().items() if name in FIELDS and isinstance(v, str)}
|
||||
data['dest'] = os.path.abspath(dest)
|
||||
for name, value in (sources or {}).items():
|
||||
if name in SOURCES and isinstance(value, str) and value.strip():
|
||||
value = os.path.abspath(value.strip())
|
||||
if usable(name, value):
|
||||
data[name] = value
|
||||
try:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp.write_text(json.dumps({'format': FORMAT, **data}), encoding='utf-8')
|
||||
os.replace(tmp, target)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -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'
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
"""The screen shapes and button prompts this player needs RomFS patch folders for (steps.Shapes).
|
||||
|
||||
A game resolution of another shape than 16:9 takes romfs-patches-<w>x<h>, the UI laid out for that shape
|
||||
(tools/make_romfs_patches.py --aspect), and the prompts' folder of that shape (romfs-patches-<style>-<w>x<h>). The
|
||||
layout depends only on the aspect ratio (tools/ultrawide_layout.py apply), so the setup writes one folder per shape,
|
||||
named after the shape's size in ASPECT_SIZES (shape_size); runtime/romfs.c overlay_init maps the game resolution the
|
||||
same way (cfg.c cfg_shape_size). It writes them only for the shapes of the connected displays and the totk.ini
|
||||
output_res, and the prompts' ones only for the style totk.ini selects (prompts_style).
|
||||
"""
|
||||
import ctypes
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
# The game resolutions of another shape than 16:9 that runtime/ui/menu.cpp row_output_res lists, in the order of
|
||||
# runtime/cfg.c SHAPED: 21:9 and 32:9 monitors, 16:10 screens (the Steam Deck's 1280x800, handhelds and laptops) and 3:2
|
||||
# screens (Surface and Framework laptops and tablets)
|
||||
ASPECT_SIZES = ('2560x1080', '3440x1440', '3840x1600', '5120x2160', '3840x1080', '5120x1440',
|
||||
'1280x800', '1680x1050', '1920x1200', '2560x1600',
|
||||
'1920x1280', '2160x1440', '2256x1504', '2880x1920', '3000x2000')
|
||||
SHAPED = tuple(tuple(int(v) for v in s.split('x')) for s in ASPECT_SIZES)
|
||||
TOLERANCE = 0.01 # cfg.c and resolution.c res_is_16x9: shapes within 1% are the same
|
||||
|
||||
|
||||
def is_16x9(w, h):
|
||||
return abs((w / h) / (16 / 9) - 1) <= TOLERANCE
|
||||
|
||||
|
||||
def shape_size(w, h):
|
||||
"""The folder size of w x h's shape: of ASPECT_SIZES within 1% of its aspect ratio, the closest, the first of equal
|
||||
ones (5120x2160 is 2560x1080's shape). None for 16:9 and for a shape the setup has no layout for. The same rule as
|
||||
runtime/cfg.c cfg_shape_size."""
|
||||
if not w or not h or is_16x9(w, h):
|
||||
return None
|
||||
r, best, err = w / h, None, None
|
||||
for sw, sh in SHAPED:
|
||||
e = abs(sw / sh / r - 1)
|
||||
if e <= TOLERANCE and (err is None or e < err):
|
||||
best, err = f'{sw}x{sh}', e
|
||||
return best
|
||||
|
||||
|
||||
def default_size(w, h):
|
||||
"""The output_res the game picks on a display of w x h while totk.ini sets none (runtime/cfg.c screen_default): of
|
||||
ASPECT_SIZES within 1% of its shape, the smallest at least 1080 high that fits, else the largest that fits."""
|
||||
if not w or not h or is_16x9(w, h):
|
||||
return None
|
||||
r, best, fit = w / h, None, None
|
||||
for sw, sh in SHAPED:
|
||||
if abs(sw / sh / r - 1) > TOLERANCE or sw > w or sh > h:
|
||||
continue
|
||||
if fit is None or sw > fit[0]:
|
||||
fit = (sw, sh)
|
||||
if sh >= 1080 and (best is None or sw < best[0]):
|
||||
best = (sw, sh)
|
||||
best = best or fit
|
||||
return f'{best[0]}x{best[1]}' if best else None
|
||||
|
||||
|
||||
# ---- the connected displays, as (width, height) of their current mode, the long side first (a portrait monitor or
|
||||
# the Steam Deck's panel reports its height first; the game window is landscape)
|
||||
|
||||
class DISPLAY_DEVICEW(ctypes.Structure):
|
||||
_fields_ = [('cb', ctypes.c_uint32), ('DeviceName', ctypes.c_wchar * 32), ('DeviceString', ctypes.c_wchar * 128),
|
||||
('StateFlags', ctypes.c_uint32), ('DeviceID', ctypes.c_wchar * 128), ('DeviceKey', ctypes.c_wchar * 128)]
|
||||
|
||||
|
||||
ATTACHED_TO_DESKTOP = 0x1
|
||||
ENUM_CURRENT_SETTINGS = -1
|
||||
DEVMODEW_SIZE = 220 # DEVMODEW: dmSize at 68, dmPelsWidth at 172, dmPelsHeight at 176
|
||||
DEVMODE_PELS = 172
|
||||
|
||||
|
||||
def windows_displays():
|
||||
"""Every display attached to the desktop: EnumDisplayDevicesW over the adapters, EnumDisplaySettingsW for the
|
||||
current mode, which is in pixels whatever the DPI awareness of this process."""
|
||||
user32 = ctypes.WinDLL('user32')
|
||||
out, i = [], 0
|
||||
while True:
|
||||
dev = DISPLAY_DEVICEW()
|
||||
dev.cb = ctypes.sizeof(dev)
|
||||
if not user32.EnumDisplayDevicesW(None, i, ctypes.byref(dev), 0):
|
||||
break
|
||||
i += 1
|
||||
if not dev.StateFlags & ATTACHED_TO_DESKTOP:
|
||||
continue
|
||||
mode = ctypes.create_string_buffer(DEVMODEW_SIZE)
|
||||
ctypes.c_uint16.from_buffer(mode, 68).value = DEVMODEW_SIZE
|
||||
if user32.EnumDisplaySettingsW(dev.DeviceName, ENUM_CURRENT_SETTINGS, mode):
|
||||
out.append((ctypes.c_uint32.from_buffer(mode, DEVMODE_PELS).value,
|
||||
ctypes.c_uint32.from_buffer(mode, DEVMODE_PELS + 4).value))
|
||||
return out
|
||||
|
||||
|
||||
XRANDR = re.compile(r'\sconnected\s+(?:primary\s+)?(\d+)x(\d+)\+')
|
||||
|
||||
|
||||
def linux_displays():
|
||||
"""xrandr's connected outputs (X11 and XWayland); without xrandr the preferred mode of each connected DRM
|
||||
connector."""
|
||||
if shutil.which('xrandr'):
|
||||
try:
|
||||
text = subprocess.run(['xrandr', '--current'], capture_output=True, text=True, timeout=10).stdout
|
||||
found = [(int(w), int(h)) for w, h in XRANDR.findall(text)]
|
||||
if found:
|
||||
return found
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
out = []
|
||||
for conn in sorted(Path('/sys/class/drm').glob('card*-*')):
|
||||
try:
|
||||
if (conn / 'status').read_text().strip() != 'connected':
|
||||
continue
|
||||
m = re.match(r'(\d+)x(\d+)', (conn / 'modes').read_text())
|
||||
except OSError:
|
||||
continue
|
||||
if m:
|
||||
out.append((int(m.group(1)), int(m.group(2))))
|
||||
return out
|
||||
|
||||
|
||||
def displays():
|
||||
try:
|
||||
found = windows_displays() if os.name == 'nt' else linux_displays()
|
||||
except (OSError, AttributeError, ValueError):
|
||||
found = []
|
||||
return sorted({(max(w, h), min(w, h)) for w, h in found if w and h})
|
||||
|
||||
|
||||
# ---- totk.ini (runtime/cfg.c reads the same keys, in any section, with or without the totk_ prefix)
|
||||
|
||||
def ini_value(text, name):
|
||||
value = None
|
||||
for line in text.splitlines():
|
||||
m = re.match(rf'^\s*(?:totk_)?{name}\s*=\s*([^\s#;]*)', line, re.IGNORECASE)
|
||||
if m:
|
||||
value = m.group(1)
|
||||
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' 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'
|
||||
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 nintendo else 'xbox-label'
|
||||
|
||||
|
||||
def wanted(dest, screens=None):
|
||||
"""(sizes, style): the shape sizes to write layouts for, sorted, and the prompts style. A shape is wanted for each
|
||||
display's own size and for the output_res the game defaults to there, and for the totk.ini output_res."""
|
||||
screens = displays() if screens is None else screens
|
||||
try:
|
||||
text = (Path(dest) / 'totk.ini').read_text(encoding='utf-8-sig', errors='replace')
|
||||
except OSError:
|
||||
text = ''
|
||||
sizes = set()
|
||||
for w, h in screens:
|
||||
w, h = max(w, h), min(w, h)
|
||||
sizes.add(shape_size(w, h))
|
||||
d = default_size(w, h)
|
||||
if d:
|
||||
sizes.add(shape_size(*(int(v) for v in d.split('x'))))
|
||||
m = re.fullmatch(r'(\d+)x(\d+)', (ini_value(text, 'output_res') or '').lower())
|
||||
if m:
|
||||
sizes.add(shape_size(int(m.group(1)), int(m.group(2))))
|
||||
sizes.discard(None)
|
||||
return sorted(sizes, key=ASPECT_SIZES.index), prompts_style(text)
|
||||
+1052
-81
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,215 @@
|
||||
{
|
||||
"step.check": "Computer und Spieldateien prüfen",
|
||||
"step.kit": "Build-Kit in den Spielordner kopieren",
|
||||
"step.fonts": "Systemschriften extrahieren",
|
||||
"step.extract": "Spiel entpacken",
|
||||
"step.lift": "Spielcode nach C übersetzen",
|
||||
"step.compile": "{game_exe} kompilieren",
|
||||
"step.prepare": "Shader vorbereiten",
|
||||
"step.pc_prompts": "Tastatur- und Maussymbole zeichnen",
|
||||
"step.shapes": "Spielbildschirme für deine Monitore anordnen",
|
||||
"step.dlss": "NVIDIA DLSS herunterladen",
|
||||
"step.cleanup": "Aufräumen",
|
||||
"phase.check.host": "Prozessor und Grafikkarte prüfen",
|
||||
"phase.check.verify": "Bereits installierte Dateien prüfen",
|
||||
"phase.check.verify_romfs": "Installierte Spieldaten prüfen",
|
||||
"phase.check.inputs": "Spieldateien mit den Schlüsseln öffnen",
|
||||
"phase.check.unpack_base": "Komprimiertes Basisspiel entpacken",
|
||||
"phase.check.unpack_update": "Komprimiertes Update entpacken",
|
||||
"phase.check.versions": "Spielversionen prüfen",
|
||||
"phase.kit.copy": "Die Werkzeuge kopieren, mit denen sich das Spiel für Code-Mods neu baut",
|
||||
"phase.fonts.extract": "Gemeinsame Schriften aus der Firmware extrahieren",
|
||||
"phase.fonts.copy": "Gemeinsame Schriften in den Installationsordner kopieren",
|
||||
"phase.extract.hash_base": "Prüfsumme des Hauptspiels berechnen",
|
||||
"phase.extract.hash_update": "Prüfsumme des Updates berechnen",
|
||||
"phase.extract.exefs": "Spielcode extrahieren",
|
||||
"phase.extract.copy": "Spieldaten kopieren",
|
||||
"phase.extract.merge": "Update auf die Spieldaten anwenden",
|
||||
"phase.extract.diagnose": "Beschädigte Spieldatei suchen",
|
||||
"phase.extract.index": "Spieldaten überprüfen",
|
||||
"phase.lift.discover": "Funktionen suchen",
|
||||
"phase.lift.emit": "C-Code schreiben",
|
||||
"phase.compile.compile": "Kompilieren",
|
||||
"phase.compile.link": "{game_exe} linken",
|
||||
"phase.prepare.romfs_patches": "Spieldaten-Patches für 60 fps schreiben",
|
||||
"phase.pc_prompts.draw": "Tastatur- und Maustastensymbole nach den Belegungen in totk.ini zeichnen",
|
||||
"phase.prepare.seed": "Shader aus den Spieldaten lesen",
|
||||
"phase.prepare.translate": "Shader übersetzen",
|
||||
"phase.prepare.libraries": "Shader für den Grafiktreiber erstellen",
|
||||
"phase.prepare.pack": "Shader-Cache in eine Datei packen",
|
||||
"phase.shapes.layouts": "Bildschirmlayouts und Tastensymbole für jedes Bildschirmformat schreiben",
|
||||
"phase.dlss.download": "nvngx_dlss.dll aus NVIDIAs DLSS SDK herunterladen",
|
||||
"phase.cleanup.ini": "totk.ini schreiben",
|
||||
"phase.cleanup.temp": "Temporäre Dateien entfernen",
|
||||
"cli.usage": "Ungültige Befehlszeile: {detail}",
|
||||
"internal": "Unerwarteter Fehler ({exception}): {detail}",
|
||||
"state.unreadable": "{path} kann nicht gelesen werden. Wähle einen anderen Ordner oder lösche diese Datei.",
|
||||
"state.newer_format": "{path} wurde von einem neueren Installationsprogramm geschrieben. Verwende dieses oder einen anderen Ordner.",
|
||||
"state.output_changed": "Installierte Dateien des Schritts „{step}“ haben sich seit ihrer Erstellung geändert; dieser Schritt läuft erneut.",
|
||||
"check.release_incomplete": "Der Ordner des Installationsprogramms ist unvollständig; es fehlt: {paths}. Entpacke das Release erneut.",
|
||||
"check.dest_not_folder": "Der Installationsort {path} ist eine Datei, kein Ordner.",
|
||||
"check.dest_not_empty": "Der Installationsordner {path} ist nicht leer und enthält keine frühere Installation. Wähle einen leeren Ordner.",
|
||||
"check.lang_missing": "Wähle die Spielsprache.",
|
||||
"check.lang_unknown": "Unbekannte Sprache „{lang}“. Bekannt: {known}.",
|
||||
"check.toolchain_broken": "Der mitgelieferte Compiler funktioniert nicht: {detail}",
|
||||
"check.glibc_old": "Die C-Bibliothek dieses Systems ist glibc {version}; der Compiler des Setups braucht {need} oder neuer (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 und neuer haben sie). Ein Systemupdate behebt das.",
|
||||
"check.host_probe_failed": "Die Computerprüfung ist nicht gelaufen (Exit-Code {code}).",
|
||||
"check.cpu_too_old": "Diesem Prozessor fehlt x86-64-v2 (SSE4.2, POPCNT und CMPXCHG16B), die älteste Stufe, für die das Spiel gebaut wird. Intel Nehalem (2008) oder AMD Bulldozer (2011) und neuer haben sie.",
|
||||
"check.vulkan_missing": "Es ist kein Vulkan-Treiber installiert. Installiere den neuesten Treiber für deine Grafikkarte.",
|
||||
"check.vulkan_no_device": "Vulkan findet keine Grafikkarte. Installiere den neuesten Treiber für deine Grafikkarte.",
|
||||
"check.vulkan_too_old": "Das Spiel braucht eine Grafikkarte mit Vulkan 1.3; gefunden: {devices}. Aktualisiere den Grafiktreiber.",
|
||||
"check.no_display": "Zum Vorbereiten der Shader wird ein Bildschirm gebraucht. Starte das Setup aus der Desktop-Sitzung oder setze DISPLAY=:0 (auf einem Steam Deck im Spielmodus zusätzlich XDG_RUNTIME_DIR=/run/user/1000).",
|
||||
"check.inputs_needed": "Die Spieldateien werden gebraucht: wähle das Hauptspiel, das Update 1.1.0, 1.2.1 oder 1.4.3 und prod.keys.",
|
||||
"check.input_missing": "Datei nicht gefunden ({input}): {path}",
|
||||
"check.keys_unreadable": "Die Schlüsseldatei kann nicht gelesen werden. Wähle eine prod.keys-Datei.",
|
||||
"check.keys_no_header_key": "Die Schlüsseldatei enthält keinen header_key. Lies prod.keys erneut von deiner Konsole aus.",
|
||||
"check.keys_wrong": "Die Schlüssel können die Datei ({input}) nicht öffnen. Verwende die prod.keys deiner Konsole.",
|
||||
"check.keys_too_old": "Die Schlüsseldatei ist zu alt für die Datei ({input}) (braucht Schlüsselgeneration {generation}). Lies prod.keys von einer Konsole mit neuerer Firmware aus.",
|
||||
"check.not_game_file": "Die Datei ({input}) ist keine XCI-, NSP-, XCZ- oder NSZ-Spieldatei.",
|
||||
"check.file_unreadable": "Die Datei ({input}) kann nicht gelesen werden: {detail}",
|
||||
"check.unpack_failed": "Die komprimierte Datei {input} konnte nicht entpackt werden: {detail}",
|
||||
"check.ticket_personalized": "Die Datei ({input}) enthält ein personalisiertes Ticket; ein allgemeines Ticket wird gebraucht.",
|
||||
"check.ticket_missing": "Der Datei ({input}) fehlt das Ticket, das ihr Inhalt braucht.",
|
||||
"check.base_not_totk": "Die Hauptspieldatei ist nicht The Legend of Zelda: Tears of the Kingdom ({detail}).",
|
||||
"check.base_is_update": "Die Hauptspieldatei ist ein Update. Wähle hier das Hauptspiel als NSP oder XCI (Version 1.0.0) und diese Datei als Update.",
|
||||
"check.base_combined": "Die Hauptspieldatei enthält mehrere Pakete (Hauptspiel, Update oder DLC in einer Datei). Wähle einen Dump des Hauptspiels, der nur das Spiel enthält.",
|
||||
"check.update_not_nsp": "Das Update muss eine NSP- oder NSZ-Datei sein.",
|
||||
"check.update_is_base": "Die Update-Datei enthält ein Hauptspiel. Wähle die NSP des Updates 1.1.0, 1.2.1 oder 1.4.3.",
|
||||
"check.update_not_totk": "Die Update-Datei ist kein Update von Tears of the Kingdom ({detail}).",
|
||||
"check.exefs_failed": "Der Spielcode der Datei ({input}) hat die Prüfungen nicht bestanden; siehe {log}.",
|
||||
"check.input_damaged": "Die Datei ({input}) ist beschädigt oder unvollständig: {path} ({detail}). Kopiere diese Datei erneut von ihrer Quelle oder erstelle den Dump neu und starte das Setup dann erneut.",
|
||||
"check.base_wrong_version": "Das Hauptspiel ist nicht Version 1.0.0 ({modules} weichen ab).",
|
||||
"check.update_wrong_version": "Das Update hat Version {found}; dieses Release verwendet {wanted}.",
|
||||
"check.disk_space": "Nicht genug freier Speicher für {path}: {need_gb} GB nötig, {free_gb} GB frei.",
|
||||
"check.firmware_missing": "Der Firmware-Ordner {path} existiert nicht. Wähle den Ordner Contents/registered der Firmware.",
|
||||
"check.firmware_empty": "Der Firmware-Ordner {path} enthält keine NCA-Dateien. Wähle den Ordner Contents/registered der Firmware.",
|
||||
"check.fonts_keys_needed": "Die gemeinsamen Schriften für diese Sprache sind noch nicht installiert; wähle prod.keys, damit das Setup sie aus der Firmware extrahieren kann.",
|
||||
"extract.exefs_mismatch": "Der extrahierte Spielcode passt nicht zu Version {version} ({modules}).",
|
||||
"extract.romfs_merge_failed": "Das Anwenden des Updates auf die Spieldaten ist fehlgeschlagen: {detail}. Details: {log}",
|
||||
"extract.romfs_mismatch": "Die extrahierten Spieldaten passen nicht zu Version {version} (Größe {size}, Prüfsumme {sha256}...).",
|
||||
"fonts.failed": "Das Extrahieren der gemeinsamen Schriften ist fehlgeschlagen (Exit-Code {code}): {detail}. Details: {log}",
|
||||
"fonts.incomplete": "Beim Extrahieren der gemeinsamen Schriften wurden nicht alle Dateien geschrieben ({files}).",
|
||||
"fonts.copy_failed": "Die gemeinsamen Schriften können nicht nach {path} kopiert werden: {detail}",
|
||||
"lift.failed": "Das Übersetzen des Spielcodes ist fehlgeschlagen (Exit-Code {code}). Details: {log}",
|
||||
"compile.failed": "Das Kompilieren von {game_exe} ist fehlgeschlagen (Exit-Code {code}). Details: {log}",
|
||||
"compile.exe_in_use": "{path} wird verwendet. Schließe das Spiel und starte das Installationsprogramm erneut.",
|
||||
"kit.in_use": "{path} wird gerade verwendet. Schließe das Spiel und jedes offene Setup- oder Neubau-Fenster und starte das Setup dann erneut.",
|
||||
"kit.copy_failed": "Das Build-Kit kann nicht nach {path} kopiert werden: {detail}",
|
||||
"compile.exe_locked": "{path} kann nicht geschrieben werden: Ein anderes Programm hält die Datei, etwa ein aus diesem Ordner gestartetes Spiel oder ein Virenscanner, der die Datei gemeldet hat. Schließe das Spiel, nimm den Ordner des Setups und den Installationsordner in die Ausnahmen des Virenscanners auf, starte Windows neu und starte das Setup dann erneut. Details: {log}",
|
||||
"prepare.xlate_in_use": "{path} wird verwendet. Schließe das Spiel, beende jeden von einem früheren Lauf übrigen totk_xlate-Prozess und starte das Installationsprogramm erneut.",
|
||||
"prepare.shader_list_missing": "Die Shader-Liste fehlt.",
|
||||
"prepare.romfs_patches_failed": "Das Schreiben der Spieldaten-Patches ist fehlgeschlagen (Exit-Code {code}). Details: {log}",
|
||||
"prepare.shaders_failed": "Das Vorbereiten der Shader ist fehlgeschlagen (Exit-Code {code}). Details: {log}",
|
||||
"cleanup.romfs_unreadable": "Die Spieldaten in {path} fehlen nach der Installation oder können nicht gelesen werden. Starte Windows neu und führe das Installationsprogramm erneut auf demselben Ordner aus: Es entpackt die Spieldaten erneut und behält den Rest.",
|
||||
"prepare.pack_failed": "Das Packen des Shader-Caches ist fehlgeschlagen (Exit-Code {code}). Details: {log}",
|
||||
"cleanup.ini_failed": "totk.ini kann nicht geschrieben werden: {detail}",
|
||||
"warn.lang_needs_fonts": "Text auf {lang} braucht die Systemschriften der Switch, und es wurden keine angegeben. Das Spiel startet in dieser Sprache erst, wenn sie hinzugefügt sind. Wähle den Firmware-Ordner (Contents/registered) oder lies „Switch system fonts“ in docs/installer.md.",
|
||||
"warn.npdm_differs": "main.npdm weicht vom Referenz-Dump {version} ab; nur die Codemodule werden verwendet.",
|
||||
"warn.cheats_skipped": "Die Cheats des Mods-Ordners, die den Spielcode ändern, konnten nicht gebaut werden; das Spiel wird ohne sie installiert. Details: {log}",
|
||||
"warn.exefs_skipped": "Die ExeFS-Patches der Mods (.ips, .pchtxt) konnten nicht gebaut werden; das Spiel wird ohne sie installiert. Details: {log}",
|
||||
"warn.plugins_skipped": "Die Code-Plugins der Mods (exefs subsdk) konnten nicht gebaut werden; das Spiel wird ohne sie installiert. Details: {log}",
|
||||
"warn.xbox_prompts_failed": "Die Xbox-, PlayStation- oder PC-Tastensymbole konnten nicht vorbereitet werden (Exit-Code {code}); das Spiel behält die Switch-Symbole. Details: {log}",
|
||||
"warn.shaders_skipped": "Der Grafiktreiber ist beim Erstellen einiger Shader abgestürzt, daher wurden {count} bei der Vorbereitung ausgelassen. Das Spiel erstellt sie, wenn es sie zum ersten Mal braucht, und der Treiber kann dort ebenfalls abstürzen; ein Treiberupdate kann das beheben. Details: {log}",
|
||||
"warn.kernel_old": "Linux {version} fehlt das Schreib-Tracking, auf das das Spiel angewiesen ist (6.7 oder neuer); das Spiel kann sehr langsam laufen. Ein Systemupdate behebt das.",
|
||||
"warn.dlss_kept": "Im Installationsordner liegt bereits eine DLSS-Bibliothek ({path}); das Setup behält sie.",
|
||||
"warn.dlss_download_failed": "NVIDIA DLSS konnte nicht von {url} heruntergeladen werden: {detail}. Das Spiel läuft ohne; der nächste Setup-Lauf versucht es erneut.",
|
||||
"ui.title": "TotK-Setup",
|
||||
"ui.rebuild_title": "Spiel für deine Mods neu bauen",
|
||||
"ui.start_game": "Spiel starten",
|
||||
"ui.version": "Version {version}",
|
||||
"ui.intro": "Erstellt aus deinen eigenen Spieldateien einen spielbaren Ordner von Tears of the Kingdom. Das dauert eine Weile und läuft einmal.",
|
||||
"ui.notice": "Der Ordner, den dieses Setup erstellt, enthält das Spiel. Er ist nur für deinen eigenen Gebrauch; teile ihn nicht und lade ihn nicht hoch.",
|
||||
"ui.keys_private": "Die Schlüsseldatei wird an Ort und Stelle gelesen. Ihr Inhalt wird nie angezeigt, kopiert oder gespeichert.",
|
||||
"ui.base": "Hauptspiel",
|
||||
"ui.update": "Update",
|
||||
"ui.keys": "prod.keys",
|
||||
"ui.firmware": "Firmware (optional)",
|
||||
"ui.game_language": "Spielsprache",
|
||||
"ui.dest": "Installationsordner",
|
||||
"ui.browse": "Durchsuchen...",
|
||||
"ui.pick_game": "Hauptspieldatei wählen",
|
||||
"ui.pick_update": "Datei des Updates 1.1.0, 1.2.1 oder 1.4.3 wählen",
|
||||
"ui.pick_keys": "prod.keys wählen",
|
||||
"ui.pick_firmware": "Ordner der Switch-Firmware wählen (Contents/registered)",
|
||||
"ui.pick_dest": "Installationsordner wählen",
|
||||
"ui.firmware_help": "Für chinesischen, koreanischen und traditionell chinesischen Text: der Ordner Contents/registered der Firmware, zum Beispiel aus Ryujinx oder Yuzu. Das Setup kopiert daraus die Systemschriften der Switch in den Installationsordner.",
|
||||
"ui.dlss": "NVIDIA DLSS (nvngx_dlss.dll) für NVIDIA-RTX-Grafikkarten herunterladen",
|
||||
"ui.dlss_help": "Aus NVIDIAs DLSS SDK auf GitHub, unter NVIDIAs RTX-SDK-Lizenz (github.com/NVIDIA/DLSS). Damit funktionieren die Einstellungen dlaa und DLSS; ohne die Datei bewirken sie nichts.",
|
||||
"ui.compressed_help": "Komprimierte NSZ- und XCZ-Dateien funktionieren direkt: Das Setup entpackt sie selbst (bis die Spieldaten extrahiert sind, braucht das so viel freien Speicher, wie die entpackten Dateien belegen).",
|
||||
"ui.section_files": "Spieldateien",
|
||||
"ui.section_install": "Installation",
|
||||
"ui.more_details": "▸ Weitere Details",
|
||||
"ui.fewer_details": "▾ Details ausblenden",
|
||||
"ui.formats_help": "Hauptspiel: NSP, XCI, NSZ oder XCZ. Update: 1.1.0, 1.2.1 oder 1.4.3, als NSP oder NSZ.",
|
||||
"ui.type_game": "Spieldateien (NSP, XCI, NSZ, XCZ)",
|
||||
"ui.type_keys": "Schlüsseldateien (*.keys)",
|
||||
"ui.type_all": "Alle Dateien",
|
||||
"ui.start": "Starten",
|
||||
"ui.cancel": "Abbrechen",
|
||||
"ui.cancelling": "Wird abgebrochen...",
|
||||
"ui.show_log": "Protokoll zeigen",
|
||||
"ui.hide_log": "Protokoll ausblenden",
|
||||
"ui.close": "Schließen",
|
||||
"ui.back": "Zurück",
|
||||
"ui.open_folder": "Ordner öffnen",
|
||||
"ui.update_mode": "Dieser Ordner enthält eine frühere Installation. Das Setup setzt sie fort oder aktualisiert sie; die Spieldateien werden nur verlangt, wenn sie erneut gebraucht werden.",
|
||||
"ui.need_dest": "Wähle den Installationsordner.",
|
||||
"ui.need_base": "Wähle die Hauptspieldatei.",
|
||||
"ui.need_update": "Wähle die Datei des Updates 1.1.0, 1.2.1 oder 1.4.3.",
|
||||
"ui.need_keys": "Wähle die Datei prod.keys.",
|
||||
"ui.need_lang": "Wähle die Spielsprache.",
|
||||
"ui.missing_base": "Die Hauptspieldatei existiert nicht.",
|
||||
"ui.missing_update": "Die Update-Datei existiert nicht.",
|
||||
"ui.missing_keys": "Die Schlüsseldatei existiert nicht.",
|
||||
"ui.missing_firmware": "Der Firmware-Ordner existiert nicht.",
|
||||
"ui.running_install": "Installation",
|
||||
"ui.running_resume": "Früheres Setup wird fortgesetzt",
|
||||
"ui.running_update": "Installation wird aktualisiert",
|
||||
"ui.state_started": "gestartet",
|
||||
"ui.state_done": "fertig",
|
||||
"ui.state_skipped": "übersprungen",
|
||||
"ui.state_pending": "wartet",
|
||||
"ui.state_running": "läuft",
|
||||
"ui.state_failed": "fehlgeschlagen",
|
||||
"ui.log_warning": "Warnung",
|
||||
"ui.log_error": "Fehler",
|
||||
"ui.log_space": "Benötigter Speicher: {need} GB, frei: {free} GB",
|
||||
"ui.log_end": "Beendet",
|
||||
"ui.result_ok": "Das Spiel ist bereit",
|
||||
"ui.result_failed": "Das Setup ist fehlgeschlagen",
|
||||
"ui.result_cancelled": "Das Setup wurde abgebrochen",
|
||||
"ui.done_text": "Starte {game_exe} aus {dest}. Das Setup-Programm und die gewählten Spieldateien werden nicht mehr gebraucht.",
|
||||
"ui.cancelled_text": "Die fertigen Schritte bleiben erhalten. Starte das Setup erneut mit demselben Ordner, um fortzufahren.",
|
||||
"ui.log_file": "Protokolldatei: {path}",
|
||||
"ui.process_died": "Das Setup wurde unerwartet beendet (Exit-Code {code}).",
|
||||
"ui.confirm_cancel": "Das Setup läuft. Abbrechen und das Fenster schließen?",
|
||||
"ui.space_one": "Benötigter freier Speicher auf {path}: {need} GB (frei: {free} GB).",
|
||||
"ui.space_two": "Benötigter freier Speicher auf {path}: {need} GB (frei: {free} GB); auf {temp}: {temp_need} GB (frei: {temp_free} GB).",
|
||||
"ui.amount_bytes": "{done} / {total} GB",
|
||||
"ui.amount_chunks": "{done} / {total} Teile",
|
||||
"ui.amount_objects": "{done} / {total} Dateien",
|
||||
"ui.amount_shaders": "{done} / {total} Shader",
|
||||
"ui.amount_other": "{done} / {total} {unit}",
|
||||
"ui.seconds": "{n} s",
|
||||
"param.input.base": "Hauptspiel",
|
||||
"param.input.update": "Update",
|
||||
"param.input.keys": "Schlüssel",
|
||||
"launcher.title": "TotK-Setup",
|
||||
"launcher.python_missing": "Die Setup-Dateien sind unvollständig: Der Ordner python neben TotK-Setup.exe fehlt. Entpacke das ganze Archiv erneut und starte TotK-Setup.exe aus dem entpackten Ordner.",
|
||||
"lang.ja": "Japanisch",
|
||||
"lang.en-US": "Englisch (USA)",
|
||||
"lang.en-GB": "Englisch (UK)",
|
||||
"lang.fr": "Französisch",
|
||||
"lang.fr-CA": "Französisch (Kanada)",
|
||||
"lang.de": "Deutsch",
|
||||
"lang.it": "Italienisch",
|
||||
"lang.es": "Spanisch",
|
||||
"lang.es-419": "Spanisch (Lateinamerika)",
|
||||
"lang.nl": "Niederländisch",
|
||||
"lang.pt": "Portugiesisch",
|
||||
"lang.pt-BR": "Portugiesisch (Brasilien)",
|
||||
"lang.ru": "Russisch",
|
||||
"lang.ko": "Koreanisch",
|
||||
"lang.zh-Hans": "Chinesisch (vereinfacht)",
|
||||
"lang.zh-Hant": "Chinesisch (traditionell)"
|
||||
}
|
||||
+65
-17
@@ -1,16 +1,26 @@
|
||||
{
|
||||
"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",
|
||||
"step.compile": "Compiling totk.exe",
|
||||
"step.compile": "Compiling {game_exe}",
|
||||
"step.prepare": "Preparing the shaders",
|
||||
"step.pc_prompts": "Drawing the keyboard and mouse prompts",
|
||||
"step.shapes": "Laying out the game screens for your displays",
|
||||
"step.dlss": "Downloading NVIDIA DLSS",
|
||||
"step.cleanup": "Cleaning up",
|
||||
|
||||
"phase.check.host": "Checking the processor and the graphics card",
|
||||
"phase.check.verify": "Checking the files already installed",
|
||||
"phase.check.verify_romfs": "Checking the installed game data",
|
||||
"phase.check.inputs": "Opening the game files with the keys",
|
||||
"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",
|
||||
"phase.extract.hash_update": "Computing the checksum of the update",
|
||||
"phase.extract.exefs": "Extracting the game code",
|
||||
@@ -21,12 +31,15 @@
|
||||
"phase.lift.discover": "Finding the functions",
|
||||
"phase.lift.emit": "Writing C code",
|
||||
"phase.compile.compile": "Compiling",
|
||||
"phase.compile.link": "Linking totk.exe",
|
||||
"phase.compile.link": "Linking {game_exe}",
|
||||
"phase.prepare.romfs_patches": "Writing the 60 fps game data patches",
|
||||
"phase.pc_prompts.draw": "Drawing the keyboard and mouse button prompts from totk.ini's bindings",
|
||||
"phase.prepare.seed": "Reading the shaders from the game data",
|
||||
"phase.prepare.translate": "Translating the shaders",
|
||||
"phase.prepare.libraries": "Building the shaders for the graphics driver",
|
||||
"phase.prepare.pack": "Packing the shader cache into one file",
|
||||
"phase.shapes.layouts": "Writing the screen layouts and button prompts for each display shape",
|
||||
"phase.dlss.download": "Downloading nvngx_dlss.dll from NVIDIA's DLSS SDK",
|
||||
"phase.cleanup.ini": "Writing totk.ini",
|
||||
"phase.cleanup.temp": "Removing temporary files",
|
||||
|
||||
@@ -42,37 +55,52 @@
|
||||
"check.lang_missing": "Choose the game language.",
|
||||
"check.lang_unknown": "Unknown language '{lang}'. Known: {known}.",
|
||||
"check.toolchain_broken": "The bundled compiler does not work: {detail}",
|
||||
"check.glibc_old": "This system's C library is glibc {version}; the setup's compiler needs {need} or later (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 and newer have it). Updating the system fixes this.",
|
||||
"check.host_probe_failed": "The computer check did not run (exit code {code}).",
|
||||
"check.cpu_no_avx2": "This processor lacks AVX2 (x86-64-v3), which the game needs. Intel Haswell (2013) or AMD Excavator / Zen and newer have it.",
|
||||
"check.cpu_too_old": "This processor lacks x86-64-v2 (SSE4.2, POPCNT and CMPXCHG16B), the oldest level the game is built for. Intel Nehalem (2008) or AMD Bulldozer (2011) and newer have it.",
|
||||
"check.vulkan_missing": "No Vulkan driver is installed. Install the latest driver for your graphics card.",
|
||||
"check.vulkan_no_device": "Vulkan finds no graphics card. Install the latest driver for your graphics card.",
|
||||
"check.vulkan_too_old": "The game needs a graphics card with Vulkan 1.3; found: {devices}. Update the graphics driver.",
|
||||
"check.inputs_needed": "The game files are needed: choose the base game, the 1.2.1 or 1.4.3 update and prod.keys.",
|
||||
"check.no_display": "Preparing the shaders needs a display. Run the setup from the desktop session, or export DISPLAY=:0 (on a Steam Deck in Game Mode also XDG_RUNTIME_DIR=/run/user/1000).",
|
||||
"check.inputs_needed": "The game files are needed: choose the base game, the 1.1.0 or 1.2.1 or 1.4.3 update and prod.keys.",
|
||||
"check.input_missing": "File not found ({input}): {path}",
|
||||
"check.keys_unreadable": "The keys file cannot be read. Choose a prod.keys file.",
|
||||
"check.keys_no_header_key": "The keys file has no header_key. Dump prod.keys from your console again.",
|
||||
"check.keys_wrong": "The keys cannot open the {input} file. Use the prod.keys of your console.",
|
||||
"check.keys_too_old": "The keys file is too old for the {input} file (needs key generation {generation}). Dump prod.keys from a console with newer firmware.",
|
||||
"check.not_game_file": "The {input} file is not an XCI or NSP game file.",
|
||||
"check.not_game_file": "The {input} file is not an XCI, NSP, XCZ or NSZ game file.",
|
||||
"check.file_unreadable": "The {input} file cannot be read: {detail}",
|
||||
"check.unpack_failed": "The compressed {input} file could not be unpacked: {detail}",
|
||||
"check.ticket_personalized": "The {input} file carries a personalized ticket; a common ticket is needed.",
|
||||
"check.ticket_missing": "The {input} file lacks the ticket its content needs.",
|
||||
"check.base_not_totk": "The base game file is not The Legend of Zelda: Tears of the Kingdom ({detail}).",
|
||||
"check.update_not_nsp": "The update must be an NSP file.",
|
||||
"check.update_is_base": "The update file holds a base game. Choose the 1.2.1 or 1.4.3 update NSP.",
|
||||
"check.base_is_update": "The base game file is an update. Choose the base game NSP or XCI (version 1.0.0) here and this file as the update.",
|
||||
"check.base_combined": "The base game file holds several packages (base game, update or DLC in one file). Choose a base game dump that contains only the game.",
|
||||
"check.update_not_nsp": "The update must be an NSP or NSZ file.",
|
||||
"check.update_is_base": "The update file holds a base game. Choose the 1.1.0 or 1.2.1 or 1.4.3 update NSP.",
|
||||
"check.update_not_totk": "The update file is not a Tears of the Kingdom update ({detail}).",
|
||||
"check.exefs_failed": "The game code of the {input} file failed its checks; see {log}.",
|
||||
"check.input_damaged": "The {input} file is damaged or incomplete: {path} ({detail}). Copy that file again from its source, or dump it again, then run the setup again.",
|
||||
"check.base_wrong_version": "The base game is not version 1.0.0 ({modules} differ).",
|
||||
"check.update_wrong_version": "The update is version {found}; this release takes {wanted}.",
|
||||
"check.disk_space": "Not enough free space for {path}: {need_gb} GB needed, {free_gb} GB free.",
|
||||
"check.firmware_missing": "The firmware folder {path} does not exist. Choose the firmware's Contents/registered folder.",
|
||||
"check.firmware_empty": "The firmware folder {path} holds no NCA files. Choose the firmware's Contents/registered folder.",
|
||||
"check.fonts_keys_needed": "The shared fonts for this language are not installed yet; choose prod.keys so the setup can extract them from the firmware.",
|
||||
|
||||
"extract.exefs_mismatch": "The extracted game code does not match version {version} ({modules}).",
|
||||
"extract.romfs_merge_failed": "Applying the update to the game data failed: {detail}. Details: {log}",
|
||||
"extract.romfs_mismatch": "The extracted game data does not match version {version} (size {size}, checksum {sha256}...).",
|
||||
"fonts.failed": "Extracting the shared fonts failed (exit code {code}): {detail}. Details: {log}",
|
||||
"fonts.incomplete": "The shared font extraction did not write every file ({files}).",
|
||||
"fonts.copy_failed": "The shared fonts cannot be copied into {path}: {detail}",
|
||||
"lift.failed": "Translating the game code failed (exit code {code}). Details: {log}",
|
||||
"compile.failed": "Compiling totk.exe 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.",
|
||||
"prepare.romfs_patches_failed": "Writing the game data patches failed (exit code {code}). Details: {log}",
|
||||
"prepare.shaders_failed": "Preparing the shaders failed (exit code {code}). Details: {log}",
|
||||
@@ -80,27 +108,46 @@
|
||||
"prepare.pack_failed": "Packing the shader cache failed (exit code {code}). Details: {log}",
|
||||
"cleanup.ini_failed": "totk.ini cannot be written: {detail}",
|
||||
|
||||
"warn.lang_needs_fonts": "Text in {lang} needs the Switch system fonts, which the installer does not extract; some text may not show.",
|
||||
"warn.lang_needs_fonts": "Text in {lang} needs the Switch system fonts, and none were given. The game will not start in this language until they are added. Choose the firmware folder (Contents/registered), or see \"Switch system fonts\" in docs/installer.md.",
|
||||
"warn.npdm_differs": "main.npdm differs from the reference {version} dump; only the code modules are used.",
|
||||
"warn.xbox_prompts_failed": "The Xbox button prompts could not be prepared (exit code {code}); the game keeps the Switch prompts. Details: {log}",
|
||||
"warn.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.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.",
|
||||
"warn.dlss_download_failed": "NVIDIA DLSS could not be downloaded from {url}: {detail}. The game runs without it; the next setup run tries again.",
|
||||
|
||||
"ui.title": "TotK Setup",
|
||||
"ui.rebuild_title": "Rebuilding the game for your mods",
|
||||
"ui.start_game": "Start the game",
|
||||
"ui.version": "version {version}",
|
||||
"ui.intro": "Builds a playable Tears of the Kingdom folder from your own game files. This takes a while and runs once.",
|
||||
"ui.notice": "The folder this setup builds contains the game. It is for your own use only; do not share or upload it.",
|
||||
"ui.keys_private": "The keys file is read in place. Its contents are never shown, copied or stored.",
|
||||
"ui.base": "Base game (NSP or XCI)",
|
||||
"ui.update": "Update 1.2.1 or 1.4.3 (NSP)",
|
||||
"ui.base": "Base game",
|
||||
"ui.update": "Update",
|
||||
"ui.keys": "prod.keys",
|
||||
"ui.firmware": "Firmware (optional)",
|
||||
"ui.game_language": "Game language",
|
||||
"ui.dest": "Install folder",
|
||||
"ui.browse": "Browse...",
|
||||
"ui.pick_game": "Choose the base game file",
|
||||
"ui.pick_update": "Choose the 1.2.1 or 1.4.3 update file",
|
||||
"ui.pick_update": "Choose the 1.1.0 or 1.2.1 or 1.4.3 update file",
|
||||
"ui.pick_keys": "Choose prod.keys",
|
||||
"ui.pick_firmware": "Choose the Switch firmware folder (Contents/registered)",
|
||||
"ui.pick_dest": "Choose the install folder",
|
||||
"ui.type_game": "Game files (NSP, XCI)",
|
||||
"ui.type_nsp": "NSP files",
|
||||
"ui.firmware_help": "For Chinese, Korean and Traditional Chinese text: the firmware's Contents/registered folder, for example from Ryujinx or Yuzu. The setup copies the Switch system fonts from it into the install folder.",
|
||||
"ui.dlss": "Download NVIDIA DLSS (nvngx_dlss.dll) for NVIDIA RTX graphics cards",
|
||||
"ui.dlss_help": "From NVIDIA's DLSS SDK on GitHub, under NVIDIA's RTX SDK license (github.com/NVIDIA/DLSS). It makes the dlaa and DLSS settings work; without it they do nothing.",
|
||||
"ui.compressed_help": "Compressed NSZ and XCZ files work as they are: the setup unpacks them by itself (until the game data is extracted, that needs as much free space as the unpacked files take).",
|
||||
"ui.section_files": "Game files",
|
||||
"ui.section_install": "Install",
|
||||
"ui.more_details": "▸ More details",
|
||||
"ui.fewer_details": "▾ Hide details",
|
||||
"ui.formats_help": "Base game: NSP, XCI, NSZ or XCZ. Update: 1.1.0, 1.2.1 or 1.4.3, as NSP or NSZ.",
|
||||
"ui.type_game": "Game files (NSP, XCI, NSZ, XCZ)",
|
||||
"ui.type_keys": "Key files (*.keys)",
|
||||
"ui.type_all": "All files",
|
||||
"ui.start": "Start",
|
||||
@@ -114,12 +161,13 @@
|
||||
"ui.update_mode": "This folder holds an earlier installation. The setup continues or updates it; the game files are asked for only if they are needed again.",
|
||||
"ui.need_dest": "Choose the install folder.",
|
||||
"ui.need_base": "Choose the base game file.",
|
||||
"ui.need_update": "Choose the 1.2.1 or 1.4.3 update file.",
|
||||
"ui.need_update": "Choose the 1.1.0 or 1.2.1 or 1.4.3 update file.",
|
||||
"ui.need_keys": "Choose the prod.keys file.",
|
||||
"ui.need_lang": "Choose the game language.",
|
||||
"ui.missing_base": "The base game file does not exist.",
|
||||
"ui.missing_update": "The update file does not exist.",
|
||||
"ui.missing_keys": "The keys file does not exist.",
|
||||
"ui.missing_firmware": "The firmware folder does not exist.",
|
||||
"ui.running_install": "Installing",
|
||||
"ui.running_resume": "Continuing the earlier setup",
|
||||
"ui.running_update": "Updating the installation",
|
||||
@@ -136,7 +184,7 @@
|
||||
"ui.result_ok": "The game is ready",
|
||||
"ui.result_failed": "The setup failed",
|
||||
"ui.result_cancelled": "The setup was cancelled",
|
||||
"ui.done_text": "Start totk.exe from {dest}. The setup program and the game files you chose are no longer needed.",
|
||||
"ui.done_text": "Start {game_exe} from {dest}. The setup program and the game files you chose are no longer needed.",
|
||||
"ui.cancelled_text": "The finished steps are kept. Start the setup again with the same folder to continue.",
|
||||
"ui.log_file": "Log file: {path}",
|
||||
"ui.process_died": "The setup stopped unexpectedly (exit code {code}).",
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
{
|
||||
"step.check": "Comprobando el equipo y los archivos del juego",
|
||||
"step.kit": "Copiando el kit de compilación en la carpeta del juego",
|
||||
"step.fonts": "Extrayendo las fuentes del sistema",
|
||||
"step.extract": "Extrayendo el juego",
|
||||
"step.lift": "Traduciendo el código del juego a C",
|
||||
"step.compile": "Compilando {game_exe}",
|
||||
"step.prepare": "Preparando los shaders",
|
||||
"step.pc_prompts": "Dibujando los iconos de teclado y ratón",
|
||||
"step.shapes": "Ajustando las pantallas del juego a tus monitores",
|
||||
"step.dlss": "Descargando NVIDIA DLSS",
|
||||
"step.cleanup": "Limpiando",
|
||||
"phase.check.host": "Comprobando el procesador y la tarjeta gráfica",
|
||||
"phase.check.verify": "Comprobando los archivos ya instalados",
|
||||
"phase.check.verify_romfs": "Comprobando los datos del juego instalados",
|
||||
"phase.check.inputs": "Abriendo los archivos del juego con las claves",
|
||||
"phase.check.unpack_base": "Descomprimiendo el juego base comprimido",
|
||||
"phase.check.unpack_update": "Descomprimiendo la actualización comprimida",
|
||||
"phase.check.versions": "Comprobando las versiones del juego",
|
||||
"phase.kit.copy": "Copiando las herramientas con las que el juego se recompila para los mods de código",
|
||||
"phase.fonts.extract": "Extrayendo las fuentes compartidas del firmware",
|
||||
"phase.fonts.copy": "Copiando las fuentes compartidas a la carpeta de instalación",
|
||||
"phase.extract.hash_base": "Calculando la suma de comprobación del juego base",
|
||||
"phase.extract.hash_update": "Calculando la suma de comprobación de la actualización",
|
||||
"phase.extract.exefs": "Extrayendo el código del juego",
|
||||
"phase.extract.copy": "Copiando los datos del juego",
|
||||
"phase.extract.merge": "Aplicando la actualización a los datos del juego",
|
||||
"phase.extract.diagnose": "Buscando el archivo del juego dañado",
|
||||
"phase.extract.index": "Verificando los datos del juego",
|
||||
"phase.lift.discover": "Buscando las funciones",
|
||||
"phase.lift.emit": "Escribiendo código C",
|
||||
"phase.compile.compile": "Compilando",
|
||||
"phase.compile.link": "Enlazando {game_exe}",
|
||||
"phase.prepare.romfs_patches": "Escribiendo los parches de datos para 60 fps",
|
||||
"phase.pc_prompts.draw": "Dibujando los iconos de teclas y botones del ratón según las asignaciones de totk.ini",
|
||||
"phase.prepare.seed": "Leyendo los shaders de los datos del juego",
|
||||
"phase.prepare.translate": "Traduciendo los shaders",
|
||||
"phase.prepare.libraries": "Creando los shaders para el controlador gráfico",
|
||||
"phase.prepare.pack": "Empaquetando la caché de shaders en un archivo",
|
||||
"phase.shapes.layouts": "Escribiendo las disposiciones de pantalla y los iconos de botones para cada formato de pantalla",
|
||||
"phase.dlss.download": "Descargando nvngx_dlss.dll del DLSS SDK de NVIDIA",
|
||||
"phase.cleanup.ini": "Escribiendo totk.ini",
|
||||
"phase.cleanup.temp": "Eliminando los archivos temporales",
|
||||
"cli.usage": "Línea de comandos no válida: {detail}",
|
||||
"internal": "Error inesperado ({exception}): {detail}",
|
||||
"state.unreadable": "No se puede leer {path}. Elige otra carpeta o elimina ese archivo.",
|
||||
"state.newer_format": "{path} lo escribió un instalador más reciente. Usa ese instalador u otra carpeta.",
|
||||
"state.output_changed": "Los archivos instalados del paso '{step}' cambiaron desde que se crearon; ese paso se ejecuta de nuevo.",
|
||||
"check.release_incomplete": "La carpeta del instalador está incompleta; falta: {paths}. Descomprime la versión de nuevo.",
|
||||
"check.dest_not_folder": "La ubicación de instalación {path} es un archivo, no una carpeta.",
|
||||
"check.dest_not_empty": "La carpeta de instalación {path} no está vacía y no contiene ninguna instalación anterior. Elige una carpeta vacía.",
|
||||
"check.lang_missing": "Elige el idioma del juego.",
|
||||
"check.lang_unknown": "Idioma desconocido '{lang}'. Conocidos: {known}.",
|
||||
"check.toolchain_broken": "El compilador incluido no funciona: {detail}",
|
||||
"check.glibc_old": "La biblioteca C de este sistema es glibc {version}; el compilador del instalador necesita {need} o posterior (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 y posteriores la tienen). Actualizar el sistema lo soluciona.",
|
||||
"check.host_probe_failed": "La comprobación del equipo no se ejecutó (código de salida {code}).",
|
||||
"check.cpu_too_old": "Este procesador no tiene x86-64-v2 (SSE4.2, POPCNT y CMPXCHG16B), el nivel más antiguo para el que se compila el juego. Intel Nehalem (2008) o AMD Bulldozer (2011) y posteriores lo tienen.",
|
||||
"check.vulkan_missing": "No hay ningún controlador Vulkan instalado. Instala el controlador más reciente de tu tarjeta gráfica.",
|
||||
"check.vulkan_no_device": "Vulkan no encuentra ninguna tarjeta gráfica. Instala el controlador más reciente de tu tarjeta gráfica.",
|
||||
"check.vulkan_too_old": "El juego necesita una tarjeta gráfica con Vulkan 1.3; encontrado: {devices}. Actualiza el controlador gráfico.",
|
||||
"check.no_display": "Preparar los shaders necesita una pantalla. Ejecuta el instalador desde la sesión de escritorio o exporta DISPLAY=:0 (en una Steam Deck en modo Juego, también XDG_RUNTIME_DIR=/run/user/1000).",
|
||||
"check.inputs_needed": "Se necesitan los archivos del juego: elige el juego base, la actualización 1.1.0, 1.2.1 o 1.4.3 y prod.keys.",
|
||||
"check.input_missing": "Archivo no encontrado ({input}): {path}",
|
||||
"check.keys_unreadable": "No se puede leer el archivo de claves. Elige un archivo prod.keys.",
|
||||
"check.keys_no_header_key": "El archivo de claves no tiene header_key. Vuelve a extraer prod.keys de tu consola.",
|
||||
"check.keys_wrong": "Las claves no pueden abrir el archivo ({input}). Usa el prod.keys de tu consola.",
|
||||
"check.keys_too_old": "El archivo de claves es demasiado antiguo para el archivo ({input}) (necesita la generación de claves {generation}). Extrae prod.keys de una consola con un firmware más reciente.",
|
||||
"check.not_game_file": "El archivo ({input}) no es un archivo de juego XCI, NSP, XCZ o NSZ.",
|
||||
"check.file_unreadable": "No se puede leer el archivo ({input}): {detail}",
|
||||
"check.unpack_failed": "No se pudo descomprimir el archivo comprimido {input}: {detail}",
|
||||
"check.ticket_personalized": "El archivo ({input}) lleva un ticket personalizado; se necesita un ticket común.",
|
||||
"check.ticket_missing": "Al archivo ({input}) le falta el ticket que necesita su contenido.",
|
||||
"check.base_not_totk": "El archivo del juego base no es The Legend of Zelda: Tears of the Kingdom ({detail}).",
|
||||
"check.base_is_update": "El archivo del juego base es una actualización. Elige aquí el juego base en NSP o XCI (versión 1.0.0) y este archivo como actualización.",
|
||||
"check.base_combined": "El archivo del juego base contiene varios paquetes (juego base, actualización o DLC en un solo archivo). Elige un volcado del juego base que contenga solo el juego.",
|
||||
"check.update_not_nsp": "La actualización debe ser un archivo NSP o NSZ.",
|
||||
"check.update_is_base": "El archivo de actualización contiene un juego base. Elige el NSP de la actualización 1.1.0, 1.2.1 o 1.4.3.",
|
||||
"check.update_not_totk": "El archivo de actualización no es una actualización de Tears of the Kingdom ({detail}).",
|
||||
"check.exefs_failed": "El código del juego del archivo ({input}) no superó las comprobaciones; consulta {log}.",
|
||||
"check.input_damaged": "El archivo ({input}) está dañado o incompleto: {path} ({detail}). Vuelve a copiar ese archivo desde su origen o vuelve a volcarlo y ejecuta el instalador de nuevo.",
|
||||
"check.base_wrong_version": "El juego base no es la versión 1.0.0 ({modules} difieren).",
|
||||
"check.update_wrong_version": "La actualización es la versión {found}; esta versión usa {wanted}.",
|
||||
"check.disk_space": "No hay suficiente espacio libre para {path}: se necesitan {need_gb} GB, hay {free_gb} GB libres.",
|
||||
"check.firmware_missing": "La carpeta del firmware {path} no existe. Elige la carpeta Contents/registered del firmware.",
|
||||
"check.firmware_empty": "La carpeta del firmware {path} no contiene archivos NCA. Elige la carpeta Contents/registered del firmware.",
|
||||
"check.fonts_keys_needed": "Las fuentes compartidas de este idioma aún no están instaladas; elige prod.keys para que el instalador pueda extraerlas del firmware.",
|
||||
"extract.exefs_mismatch": "El código del juego extraído no coincide con la versión {version} ({modules}).",
|
||||
"extract.romfs_merge_failed": "Falló la aplicación de la actualización a los datos del juego: {detail}. Detalles: {log}",
|
||||
"extract.romfs_mismatch": "Los datos del juego extraídos no coinciden con la versión {version} (tamaño {size}, suma de comprobación {sha256}...).",
|
||||
"fonts.failed": "Falló la extracción de las fuentes compartidas (código de salida {code}): {detail}. Detalles: {log}",
|
||||
"fonts.incomplete": "La extracción de las fuentes compartidas no escribió todos los archivos ({files}).",
|
||||
"fonts.copy_failed": "No se pueden copiar las fuentes compartidas a {path}: {detail}",
|
||||
"lift.failed": "Falló la traducción del código del juego (código de salida {code}). Detalles: {log}",
|
||||
"compile.failed": "Falló la compilación de {game_exe} (código de salida {code}). Detalles: {log}",
|
||||
"compile.exe_in_use": "{path} está en uso. Cierra el juego y vuelve a ejecutar el instalador.",
|
||||
"kit.in_use": "{path} está en uso. Cierra el juego y cualquier ventana de instalación o recompilación abierta, y vuelve a ejecutar el instalador.",
|
||||
"kit.copy_failed": "No se puede copiar el kit de compilación en {path}: {detail}",
|
||||
"compile.exe_locked": "No se puede escribir {path}: otro programa lo retiene, un juego iniciado desde esa carpeta o un antivirus que marcó el archivo. Cierra el juego, añade la carpeta del instalador y la carpeta de instalación a las exclusiones del antivirus, reinicia Windows y vuelve a ejecutar el instalador. Detalles: {log}",
|
||||
"prepare.xlate_in_use": "{path} está en uso. Cierra el juego, termina cualquier proceso totk_xlate que haya quedado de una ejecución anterior y vuelve a ejecutar el instalador.",
|
||||
"prepare.shader_list_missing": "Falta la lista de shaders.",
|
||||
"prepare.romfs_patches_failed": "Falló la escritura de los parches de datos del juego (código de salida {code}). Detalles: {log}",
|
||||
"prepare.shaders_failed": "Falló la preparación de los shaders (código de salida {code}). Detalles: {log}",
|
||||
"cleanup.romfs_unreadable": "Los datos del juego en {path} faltan o no se pueden leer tras la instalación. Reinicia Windows y vuelve a ejecutar el instalador en la misma carpeta: extrae de nuevo los datos del juego y conserva el resto.",
|
||||
"prepare.pack_failed": "Falló el empaquetado de la caché de shaders (código de salida {code}). Detalles: {log}",
|
||||
"cleanup.ini_failed": "No se puede escribir totk.ini: {detail}",
|
||||
"warn.lang_needs_fonts": "El texto en {lang} necesita las fuentes del sistema de Switch y no se indicó ninguna. El juego no se iniciará en este idioma hasta que se añadan. Elige la carpeta del firmware (Contents/registered) o consulta «Switch system fonts» en docs/installer.md.",
|
||||
"warn.npdm_differs": "main.npdm difiere del volcado de referencia {version}; solo se usan los módulos de código.",
|
||||
"warn.cheats_skipped": "No se pudieron crear los trucos de la carpeta mods que cambian el código del juego; el juego se instala sin ellos. Detalles: {log}",
|
||||
"warn.exefs_skipped": "No se pudieron crear los parches ExeFS de los mods (.ips, .pchtxt); el juego se instala sin ellos. Detalles: {log}",
|
||||
"warn.plugins_skipped": "No se pudieron compilar los plugins de código de los mods (exefs subsdk); el juego se instala sin ellos. Detalles: {log}",
|
||||
"warn.xbox_prompts_failed": "No se pudieron preparar los iconos de botones de Xbox, PlayStation o PC (código de salida {code}); el juego mantiene los iconos de Switch. Detalles: {log}",
|
||||
"warn.shaders_skipped": "El controlador gráfico falló al crear algunos shaders, así que {count} quedaron fuera de la preparación. El juego los crea cuando los necesita por primera vez, y el controlador también puede fallar ahí; una actualización del controlador puede solucionarlo. Detalles: {log}",
|
||||
"warn.kernel_old": "Linux {version} no tiene el seguimiento de escrituras del que depende el juego (6.7 o posterior); el juego puede ir muy lento. Actualizar el sistema lo soluciona.",
|
||||
"warn.dlss_kept": "Ya hay una biblioteca DLSS en la carpeta de instalación ({path}); el instalador la conserva.",
|
||||
"warn.dlss_download_failed": "No se pudo descargar NVIDIA DLSS desde {url}: {detail}. El juego funciona sin él; la próxima ejecución del instalador lo intentará de nuevo.",
|
||||
"ui.title": "Instalador de TotK",
|
||||
"ui.rebuild_title": "Reconstruyendo el juego para tus mods",
|
||||
"ui.start_game": "Iniciar el juego",
|
||||
"ui.version": "versión {version}",
|
||||
"ui.intro": "Crea una carpeta jugable de Tears of the Kingdom a partir de tus propios archivos del juego. Tarda un rato y se ejecuta una sola vez.",
|
||||
"ui.notice": "La carpeta que crea este instalador contiene el juego. Es solo para tu uso personal; no la compartas ni la subas.",
|
||||
"ui.keys_private": "El archivo de claves se lee en su sitio. Su contenido nunca se muestra, copia ni guarda.",
|
||||
"ui.base": "Juego base",
|
||||
"ui.update": "Actualización",
|
||||
"ui.keys": "prod.keys",
|
||||
"ui.firmware": "Firmware (opcional)",
|
||||
"ui.game_language": "Idioma del juego",
|
||||
"ui.dest": "Carpeta de instalación",
|
||||
"ui.browse": "Examinar...",
|
||||
"ui.pick_game": "Elige el archivo del juego base",
|
||||
"ui.pick_update": "Elige el archivo de la actualización 1.1.0, 1.2.1 o 1.4.3",
|
||||
"ui.pick_keys": "Elige prod.keys",
|
||||
"ui.pick_firmware": "Elige la carpeta del firmware de Switch (Contents/registered)",
|
||||
"ui.pick_dest": "Elige la carpeta de instalación",
|
||||
"ui.firmware_help": "Para texto en chino, coreano y chino tradicional: la carpeta Contents/registered del firmware, por ejemplo de Ryujinx o Yuzu. El instalador copia de ella las fuentes del sistema de Switch a la carpeta de instalación.",
|
||||
"ui.dlss": "Descargar NVIDIA DLSS (nvngx_dlss.dll) para tarjetas gráficas NVIDIA RTX",
|
||||
"ui.dlss_help": "Del DLSS SDK de NVIDIA en GitHub, bajo la licencia RTX SDK de NVIDIA (github.com/NVIDIA/DLSS). Hace que funcionen los ajustes dlaa y DLSS; sin él no hacen nada.",
|
||||
"ui.compressed_help": "Los archivos comprimidos NSZ y XCZ funcionan tal cual: el instalador los descomprime por sí mismo (hasta que se extraen los datos del juego, necesita tanto espacio libre como ocupan los archivos descomprimidos).",
|
||||
"ui.section_files": "Archivos del juego",
|
||||
"ui.section_install": "Instalación",
|
||||
"ui.more_details": "▸ Más detalles",
|
||||
"ui.fewer_details": "▾ Ocultar detalles",
|
||||
"ui.formats_help": "Juego base: NSP, XCI, NSZ o XCZ. Actualización: 1.1.0, 1.2.1 o 1.4.3, en NSP o NSZ.",
|
||||
"ui.type_game": "Archivos de juego (NSP, XCI, NSZ, XCZ)",
|
||||
"ui.type_keys": "Archivos de claves (*.keys)",
|
||||
"ui.type_all": "Todos los archivos",
|
||||
"ui.start": "Iniciar",
|
||||
"ui.cancel": "Cancelar",
|
||||
"ui.cancelling": "Cancelando...",
|
||||
"ui.show_log": "Mostrar registro",
|
||||
"ui.hide_log": "Ocultar registro",
|
||||
"ui.close": "Cerrar",
|
||||
"ui.back": "Atrás",
|
||||
"ui.open_folder": "Abrir carpeta",
|
||||
"ui.update_mode": "Esta carpeta contiene una instalación anterior. El instalador la continúa o la actualiza; los archivos del juego solo se piden si vuelven a ser necesarios.",
|
||||
"ui.need_dest": "Elige la carpeta de instalación.",
|
||||
"ui.need_base": "Elige el archivo del juego base.",
|
||||
"ui.need_update": "Elige el archivo de la actualización 1.1.0, 1.2.1 o 1.4.3.",
|
||||
"ui.need_keys": "Elige el archivo prod.keys.",
|
||||
"ui.need_lang": "Elige el idioma del juego.",
|
||||
"ui.missing_base": "El archivo del juego base no existe.",
|
||||
"ui.missing_update": "El archivo de actualización no existe.",
|
||||
"ui.missing_keys": "El archivo de claves no existe.",
|
||||
"ui.missing_firmware": "La carpeta del firmware no existe.",
|
||||
"ui.running_install": "Instalando",
|
||||
"ui.running_resume": "Continuando la instalación anterior",
|
||||
"ui.running_update": "Actualizando la instalación",
|
||||
"ui.state_started": "iniciado",
|
||||
"ui.state_done": "hecho",
|
||||
"ui.state_skipped": "omitido",
|
||||
"ui.state_pending": "en espera",
|
||||
"ui.state_running": "en curso",
|
||||
"ui.state_failed": "fallido",
|
||||
"ui.log_warning": "Advertencia",
|
||||
"ui.log_error": "Error",
|
||||
"ui.log_space": "Espacio necesario: {need} GB, libre: {free} GB",
|
||||
"ui.log_end": "Terminado",
|
||||
"ui.result_ok": "El juego está listo",
|
||||
"ui.result_failed": "La instalación falló",
|
||||
"ui.result_cancelled": "La instalación se canceló",
|
||||
"ui.done_text": "Inicia {game_exe} desde {dest}. El instalador y los archivos del juego que elegiste ya no son necesarios.",
|
||||
"ui.cancelled_text": "Los pasos terminados se conservan. Vuelve a iniciar el instalador con la misma carpeta para continuar.",
|
||||
"ui.log_file": "Archivo de registro: {path}",
|
||||
"ui.process_died": "El instalador se detuvo inesperadamente (código de salida {code}).",
|
||||
"ui.confirm_cancel": "El instalador está en marcha. ¿Cancelarlo y cerrar la ventana?",
|
||||
"ui.space_one": "Espacio libre necesario en {path}: {need} GB (libre: {free} GB).",
|
||||
"ui.space_two": "Espacio libre necesario en {path}: {need} GB (libre: {free} GB); en {temp}: {temp_need} GB (libre: {temp_free} GB).",
|
||||
"ui.amount_bytes": "{done} / {total} GB",
|
||||
"ui.amount_chunks": "{done} / {total} partes",
|
||||
"ui.amount_objects": "{done} / {total} archivos",
|
||||
"ui.amount_shaders": "{done} / {total} shaders",
|
||||
"ui.amount_other": "{done} / {total} {unit}",
|
||||
"ui.seconds": "{n} s",
|
||||
"param.input.base": "juego base",
|
||||
"param.input.update": "actualización",
|
||||
"param.input.keys": "claves",
|
||||
"launcher.title": "Instalador de TotK",
|
||||
"launcher.python_missing": "Los archivos del instalador están incompletos: falta la carpeta python junto a TotK-Setup.exe. Descomprime de nuevo todo el archivo e inicia TotK-Setup.exe desde la carpeta descomprimida.",
|
||||
"lang.ja": "Japonés",
|
||||
"lang.en-US": "Inglés (EE. UU.)",
|
||||
"lang.en-GB": "Inglés (Reino Unido)",
|
||||
"lang.fr": "Francés",
|
||||
"lang.fr-CA": "Francés (Canadá)",
|
||||
"lang.de": "Alemán",
|
||||
"lang.it": "Italiano",
|
||||
"lang.es": "Español",
|
||||
"lang.es-419": "Español (Latinoamérica)",
|
||||
"lang.nl": "Neerlandés",
|
||||
"lang.pt": "Portugués",
|
||||
"lang.pt-BR": "Portugués (Brasil)",
|
||||
"lang.ru": "Ruso",
|
||||
"lang.ko": "Coreano",
|
||||
"lang.zh-Hans": "Chino (simplificado)",
|
||||
"lang.zh-Hant": "Chino (tradicional)"
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
{
|
||||
"step.check": "Vérification de l'ordinateur et des fichiers du jeu",
|
||||
"step.kit": "Copie du kit de compilation dans le dossier du jeu",
|
||||
"step.fonts": "Extraction des polices système",
|
||||
"step.extract": "Extraction du jeu",
|
||||
"step.lift": "Traduction du code du jeu en C",
|
||||
"step.compile": "Compilation de {game_exe}",
|
||||
"step.prepare": "Préparation des shaders",
|
||||
"step.pc_prompts": "Dessin des icônes du clavier et de la souris",
|
||||
"step.shapes": "Mise en page des écrans du jeu pour vos moniteurs",
|
||||
"step.dlss": "Téléchargement de NVIDIA DLSS",
|
||||
"step.cleanup": "Nettoyage",
|
||||
"phase.check.host": "Vérification du processeur et de la carte graphique",
|
||||
"phase.check.verify": "Vérification des fichiers déjà installés",
|
||||
"phase.check.verify_romfs": "Vérification des données du jeu installées",
|
||||
"phase.check.inputs": "Ouverture des fichiers du jeu avec les clés",
|
||||
"phase.check.unpack_base": "Décompression du jeu de base compressé",
|
||||
"phase.check.unpack_update": "Décompression de la mise à jour compressée",
|
||||
"phase.check.versions": "Vérification des versions du jeu",
|
||||
"phase.kit.copy": "Copie des outils avec lesquels le jeu se recompile pour les mods de code",
|
||||
"phase.fonts.extract": "Extraction des polices partagées depuis le firmware",
|
||||
"phase.fonts.copy": "Copie des polices partagées dans le dossier d'installation",
|
||||
"phase.extract.hash_base": "Calcul de la somme de contrôle du jeu de base",
|
||||
"phase.extract.hash_update": "Calcul de la somme de contrôle de la mise à jour",
|
||||
"phase.extract.exefs": "Extraction du code du jeu",
|
||||
"phase.extract.copy": "Copie des données du jeu",
|
||||
"phase.extract.merge": "Application de la mise à jour aux données du jeu",
|
||||
"phase.extract.diagnose": "Recherche du fichier du jeu endommagé",
|
||||
"phase.extract.index": "Vérification des données du jeu",
|
||||
"phase.lift.discover": "Recherche des fonctions",
|
||||
"phase.lift.emit": "Écriture du code C",
|
||||
"phase.compile.compile": "Compilation",
|
||||
"phase.compile.link": "Édition des liens de {game_exe}",
|
||||
"phase.prepare.romfs_patches": "Écriture des correctifs de données pour 60 fps",
|
||||
"phase.pc_prompts.draw": "Dessin des icônes des touches du clavier et de la souris d’après les affectations de totk.ini",
|
||||
"phase.prepare.seed": "Lecture des shaders dans les données du jeu",
|
||||
"phase.prepare.translate": "Traduction des shaders",
|
||||
"phase.prepare.libraries": "Construction des shaders pour le pilote graphique",
|
||||
"phase.prepare.pack": "Regroupement du cache de shaders en un fichier",
|
||||
"phase.shapes.layouts": "Écriture des mises en page et des icônes de boutons pour chaque format d’écran",
|
||||
"phase.dlss.download": "Téléchargement de nvngx_dlss.dll depuis le DLSS SDK de NVIDIA",
|
||||
"phase.cleanup.ini": "Écriture de totk.ini",
|
||||
"phase.cleanup.temp": "Suppression des fichiers temporaires",
|
||||
"cli.usage": "Ligne de commande invalide : {detail}",
|
||||
"internal": "Erreur inattendue ({exception}) : {detail}",
|
||||
"state.unreadable": "{path} est illisible. Choisissez un autre dossier ou supprimez ce fichier.",
|
||||
"state.newer_format": "{path} a été écrit par un installateur plus récent. Utilisez cet installateur ou un autre dossier.",
|
||||
"state.output_changed": "Les fichiers installés de l'étape « {step} » ont changé depuis leur création ; cette étape est relancée.",
|
||||
"check.release_incomplete": "Le dossier de l'installateur est incomplet ; il manque : {paths}. Décompressez à nouveau la version.",
|
||||
"check.dest_not_folder": "L'emplacement d'installation {path} est un fichier, pas un dossier.",
|
||||
"check.dest_not_empty": "Le dossier d'installation {path} n'est pas vide et ne contient aucune installation antérieure. Choisissez un dossier vide.",
|
||||
"check.lang_missing": "Choisissez la langue du jeu.",
|
||||
"check.lang_unknown": "Langue inconnue « {lang} ». Langues connues : {known}.",
|
||||
"check.toolchain_broken": "Le compilateur fourni ne fonctionne pas : {detail}",
|
||||
"check.glibc_old": "La bibliothèque C de ce système est glibc {version} ; le compilateur de l'installation demande {need} ou plus récent (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 et plus récents l'ont). Mettre à jour le système corrige cela.",
|
||||
"check.host_probe_failed": "La vérification de l'ordinateur ne s'est pas exécutée (code de sortie {code}).",
|
||||
"check.cpu_too_old": "Ce processeur ne prend pas en charge x86-64-v2 (SSE4.2, POPCNT et CMPXCHG16B), le niveau le plus ancien pour lequel le jeu est compilé. Intel Nehalem (2008) ou AMD Bulldozer (2011) et plus récents l'ont.",
|
||||
"check.vulkan_missing": "Aucun pilote Vulkan n'est installé. Installez le dernier pilote de votre carte graphique.",
|
||||
"check.vulkan_no_device": "Vulkan ne trouve aucune carte graphique. Installez le dernier pilote de votre carte graphique.",
|
||||
"check.vulkan_too_old": "Le jeu demande une carte graphique avec Vulkan 1.3 ; trouvé : {devices}. Mettez à jour le pilote graphique.",
|
||||
"check.no_display": "La préparation des shaders a besoin d'un écran. Lancez l'installation depuis la session de bureau, ou exportez DISPLAY=:0 (sur un Steam Deck en mode Jeu, aussi XDG_RUNTIME_DIR=/run/user/1000).",
|
||||
"check.inputs_needed": "Les fichiers du jeu sont nécessaires : choisissez le jeu de base, la mise à jour 1.1.0, 1.2.1 ou 1.4.3 et prod.keys.",
|
||||
"check.input_missing": "Fichier introuvable ({input}) : {path}",
|
||||
"check.keys_unreadable": "Le fichier de clés est illisible. Choisissez un fichier prod.keys.",
|
||||
"check.keys_no_header_key": "Le fichier de clés ne contient pas de header_key. Extrayez à nouveau prod.keys de votre console.",
|
||||
"check.keys_wrong": "Les clés ne peuvent pas ouvrir le fichier ({input}). Utilisez le prod.keys de votre console.",
|
||||
"check.keys_too_old": "Le fichier de clés est trop ancien pour le fichier ({input}) (génération de clés {generation} requise). Extrayez prod.keys d'une console avec un firmware plus récent.",
|
||||
"check.not_game_file": "Le fichier ({input}) n'est pas un fichier de jeu XCI, NSP, XCZ ou NSZ.",
|
||||
"check.file_unreadable": "Le fichier ({input}) est illisible : {detail}",
|
||||
"check.unpack_failed": "Le fichier compressé {input} n'a pas pu être décompressé : {detail}",
|
||||
"check.ticket_personalized": "Le fichier ({input}) contient un ticket personnalisé ; un ticket commun est nécessaire.",
|
||||
"check.ticket_missing": "Il manque au fichier ({input}) le ticket dont son contenu a besoin.",
|
||||
"check.base_not_totk": "Le fichier du jeu de base n'est pas The Legend of Zelda: Tears of the Kingdom ({detail}).",
|
||||
"check.base_is_update": "Le fichier du jeu de base est une mise à jour. Choisissez ici le jeu de base en NSP ou XCI (version 1.0.0) et ce fichier comme mise à jour.",
|
||||
"check.base_combined": "Le fichier du jeu de base contient plusieurs paquets (jeu de base, mise à jour ou DLC dans un seul fichier). Choisissez un dump du jeu de base qui ne contient que le jeu.",
|
||||
"check.update_not_nsp": "La mise à jour doit être un fichier NSP ou NSZ.",
|
||||
"check.update_is_base": "Le fichier de mise à jour contient un jeu de base. Choisissez le NSP de la mise à jour 1.1.0, 1.2.1 ou 1.4.3.",
|
||||
"check.update_not_totk": "Le fichier de mise à jour n'est pas une mise à jour de Tears of the Kingdom ({detail}).",
|
||||
"check.exefs_failed": "Le code du jeu du fichier ({input}) n'a pas passé les vérifications ; voir {log}.",
|
||||
"check.input_damaged": "Le fichier ({input}) est endommagé ou incomplet : {path} ({detail}). Copiez à nouveau ce fichier depuis sa source ou refaites le dump, puis relancez l'installation.",
|
||||
"check.base_wrong_version": "Le jeu de base n'est pas en version 1.0.0 ({modules} diffèrent).",
|
||||
"check.update_wrong_version": "La mise à jour est en version {found} ; cette version prend {wanted}.",
|
||||
"check.disk_space": "Espace libre insuffisant pour {path} : {need_gb} Go nécessaires, {free_gb} Go libres.",
|
||||
"check.firmware_missing": "Le dossier du firmware {path} n'existe pas. Choisissez le dossier Contents/registered du firmware.",
|
||||
"check.firmware_empty": "Le dossier du firmware {path} ne contient aucun fichier NCA. Choisissez le dossier Contents/registered du firmware.",
|
||||
"check.fonts_keys_needed": "Les polices partagées de cette langue ne sont pas encore installées ; choisissez prod.keys pour que l'installation puisse les extraire du firmware.",
|
||||
"extract.exefs_mismatch": "Le code du jeu extrait ne correspond pas à la version {version} ({modules}).",
|
||||
"extract.romfs_merge_failed": "L'application de la mise à jour aux données du jeu a échoué : {detail}. Détails : {log}",
|
||||
"extract.romfs_mismatch": "Les données du jeu extraites ne correspondent pas à la version {version} (taille {size}, somme de contrôle {sha256}...).",
|
||||
"fonts.failed": "L'extraction des polices partagées a échoué (code de sortie {code}) : {detail}. Détails : {log}",
|
||||
"fonts.incomplete": "L'extraction des polices partagées n'a pas écrit tous les fichiers ({files}).",
|
||||
"fonts.copy_failed": "Les polices partagées ne peuvent pas être copiées dans {path} : {detail}",
|
||||
"lift.failed": "La traduction du code du jeu a échoué (code de sortie {code}). Détails : {log}",
|
||||
"compile.failed": "La compilation de {game_exe} a échoué (code de sortie {code}). Détails : {log}",
|
||||
"compile.exe_in_use": "{path} est en cours d'utilisation. Fermez le jeu et relancez l'installateur.",
|
||||
"kit.in_use": "{path} est en cours d’utilisation. Fermez le jeu et toute fenêtre d’installation ou de recompilation ouverte, puis relancez l’installation.",
|
||||
"kit.copy_failed": "Impossible de copier le kit de compilation dans {path} : {detail}",
|
||||
"compile.exe_locked": "Impossible d’écrire {path} : un autre programme le retient, un jeu lancé depuis ce dossier ou un antivirus qui a signalé le fichier. Fermez le jeu, ajoutez le dossier du programme d’installation et le dossier d’installation aux exclusions de l’antivirus, redémarrez Windows, puis relancez l’installation. Détails : {log}",
|
||||
"prepare.xlate_in_use": "{path} est en cours d'utilisation. Fermez le jeu, terminez tout processus totk_xlate restant d'une exécution précédente, puis relancez l'installateur.",
|
||||
"prepare.shader_list_missing": "La liste des shaders est manquante.",
|
||||
"prepare.romfs_patches_failed": "L'écriture des correctifs de données du jeu a échoué (code de sortie {code}). Détails : {log}",
|
||||
"prepare.shaders_failed": "La préparation des shaders a échoué (code de sortie {code}). Détails : {log}",
|
||||
"cleanup.romfs_unreadable": "Les données du jeu dans {path} sont manquantes ou illisibles après l'installation. Redémarrez Windows, puis relancez l'installateur sur le même dossier : il extrait à nouveau les données du jeu et conserve le reste.",
|
||||
"prepare.pack_failed": "Le regroupement du cache de shaders a échoué (code de sortie {code}). Détails : {log}",
|
||||
"cleanup.ini_failed": "totk.ini ne peut pas être écrit : {detail}",
|
||||
"warn.lang_needs_fonts": "Le texte en {lang} nécessite les polices système de la Switch, et aucune n'a été fournie. Le jeu ne démarrera pas dans cette langue tant qu'elles ne sont pas ajoutées. Choisissez le dossier du firmware (Contents/registered), ou consultez « Switch system fonts » dans docs/installer.md.",
|
||||
"warn.npdm_differs": "main.npdm diffère du dump de référence {version} ; seuls les modules de code sont utilisés.",
|
||||
"warn.cheats_skipped": "Les codes de triche du dossier mods qui modifient le code du jeu n'ont pas pu être construits ; le jeu s'installe sans eux. Détails : {log}",
|
||||
"warn.exefs_skipped": "Les correctifs ExeFS des mods (.ips, .pchtxt) n'ont pas pu être construits ; le jeu s'installe sans eux. Détails : {log}",
|
||||
"warn.plugins_skipped": "Les plugins de code des mods (exefs subsdk) n’ont pas pu être compilés ; le jeu s’installe sans eux. Détails : {log}",
|
||||
"warn.xbox_prompts_failed": "Les icônes de boutons Xbox, PlayStation ou PC n'ont pas pu être préparées (code de sortie {code}) ; le jeu garde les icônes Switch. Détails : {log}",
|
||||
"warn.shaders_skipped": "Le pilote graphique a planté pendant la construction de certains shaders ; {count} ont donc été exclus de la préparation. Le jeu les construit quand il en a besoin pour la première fois, et le pilote peut y planter aussi ; une mise à jour du pilote peut corriger cela. Détails : {log}",
|
||||
"warn.kernel_old": "Linux {version} ne dispose pas du suivi des écritures dont le jeu dépend (6.7 ou plus récent) ; le jeu peut être très lent. Mettre à jour le système corrige cela.",
|
||||
"warn.dlss_kept": "Une bibliothèque DLSS se trouve déjà dans le dossier d'installation ({path}) ; l'installation la conserve.",
|
||||
"warn.dlss_download_failed": "NVIDIA DLSS n'a pas pu être téléchargé depuis {url} : {detail}. Le jeu fonctionne sans ; la prochaine installation réessaiera.",
|
||||
"ui.title": "Installation de TotK",
|
||||
"ui.rebuild_title": "Reconstruction du jeu pour vos mods",
|
||||
"ui.start_game": "Lancer le jeu",
|
||||
"ui.version": "version {version}",
|
||||
"ui.intro": "Construit un dossier jouable de Tears of the Kingdom à partir de vos propres fichiers du jeu. Cela prend du temps et ne s'exécute qu'une fois.",
|
||||
"ui.notice": "Le dossier construit par cette installation contient le jeu. Il est réservé à votre usage personnel ; ne le partagez pas et ne le mettez pas en ligne.",
|
||||
"ui.keys_private": "Le fichier de clés est lu sur place. Son contenu n'est jamais affiché, copié ni conservé.",
|
||||
"ui.base": "Jeu de base",
|
||||
"ui.update": "Mise à jour",
|
||||
"ui.keys": "prod.keys",
|
||||
"ui.firmware": "Firmware (facultatif)",
|
||||
"ui.game_language": "Langue du jeu",
|
||||
"ui.dest": "Dossier d'installation",
|
||||
"ui.browse": "Parcourir...",
|
||||
"ui.pick_game": "Choisissez le fichier du jeu de base",
|
||||
"ui.pick_update": "Choisissez le fichier de la mise à jour 1.1.0, 1.2.1 ou 1.4.3",
|
||||
"ui.pick_keys": "Choisissez prod.keys",
|
||||
"ui.pick_firmware": "Choisissez le dossier du firmware Switch (Contents/registered)",
|
||||
"ui.pick_dest": "Choisissez le dossier d'installation",
|
||||
"ui.firmware_help": "Pour le texte en chinois, en coréen et en chinois traditionnel : le dossier Contents/registered du firmware, par exemple celui de Ryujinx ou de Yuzu. L'installation en copie les polices système de la Switch dans le dossier d'installation.",
|
||||
"ui.dlss": "Télécharger NVIDIA DLSS (nvngx_dlss.dll) pour les cartes graphiques NVIDIA RTX",
|
||||
"ui.dlss_help": "Depuis le DLSS SDK de NVIDIA sur GitHub, sous la licence RTX SDK de NVIDIA (github.com/NVIDIA/DLSS). Il fait fonctionner les réglages dlaa et DLSS ; sans lui, ils n'ont aucun effet.",
|
||||
"ui.compressed_help": "Les fichiers compressés NSZ et XCZ fonctionnent tels quels : l'installation les décompresse elle-même (jusqu'à l'extraction des données du jeu, il faut autant d'espace libre que les fichiers décompressés).",
|
||||
"ui.section_files": "Fichiers du jeu",
|
||||
"ui.section_install": "Installation",
|
||||
"ui.more_details": "▸ Plus de détails",
|
||||
"ui.fewer_details": "▾ Masquer les détails",
|
||||
"ui.formats_help": "Jeu de base : NSP, XCI, NSZ ou XCZ. Mise à jour : 1.1.0, 1.2.1 ou 1.4.3, en NSP ou NSZ.",
|
||||
"ui.type_game": "Fichiers de jeu (NSP, XCI, NSZ, XCZ)",
|
||||
"ui.type_keys": "Fichiers de clés (*.keys)",
|
||||
"ui.type_all": "Tous les fichiers",
|
||||
"ui.start": "Démarrer",
|
||||
"ui.cancel": "Annuler",
|
||||
"ui.cancelling": "Annulation...",
|
||||
"ui.show_log": "Afficher le journal",
|
||||
"ui.hide_log": "Masquer le journal",
|
||||
"ui.close": "Fermer",
|
||||
"ui.back": "Retour",
|
||||
"ui.open_folder": "Ouvrir le dossier",
|
||||
"ui.update_mode": "Ce dossier contient une installation antérieure. L'installation la poursuit ou la met à jour ; les fichiers du jeu ne sont demandés que s'ils sont de nouveau nécessaires.",
|
||||
"ui.need_dest": "Choisissez le dossier d'installation.",
|
||||
"ui.need_base": "Choisissez le fichier du jeu de base.",
|
||||
"ui.need_update": "Choisissez le fichier de la mise à jour 1.1.0, 1.2.1 ou 1.4.3.",
|
||||
"ui.need_keys": "Choisissez le fichier prod.keys.",
|
||||
"ui.need_lang": "Choisissez la langue du jeu.",
|
||||
"ui.missing_base": "Le fichier du jeu de base n'existe pas.",
|
||||
"ui.missing_update": "Le fichier de mise à jour n'existe pas.",
|
||||
"ui.missing_keys": "Le fichier de clés n'existe pas.",
|
||||
"ui.missing_firmware": "Le dossier du firmware n'existe pas.",
|
||||
"ui.running_install": "Installation",
|
||||
"ui.running_resume": "Reprise de l'installation précédente",
|
||||
"ui.running_update": "Mise à jour de l'installation",
|
||||
"ui.state_started": "démarré",
|
||||
"ui.state_done": "terminé",
|
||||
"ui.state_skipped": "ignoré",
|
||||
"ui.state_pending": "en attente",
|
||||
"ui.state_running": "en cours",
|
||||
"ui.state_failed": "échec",
|
||||
"ui.log_warning": "Avertissement",
|
||||
"ui.log_error": "Erreur",
|
||||
"ui.log_space": "Espace nécessaire : {need} Go, libre : {free} Go",
|
||||
"ui.log_end": "Terminé",
|
||||
"ui.result_ok": "Le jeu est prêt",
|
||||
"ui.result_failed": "L'installation a échoué",
|
||||
"ui.result_cancelled": "L'installation a été annulée",
|
||||
"ui.done_text": "Lancez {game_exe} depuis {dest}. Le programme d'installation et les fichiers du jeu choisis ne sont plus nécessaires.",
|
||||
"ui.cancelled_text": "Les étapes terminées sont conservées. Relancez l'installation avec le même dossier pour continuer.",
|
||||
"ui.log_file": "Fichier journal : {path}",
|
||||
"ui.process_died": "L'installation s'est arrêtée de façon inattendue (code de sortie {code}).",
|
||||
"ui.confirm_cancel": "L'installation est en cours. L'annuler et fermer la fenêtre ?",
|
||||
"ui.space_one": "Espace libre nécessaire sur {path} : {need} Go (libre : {free} Go).",
|
||||
"ui.space_two": "Espace libre nécessaire sur {path} : {need} Go (libre : {free} Go) ; sur {temp} : {temp_need} Go (libre : {temp_free} Go).",
|
||||
"ui.amount_bytes": "{done} / {total} Go",
|
||||
"ui.amount_chunks": "{done} / {total} parties",
|
||||
"ui.amount_objects": "{done} / {total} fichiers",
|
||||
"ui.amount_shaders": "{done} / {total} shaders",
|
||||
"ui.amount_other": "{done} / {total} {unit}",
|
||||
"ui.seconds": "{n} s",
|
||||
"param.input.base": "jeu de base",
|
||||
"param.input.update": "mise à jour",
|
||||
"param.input.keys": "clés",
|
||||
"launcher.title": "Installation de TotK",
|
||||
"launcher.python_missing": "Les fichiers d'installation sont incomplets : le dossier python à côté de TotK-Setup.exe est manquant. Décompressez à nouveau toute l'archive et lancez TotK-Setup.exe depuis le dossier décompressé.",
|
||||
"lang.ja": "Japonais",
|
||||
"lang.en-US": "Anglais (États-Unis)",
|
||||
"lang.en-GB": "Anglais (Royaume-Uni)",
|
||||
"lang.fr": "Français",
|
||||
"lang.fr-CA": "Français (Canada)",
|
||||
"lang.de": "Allemand",
|
||||
"lang.it": "Italien",
|
||||
"lang.es": "Espagnol",
|
||||
"lang.es-419": "Espagnol (Amérique latine)",
|
||||
"lang.nl": "Néerlandais",
|
||||
"lang.pt": "Portugais",
|
||||
"lang.pt-BR": "Portugais (Brésil)",
|
||||
"lang.ru": "Russe",
|
||||
"lang.ko": "Coréen",
|
||||
"lang.zh-Hans": "Chinois (simplifié)",
|
||||
"lang.zh-Hant": "Chinois (traditionnel)"
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
{
|
||||
"step.check": "Controllo del computer e dei file del gioco",
|
||||
"step.kit": "Copia del kit di compilazione nella cartella del gioco",
|
||||
"step.fonts": "Estrazione dei font di sistema",
|
||||
"step.extract": "Estrazione del gioco",
|
||||
"step.lift": "Traduzione del codice del gioco in C",
|
||||
"step.compile": "Compilazione di {game_exe}",
|
||||
"step.prepare": "Preparazione degli shader",
|
||||
"step.pc_prompts": "Disegno delle icone di tastiera e mouse",
|
||||
"step.shapes": "Impaginazione delle schermate del gioco per i tuoi monitor",
|
||||
"step.dlss": "Download di NVIDIA DLSS",
|
||||
"step.cleanup": "Pulizia",
|
||||
"phase.check.host": "Controllo del processore e della scheda grafica",
|
||||
"phase.check.verify": "Controllo dei file già installati",
|
||||
"phase.check.verify_romfs": "Controllo dei dati di gioco installati",
|
||||
"phase.check.inputs": "Apertura dei file del gioco con le chiavi",
|
||||
"phase.check.unpack_base": "Decompressione del gioco base compresso",
|
||||
"phase.check.unpack_update": "Decompressione dell'aggiornamento compresso",
|
||||
"phase.check.versions": "Controllo delle versioni del gioco",
|
||||
"phase.kit.copy": "Copia degli strumenti con cui il gioco si ricompila per le mod di codice",
|
||||
"phase.fonts.extract": "Estrazione dei font condivisi dal firmware",
|
||||
"phase.fonts.copy": "Copia dei font condivisi nella cartella di installazione",
|
||||
"phase.extract.hash_base": "Calcolo del checksum del gioco base",
|
||||
"phase.extract.hash_update": "Calcolo del checksum dell'aggiornamento",
|
||||
"phase.extract.exefs": "Estrazione del codice del gioco",
|
||||
"phase.extract.copy": "Copia dei dati di gioco",
|
||||
"phase.extract.merge": "Applicazione dell'aggiornamento ai dati di gioco",
|
||||
"phase.extract.diagnose": "Ricerca del file di gioco danneggiato",
|
||||
"phase.extract.index": "Verifica dei dati di gioco",
|
||||
"phase.lift.discover": "Ricerca delle funzioni",
|
||||
"phase.lift.emit": "Scrittura del codice C",
|
||||
"phase.compile.compile": "Compilazione",
|
||||
"phase.compile.link": "Collegamento di {game_exe}",
|
||||
"phase.prepare.romfs_patches": "Scrittura delle patch dei dati per i 60 fps",
|
||||
"phase.pc_prompts.draw": "Disegno delle icone dei tasti e dei pulsanti del mouse dalle assegnazioni di totk.ini",
|
||||
"phase.prepare.seed": "Lettura degli shader dai dati di gioco",
|
||||
"phase.prepare.translate": "Traduzione degli shader",
|
||||
"phase.prepare.libraries": "Creazione degli shader per il driver grafico",
|
||||
"phase.prepare.pack": "Raccolta della cache degli shader in un file",
|
||||
"phase.shapes.layouts": "Scrittura dei layout dello schermo e delle icone dei pulsanti per ogni formato di schermo",
|
||||
"phase.dlss.download": "Download di nvngx_dlss.dll dal DLSS SDK di NVIDIA",
|
||||
"phase.cleanup.ini": "Scrittura di totk.ini",
|
||||
"phase.cleanup.temp": "Rimozione dei file temporanei",
|
||||
"cli.usage": "Riga di comando non valida: {detail}",
|
||||
"internal": "Errore imprevisto ({exception}): {detail}",
|
||||
"state.unreadable": "Impossibile leggere {path}. Scegli un'altra cartella o elimina quel file.",
|
||||
"state.newer_format": "{path} è stato scritto da un programma di installazione più recente. Usa quel programma o un'altra cartella.",
|
||||
"state.output_changed": "I file installati del passaggio '{step}' sono cambiati da quando sono stati creati; quel passaggio viene ripetuto.",
|
||||
"check.release_incomplete": "La cartella del programma di installazione è incompleta; manca: {paths}. Estrai di nuovo la release.",
|
||||
"check.dest_not_folder": "Il percorso di installazione {path} è un file, non una cartella.",
|
||||
"check.dest_not_empty": "La cartella di installazione {path} non è vuota e non contiene un'installazione precedente. Scegli una cartella vuota.",
|
||||
"check.lang_missing": "Scegli la lingua del gioco.",
|
||||
"check.lang_unknown": "Lingua sconosciuta '{lang}'. Lingue note: {known}.",
|
||||
"check.toolchain_broken": "Il compilatore incluso non funziona: {detail}",
|
||||
"check.glibc_old": "La libreria C di questo sistema è glibc {version}; il compilatore dell'installazione richiede {need} o successiva (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 e successivi la hanno). Aggiornare il sistema risolve il problema.",
|
||||
"check.host_probe_failed": "Il controllo del computer non è stato eseguito (codice di uscita {code}).",
|
||||
"check.cpu_too_old": "Questo processore non supporta x86-64-v2 (SSE4.2, POPCNT e CMPXCHG16B), il livello più vecchio per cui il gioco viene compilato. Intel Nehalem (2008) o AMD Bulldozer (2011) e successivi lo supportano.",
|
||||
"check.vulkan_missing": "Non è installato alcun driver Vulkan. Installa il driver più recente della tua scheda grafica.",
|
||||
"check.vulkan_no_device": "Vulkan non trova alcuna scheda grafica. Installa il driver più recente della tua scheda grafica.",
|
||||
"check.vulkan_too_old": "Il gioco richiede una scheda grafica con Vulkan 1.3; trovato: {devices}. Aggiorna il driver grafico.",
|
||||
"check.no_display": "La preparazione degli shader richiede uno schermo. Avvia l'installazione dalla sessione desktop oppure esporta DISPLAY=:0 (su uno Steam Deck in modalità Gioco anche XDG_RUNTIME_DIR=/run/user/1000).",
|
||||
"check.inputs_needed": "Servono i file del gioco: scegli il gioco base, l'aggiornamento 1.1.0, 1.2.1 o 1.4.3 e prod.keys.",
|
||||
"check.input_missing": "File non trovato ({input}): {path}",
|
||||
"check.keys_unreadable": "Impossibile leggere il file delle chiavi. Scegli un file prod.keys.",
|
||||
"check.keys_no_header_key": "Il file delle chiavi non contiene header_key. Estrai di nuovo prod.keys dalla tua console.",
|
||||
"check.keys_wrong": "Le chiavi non riescono ad aprire il file ({input}). Usa il prod.keys della tua console.",
|
||||
"check.keys_too_old": "Il file delle chiavi è troppo vecchio per il file ({input}) (richiede la generazione di chiavi {generation}). Estrai prod.keys da una console con un firmware più recente.",
|
||||
"check.not_game_file": "Il file ({input}) non è un file di gioco XCI, NSP, XCZ o NSZ.",
|
||||
"check.file_unreadable": "Impossibile leggere il file ({input}): {detail}",
|
||||
"check.unpack_failed": "Impossibile decomprimere il file compresso {input}: {detail}",
|
||||
"check.ticket_personalized": "Il file ({input}) contiene un ticket personalizzato; serve un ticket comune.",
|
||||
"check.ticket_missing": "Al file ({input}) manca il ticket richiesto dal suo contenuto.",
|
||||
"check.base_not_totk": "Il file del gioco base non è The Legend of Zelda: Tears of the Kingdom ({detail}).",
|
||||
"check.base_is_update": "Il file del gioco base è un aggiornamento. Scegli qui il gioco base in NSP o XCI (versione 1.0.0) e questo file come aggiornamento.",
|
||||
"check.base_combined": "Il file del gioco base contiene più pacchetti (gioco base, aggiornamento o DLC in un unico file). Scegli un dump del gioco base che contenga solo il gioco.",
|
||||
"check.update_not_nsp": "L'aggiornamento deve essere un file NSP o NSZ.",
|
||||
"check.update_is_base": "Il file dell'aggiornamento contiene un gioco base. Scegli l'NSP dell'aggiornamento 1.1.0, 1.2.1 o 1.4.3.",
|
||||
"check.update_not_totk": "Il file dell'aggiornamento non è un aggiornamento di Tears of the Kingdom ({detail}).",
|
||||
"check.exefs_failed": "Il codice del gioco del file ({input}) non ha superato i controlli; vedi {log}.",
|
||||
"check.input_damaged": "Il file ({input}) è danneggiato o incompleto: {path} ({detail}). Copia di nuovo quel file dalla sua origine o rifai il dump, poi esegui di nuovo l'installazione.",
|
||||
"check.base_wrong_version": "Il gioco base non è la versione 1.0.0 ({modules} diversi).",
|
||||
"check.update_wrong_version": "L'aggiornamento è la versione {found}; questa release usa {wanted}.",
|
||||
"check.disk_space": "Spazio libero insufficiente per {path}: servono {need_gb} GB, liberi {free_gb} GB.",
|
||||
"check.firmware_missing": "La cartella del firmware {path} non esiste. Scegli la cartella Contents/registered del firmware.",
|
||||
"check.firmware_empty": "La cartella del firmware {path} non contiene file NCA. Scegli la cartella Contents/registered del firmware.",
|
||||
"check.fonts_keys_needed": "I font condivisi per questa lingua non sono ancora installati; scegli prod.keys perché l'installazione possa estrarli dal firmware.",
|
||||
"extract.exefs_mismatch": "Il codice del gioco estratto non corrisponde alla versione {version} ({modules}).",
|
||||
"extract.romfs_merge_failed": "L'applicazione dell'aggiornamento ai dati di gioco non è riuscita: {detail}. Dettagli: {log}",
|
||||
"extract.romfs_mismatch": "I dati di gioco estratti non corrispondono alla versione {version} (dimensione {size}, checksum {sha256}...).",
|
||||
"fonts.failed": "L'estrazione dei font condivisi non è riuscita (codice di uscita {code}): {detail}. Dettagli: {log}",
|
||||
"fonts.incomplete": "L'estrazione dei font condivisi non ha scritto tutti i file ({files}).",
|
||||
"fonts.copy_failed": "Impossibile copiare i font condivisi in {path}: {detail}",
|
||||
"lift.failed": "La traduzione del codice del gioco non è riuscita (codice di uscita {code}). Dettagli: {log}",
|
||||
"compile.failed": "La compilazione di {game_exe} non è riuscita (codice di uscita {code}). Dettagli: {log}",
|
||||
"compile.exe_in_use": "{path} è in uso. Chiudi il gioco ed esegui di nuovo il programma di installazione.",
|
||||
"kit.in_use": "{path} è in uso. Chiudi il gioco e ogni finestra di installazione o ricompilazione aperta, poi esegui di nuovo l'installazione.",
|
||||
"kit.copy_failed": "Impossibile copiare il kit di compilazione in {path}: {detail}",
|
||||
"compile.exe_locked": "Impossibile scrivere {path}: un altro programma lo tiene aperto, un gioco avviato da quella cartella o un antivirus che ha segnalato il file. Chiudi il gioco, aggiungi la cartella del programma di installazione e la cartella di installazione alle esclusioni dell'antivirus, riavvia Windows, poi esegui di nuovo l'installazione. Dettagli: {log}",
|
||||
"prepare.xlate_in_use": "{path} è in uso. Chiudi il gioco, termina ogni processo totk_xlate rimasto da un'esecuzione precedente, poi esegui di nuovo il programma di installazione.",
|
||||
"prepare.shader_list_missing": "Manca l'elenco degli shader.",
|
||||
"prepare.romfs_patches_failed": "La scrittura delle patch dei dati di gioco non è riuscita (codice di uscita {code}). Dettagli: {log}",
|
||||
"prepare.shaders_failed": "La preparazione degli shader non è riuscita (codice di uscita {code}). Dettagli: {log}",
|
||||
"cleanup.romfs_unreadable": "I dati di gioco in {path} mancano o non sono leggibili dopo l'installazione. Riavvia Windows, poi esegui di nuovo il programma di installazione sulla stessa cartella: estrae di nuovo i dati di gioco e mantiene il resto.",
|
||||
"prepare.pack_failed": "La raccolta della cache degli shader non è riuscita (codice di uscita {code}). Dettagli: {log}",
|
||||
"cleanup.ini_failed": "Impossibile scrivere totk.ini: {detail}",
|
||||
"warn.lang_needs_fonts": "Il testo in {lang} richiede i font di sistema di Switch e non ne è stato indicato nessuno. Il gioco non si avvierà in questa lingua finché non verranno aggiunti. Scegli la cartella del firmware (Contents/registered) o consulta \"Switch system fonts\" in docs/installer.md.",
|
||||
"warn.npdm_differs": "main.npdm è diverso dal dump di riferimento {version}; vengono usati solo i moduli di codice.",
|
||||
"warn.cheats_skipped": "Non è stato possibile creare i trucchi della cartella mods che modificano il codice del gioco; il gioco viene installato senza di essi. Dettagli: {log}",
|
||||
"warn.exefs_skipped": "Non è stato possibile creare le patch ExeFS delle mod (.ips, .pchtxt); il gioco viene installato senza di esse. Dettagli: {log}",
|
||||
"warn.plugins_skipped": "Non è stato possibile compilare i plugin di codice delle mod (exefs subsdk); il gioco si installa senza di essi. Dettagli: {log}",
|
||||
"warn.xbox_prompts_failed": "Non è stato possibile preparare le icone dei pulsanti Xbox, PlayStation o PC (codice di uscita {code}); il gioco mantiene le icone di Switch. Dettagli: {log}",
|
||||
"warn.shaders_skipped": "Il driver grafico si è bloccato durante la creazione di alcuni shader, quindi {count} sono stati esclusi dalla preparazione. Il gioco li crea quando servono per la prima volta, e anche lì il driver potrebbe bloccarsi; un aggiornamento del driver potrebbe risolvere. Dettagli: {log}",
|
||||
"warn.kernel_old": "Linux {version} non ha il tracciamento delle scritture su cui si basa il gioco (6.7 o successivo); il gioco potrebbe essere molto lento. Aggiornare il sistema risolve il problema.",
|
||||
"warn.dlss_kept": "Nella cartella di installazione c'è già una libreria DLSS ({path}); l'installazione la mantiene.",
|
||||
"warn.dlss_download_failed": "Impossibile scaricare NVIDIA DLSS da {url}: {detail}. Il gioco funziona senza; la prossima esecuzione dell'installazione riproverà.",
|
||||
"ui.title": "Installazione di TotK",
|
||||
"ui.rebuild_title": "Ricostruzione del gioco per le tue mod",
|
||||
"ui.start_game": "Avvia il gioco",
|
||||
"ui.version": "versione {version}",
|
||||
"ui.intro": "Crea una cartella giocabile di Tears of the Kingdom dai tuoi file del gioco. Richiede un po' di tempo e si esegue una sola volta.",
|
||||
"ui.notice": "La cartella creata da questa installazione contiene il gioco. È solo per uso personale; non condividerla né caricarla online.",
|
||||
"ui.keys_private": "Il file delle chiavi viene letto sul posto. Il suo contenuto non viene mai mostrato, copiato o salvato.",
|
||||
"ui.base": "Gioco base",
|
||||
"ui.update": "Aggiornamento",
|
||||
"ui.keys": "prod.keys",
|
||||
"ui.firmware": "Firmware (facoltativo)",
|
||||
"ui.game_language": "Lingua del gioco",
|
||||
"ui.dest": "Cartella di installazione",
|
||||
"ui.browse": "Sfoglia...",
|
||||
"ui.pick_game": "Scegli il file del gioco base",
|
||||
"ui.pick_update": "Scegli il file dell'aggiornamento 1.1.0, 1.2.1 o 1.4.3",
|
||||
"ui.pick_keys": "Scegli prod.keys",
|
||||
"ui.pick_firmware": "Scegli la cartella del firmware di Switch (Contents/registered)",
|
||||
"ui.pick_dest": "Scegli la cartella di installazione",
|
||||
"ui.firmware_help": "Per il testo in cinese, coreano e cinese tradizionale: la cartella Contents/registered del firmware, ad esempio da Ryujinx o Yuzu. L'installazione ne copia i font di sistema di Switch nella cartella di installazione.",
|
||||
"ui.dlss": "Scarica NVIDIA DLSS (nvngx_dlss.dll) per le schede grafiche NVIDIA RTX",
|
||||
"ui.dlss_help": "Dal DLSS SDK di NVIDIA su GitHub, con la licenza RTX SDK di NVIDIA (github.com/NVIDIA/DLSS). Fa funzionare le impostazioni dlaa e DLSS; senza, non hanno effetto.",
|
||||
"ui.compressed_help": "I file compressi NSZ e XCZ funzionano così come sono: l'installazione li decomprime da sé (finché i dati del gioco non sono estratti, serve tanto spazio libero quanto occupano i file decompressi).",
|
||||
"ui.section_files": "File del gioco",
|
||||
"ui.section_install": "Installazione",
|
||||
"ui.more_details": "▸ Altri dettagli",
|
||||
"ui.fewer_details": "▾ Nascondi dettagli",
|
||||
"ui.formats_help": "Gioco base: NSP, XCI, NSZ o XCZ. Aggiornamento: 1.1.0, 1.2.1 o 1.4.3, in NSP o NSZ.",
|
||||
"ui.type_game": "File di gioco (NSP, XCI, NSZ, XCZ)",
|
||||
"ui.type_keys": "File di chiavi (*.keys)",
|
||||
"ui.type_all": "Tutti i file",
|
||||
"ui.start": "Avvia",
|
||||
"ui.cancel": "Annulla",
|
||||
"ui.cancelling": "Annullamento...",
|
||||
"ui.show_log": "Mostra registro",
|
||||
"ui.hide_log": "Nascondi registro",
|
||||
"ui.close": "Chiudi",
|
||||
"ui.back": "Indietro",
|
||||
"ui.open_folder": "Apri cartella",
|
||||
"ui.update_mode": "Questa cartella contiene un'installazione precedente. L'installazione la prosegue o la aggiorna; i file del gioco vengono chiesti solo se servono di nuovo.",
|
||||
"ui.need_dest": "Scegli la cartella di installazione.",
|
||||
"ui.need_base": "Scegli il file del gioco base.",
|
||||
"ui.need_update": "Scegli il file dell'aggiornamento 1.1.0, 1.2.1 o 1.4.3.",
|
||||
"ui.need_keys": "Scegli il file prod.keys.",
|
||||
"ui.need_lang": "Scegli la lingua del gioco.",
|
||||
"ui.missing_base": "Il file del gioco base non esiste.",
|
||||
"ui.missing_update": "Il file dell'aggiornamento non esiste.",
|
||||
"ui.missing_keys": "Il file delle chiavi non esiste.",
|
||||
"ui.missing_firmware": "La cartella del firmware non esiste.",
|
||||
"ui.running_install": "Installazione",
|
||||
"ui.running_resume": "Ripresa dell'installazione precedente",
|
||||
"ui.running_update": "Aggiornamento dell'installazione",
|
||||
"ui.state_started": "avviato",
|
||||
"ui.state_done": "fatto",
|
||||
"ui.state_skipped": "saltato",
|
||||
"ui.state_pending": "in attesa",
|
||||
"ui.state_running": "in corso",
|
||||
"ui.state_failed": "non riuscito",
|
||||
"ui.log_warning": "Avviso",
|
||||
"ui.log_error": "Errore",
|
||||
"ui.log_space": "Spazio necessario: {need} GB, libero: {free} GB",
|
||||
"ui.log_end": "Terminato",
|
||||
"ui.result_ok": "Il gioco è pronto",
|
||||
"ui.result_failed": "L'installazione non è riuscita",
|
||||
"ui.result_cancelled": "L'installazione è stata annullata",
|
||||
"ui.done_text": "Avvia {game_exe} da {dest}. Il programma di installazione e i file del gioco scelti non servono più.",
|
||||
"ui.cancelled_text": "I passaggi completati vengono mantenuti. Avvia di nuovo l'installazione con la stessa cartella per continuare.",
|
||||
"ui.log_file": "File di registro: {path}",
|
||||
"ui.process_died": "L'installazione si è interrotta inaspettatamente (codice di uscita {code}).",
|
||||
"ui.confirm_cancel": "L'installazione è in corso. Annullarla e chiudere la finestra?",
|
||||
"ui.space_one": "Spazio libero necessario su {path}: {need} GB (libero: {free} GB).",
|
||||
"ui.space_two": "Spazio libero necessario su {path}: {need} GB (libero: {free} GB); su {temp}: {temp_need} GB (libero: {temp_free} GB).",
|
||||
"ui.amount_bytes": "{done} / {total} GB",
|
||||
"ui.amount_chunks": "{done} / {total} parti",
|
||||
"ui.amount_objects": "{done} / {total} file",
|
||||
"ui.amount_shaders": "{done} / {total} shader",
|
||||
"ui.amount_other": "{done} / {total} {unit}",
|
||||
"ui.seconds": "{n} s",
|
||||
"param.input.base": "gioco base",
|
||||
"param.input.update": "aggiornamento",
|
||||
"param.input.keys": "chiavi",
|
||||
"launcher.title": "Installazione di TotK",
|
||||
"launcher.python_missing": "I file di installazione sono incompleti: manca la cartella python accanto a TotK-Setup.exe. Estrai di nuovo l'intero archivio e avvia TotK-Setup.exe dalla cartella estratta.",
|
||||
"lang.ja": "Giapponese",
|
||||
"lang.en-US": "Inglese (USA)",
|
||||
"lang.en-GB": "Inglese (Regno Unito)",
|
||||
"lang.fr": "Francese",
|
||||
"lang.fr-CA": "Francese (Canada)",
|
||||
"lang.de": "Tedesco",
|
||||
"lang.it": "Italiano",
|
||||
"lang.es": "Spagnolo",
|
||||
"lang.es-419": "Spagnolo (America Latina)",
|
||||
"lang.nl": "Olandese",
|
||||
"lang.pt": "Portoghese",
|
||||
"lang.pt-BR": "Portoghese (Brasile)",
|
||||
"lang.ru": "Russo",
|
||||
"lang.ko": "Coreano",
|
||||
"lang.zh-Hans": "Cinese (semplificato)",
|
||||
"lang.zh-Hant": "Cinese (tradizionale)"
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
{
|
||||
"step.check": "コンピューターとゲームファイルの確認",
|
||||
"step.kit": "ビルドキットをゲームフォルダーにコピー",
|
||||
"step.fonts": "システムフォントの抽出",
|
||||
"step.extract": "ゲームの展開",
|
||||
"step.lift": "ゲームコードの C への変換",
|
||||
"step.compile": "{game_exe} のコンパイル",
|
||||
"step.prepare": "シェーダーの準備",
|
||||
"step.pc_prompts": "キーボードとマウスのボタン表示の作成",
|
||||
"step.shapes": "ディスプレイに合わせたゲーム画面のレイアウト",
|
||||
"step.dlss": "NVIDIA DLSS のダウンロード",
|
||||
"step.cleanup": "後片付け",
|
||||
"phase.check.host": "プロセッサーとグラフィックカードを確認しています",
|
||||
"phase.check.verify": "インストール済みのファイルを確認しています",
|
||||
"phase.check.verify_romfs": "インストール済みのゲームデータを確認しています",
|
||||
"phase.check.inputs": "キーでゲームファイルを開いています",
|
||||
"phase.check.unpack_base": "圧縮されたベースゲームを展開しています",
|
||||
"phase.check.unpack_update": "圧縮されたアップデートを展開しています",
|
||||
"phase.check.versions": "ゲームのバージョンを確認しています",
|
||||
"phase.kit.copy": "コード MOD 用にゲームが自身を再ビルドするためのツールをコピーしています",
|
||||
"phase.fonts.extract": "ファームウェアから共有フォントを抽出しています",
|
||||
"phase.fonts.copy": "共有フォントをインストール先フォルダーにコピーしています",
|
||||
"phase.extract.hash_base": "本編のチェックサムを計算しています",
|
||||
"phase.extract.hash_update": "アップデートのチェックサムを計算しています",
|
||||
"phase.extract.exefs": "ゲームコードを抽出しています",
|
||||
"phase.extract.copy": "ゲームデータをコピーしています",
|
||||
"phase.extract.merge": "ゲームデータにアップデートを適用しています",
|
||||
"phase.extract.diagnose": "破損したゲームファイルを探しています",
|
||||
"phase.extract.index": "ゲームデータを検証しています",
|
||||
"phase.lift.discover": "関数を探しています",
|
||||
"phase.lift.emit": "C コードを書き出しています",
|
||||
"phase.compile.compile": "コンパイルしています",
|
||||
"phase.compile.link": "{game_exe} をリンクしています",
|
||||
"phase.prepare.romfs_patches": "60 fps 用のゲームデータパッチを書き出しています",
|
||||
"phase.pc_prompts.draw": "totk.ini の割り当てからキーとマウスボタンの表示を作成しています",
|
||||
"phase.prepare.seed": "ゲームデータからシェーダーを読み込んでいます",
|
||||
"phase.prepare.translate": "シェーダーを変換しています",
|
||||
"phase.prepare.libraries": "グラフィックドライバー用にシェーダーをビルドしています",
|
||||
"phase.prepare.pack": "シェーダーキャッシュを 1 つのファイルにまとめています",
|
||||
"phase.shapes.layouts": "画面の形ごとに画面レイアウトとボタン表示を書き込んでいます",
|
||||
"phase.dlss.download": "NVIDIA の DLSS SDK から nvngx_dlss.dll をダウンロードしています",
|
||||
"phase.cleanup.ini": "totk.ini を書き込んでいます",
|
||||
"phase.cleanup.temp": "一時ファイルを削除しています",
|
||||
"cli.usage": "コマンドラインが無効です: {detail}",
|
||||
"internal": "予期しないエラー ({exception}): {detail}",
|
||||
"state.unreadable": "{path} を読み取れません。別のフォルダーを選ぶか、そのファイルを削除してください。",
|
||||
"state.newer_format": "{path} は新しいバージョンのインストーラーで書き込まれています。そのインストーラーか別のフォルダーを使ってください。",
|
||||
"state.output_changed": "手順「{step}」でインストールしたファイルが作成後に変更されています。その手順をもう一度実行します。",
|
||||
"check.release_incomplete": "インストーラーのフォルダーが不完全です。不足: {paths}。リリースをもう一度展開してください。",
|
||||
"check.dest_not_folder": "インストール先 {path} はフォルダーではなくファイルです。",
|
||||
"check.dest_not_empty": "インストール先フォルダー {path} は空ではなく、以前のインストールも含まれていません。空のフォルダーを選んでください。",
|
||||
"check.lang_missing": "ゲームの言語を選んでください。",
|
||||
"check.lang_unknown": "不明な言語「{lang}」です。使用できる言語: {known}。",
|
||||
"check.toolchain_broken": "同梱のコンパイラーが動作しません: {detail}",
|
||||
"check.glibc_old": "このシステムの C ライブラリは glibc {version} です。セットアップのコンパイラーには {need} 以降が必要です (Ubuntu 22.04、Debian 12、Fedora 35、SteamOS 3 以降にあります)。システムを更新すると解決します。",
|
||||
"check.host_probe_failed": "コンピューターの確認を実行できませんでした (終了コード {code})。",
|
||||
"check.cpu_too_old": "このプロセッサーは、ゲームのビルド対象となる最も古いレベルである x86-64-v2 (SSE4.2、POPCNT、CMPXCHG16B) に対応していません。Intel Nehalem (2008 年) または AMD Bulldozer (2011 年) 以降が対応しています。",
|
||||
"check.vulkan_missing": "Vulkan ドライバーがインストールされていません。グラフィックカードの最新ドライバーをインストールしてください。",
|
||||
"check.vulkan_no_device": "Vulkan がグラフィックカードを見つけられません。グラフィックカードの最新ドライバーをインストールしてください。",
|
||||
"check.vulkan_too_old": "このゲームには Vulkan 1.3 対応のグラフィックカードが必要です。見つかったもの: {devices}。グラフィックドライバーを更新してください。",
|
||||
"check.no_display": "シェーダーの準備にはディスプレイが必要です。デスクトップのセッションからセットアップを実行するか、DISPLAY=:0 を export してください(Steam Deck のゲームモードでは XDG_RUNTIME_DIR=/run/user/1000 も)。",
|
||||
"check.inputs_needed": "ゲームファイルが必要です。本編、1.1.0・1.2.1・1.4.3 のいずれかのアップデート、prod.keys を選んでください。",
|
||||
"check.input_missing": "ファイルが見つかりません ({input}): {path}",
|
||||
"check.keys_unreadable": "キーファイルを読み取れません。prod.keys ファイルを選んでください。",
|
||||
"check.keys_no_header_key": "キーファイルに header_key がありません。本体から prod.keys をもう一度吸い出してください。",
|
||||
"check.keys_wrong": "このキーでは{input}のファイルを開けません。ご自分の本体の prod.keys を使ってください。",
|
||||
"check.keys_too_old": "キーファイルが{input}のファイルには古すぎます (キー世代 {generation} が必要)。より新しいファームウェアの本体から prod.keys を吸い出してください。",
|
||||
"check.not_game_file": "{input}のファイルは XCI、NSP、XCZ、NSZ のいずれのゲームファイルでもありません。",
|
||||
"check.file_unreadable": "{input}のファイルを読み取れません: {detail}",
|
||||
"check.unpack_failed": "圧縮ファイル {input} を展開できませんでした: {detail}",
|
||||
"check.ticket_personalized": "{input}のファイルには個人用チケットが含まれています。共通チケットが必要です。",
|
||||
"check.ticket_missing": "{input}のファイルには、内容に必要なチケットがありません。",
|
||||
"check.base_not_totk": "本編のファイルは ゼルダの伝説 ティアーズ オブ ザ キングダム ではありません ({detail})。",
|
||||
"check.base_is_update": "本編のファイルはアップデートです。ここには本編の NSP または XCI (バージョン 1.0.0) を選び、このファイルはアップデートとして選んでください。",
|
||||
"check.base_combined": "本編のファイルに複数のパッケージ (本編、アップデート、DLC が 1 つのファイル) が含まれています。ゲームだけを含む本編のダンプを選んでください。",
|
||||
"check.update_not_nsp": "アップデートは NSP または NSZ ファイルである必要があります。",
|
||||
"check.update_is_base": "アップデートのファイルに本編が含まれています。1.1.0・1.2.1・1.4.3 のいずれかのアップデートの NSP を選んでください。",
|
||||
"check.update_not_totk": "アップデートのファイルは ティアーズ オブ ザ キングダム のアップデートではありません ({detail})。",
|
||||
"check.exefs_failed": "{input}のファイルのゲームコードが検査に合格しませんでした。{log} を参照してください。",
|
||||
"check.input_damaged": "{input}のファイルが破損しているか不完全です: {path} ({detail})。そのファイルを元の場所からもう一度コピーするか、もう一度吸い出してから、セットアップを再実行してください。",
|
||||
"check.base_wrong_version": "本編がバージョン 1.0.0 ではありません ({modules} が異なります)。",
|
||||
"check.update_wrong_version": "アップデートのバージョンは {found} です。このリリースは {wanted} に対応しています。",
|
||||
"check.disk_space": "{path} の空き容量が足りません: {need_gb} GB 必要、空き {free_gb} GB。",
|
||||
"check.firmware_missing": "ファームウェアフォルダー {path} が存在しません。ファームウェアの Contents/registered フォルダーを選んでください。",
|
||||
"check.firmware_empty": "ファームウェアフォルダー {path} に NCA ファイルがありません。ファームウェアの Contents/registered フォルダーを選んでください。",
|
||||
"check.fonts_keys_needed": "この言語用の共有フォントがまだインストールされていません。セットアップがファームウェアから抽出できるよう、prod.keys を選んでください。",
|
||||
"extract.exefs_mismatch": "抽出したゲームコードがバージョン {version} と一致しません ({modules})。",
|
||||
"extract.romfs_merge_failed": "ゲームデータへのアップデートの適用に失敗しました: {detail}。詳細: {log}",
|
||||
"extract.romfs_mismatch": "抽出したゲームデータがバージョン {version} と一致しません (サイズ {size}、チェックサム {sha256}...)。",
|
||||
"fonts.failed": "共有フォントの抽出に失敗しました (終了コード {code}): {detail}。詳細: {log}",
|
||||
"fonts.incomplete": "共有フォントの抽出で一部のファイルが書き込まれませんでした ({files})。",
|
||||
"fonts.copy_failed": "共有フォントを {path} にコピーできません: {detail}",
|
||||
"lift.failed": "ゲームコードの変換に失敗しました (終了コード {code})。詳細: {log}",
|
||||
"compile.failed": "{game_exe} のコンパイルに失敗しました (終了コード {code})。詳細: {log}",
|
||||
"compile.exe_in_use": "{path} は使用中です。ゲームを閉じてから、インストーラーをもう一度実行してください。",
|
||||
"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": "シェーダーの一覧がありません。",
|
||||
"prepare.romfs_patches_failed": "ゲームデータパッチの書き出しに失敗しました (終了コード {code})。詳細: {log}",
|
||||
"prepare.shaders_failed": "シェーダーの準備に失敗しました (終了コード {code})。詳細: {log}",
|
||||
"cleanup.romfs_unreadable": "インストール後、{path} のゲームデータが見つからないか読み取れません。Windows を再起動し、同じフォルダーでインストーラーをもう一度実行してください。ゲームデータだけを再展開し、それ以外は保持します。",
|
||||
"prepare.pack_failed": "シェーダーキャッシュのまとめに失敗しました (終了コード {code})。詳細: {log}",
|
||||
"cleanup.ini_failed": "totk.ini を書き込めません: {detail}",
|
||||
"warn.lang_needs_fonts": "{lang}のテキストには Switch のシステムフォントが必要ですが、指定されていません。追加されるまで、この言語ではゲームが起動しません。ファームウェアフォルダー (Contents/registered) を選ぶか、docs/installer.md の「Switch system fonts」を参照してください。",
|
||||
"warn.npdm_differs": "main.npdm が参照用の {version} ダンプと異なります。コードモジュールのみを使用します。",
|
||||
"warn.cheats_skipped": "mods フォルダーにあるゲームコードを変更するチートをビルドできませんでした。チートなしでゲームをインストールします。詳細: {log}",
|
||||
"warn.exefs_skipped": "Mod の ExeFS パッチ (.ips、.pchtxt) をビルドできませんでした。パッチなしでゲームをインストールします。詳細: {log}",
|
||||
"warn.plugins_skipped": "MOD のコードプラグイン (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})。セットアップはそれを残します。",
|
||||
"warn.dlss_download_failed": "NVIDIA DLSS を {url} からダウンロードできませんでした: {detail}。ゲームはなしで動作します。次回のセットアップ実行時に再試行します。",
|
||||
"ui.title": "TotK セットアップ",
|
||||
"ui.rebuild_title": "Mod に合わせてゲームを再ビルドしています",
|
||||
"ui.start_game": "ゲームを開始",
|
||||
"ui.version": "バージョン {version}",
|
||||
"ui.intro": "お持ちのゲームファイルから、プレイ可能な ティアーズ オブ ザ キングダム のフォルダーを作成します。時間がかかりますが、実行は一度だけです。",
|
||||
"ui.notice": "このセットアップが作成するフォルダーにはゲームが含まれます。個人での使用に限り、共有やアップロードはしないでください。",
|
||||
"ui.keys_private": "キーファイルはその場で読み取られます。内容が表示、コピー、保存されることはありません。",
|
||||
"ui.base": "本編",
|
||||
"ui.update": "アップデート",
|
||||
"ui.keys": "prod.keys",
|
||||
"ui.firmware": "ファームウェア (任意)",
|
||||
"ui.game_language": "ゲームの言語",
|
||||
"ui.dest": "インストール先フォルダー",
|
||||
"ui.browse": "参照...",
|
||||
"ui.pick_game": "本編のファイルを選択",
|
||||
"ui.pick_update": "1.1.0・1.2.1・1.4.3 のアップデートファイルを選択",
|
||||
"ui.pick_keys": "prod.keys を選択",
|
||||
"ui.pick_firmware": "Switch のファームウェアフォルダー (Contents/registered) を選択",
|
||||
"ui.pick_dest": "インストール先フォルダーを選択",
|
||||
"ui.firmware_help": "中国語、韓国語、繁体字中国語のテキスト用: ファームウェアの Contents/registered フォルダー (例: Ryujinx や Yuzu のもの)。セットアップはそこから Switch のシステムフォントをインストール先フォルダーにコピーします。",
|
||||
"ui.dlss": "NVIDIA RTX グラフィックカード用に NVIDIA DLSS (nvngx_dlss.dll) をダウンロードする",
|
||||
"ui.dlss_help": "GitHub 上の NVIDIA の DLSS SDK から、NVIDIA の RTX SDK ライセンスのもとで取得します (github.com/NVIDIA/DLSS)。これで dlaa と DLSS の設定が機能します。ない場合、これらの設定は効果がありません。",
|
||||
"ui.compressed_help": "圧縮された NSZ / XCZ ファイルはそのまま使えます。セットアップが自分で展開します(ゲームデータの展開が終わるまで、展開後のファイルと同じだけの空き容量が必要です)。",
|
||||
"ui.section_files": "ゲームファイル",
|
||||
"ui.section_install": "インストール",
|
||||
"ui.more_details": "▸ 詳細を表示",
|
||||
"ui.fewer_details": "▾ 詳細を隠す",
|
||||
"ui.formats_help": "本編: NSP、XCI、NSZ または XCZ。アップデート: 1.1.0、1.2.1 または 1.4.3 (NSP または NSZ)。",
|
||||
"ui.type_game": "ゲームファイル (NSP、XCI、NSZ、XCZ)",
|
||||
"ui.type_keys": "キーファイル (*.keys)",
|
||||
"ui.type_all": "すべてのファイル",
|
||||
"ui.start": "開始",
|
||||
"ui.cancel": "キャンセル",
|
||||
"ui.cancelling": "キャンセルしています...",
|
||||
"ui.show_log": "ログを表示",
|
||||
"ui.hide_log": "ログを隠す",
|
||||
"ui.close": "閉じる",
|
||||
"ui.back": "戻る",
|
||||
"ui.open_folder": "フォルダーを開く",
|
||||
"ui.update_mode": "このフォルダーには以前のインストールがあります。セットアップはそれを続行または更新します。ゲームファイルは再度必要な場合にのみ求められます。",
|
||||
"ui.need_dest": "インストール先フォルダーを選んでください。",
|
||||
"ui.need_base": "本編のファイルを選んでください。",
|
||||
"ui.need_update": "1.1.0・1.2.1・1.4.3 のアップデートファイルを選んでください。",
|
||||
"ui.need_keys": "prod.keys ファイルを選んでください。",
|
||||
"ui.need_lang": "ゲームの言語を選んでください。",
|
||||
"ui.missing_base": "本編のファイルが存在しません。",
|
||||
"ui.missing_update": "アップデートのファイルが存在しません。",
|
||||
"ui.missing_keys": "キーファイルが存在しません。",
|
||||
"ui.missing_firmware": "ファームウェアフォルダーが存在しません。",
|
||||
"ui.running_install": "インストール中",
|
||||
"ui.running_resume": "以前のセットアップを続行中",
|
||||
"ui.running_update": "インストールを更新中",
|
||||
"ui.state_started": "開始",
|
||||
"ui.state_done": "完了",
|
||||
"ui.state_skipped": "スキップ",
|
||||
"ui.state_pending": "待機中",
|
||||
"ui.state_running": "実行中",
|
||||
"ui.state_failed": "失敗",
|
||||
"ui.log_warning": "警告",
|
||||
"ui.log_error": "エラー",
|
||||
"ui.log_space": "必要な容量: {need} GB、空き: {free} GB",
|
||||
"ui.log_end": "終了",
|
||||
"ui.result_ok": "ゲームの準備ができました",
|
||||
"ui.result_failed": "セットアップに失敗しました",
|
||||
"ui.result_cancelled": "セットアップはキャンセルされました",
|
||||
"ui.done_text": "{dest} から {game_exe} を起動してください。セットアップと選んだゲームファイルはもう必要ありません。",
|
||||
"ui.cancelled_text": "完了した手順は保持されます。続けるには、同じフォルダーでセットアップをもう一度開始してください。",
|
||||
"ui.log_file": "ログファイル: {path}",
|
||||
"ui.process_died": "セットアップが予期せず停止しました (終了コード {code})。",
|
||||
"ui.confirm_cancel": "セットアップを実行中です。キャンセルしてウィンドウを閉じますか?",
|
||||
"ui.space_one": "{path} に必要な空き容量: {need} GB (空き: {free} GB)。",
|
||||
"ui.space_two": "{path} に必要な空き容量: {need} GB (空き: {free} GB)、{temp}: {temp_need} GB (空き: {temp_free} GB)。",
|
||||
"ui.amount_bytes": "{done} / {total} GB",
|
||||
"ui.amount_chunks": "{done} / {total} パート",
|
||||
"ui.amount_objects": "{done} / {total} ファイル",
|
||||
"ui.amount_shaders": "{done} / {total} シェーダー",
|
||||
"ui.amount_other": "{done} / {total} {unit}",
|
||||
"ui.seconds": "{n} 秒",
|
||||
"param.input.base": "本編",
|
||||
"param.input.update": "アップデート",
|
||||
"param.input.keys": "キー",
|
||||
"launcher.title": "TotK セットアップ",
|
||||
"launcher.python_missing": "セットアップのファイルが不完全です。TotK-Setup.exe の隣にある python フォルダーがありません。アーカイブ全体をもう一度展開し、展開したフォルダーから TotK-Setup.exe を起動してください。",
|
||||
"lang.ja": "日本語",
|
||||
"lang.en-US": "英語 (米国)",
|
||||
"lang.en-GB": "英語 (英国)",
|
||||
"lang.fr": "フランス語",
|
||||
"lang.fr-CA": "フランス語 (カナダ)",
|
||||
"lang.de": "ドイツ語",
|
||||
"lang.it": "イタリア語",
|
||||
"lang.es": "スペイン語",
|
||||
"lang.es-419": "スペイン語 (中南米)",
|
||||
"lang.nl": "オランダ語",
|
||||
"lang.pt": "ポルトガル語",
|
||||
"lang.pt-BR": "ポルトガル語 (ブラジル)",
|
||||
"lang.ru": "ロシア語",
|
||||
"lang.ko": "韓国語",
|
||||
"lang.zh-Hans": "中国語 (簡体字)",
|
||||
"lang.zh-Hant": "中国語 (繁体字)"
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
{
|
||||
"step.check": "컴퓨터와 게임 파일 확인",
|
||||
"step.kit": "빌드 키트를 게임 폴더로 복사",
|
||||
"step.fonts": "시스템 글꼴 추출",
|
||||
"step.extract": "게임 추출",
|
||||
"step.lift": "게임 코드를 C로 변환",
|
||||
"step.compile": "{game_exe} 컴파일",
|
||||
"step.prepare": "셰이더 준비",
|
||||
"step.pc_prompts": "키보드 및 마우스 버튼 표시 그리기",
|
||||
"step.shapes": "모니터에 맞게 게임 화면 배치",
|
||||
"step.dlss": "NVIDIA DLSS 다운로드",
|
||||
"step.cleanup": "정리",
|
||||
"phase.check.host": "프로세서와 그래픽 카드를 확인하는 중",
|
||||
"phase.check.verify": "이미 설치된 파일을 확인하는 중",
|
||||
"phase.check.verify_romfs": "설치된 게임 데이터를 확인하는 중",
|
||||
"phase.check.inputs": "키로 게임 파일을 여는 중",
|
||||
"phase.check.unpack_base": "압축된 기본 게임의 압축을 푸는 중",
|
||||
"phase.check.unpack_update": "압축된 업데이트의 압축을 푸는 중",
|
||||
"phase.check.versions": "게임 버전을 확인하는 중",
|
||||
"phase.kit.copy": "코드 모드용으로 게임이 스스로 다시 빌드할 때 쓰는 도구 복사 중",
|
||||
"phase.fonts.extract": "펌웨어에서 공유 글꼴을 추출하는 중",
|
||||
"phase.fonts.copy": "공유 글꼴을 설치 폴더로 복사하는 중",
|
||||
"phase.extract.hash_base": "기본 게임의 체크섬을 계산하는 중",
|
||||
"phase.extract.hash_update": "업데이트의 체크섬을 계산하는 중",
|
||||
"phase.extract.exefs": "게임 코드를 추출하는 중",
|
||||
"phase.extract.copy": "게임 데이터를 복사하는 중",
|
||||
"phase.extract.merge": "게임 데이터에 업데이트를 적용하는 중",
|
||||
"phase.extract.diagnose": "손상된 게임 파일을 찾는 중",
|
||||
"phase.extract.index": "게임 데이터를 검증하는 중",
|
||||
"phase.lift.discover": "함수를 찾는 중",
|
||||
"phase.lift.emit": "C 코드를 작성하는 중",
|
||||
"phase.compile.compile": "컴파일하는 중",
|
||||
"phase.compile.link": "{game_exe} 링크 중",
|
||||
"phase.prepare.romfs_patches": "60 fps 게임 데이터 패치를 작성하는 중",
|
||||
"phase.pc_prompts.draw": "totk.ini의 할당에 따라 키와 마우스 버튼 표시 그리는 중",
|
||||
"phase.prepare.seed": "게임 데이터에서 셰이더를 읽는 중",
|
||||
"phase.prepare.translate": "셰이더를 변환하는 중",
|
||||
"phase.prepare.libraries": "그래픽 드라이버용 셰이더를 빌드하는 중",
|
||||
"phase.prepare.pack": "셰이더 캐시를 파일 하나로 묶는 중",
|
||||
"phase.shapes.layouts": "화면 형태마다 화면 레이아웃과 버튼 표시 쓰는 중",
|
||||
"phase.dlss.download": "NVIDIA DLSS SDK에서 nvngx_dlss.dll을 다운로드하는 중",
|
||||
"phase.cleanup.ini": "totk.ini를 쓰는 중",
|
||||
"phase.cleanup.temp": "임시 파일을 삭제하는 중",
|
||||
"cli.usage": "잘못된 명령줄: {detail}",
|
||||
"internal": "예기치 않은 오류({exception}): {detail}",
|
||||
"state.unreadable": "{path}을(를) 읽을 수 없습니다. 다른 폴더를 선택하거나 해당 파일을 삭제하세요.",
|
||||
"state.newer_format": "{path}은(는) 더 새로운 설치 프로그램이 작성했습니다. 그 설치 프로그램이나 다른 폴더를 사용하세요.",
|
||||
"state.output_changed": "'{step}' 단계에서 설치한 파일이 만들어진 후 변경되었습니다. 해당 단계를 다시 실행합니다.",
|
||||
"check.release_incomplete": "설치 프로그램 폴더가 불완전합니다. 누락: {paths}. 릴리스 압축을 다시 푸세요.",
|
||||
"check.dest_not_folder": "설치 위치 {path}은(는) 폴더가 아니라 파일입니다.",
|
||||
"check.dest_not_empty": "설치 폴더 {path}이(가) 비어 있지 않으며 이전 설치도 없습니다. 빈 폴더를 선택하세요.",
|
||||
"check.lang_missing": "게임 언어를 선택하세요.",
|
||||
"check.lang_unknown": "알 수 없는 언어 '{lang}'. 사용 가능: {known}.",
|
||||
"check.toolchain_broken": "포함된 컴파일러가 작동하지 않습니다: {detail}",
|
||||
"check.glibc_old": "이 시스템의 C 라이브러리는 glibc {version}입니다. 설치 프로그램의 컴파일러에는 {need} 이상이 필요합니다(Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 이상에 있음). 시스템을 업데이트하면 해결됩니다.",
|
||||
"check.host_probe_failed": "컴퓨터 확인이 실행되지 않았습니다(종료 코드 {code}).",
|
||||
"check.cpu_too_old": "이 프로세서에는 게임이 빌드되는 가장 오래된 수준인 x86-64-v2(SSE4.2, POPCNT, CMPXCHG16B)가 없습니다. Intel Nehalem(2008) 또는 AMD Bulldozer(2011) 이후 프로세서에 있습니다.",
|
||||
"check.vulkan_missing": "Vulkan 드라이버가 설치되어 있지 않습니다. 그래픽 카드의 최신 드라이버를 설치하세요.",
|
||||
"check.vulkan_no_device": "Vulkan이 그래픽 카드를 찾지 못했습니다. 그래픽 카드의 최신 드라이버를 설치하세요.",
|
||||
"check.vulkan_too_old": "게임에는 Vulkan 1.3을 지원하는 그래픽 카드가 필요합니다. 발견된 장치: {devices}. 그래픽 드라이버를 업데이트하세요.",
|
||||
"check.no_display": "셰이더를 준비하려면 디스플레이가 필요합니다. 데스크톱 세션에서 설치 프로그램을 실행하거나 DISPLAY=:0 을 export 하세요(게임 모드의 Steam Deck에서는 XDG_RUNTIME_DIR=/run/user/1000 도).",
|
||||
"check.inputs_needed": "게임 파일이 필요합니다. 기본 게임, 1.1.0 또는 1.2.1 또는 1.4.3 업데이트, prod.keys를 선택하세요.",
|
||||
"check.input_missing": "파일을 찾을 수 없음({input}): {path}",
|
||||
"check.keys_unreadable": "키 파일을 읽을 수 없습니다. prod.keys 파일을 선택하세요.",
|
||||
"check.keys_no_header_key": "키 파일에 header_key가 없습니다. 본체에서 prod.keys를 다시 덤프하세요.",
|
||||
"check.keys_wrong": "키로 {input} 파일을 열 수 없습니다. 본인 본체의 prod.keys를 사용하세요.",
|
||||
"check.keys_too_old": "키 파일이 {input} 파일에 비해 너무 오래되었습니다(키 세대 {generation} 필요). 더 새로운 펌웨어의 본체에서 prod.keys를 덤프하세요.",
|
||||
"check.not_game_file": "{input} 파일은 XCI, NSP, XCZ 또는 NSZ 게임 파일이 아닙니다.",
|
||||
"check.file_unreadable": "{input} 파일을 읽을 수 없습니다: {detail}",
|
||||
"check.unpack_failed": "압축 파일 {input}의 압축을 풀 수 없습니다: {detail}",
|
||||
"check.ticket_personalized": "{input} 파일에 개인화된 티켓이 들어 있습니다. 공통 티켓이 필요합니다.",
|
||||
"check.ticket_missing": "{input} 파일에 콘텐츠에 필요한 티켓이 없습니다.",
|
||||
"check.base_not_totk": "기본 게임 파일이 젤다의 전설 티어스 오브 더 킹덤이 아닙니다({detail}).",
|
||||
"check.base_is_update": "기본 게임 파일이 업데이트입니다. 여기에는 기본 게임 NSP 또는 XCI(버전 1.0.0)를 선택하고 이 파일은 업데이트로 선택하세요.",
|
||||
"check.base_combined": "기본 게임 파일에 여러 패키지(기본 게임, 업데이트 또는 DLC가 한 파일에)가 들어 있습니다. 게임만 들어 있는 기본 게임 덤프를 선택하세요.",
|
||||
"check.update_not_nsp": "업데이트는 NSP 또는 NSZ 파일이어야 합니다.",
|
||||
"check.update_is_base": "업데이트 파일에 기본 게임이 들어 있습니다. 1.1.0 또는 1.2.1 또는 1.4.3 업데이트 NSP를 선택하세요.",
|
||||
"check.update_not_totk": "업데이트 파일이 티어스 오브 더 킹덤 업데이트가 아닙니다({detail}).",
|
||||
"check.exefs_failed": "{input} 파일의 게임 코드가 검사를 통과하지 못했습니다. {log}을(를) 참조하세요.",
|
||||
"check.input_damaged": "{input} 파일이 손상되었거나 불완전합니다: {path}({detail}). 원본에서 파일을 다시 복사하거나 다시 덤프한 다음 설치를 다시 실행하세요.",
|
||||
"check.base_wrong_version": "기본 게임이 버전 1.0.0이 아닙니다({modules} 다름).",
|
||||
"check.update_wrong_version": "업데이트 버전은 {found}입니다. 이 릴리스는 {wanted}을(를) 사용합니다.",
|
||||
"check.disk_space": "{path}의 여유 공간이 부족합니다. {need_gb} GB 필요, {free_gb} GB 사용 가능.",
|
||||
"check.firmware_missing": "펌웨어 폴더 {path}이(가) 없습니다. 펌웨어의 Contents/registered 폴더를 선택하세요.",
|
||||
"check.firmware_empty": "펌웨어 폴더 {path}에 NCA 파일이 없습니다. 펌웨어의 Contents/registered 폴더를 선택하세요.",
|
||||
"check.fonts_keys_needed": "이 언어의 공유 글꼴이 아직 설치되지 않았습니다. 설치 프로그램이 펌웨어에서 추출할 수 있도록 prod.keys를 선택하세요.",
|
||||
"extract.exefs_mismatch": "추출한 게임 코드가 버전 {version}과(와) 일치하지 않습니다({modules}).",
|
||||
"extract.romfs_merge_failed": "게임 데이터에 업데이트를 적용하지 못했습니다: {detail}. 자세히: {log}",
|
||||
"extract.romfs_mismatch": "추출한 게임 데이터가 버전 {version}과(와) 일치하지 않습니다(크기 {size}, 체크섬 {sha256}...).",
|
||||
"fonts.failed": "공유 글꼴 추출에 실패했습니다(종료 코드 {code}): {detail}. 자세히: {log}",
|
||||
"fonts.incomplete": "공유 글꼴 추출에서 일부 파일이 작성되지 않았습니다({files}).",
|
||||
"fonts.copy_failed": "공유 글꼴을 {path}(으)로 복사할 수 없습니다: {detail}",
|
||||
"lift.failed": "게임 코드 변환에 실패했습니다(종료 코드 {code}). 자세히: {log}",
|
||||
"compile.failed": "{game_exe} 컴파일에 실패했습니다(종료 코드 {code}). 자세히: {log}",
|
||||
"compile.exe_in_use": "{path}이(가) 사용 중입니다. 게임을 닫고 설치 프로그램을 다시 실행하세요.",
|
||||
"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": "셰이더 목록이 없습니다.",
|
||||
"prepare.romfs_patches_failed": "게임 데이터 패치 작성에 실패했습니다(종료 코드 {code}). 자세히: {log}",
|
||||
"prepare.shaders_failed": "셰이더 준비에 실패했습니다(종료 코드 {code}). 자세히: {log}",
|
||||
"cleanup.romfs_unreadable": "설치 후 {path}의 게임 데이터가 없거나 읽을 수 없습니다. Windows를 다시 시작한 다음 같은 폴더로 설치 프로그램을 다시 실행하세요. 게임 데이터만 다시 추출하고 나머지는 유지합니다.",
|
||||
"prepare.pack_failed": "셰이더 캐시 묶기에 실패했습니다(종료 코드 {code}). 자세히: {log}",
|
||||
"cleanup.ini_failed": "totk.ini를 쓸 수 없습니다: {detail}",
|
||||
"warn.lang_needs_fonts": "{lang} 텍스트에는 Switch 시스템 글꼴이 필요하지만 지정되지 않았습니다. 글꼴을 추가할 때까지 이 언어로는 게임이 시작되지 않습니다. 펌웨어 폴더(Contents/registered)를 선택하거나 docs/installer.md의 \"Switch system fonts\"를 참조하세요.",
|
||||
"warn.npdm_differs": "main.npdm이 참조용 {version} 덤프와 다릅니다. 코드 모듈만 사용합니다.",
|
||||
"warn.cheats_skipped": "mods 폴더에서 게임 코드를 바꾸는 치트를 빌드할 수 없었습니다. 치트 없이 게임을 설치합니다. 자세히: {log}",
|
||||
"warn.exefs_skipped": "모드의 ExeFS 패치(.ips, .pchtxt)를 빌드할 수 없었습니다. 패치 없이 게임을 설치합니다. 자세히: {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}). 설치 프로그램은 그대로 둡니다.",
|
||||
"warn.dlss_download_failed": "{url}에서 NVIDIA DLSS를 다운로드할 수 없습니다: {detail}. 게임은 없이도 실행되며, 다음 설치 실행 때 다시 시도합니다.",
|
||||
"ui.title": "TotK 설치",
|
||||
"ui.rebuild_title": "모드에 맞게 게임을 다시 빌드하는 중",
|
||||
"ui.start_game": "게임 시작",
|
||||
"ui.version": "버전 {version}",
|
||||
"ui.intro": "보유한 게임 파일로 플레이 가능한 티어스 오브 더 킹덤 폴더를 만듭니다. 시간이 걸리며 한 번만 실행됩니다.",
|
||||
"ui.notice": "이 설치 프로그램이 만드는 폴더에는 게임이 들어 있습니다. 개인 용도로만 사용하고 공유하거나 업로드하지 마세요.",
|
||||
"ui.keys_private": "키 파일은 그 자리에서 읽습니다. 내용은 표시, 복사, 저장되지 않습니다.",
|
||||
"ui.base": "기본 게임",
|
||||
"ui.update": "업데이트",
|
||||
"ui.keys": "prod.keys",
|
||||
"ui.firmware": "펌웨어(선택 사항)",
|
||||
"ui.game_language": "게임 언어",
|
||||
"ui.dest": "설치 폴더",
|
||||
"ui.browse": "찾아보기...",
|
||||
"ui.pick_game": "기본 게임 파일 선택",
|
||||
"ui.pick_update": "1.1.0 또는 1.2.1 또는 1.4.3 업데이트 파일 선택",
|
||||
"ui.pick_keys": "prod.keys 선택",
|
||||
"ui.pick_firmware": "Switch 펌웨어 폴더 선택(Contents/registered)",
|
||||
"ui.pick_dest": "설치 폴더 선택",
|
||||
"ui.firmware_help": "중국어, 한국어, 번체 중국어 텍스트용: 펌웨어의 Contents/registered 폴더(예: Ryujinx 또는 Yuzu의 폴더). 설치 프로그램이 여기에서 Switch 시스템 글꼴을 설치 폴더로 복사합니다.",
|
||||
"ui.dlss": "NVIDIA RTX 그래픽 카드용 NVIDIA DLSS (nvngx_dlss.dll) 다운로드",
|
||||
"ui.dlss_help": "GitHub의 NVIDIA DLSS SDK에서, NVIDIA RTX SDK 라이선스에 따라 받습니다(github.com/NVIDIA/DLSS). 이 파일이 있어야 dlaa 및 DLSS 설정이 작동하며, 없으면 아무 효과가 없습니다.",
|
||||
"ui.compressed_help": "압축된 NSZ 및 XCZ 파일은 그대로 사용할 수 있습니다. 설치 프로그램이 직접 압축을 풉니다(게임 데이터를 추출할 때까지 압축을 푼 파일만큼의 여유 공간이 필요합니다).",
|
||||
"ui.section_files": "게임 파일",
|
||||
"ui.section_install": "설치",
|
||||
"ui.more_details": "▸ 자세히 보기",
|
||||
"ui.fewer_details": "▾ 자세히 숨기기",
|
||||
"ui.formats_help": "기본 게임: NSP, XCI, NSZ 또는 XCZ. 업데이트: 1.1.0, 1.2.1 또는 1.4.3(NSP 또는 NSZ).",
|
||||
"ui.type_game": "게임 파일(NSP, XCI, NSZ, XCZ)",
|
||||
"ui.type_keys": "키 파일(*.keys)",
|
||||
"ui.type_all": "모든 파일",
|
||||
"ui.start": "시작",
|
||||
"ui.cancel": "취소",
|
||||
"ui.cancelling": "취소하는 중...",
|
||||
"ui.show_log": "로그 보기",
|
||||
"ui.hide_log": "로그 숨기기",
|
||||
"ui.close": "닫기",
|
||||
"ui.back": "뒤로",
|
||||
"ui.open_folder": "폴더 열기",
|
||||
"ui.update_mode": "이 폴더에 이전 설치가 있습니다. 설치 프로그램이 이를 이어서 진행하거나 업데이트합니다. 게임 파일은 다시 필요한 경우에만 요청합니다.",
|
||||
"ui.need_dest": "설치 폴더를 선택하세요.",
|
||||
"ui.need_base": "기본 게임 파일을 선택하세요.",
|
||||
"ui.need_update": "1.1.0 또는 1.2.1 또는 1.4.3 업데이트 파일을 선택하세요.",
|
||||
"ui.need_keys": "prod.keys 파일을 선택하세요.",
|
||||
"ui.need_lang": "게임 언어를 선택하세요.",
|
||||
"ui.missing_base": "기본 게임 파일이 없습니다.",
|
||||
"ui.missing_update": "업데이트 파일이 없습니다.",
|
||||
"ui.missing_keys": "키 파일이 없습니다.",
|
||||
"ui.missing_firmware": "펌웨어 폴더가 없습니다.",
|
||||
"ui.running_install": "설치 중",
|
||||
"ui.running_resume": "이전 설치를 이어서 진행하는 중",
|
||||
"ui.running_update": "설치를 업데이트하는 중",
|
||||
"ui.state_started": "시작됨",
|
||||
"ui.state_done": "완료",
|
||||
"ui.state_skipped": "건너뜀",
|
||||
"ui.state_pending": "대기 중",
|
||||
"ui.state_running": "실행 중",
|
||||
"ui.state_failed": "실패",
|
||||
"ui.log_warning": "경고",
|
||||
"ui.log_error": "오류",
|
||||
"ui.log_space": "필요한 공간: {need} GB, 여유: {free} GB",
|
||||
"ui.log_end": "끝남",
|
||||
"ui.result_ok": "게임이 준비되었습니다",
|
||||
"ui.result_failed": "설치에 실패했습니다",
|
||||
"ui.result_cancelled": "설치가 취소되었습니다",
|
||||
"ui.done_text": "{dest}에서 {game_exe}을(를) 실행하세요. 설치 프로그램과 선택한 게임 파일은 더 이상 필요하지 않습니다.",
|
||||
"ui.cancelled_text": "완료된 단계는 유지됩니다. 계속하려면 같은 폴더로 설치를 다시 시작하세요.",
|
||||
"ui.log_file": "로그 파일: {path}",
|
||||
"ui.process_died": "설치가 예기치 않게 중지되었습니다(종료 코드 {code}).",
|
||||
"ui.confirm_cancel": "설치가 실행 중입니다. 취소하고 창을 닫을까요?",
|
||||
"ui.space_one": "{path}에 필요한 여유 공간: {need} GB(여유: {free} GB).",
|
||||
"ui.space_two": "{path}에 필요한 여유 공간: {need} GB(여유: {free} GB), {temp}: {temp_need} GB(여유: {temp_free} GB).",
|
||||
"ui.amount_bytes": "{done} / {total} GB",
|
||||
"ui.amount_chunks": "{done} / {total} 부분",
|
||||
"ui.amount_objects": "{done} / {total} 파일",
|
||||
"ui.amount_shaders": "{done} / {total} 셰이더",
|
||||
"ui.amount_other": "{done} / {total} {unit}",
|
||||
"ui.seconds": "{n}초",
|
||||
"param.input.base": "기본 게임",
|
||||
"param.input.update": "업데이트",
|
||||
"param.input.keys": "키",
|
||||
"launcher.title": "TotK 설치",
|
||||
"launcher.python_missing": "설치 파일이 불완전합니다. TotK-Setup.exe 옆의 python 폴더가 없습니다. 전체 압축 파일을 다시 풀고 압축을 푼 폴더에서 TotK-Setup.exe를 실행하세요.",
|
||||
"lang.ja": "일본어",
|
||||
"lang.en-US": "영어(미국)",
|
||||
"lang.en-GB": "영어(영국)",
|
||||
"lang.fr": "프랑스어",
|
||||
"lang.fr-CA": "프랑스어(캐나다)",
|
||||
"lang.de": "독일어",
|
||||
"lang.it": "이탈리아어",
|
||||
"lang.es": "스페인어",
|
||||
"lang.es-419": "스페인어(중남미)",
|
||||
"lang.nl": "네덜란드어",
|
||||
"lang.pt": "포르투갈어",
|
||||
"lang.pt-BR": "포르투갈어(브라질)",
|
||||
"lang.ru": "러시아어",
|
||||
"lang.ko": "한국어",
|
||||
"lang.zh-Hans": "중국어(간체)",
|
||||
"lang.zh-Hant": "중국어(번체)"
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
{
|
||||
"step.check": "Computer en spelbestanden controleren",
|
||||
"step.kit": "De bouwkit naar de spelmap kopiëren",
|
||||
"step.fonts": "Systeemlettertypen uitpakken",
|
||||
"step.extract": "Spel uitpakken",
|
||||
"step.lift": "Spelcode naar C vertalen",
|
||||
"step.compile": "{game_exe} compileren",
|
||||
"step.prepare": "Shaders voorbereiden",
|
||||
"step.pc_prompts": "Toetsenbord- en muispictogrammen tekenen",
|
||||
"step.shapes": "De spelschermen voor je beeldschermen indelen",
|
||||
"step.dlss": "NVIDIA DLSS downloaden",
|
||||
"step.cleanup": "Opruimen",
|
||||
"phase.check.host": "Processor en videokaart controleren",
|
||||
"phase.check.verify": "Al geïnstalleerde bestanden controleren",
|
||||
"phase.check.verify_romfs": "Geïnstalleerde spelgegevens controleren",
|
||||
"phase.check.inputs": "Spelbestanden openen met de sleutels",
|
||||
"phase.check.unpack_base": "Gecomprimeerd basisspel uitpakken",
|
||||
"phase.check.unpack_update": "Gecomprimeerde update uitpakken",
|
||||
"phase.check.versions": "Spelversies controleren",
|
||||
"phase.kit.copy": "De hulpmiddelen kopiëren waarmee het spel zichzelf opnieuw bouwt voor codemods",
|
||||
"phase.fonts.extract": "Gedeelde lettertypen uit de firmware uitpakken",
|
||||
"phase.fonts.copy": "Gedeelde lettertypen naar de installatiemap kopiëren",
|
||||
"phase.extract.hash_base": "Controlesom van het basisspel berekenen",
|
||||
"phase.extract.hash_update": "Controlesom van de update berekenen",
|
||||
"phase.extract.exefs": "Spelcode uitpakken",
|
||||
"phase.extract.copy": "Spelgegevens kopiëren",
|
||||
"phase.extract.merge": "Update op de spelgegevens toepassen",
|
||||
"phase.extract.diagnose": "Beschadigd spelbestand zoeken",
|
||||
"phase.extract.index": "Spelgegevens verifiëren",
|
||||
"phase.lift.discover": "Functies zoeken",
|
||||
"phase.lift.emit": "C-code schrijven",
|
||||
"phase.compile.compile": "Compileren",
|
||||
"phase.compile.link": "{game_exe} linken",
|
||||
"phase.prepare.romfs_patches": "Spelgegevenspatches voor 60 fps schrijven",
|
||||
"phase.pc_prompts.draw": "Toets- en muisknoppictogrammen tekenen volgens de toewijzingen in totk.ini",
|
||||
"phase.prepare.seed": "Shaders uit de spelgegevens lezen",
|
||||
"phase.prepare.translate": "Shaders vertalen",
|
||||
"phase.prepare.libraries": "Shaders voor het grafische stuurprogramma bouwen",
|
||||
"phase.prepare.pack": "Shadercache in één bestand verpakken",
|
||||
"phase.shapes.layouts": "Schermindelingen en knoppictogrammen voor elke schermvorm schrijven",
|
||||
"phase.dlss.download": "nvngx_dlss.dll downloaden uit NVIDIA's DLSS SDK",
|
||||
"phase.cleanup.ini": "totk.ini schrijven",
|
||||
"phase.cleanup.temp": "Tijdelijke bestanden verwijderen",
|
||||
"cli.usage": "Ongeldige opdrachtregel: {detail}",
|
||||
"internal": "Onverwachte fout ({exception}): {detail}",
|
||||
"state.unreadable": "{path} kan niet worden gelezen. Kies een andere map of verwijder dat bestand.",
|
||||
"state.newer_format": "{path} is geschreven door een nieuwer installatieprogramma. Gebruik dat programma of een andere map.",
|
||||
"state.output_changed": "Geïnstalleerde bestanden van stap '{step}' zijn gewijzigd sinds ze zijn gemaakt; die stap wordt opnieuw uitgevoerd.",
|
||||
"check.release_incomplete": "De map van het installatieprogramma is onvolledig; ontbreekt: {paths}. Pak de release opnieuw uit.",
|
||||
"check.dest_not_folder": "De installatielocatie {path} is een bestand, geen map.",
|
||||
"check.dest_not_empty": "De installatiemap {path} is niet leeg en bevat geen eerdere installatie. Kies een lege map.",
|
||||
"check.lang_missing": "Kies de taal van het spel.",
|
||||
"check.lang_unknown": "Onbekende taal '{lang}'. Bekend: {known}.",
|
||||
"check.toolchain_broken": "De meegeleverde compiler werkt niet: {detail}",
|
||||
"check.glibc_old": "De C-bibliotheek van dit systeem is glibc {version}; de compiler van de installatie heeft {need} of nieuwer nodig (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 en nieuwer hebben die). Het systeem bijwerken lost dit op.",
|
||||
"check.host_probe_failed": "De computercontrole is niet uitgevoerd (afsluitcode {code}).",
|
||||
"check.cpu_too_old": "Deze processor mist x86-64-v2 (SSE4.2, POPCNT en CMPXCHG16B), het oudste niveau waarvoor het spel wordt gebouwd. Intel Nehalem (2008) of AMD Bulldozer (2011) en nieuwer hebben het.",
|
||||
"check.vulkan_missing": "Er is geen Vulkan-stuurprogramma geïnstalleerd. Installeer het nieuwste stuurprogramma voor je videokaart.",
|
||||
"check.vulkan_no_device": "Vulkan vindt geen videokaart. Installeer het nieuwste stuurprogramma voor je videokaart.",
|
||||
"check.vulkan_too_old": "Het spel heeft een videokaart met Vulkan 1.3 nodig; gevonden: {devices}. Werk het grafische stuurprogramma bij.",
|
||||
"check.no_display": "Voor het voorbereiden van de shaders is een scherm nodig. Start de installatie vanuit de bureaubladsessie of exporteer DISPLAY=:0 (op een Steam Deck in de Gamemodus ook XDG_RUNTIME_DIR=/run/user/1000).",
|
||||
"check.inputs_needed": "De spelbestanden zijn nodig: kies het basisspel, de update 1.1.0, 1.2.1 of 1.4.3 en prod.keys.",
|
||||
"check.input_missing": "Bestand niet gevonden ({input}): {path}",
|
||||
"check.keys_unreadable": "Het sleutelbestand kan niet worden gelezen. Kies een prod.keys-bestand.",
|
||||
"check.keys_no_header_key": "Het sleutelbestand heeft geen header_key. Lees prod.keys opnieuw uit je console uit.",
|
||||
"check.keys_wrong": "De sleutels kunnen het bestand ({input}) niet openen. Gebruik de prod.keys van je console.",
|
||||
"check.keys_too_old": "Het sleutelbestand is te oud voor het bestand ({input}) (sleutelgeneratie {generation} nodig). Lees prod.keys uit een console met nieuwere firmware.",
|
||||
"check.not_game_file": "Het bestand ({input}) is geen XCI-, NSP-, XCZ- of NSZ-spelbestand.",
|
||||
"check.file_unreadable": "Het bestand ({input}) kan niet worden gelezen: {detail}",
|
||||
"check.unpack_failed": "Het gecomprimeerde bestand {input} kon niet worden uitgepakt: {detail}",
|
||||
"check.ticket_personalized": "Het bestand ({input}) bevat een gepersonaliseerd ticket; een algemeen ticket is nodig.",
|
||||
"check.ticket_missing": "Het bestand ({input}) mist het ticket dat de inhoud nodig heeft.",
|
||||
"check.base_not_totk": "Het basisspelbestand is niet The Legend of Zelda: Tears of the Kingdom ({detail}).",
|
||||
"check.base_is_update": "Het basisspelbestand is een update. Kies hier het basisspel als NSP of XCI (versie 1.0.0) en dit bestand als update.",
|
||||
"check.base_combined": "Het basisspelbestand bevat meerdere pakketten (basisspel, update of DLC in één bestand). Kies een dump van het basisspel die alleen het spel bevat.",
|
||||
"check.update_not_nsp": "De update moet een NSP- of NSZ-bestand zijn.",
|
||||
"check.update_is_base": "Het updatebestand bevat een basisspel. Kies de NSP van update 1.1.0, 1.2.1 of 1.4.3.",
|
||||
"check.update_not_totk": "Het updatebestand is geen update van Tears of the Kingdom ({detail}).",
|
||||
"check.exefs_failed": "De spelcode van het bestand ({input}) heeft de controles niet doorstaan; zie {log}.",
|
||||
"check.input_damaged": "Het bestand ({input}) is beschadigd of onvolledig: {path} ({detail}). Kopieer dat bestand opnieuw vanaf de bron of maak de dump opnieuw en voer de installatie dan opnieuw uit.",
|
||||
"check.base_wrong_version": "Het basisspel is niet versie 1.0.0 ({modules} wijken af).",
|
||||
"check.update_wrong_version": "De update is versie {found}; deze release gebruikt {wanted}.",
|
||||
"check.disk_space": "Niet genoeg vrije ruimte voor {path}: {need_gb} GB nodig, {free_gb} GB vrij.",
|
||||
"check.firmware_missing": "De firmwaremap {path} bestaat niet. Kies de map Contents/registered van de firmware.",
|
||||
"check.firmware_empty": "De firmwaremap {path} bevat geen NCA-bestanden. Kies de map Contents/registered van de firmware.",
|
||||
"check.fonts_keys_needed": "De gedeelde lettertypen voor deze taal zijn nog niet geïnstalleerd; kies prod.keys zodat de installatie ze uit de firmware kan uitpakken.",
|
||||
"extract.exefs_mismatch": "De uitgepakte spelcode komt niet overeen met versie {version} ({modules}).",
|
||||
"extract.romfs_merge_failed": "Het toepassen van de update op de spelgegevens is mislukt: {detail}. Details: {log}",
|
||||
"extract.romfs_mismatch": "De uitgepakte spelgegevens komen niet overeen met versie {version} (grootte {size}, controlesom {sha256}...).",
|
||||
"fonts.failed": "Het uitpakken van de gedeelde lettertypen is mislukt (afsluitcode {code}): {detail}. Details: {log}",
|
||||
"fonts.incomplete": "Het uitpakken van de gedeelde lettertypen heeft niet elk bestand geschreven ({files}).",
|
||||
"fonts.copy_failed": "De gedeelde lettertypen kunnen niet naar {path} worden gekopieerd: {detail}",
|
||||
"lift.failed": "Het vertalen van de spelcode is mislukt (afsluitcode {code}). Details: {log}",
|
||||
"compile.failed": "Het compileren van {game_exe} is mislukt (afsluitcode {code}). Details: {log}",
|
||||
"compile.exe_in_use": "{path} is in gebruik. Sluit het spel en voer het installatieprogramma opnieuw uit.",
|
||||
"kit.in_use": "{path} is in gebruik. Sluit het spel en elk geopend installatie- of herbouwvenster en start de installatie daarna opnieuw.",
|
||||
"kit.copy_failed": "De bouwkit kan niet naar {path} worden gekopieerd: {detail}",
|
||||
"compile.exe_locked": "{path} kan niet worden geschreven: een ander programma houdt het vast, een spel dat vanuit die map is gestart of een virusscanner die het bestand heeft gemarkeerd. Sluit het spel, voeg de map van de installatie en de installatiemap toe aan de uitzonderingen van de virusscanner, start Windows opnieuw en start de installatie daarna opnieuw. Details: {log}",
|
||||
"prepare.xlate_in_use": "{path} is in gebruik. Sluit het spel, beëindig elk totk_xlate-proces dat van een eerdere uitvoering over is en voer het installatieprogramma opnieuw uit.",
|
||||
"prepare.shader_list_missing": "De shaderlijst ontbreekt.",
|
||||
"prepare.romfs_patches_failed": "Het schrijven van de spelgegevenspatches is mislukt (afsluitcode {code}). Details: {log}",
|
||||
"prepare.shaders_failed": "Het voorbereiden van de shaders is mislukt (afsluitcode {code}). Details: {log}",
|
||||
"cleanup.romfs_unreadable": "De spelgegevens in {path} ontbreken of kunnen na de installatie niet worden gelezen. Start Windows opnieuw en voer het installatieprogramma opnieuw uit op dezelfde map: het pakt de spelgegevens opnieuw uit en behoudt de rest.",
|
||||
"prepare.pack_failed": "Het verpakken van de shadercache is mislukt (afsluitcode {code}). Details: {log}",
|
||||
"cleanup.ini_failed": "totk.ini kan niet worden geschreven: {detail}",
|
||||
"warn.lang_needs_fonts": "Tekst in het {lang} heeft de systeemlettertypen van de Switch nodig, en die zijn niet opgegeven. Het spel start niet in deze taal totdat ze zijn toegevoegd. Kies de firmwaremap (Contents/registered) of zie \"Switch system fonts\" in docs/installer.md.",
|
||||
"warn.npdm_differs": "main.npdm wijkt af van de referentiedump {version}; alleen de codemodules worden gebruikt.",
|
||||
"warn.cheats_skipped": "De cheats uit de modsmap die de spelcode wijzigen konden niet worden gebouwd; het spel wordt zonder ze geïnstalleerd. Details: {log}",
|
||||
"warn.exefs_skipped": "De ExeFS-patches van de mods (.ips, .pchtxt) konden niet worden gebouwd; het spel wordt zonder ze geïnstalleerd. Details: {log}",
|
||||
"warn.plugins_skipped": "De codeplug-ins van de mods (exefs subsdk) konden niet worden gebouwd; het spel wordt zonder ze geïnstalleerd. Details: {log}",
|
||||
"warn.xbox_prompts_failed": "De Xbox-, PlayStation- of pc-knoppictogrammen konden niet worden voorbereid (afsluitcode {code}); het spel houdt de Switch-pictogrammen. Details: {log}",
|
||||
"warn.shaders_skipped": "Het grafische stuurprogramma is gecrasht bij het bouwen van enkele shaders, dus {count} zijn uit de voorbereiding weggelaten. Het spel bouwt ze wanneer het ze voor het eerst nodig heeft, en het stuurprogramma kan daar ook crashen; een update van het stuurprogramma kan dit oplossen. Details: {log}",
|
||||
"warn.kernel_old": "Linux {version} mist de schrijftracering waar het spel op rekent (6.7 of nieuwer); het spel kan erg traag zijn. Het systeem bijwerken lost dit op.",
|
||||
"warn.dlss_kept": "Er staat al een DLSS-bibliotheek in de installatiemap ({path}); de installatie laat die staan.",
|
||||
"warn.dlss_download_failed": "NVIDIA DLSS kon niet worden gedownload van {url}: {detail}. Het spel werkt zonder; de volgende installatieronde probeert het opnieuw.",
|
||||
"ui.title": "TotK-installatie",
|
||||
"ui.rebuild_title": "Spel opnieuw bouwen voor je mods",
|
||||
"ui.start_game": "Spel starten",
|
||||
"ui.version": "versie {version}",
|
||||
"ui.intro": "Bouwt een speelbare map van Tears of the Kingdom uit je eigen spelbestanden. Dit duurt even en gebeurt één keer.",
|
||||
"ui.notice": "De map die deze installatie bouwt bevat het spel. Die is alleen voor eigen gebruik; deel of upload hem niet.",
|
||||
"ui.keys_private": "Het sleutelbestand wordt ter plaatse gelezen. De inhoud wordt nooit getoond, gekopieerd of opgeslagen.",
|
||||
"ui.base": "Basisspel",
|
||||
"ui.update": "Update",
|
||||
"ui.keys": "prod.keys",
|
||||
"ui.firmware": "Firmware (optioneel)",
|
||||
"ui.game_language": "Taal van het spel",
|
||||
"ui.dest": "Installatiemap",
|
||||
"ui.browse": "Bladeren...",
|
||||
"ui.pick_game": "Kies het basisspelbestand",
|
||||
"ui.pick_update": "Kies het bestand van update 1.1.0, 1.2.1 of 1.4.3",
|
||||
"ui.pick_keys": "Kies prod.keys",
|
||||
"ui.pick_firmware": "Kies de map van de Switch-firmware (Contents/registered)",
|
||||
"ui.pick_dest": "Kies de installatiemap",
|
||||
"ui.firmware_help": "Voor Chinese, Koreaanse en traditioneel Chinese tekst: de map Contents/registered van de firmware, bijvoorbeeld uit Ryujinx of Yuzu. De installatie kopieert daaruit de systeemlettertypen van de Switch naar de installatiemap.",
|
||||
"ui.dlss": "NVIDIA DLSS (nvngx_dlss.dll) downloaden voor NVIDIA RTX-videokaarten",
|
||||
"ui.dlss_help": "Uit NVIDIA's DLSS SDK op GitHub, onder NVIDIA's RTX SDK-licentie (github.com/NVIDIA/DLSS). Hiermee werken de instellingen dlaa en DLSS; zonder doen ze niets.",
|
||||
"ui.compressed_help": "Gecomprimeerde NSZ- en XCZ-bestanden werken zoals ze zijn: de installatie pakt ze zelf uit (tot de spelgegevens zijn uitgepakt, is daarvoor evenveel vrije ruimte nodig als de uitgepakte bestanden innemen).",
|
||||
"ui.section_files": "Spelbestanden",
|
||||
"ui.section_install": "Installatie",
|
||||
"ui.more_details": "▸ Meer details",
|
||||
"ui.fewer_details": "▾ Details verbergen",
|
||||
"ui.formats_help": "Basisspel: NSP, XCI, NSZ of XCZ. Update: 1.1.0, 1.2.1 of 1.4.3, als NSP of NSZ.",
|
||||
"ui.type_game": "Spelbestanden (NSP, XCI, NSZ, XCZ)",
|
||||
"ui.type_keys": "Sleutelbestanden (*.keys)",
|
||||
"ui.type_all": "Alle bestanden",
|
||||
"ui.start": "Starten",
|
||||
"ui.cancel": "Annuleren",
|
||||
"ui.cancelling": "Annuleren...",
|
||||
"ui.show_log": "Logboek tonen",
|
||||
"ui.hide_log": "Logboek verbergen",
|
||||
"ui.close": "Sluiten",
|
||||
"ui.back": "Terug",
|
||||
"ui.open_folder": "Map openen",
|
||||
"ui.update_mode": "Deze map bevat een eerdere installatie. De installatie zet die voort of werkt die bij; de spelbestanden worden alleen gevraagd als ze opnieuw nodig zijn.",
|
||||
"ui.need_dest": "Kies de installatiemap.",
|
||||
"ui.need_base": "Kies het basisspelbestand.",
|
||||
"ui.need_update": "Kies het bestand van update 1.1.0, 1.2.1 of 1.4.3.",
|
||||
"ui.need_keys": "Kies het bestand prod.keys.",
|
||||
"ui.need_lang": "Kies de taal van het spel.",
|
||||
"ui.missing_base": "Het basisspelbestand bestaat niet.",
|
||||
"ui.missing_update": "Het updatebestand bestaat niet.",
|
||||
"ui.missing_keys": "Het sleutelbestand bestaat niet.",
|
||||
"ui.missing_firmware": "De firmwaremap bestaat niet.",
|
||||
"ui.running_install": "Installeren",
|
||||
"ui.running_resume": "Eerdere installatie voortzetten",
|
||||
"ui.running_update": "Installatie bijwerken",
|
||||
"ui.state_started": "gestart",
|
||||
"ui.state_done": "klaar",
|
||||
"ui.state_skipped": "overgeslagen",
|
||||
"ui.state_pending": "wacht",
|
||||
"ui.state_running": "bezig",
|
||||
"ui.state_failed": "mislukt",
|
||||
"ui.log_warning": "Waarschuwing",
|
||||
"ui.log_error": "Fout",
|
||||
"ui.log_space": "Benodigde ruimte: {need} GB, vrij: {free} GB",
|
||||
"ui.log_end": "Klaar",
|
||||
"ui.result_ok": "Het spel is klaar",
|
||||
"ui.result_failed": "De installatie is mislukt",
|
||||
"ui.result_cancelled": "De installatie is geannuleerd",
|
||||
"ui.done_text": "Start {game_exe} vanuit {dest}. Het installatieprogramma en de gekozen spelbestanden zijn niet meer nodig.",
|
||||
"ui.cancelled_text": "De voltooide stappen blijven bewaard. Start de installatie opnieuw met dezelfde map om verder te gaan.",
|
||||
"ui.log_file": "Logbestand: {path}",
|
||||
"ui.process_died": "De installatie is onverwacht gestopt (afsluitcode {code}).",
|
||||
"ui.confirm_cancel": "De installatie is bezig. Annuleren en het venster sluiten?",
|
||||
"ui.space_one": "Benodigde vrije ruimte op {path}: {need} GB (vrij: {free} GB).",
|
||||
"ui.space_two": "Benodigde vrije ruimte op {path}: {need} GB (vrij: {free} GB); op {temp}: {temp_need} GB (vrij: {temp_free} GB).",
|
||||
"ui.amount_bytes": "{done} / {total} GB",
|
||||
"ui.amount_chunks": "{done} / {total} delen",
|
||||
"ui.amount_objects": "{done} / {total} bestanden",
|
||||
"ui.amount_shaders": "{done} / {total} shaders",
|
||||
"ui.amount_other": "{done} / {total} {unit}",
|
||||
"ui.seconds": "{n} s",
|
||||
"param.input.base": "basisspel",
|
||||
"param.input.update": "update",
|
||||
"param.input.keys": "sleutels",
|
||||
"launcher.title": "TotK-installatie",
|
||||
"launcher.python_missing": "De installatiebestanden zijn onvolledig: de map python naast TotK-Setup.exe ontbreekt. Pak het hele archief opnieuw uit en start TotK-Setup.exe vanuit de uitgepakte map.",
|
||||
"lang.ja": "Japans",
|
||||
"lang.en-US": "Engels (VS)",
|
||||
"lang.en-GB": "Engels (VK)",
|
||||
"lang.fr": "Frans",
|
||||
"lang.fr-CA": "Frans (Canada)",
|
||||
"lang.de": "Duits",
|
||||
"lang.it": "Italiaans",
|
||||
"lang.es": "Spaans",
|
||||
"lang.es-419": "Spaans (Latijns-Amerika)",
|
||||
"lang.nl": "Nederlands",
|
||||
"lang.pt": "Portugees",
|
||||
"lang.pt-BR": "Portugees (Brazilië)",
|
||||
"lang.ru": "Russisch",
|
||||
"lang.ko": "Koreaans",
|
||||
"lang.zh-Hans": "Chinees (vereenvoudigd)",
|
||||
"lang.zh-Hant": "Chinees (traditioneel)"
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
{
|
||||
"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",
|
||||
"step.compile": "Compilando o {game_exe}",
|
||||
"step.prepare": "Preparando os shaders",
|
||||
"step.pc_prompts": "Desenhando os ícones de teclado e mouse",
|
||||
"step.shapes": "Ajustando as telas do jogo aos seus monitores",
|
||||
"step.dlss": "Baixando o NVIDIA DLSS",
|
||||
"step.cleanup": "Finalizando",
|
||||
|
||||
"phase.check.host": "Verificando o processador e a placa de vídeo",
|
||||
"phase.check.verify": "Verificando os arquivos já instalados",
|
||||
"phase.check.verify_romfs": "Verificando os dados do jogo instalados",
|
||||
"phase.check.inputs": "Abrindo os arquivos do jogo com as chaves",
|
||||
"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",
|
||||
"phase.extract.hash_update": "Calculando o checksum da atualização",
|
||||
"phase.extract.exefs": "Extraindo o código do jogo",
|
||||
"phase.extract.copy": "Copiando os dados do jogo",
|
||||
"phase.extract.merge": "Aplicando a atualização aos dados do jogo",
|
||||
"phase.extract.diagnose": "Procurando o arquivo do jogo danificado",
|
||||
"phase.extract.index": "Verificando os dados do jogo",
|
||||
"phase.lift.discover": "Encontrando as funções",
|
||||
"phase.lift.emit": "Gerando o código C",
|
||||
"phase.compile.compile": "Compilando",
|
||||
"phase.compile.link": "Ligando o {game_exe}",
|
||||
"phase.prepare.romfs_patches": "Gravando os patches de 60 fps nos dados do jogo",
|
||||
"phase.pc_prompts.draw": "Desenhando os ícones de teclas e botões do mouse a partir das atribuições do totk.ini",
|
||||
"phase.prepare.seed": "Lendo os shaders dos dados do jogo",
|
||||
"phase.prepare.translate": "Traduzindo os shaders",
|
||||
"phase.prepare.libraries": "Montando os shaders para o driver de vídeo",
|
||||
"phase.prepare.pack": "Juntando o cache de shaders num único arquivo",
|
||||
"phase.shapes.layouts": "Gravando os layouts de tela e os botões para cada formato de monitor",
|
||||
"phase.dlss.download": "Baixando o nvngx_dlss.dll do DLSS SDK da NVIDIA",
|
||||
"phase.cleanup.ini": "Gravando o totk.ini",
|
||||
"phase.cleanup.temp": "Removendo os arquivos temporários",
|
||||
|
||||
"cli.usage": "Linha de comando inválida: {detail}",
|
||||
"internal": "Erro inesperado ({exception}): {detail}",
|
||||
"state.unreadable": "Não foi possível ler {path}. Escolha outra pasta ou apague esse arquivo.",
|
||||
"state.newer_format": "{path} foi gravado por um instalador mais novo. Use esse instalador ou outra pasta.",
|
||||
"state.output_changed": "Os arquivos instalados da etapa '{step}' mudaram desde que foram criados; essa etapa será executada de novo.",
|
||||
|
||||
"check.release_incomplete": "A pasta do instalador está incompleta; faltam: {paths}. Extraia o pacote de novo.",
|
||||
"check.dest_not_folder": "O local de instalação {path} é um arquivo, não uma pasta.",
|
||||
"check.dest_not_empty": "A pasta de instalação {path} não está vazia e não tem uma instalação anterior. Escolha uma pasta vazia.",
|
||||
"check.lang_missing": "Escolha o idioma do jogo.",
|
||||
"check.lang_unknown": "Idioma desconhecido '{lang}'. Conhecidos: {known}.",
|
||||
"check.toolchain_broken": "O compilador incluído não funciona: {detail}",
|
||||
"check.glibc_old": "A biblioteca C deste sistema é a glibc {version}; o compilador da instalação precisa da {need} ou mais nova (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 e mais novos têm). Atualizar o sistema resolve.",
|
||||
"check.host_probe_failed": "A verificação do computador não rodou (código de saída {code}).",
|
||||
"check.cpu_too_old": "Este processador não tem x86-64-v2 (SSE4.2, POPCNT e CMPXCHG16B), o nível mais antigo para o qual o jogo é compilado. Intel Nehalem (2008) ou AMD Bulldozer (2011) e mais novos têm.",
|
||||
"check.vulkan_missing": "Nenhum driver Vulkan está instalado. Instale o driver mais recente da sua placa de vídeo.",
|
||||
"check.vulkan_no_device": "O Vulkan não encontra nenhuma placa de vídeo. Instale o driver mais recente da sua placa de vídeo.",
|
||||
"check.vulkan_too_old": "O jogo precisa de uma placa de vídeo com Vulkan 1.3; encontrado: {devices}. Atualize o driver de vídeo.",
|
||||
"check.no_display": "Preparar os shaders exige uma tela. Execute a instalação na sessão da área de trabalho ou use export DISPLAY=:0 (no Steam Deck em Game Mode, também XDG_RUNTIME_DIR=/run/user/1000).",
|
||||
"check.inputs_needed": "Os arquivos do jogo são necessários: escolha o jogo base, a atualização 1.1.0, 1.2.1 ou 1.4.3 e o prod.keys.",
|
||||
"check.input_missing": "Arquivo não encontrado ({input}): {path}",
|
||||
"check.keys_unreadable": "Não foi possível ler o arquivo de chaves. Escolha um arquivo prod.keys.",
|
||||
"check.keys_no_header_key": "O arquivo de chaves não tem header_key. Extraia o prod.keys do seu console de novo.",
|
||||
"check.keys_wrong": "As chaves não abrem o arquivo de {input}. Use o prod.keys do seu console.",
|
||||
"check.keys_too_old": "O arquivo de chaves é antigo demais para o arquivo de {input} (precisa da geração de chaves {generation}). Extraia o prod.keys de um console com firmware mais novo.",
|
||||
"check.not_game_file": "O arquivo de {input} não é um arquivo de jogo XCI, NSP, XCZ ou NSZ.",
|
||||
"check.file_unreadable": "Não foi possível ler o arquivo de {input}: {detail}",
|
||||
"check.unpack_failed": "Não foi possível descompactar o arquivo compactado de {input}: {detail}",
|
||||
"check.ticket_personalized": "O arquivo de {input} tem um ticket personalizado; é preciso um ticket comum.",
|
||||
"check.ticket_missing": "O arquivo de {input} não tem o ticket de que o conteúdo precisa.",
|
||||
"check.base_not_totk": "O arquivo do jogo base não é The Legend of Zelda: Tears of the Kingdom ({detail}).",
|
||||
"check.base_is_update": "O arquivo do jogo base é uma atualização. Escolha aqui o NSP ou XCI do jogo base (versão 1.0.0) e este arquivo como a atualização.",
|
||||
"check.base_combined": "O arquivo do jogo base contém vários pacotes (jogo base, atualização ou DLC em um só arquivo). Escolha um dump do jogo base que contenha só o jogo.",
|
||||
"check.update_not_nsp": "A atualização precisa ser um arquivo NSP ou NSZ.",
|
||||
"check.update_is_base": "O arquivo de atualização contém um jogo base. Escolha o NSP da atualização 1.1.0, 1.2.1 ou 1.4.3.",
|
||||
"check.update_not_totk": "O arquivo de atualização não é uma atualização de Tears of the Kingdom ({detail}).",
|
||||
"check.exefs_failed": "O código do jogo no arquivo de {input} falhou nas verificações; veja {log}.",
|
||||
"check.input_damaged": "O arquivo de {input} está danificado ou incompleto: {path} ({detail}). Copie esse arquivo de novo da origem, ou extraia-o de novo, e então execute a instalação outra vez.",
|
||||
"check.base_wrong_version": "O jogo base não é a versão 1.0.0 ({modules} diferem).",
|
||||
"check.update_wrong_version": "A atualização é a versão {found}; esta versão do instalador aceita {wanted}.",
|
||||
"check.disk_space": "Espaço livre insuficiente em {path}: são necessários {need_gb} GB, há {free_gb} GB livres.",
|
||||
"check.firmware_missing": "A pasta de firmware {path} não existe. Escolha a pasta Contents/registered do firmware.",
|
||||
"check.firmware_empty": "A pasta de firmware {path} não contém arquivos NCA. Escolha a pasta Contents/registered do firmware.",
|
||||
"check.fonts_keys_needed": "As fontes compartilhadas deste idioma ainda não estão instaladas; escolha o prod.keys para que a instalação possa extraí-las do firmware.",
|
||||
|
||||
"extract.exefs_mismatch": "O código do jogo extraído não corresponde à versão {version} ({modules}).",
|
||||
"extract.romfs_merge_failed": "Falha ao aplicar a atualização aos dados do jogo: {detail}. Detalhes: {log}",
|
||||
"extract.romfs_mismatch": "Os dados do jogo extraídos não correspondem à versão {version} (tamanho {size}, checksum {sha256}...).",
|
||||
"fonts.failed": "A extração das fontes compartilhadas falhou (código de saída {code}): {detail}. Detalhes: {log}",
|
||||
"fonts.incomplete": "A extração das fontes compartilhadas não gravou todos os arquivos ({files}).",
|
||||
"fonts.copy_failed": "Não foi possível copiar as fontes compartilhadas para {path}: {detail}",
|
||||
"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.",
|
||||
"prepare.romfs_patches_failed": "Falha ao gravar os patches nos dados do jogo (código de saída {code}). Detalhes: {log}",
|
||||
"prepare.shaders_failed": "Falha ao preparar os shaders (código de saída {code}). Detalhes: {log}",
|
||||
"cleanup.romfs_unreadable": "Os dados do jogo em {path} estão faltando ou não podem ser lidos depois da instalação. Reinicie o Windows e execute o instalador de novo na mesma pasta: ele extrai os dados do jogo outra vez e mantém o resto.",
|
||||
"prepare.pack_failed": "Falha ao juntar o cache de shaders (código de saída {code}). Detalhes: {log}",
|
||||
"cleanup.ini_failed": "Não foi possível gravar o totk.ini: {detail}",
|
||||
|
||||
"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, 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.",
|
||||
"warn.dlss_download_failed": "Não foi possível baixar o NVIDIA DLSS de {url}: {detail}. O jogo funciona sem ele; a próxima execução da instalação tenta de novo.",
|
||||
|
||||
"ui.title": "Instalação do TotK",
|
||||
"ui.rebuild_title": "Recompilando o jogo para os seus mods",
|
||||
"ui.start_game": "Iniciar o jogo",
|
||||
"ui.version": "versão {version}",
|
||||
"ui.intro": "Monta uma pasta jogável de Tears of the Kingdom a partir dos seus próprios arquivos do jogo. Isso demora um pouco e só precisa ser feito uma vez.",
|
||||
"ui.notice": "A pasta que esta instalação monta contém o jogo. Ela é só para seu uso pessoal; não compartilhe nem envie para a internet.",
|
||||
"ui.keys_private": "O arquivo de chaves é lido no lugar. O conteúdo dele nunca é mostrado, copiado nem guardado.",
|
||||
"ui.base": "Jogo base",
|
||||
"ui.update": "Atualização",
|
||||
"ui.keys": "prod.keys",
|
||||
"ui.firmware": "Firmware (opcional)",
|
||||
"ui.game_language": "Idioma do jogo",
|
||||
"ui.dest": "Pasta de instalação",
|
||||
"ui.browse": "Procurar...",
|
||||
"ui.pick_game": "Escolha o arquivo do jogo base",
|
||||
"ui.pick_update": "Escolha o arquivo da atualização 1.1.0, 1.2.1 ou 1.4.3",
|
||||
"ui.pick_keys": "Escolha o prod.keys",
|
||||
"ui.pick_firmware": "Escolha a pasta de firmware do Switch (Contents/registered)",
|
||||
"ui.pick_dest": "Escolha a pasta de instalação",
|
||||
"ui.firmware_help": "Para textos em chinês, coreano e chinês tradicional: a pasta Contents/registered do firmware, por exemplo do Ryujinx ou do Yuzu. A instalação copia dela as fontes do sistema do Switch para a pasta de instalação.",
|
||||
"ui.dlss": "Baixar o NVIDIA DLSS (nvngx_dlss.dll) para placas de vídeo NVIDIA RTX",
|
||||
"ui.dlss_help": "Do DLSS SDK da NVIDIA no GitHub, sob a licença NVIDIA RTX SDK (github.com/NVIDIA/DLSS). Sem ele as opções dlaa e DLSS não fazem nada.",
|
||||
"ui.compressed_help": "Arquivos compactados NSZ e XCZ funcionam do jeito que estão: a instalação os descompacta sozinha (para isso, até os dados do jogo serem extraídos, ela precisa de tanto espaço livre quanto ocupam os arquivos descompactados).",
|
||||
"ui.section_files": "Arquivos do jogo",
|
||||
"ui.section_install": "Instalação",
|
||||
"ui.more_details": "▸ Mais detalhes",
|
||||
"ui.fewer_details": "▾ Ocultar detalhes",
|
||||
"ui.formats_help": "Jogo base: NSP, XCI, NSZ ou XCZ. Atualização: 1.1.0, 1.2.1 ou 1.4.3, em NSP ou NSZ.",
|
||||
"ui.type_game": "Arquivos de jogo (NSP, XCI, NSZ, XCZ)",
|
||||
"ui.type_keys": "Arquivos de chaves (*.keys)",
|
||||
"ui.type_all": "Todos os arquivos",
|
||||
"ui.start": "Iniciar",
|
||||
"ui.cancel": "Cancelar",
|
||||
"ui.cancelling": "Cancelando...",
|
||||
"ui.show_log": "Mostrar log",
|
||||
"ui.hide_log": "Ocultar log",
|
||||
"ui.close": "Fechar",
|
||||
"ui.back": "Voltar",
|
||||
"ui.open_folder": "Abrir pasta",
|
||||
"ui.update_mode": "Esta pasta tem uma instalação anterior. A instalação vai continuar ou atualizá-la; os arquivos do jogo só são pedidos se forem necessários de novo.",
|
||||
"ui.need_dest": "Escolha a pasta de instalação.",
|
||||
"ui.need_base": "Escolha o arquivo do jogo base.",
|
||||
"ui.need_update": "Escolha o arquivo da atualização 1.1.0, 1.2.1 ou 1.4.3.",
|
||||
"ui.need_keys": "Escolha o arquivo prod.keys.",
|
||||
"ui.need_lang": "Escolha o idioma do jogo.",
|
||||
"ui.missing_base": "O arquivo do jogo base não existe.",
|
||||
"ui.missing_update": "O arquivo de atualização não existe.",
|
||||
"ui.missing_keys": "O arquivo de chaves não existe.",
|
||||
"ui.missing_firmware": "A pasta de firmware não existe.",
|
||||
"ui.running_install": "Instalando",
|
||||
"ui.running_resume": "Continuando a instalação anterior",
|
||||
"ui.running_update": "Atualizando a instalação",
|
||||
"ui.state_started": "iniciada",
|
||||
"ui.state_done": "concluída",
|
||||
"ui.state_skipped": "pulada",
|
||||
"ui.state_pending": "aguardando",
|
||||
"ui.state_running": "em andamento",
|
||||
"ui.state_failed": "falhou",
|
||||
"ui.log_warning": "Aviso",
|
||||
"ui.log_error": "Erro",
|
||||
"ui.log_space": "Espaço necessário: {need} GB, livre: {free} GB",
|
||||
"ui.log_end": "Concluído",
|
||||
"ui.result_ok": "O jogo está pronto",
|
||||
"ui.result_failed": "A instalação falhou",
|
||||
"ui.result_cancelled": "A instalação foi cancelada",
|
||||
"ui.done_text": "Abra o {game_exe} em {dest}. O programa de instalação e os arquivos do jogo que você escolheu não são mais necessários.",
|
||||
"ui.cancelled_text": "As etapas concluídas são mantidas. Inicie a instalação de novo com a mesma pasta para continuar.",
|
||||
"ui.log_file": "Arquivo de log: {path}",
|
||||
"ui.process_died": "A instalação parou de forma inesperada (código de saída {code}).",
|
||||
"ui.confirm_cancel": "A instalação está em andamento. Cancelar e fechar a janela?",
|
||||
"ui.space_one": "Espaço livre necessário em {path}: {need} GB (livre: {free} GB).",
|
||||
"ui.space_two": "Espaço livre necessário em {path}: {need} GB (livre: {free} GB); em {temp}: {temp_need} GB (livre: {temp_free} GB).",
|
||||
"ui.amount_bytes": "{done} / {total} GB",
|
||||
"ui.amount_chunks": "{done} / {total} partes",
|
||||
"ui.amount_objects": "{done} / {total} arquivos",
|
||||
"ui.amount_shaders": "{done} / {total} shaders",
|
||||
"ui.amount_other": "{done} / {total} {unit}",
|
||||
"ui.seconds": "{n} s",
|
||||
"param.input.base": "jogo base",
|
||||
"param.input.update": "atualização",
|
||||
"param.input.keys": "chaves",
|
||||
|
||||
"launcher.title": "Instalação do TotK",
|
||||
"launcher.python_missing": "Os arquivos de instalação estão incompletos: a pasta python ao lado do TotK-Setup.exe não existe. Extraia o arquivo compactado inteiro de novo e abra o TotK-Setup.exe a partir da pasta extraída.",
|
||||
|
||||
"lang.ja": "Japonês",
|
||||
"lang.en-US": "Inglês (EUA)",
|
||||
"lang.en-GB": "Inglês (Reino Unido)",
|
||||
"lang.fr": "Francês",
|
||||
"lang.fr-CA": "Francês (Canadá)",
|
||||
"lang.de": "Alemão",
|
||||
"lang.it": "Italiano",
|
||||
"lang.es": "Espanhol",
|
||||
"lang.es-419": "Espanhol (América Latina)",
|
||||
"lang.nl": "Holandês",
|
||||
"lang.pt": "Português",
|
||||
"lang.pt-BR": "Português (Brasil)",
|
||||
"lang.ru": "Russo",
|
||||
"lang.ko": "Coreano",
|
||||
"lang.zh-Hans": "Chinês (Simplificado)",
|
||||
"lang.zh-Hant": "Chinês (Tradicional)"
|
||||
}
|
||||
+65
-17
@@ -1,16 +1,26 @@
|
||||
{
|
||||
"step.check": "Проверка компьютера и игровых файлов",
|
||||
"step.kit": "Копирование набора сборки в папку игры",
|
||||
"step.fonts": "Извлечение системных шрифтов",
|
||||
"step.extract": "Распаковка игры",
|
||||
"step.lift": "Перевод кода игры в C",
|
||||
"step.compile": "Сборка totk.exe",
|
||||
"step.compile": "Сборка {game_exe}",
|
||||
"step.prepare": "Подготовка шейдеров",
|
||||
"step.pc_prompts": "Рисование подсказок клавиатуры и мыши",
|
||||
"step.shapes": "Раскладка экранов игры под ваши мониторы",
|
||||
"step.dlss": "Загрузка NVIDIA DLSS",
|
||||
"step.cleanup": "Уборка",
|
||||
|
||||
"phase.check.host": "Проверка процессора и видеокарты",
|
||||
"phase.check.verify": "Проверка уже установленных файлов",
|
||||
"phase.check.verify_romfs": "Проверка установленных данных игры",
|
||||
"phase.check.inputs": "Открытие игровых файлов с помощью ключей",
|
||||
"phase.check.unpack_base": "Распаковка сжатой базовой игры",
|
||||
"phase.check.unpack_update": "Распаковка сжатого обновления",
|
||||
"phase.check.versions": "Проверка версий игры",
|
||||
"phase.kit.copy": "Копирование инструментов, которыми игра пересобирает себя для модов с кодом",
|
||||
"phase.fonts.extract": "Извлечение общих шрифтов из прошивки",
|
||||
"phase.fonts.copy": "Копирование общих шрифтов в папку установки",
|
||||
"phase.extract.hash_base": "Подсчёт контрольной суммы базовой игры",
|
||||
"phase.extract.hash_update": "Подсчёт контрольной суммы обновления",
|
||||
"phase.extract.exefs": "Распаковка кода игры",
|
||||
@@ -21,12 +31,15 @@
|
||||
"phase.lift.discover": "Поиск функций",
|
||||
"phase.lift.emit": "Запись кода на C",
|
||||
"phase.compile.compile": "Компиляция",
|
||||
"phase.compile.link": "Компоновка totk.exe",
|
||||
"phase.compile.link": "Компоновка {game_exe}",
|
||||
"phase.prepare.romfs_patches": "Запись патчей данных игры для 60 кадров/с",
|
||||
"phase.pc_prompts.draw": "Рисование подсказок клавиш и кнопок мыши по назначениям из totk.ini",
|
||||
"phase.prepare.seed": "Чтение шейдеров из данных игры",
|
||||
"phase.prepare.translate": "Трансляция шейдеров",
|
||||
"phase.prepare.libraries": "Сборка шейдеров для драйвера видеокарты",
|
||||
"phase.prepare.pack": "Упаковка кэша шейдеров в один файл",
|
||||
"phase.shapes.layouts": "Запись раскладок экрана и кнопок для каждой формы монитора",
|
||||
"phase.dlss.download": "Загрузка nvngx_dlss.dll из DLSS SDK от NVIDIA",
|
||||
"phase.cleanup.ini": "Запись totk.ini",
|
||||
"phase.cleanup.temp": "Удаление временных файлов",
|
||||
|
||||
@@ -42,37 +55,52 @@
|
||||
"check.lang_missing": "Выберите язык игры.",
|
||||
"check.lang_unknown": "Неизвестный язык «{lang}». Доступные: {known}.",
|
||||
"check.toolchain_broken": "Встроенный компилятор не работает: {detail}",
|
||||
"check.glibc_old": "Библиотека C этой системы — glibc {version}; компилятору установщика нужна {need} или новее (она есть в Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 и новее). Обновление системы это исправит.",
|
||||
"check.host_probe_failed": "Проверка компьютера не выполнилась (код выхода {code}).",
|
||||
"check.cpu_no_avx2": "Этому процессору не хватает AVX2 (x86-64-v3), который нужен игре. AVX2 есть у Intel Haswell (2013) и новее, у AMD Excavator и Zen и новее.",
|
||||
"check.cpu_too_old": "Этому процессору не хватает x86-64-v2 (SSE4.2, POPCNT и CMPXCHG16B) — минимального уровня, под который собрана игра. Он есть у Intel Nehalem (2008) и AMD Bulldozer (2011) и новее.",
|
||||
"check.vulkan_missing": "Драйвер Vulkan не установлен. Установите свежий драйвер видеокарты.",
|
||||
"check.vulkan_no_device": "Vulkan не находит видеокарту. Установите свежий драйвер видеокарты.",
|
||||
"check.vulkan_too_old": "Игре нужна видеокарта с Vulkan 1.3; найдено: {devices}. Обновите драйвер видеокарты.",
|
||||
"check.inputs_needed": "Нужны игровые файлы: выберите базовую игру, обновление 1.2.1 или 1.4.3 и prod.keys.",
|
||||
"check.no_display": "Для подготовки шейдеров нужен дисплей. Запустите установку из сеанса рабочего стола или выполните export DISPLAY=:0 (на Steam Deck в игровом режиме ещё XDG_RUNTIME_DIR=/run/user/1000).",
|
||||
"check.inputs_needed": "Нужны игровые файлы: выберите базовую игру, обновление 1.1.0 или 1.2.1 или 1.4.3 и prod.keys.",
|
||||
"check.input_missing": "Файл не найден ({input}): {path}",
|
||||
"check.keys_unreadable": "Не удаётся прочитать файл ключей. Выберите файл prod.keys.",
|
||||
"check.keys_no_header_key": "В файле ключей нет header_key. Снова получите prod.keys со своей консоли.",
|
||||
"check.keys_wrong": "Эти ключи не открывают файл «{input}». Используйте prod.keys со своей консоли.",
|
||||
"check.keys_too_old": "Файл ключей слишком старый для файла «{input}» (нужно поколение ключей {generation}). Получите prod.keys с консоли с более новой прошивкой.",
|
||||
"check.not_game_file": "Файл «{input}» не является игровым файлом XCI или NSP.",
|
||||
"check.not_game_file": "Файл «{input}» не является игровым файлом XCI, NSP, XCZ или NSZ.",
|
||||
"check.file_unreadable": "Не удаётся прочитать файл «{input}»: {detail}",
|
||||
"check.unpack_failed": "Не удалось распаковать сжатый файл «{input}»: {detail}",
|
||||
"check.ticket_personalized": "В файле «{input}» личный тикет; нужен общий тикет.",
|
||||
"check.ticket_missing": "В файле «{input}» нет тикета, который нужен его содержимому.",
|
||||
"check.base_not_totk": "Файл базовой игры — не The Legend of Zelda: Tears of the Kingdom ({detail}).",
|
||||
"check.update_not_nsp": "Обновление должно быть файлом NSP.",
|
||||
"check.update_is_base": "Файл обновления содержит базовую игру. Выберите NSP с обновлением 1.2.1 или 1.4.3.",
|
||||
"check.base_is_update": "Файл базовой игры — это обновление. Выберите здесь NSP или XCI базовой игры (версия 1.0.0), а этот файл укажите как обновление.",
|
||||
"check.base_combined": "Файл базовой игры содержит несколько пакетов (игра, обновление или DLC в одном файле). Выберите дамп, в котором только базовая игра.",
|
||||
"check.update_not_nsp": "Обновление должно быть файлом NSP или NSZ.",
|
||||
"check.update_is_base": "Файл обновления содержит базовую игру. Выберите NSP с обновлением 1.1.0 или 1.2.1 или 1.4.3.",
|
||||
"check.update_not_totk": "Файл обновления — не обновление Tears of the Kingdom ({detail}).",
|
||||
"check.exefs_failed": "Код игры из файла «{input}» не прошёл проверку; подробности в {log}.",
|
||||
"check.input_damaged": "Файл «{input}» повреждён или скопирован не полностью: {path} ({detail}). Скопируйте этот файл заново из источника или сделайте дамп ещё раз, затем снова запустите установку.",
|
||||
"check.base_wrong_version": "Базовая игра не версии 1.0.0 (отличаются модули: {modules}).",
|
||||
"check.update_wrong_version": "Версия обновления {found}; этот выпуск принимает {wanted}.",
|
||||
"check.disk_space": "Не хватает свободного места для {path}: нужно {need_gb} ГБ, свободно {free_gb} ГБ.",
|
||||
"check.firmware_missing": "Папки прошивки {path} нет. Выберите папку Contents/registered прошивки.",
|
||||
"check.firmware_empty": "В папке прошивки {path} нет файлов NCA. Выберите папку Contents/registered прошивки.",
|
||||
"check.fonts_keys_needed": "Общие шрифты для этого языка ещё не установлены; выберите prod.keys, чтобы установка извлекла их из прошивки.",
|
||||
|
||||
"extract.exefs_mismatch": "Распакованный код игры не соответствует версии {version} ({modules}).",
|
||||
"extract.romfs_merge_failed": "Не удалось применить обновление к данным игры: {detail}. Подробности: {log}",
|
||||
"extract.romfs_mismatch": "Распакованные данные игры не соответствуют версии {version} (размер {size}, контрольная сумма {sha256}...).",
|
||||
"fonts.failed": "Не удалось извлечь общие шрифты (код выхода {code}): {detail}. Подробности: {log}",
|
||||
"fonts.incomplete": "При извлечении общих шрифтов записаны не все файлы ({files}).",
|
||||
"fonts.copy_failed": "Не удаётся скопировать общие шрифты в {path}: {detail}",
|
||||
"lift.failed": "Не удалось перевести код игры (код выхода {code}). Подробности: {log}",
|
||||
"compile.failed": "Не удалось собрать totk.exe (код выхода {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": "Нет списка шейдеров.",
|
||||
"prepare.romfs_patches_failed": "Не удалось записать патчи данных игры (код выхода {code}). Подробности: {log}",
|
||||
"prepare.shaders_failed": "Не удалось подготовить шейдеры (код выхода {code}). Подробности: {log}",
|
||||
@@ -80,27 +108,46 @@
|
||||
"prepare.pack_failed": "Не удалось упаковать кэш шейдеров (код выхода {code}). Подробности: {log}",
|
||||
"cleanup.ini_failed": "Не удаётся записать totk.ini: {detail}",
|
||||
|
||||
"warn.lang_needs_fonts": "Для языка «{lang}» нужны системные шрифты Switch, которые установка не извлекает; часть текста может не отображаться.",
|
||||
"warn.lang_needs_fonts": "Для языка «{lang}» нужны системные шрифты Switch, а они не указаны. Игра не запустится на этом языке, пока их не добавят. Выберите папку прошивки (Contents/registered) или см. раздел «Switch system fonts» в docs/installer.md.",
|
||||
"warn.npdm_differs": "main.npdm отличается от эталонного дампа {version}; используются только модули с кодом.",
|
||||
"warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}",
|
||||
"warn.cheats_skipped": "Не удалось собрать читы из папки модов, меняющие код игры; игра установится без них. Подробности: {log}",
|
||||
"warn.exefs_skipped": "Не удалось собрать ExeFS-патчи модов (.ips, .pchtxt); игра установится без них. Подробности: {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}); установка её оставляет.",
|
||||
"warn.dlss_download_failed": "Не удалось загрузить NVIDIA DLSS с {url}: {detail}. Игра работает и без него; при следующем запуске установка попробует снова.",
|
||||
|
||||
"ui.title": "Установка TotK",
|
||||
"ui.rebuild_title": "Пересборка игры под ваши моды",
|
||||
"ui.start_game": "Запустить игру",
|
||||
"ui.version": "версия {version}",
|
||||
"ui.intro": "Собирает готовую к запуску папку с Tears of the Kingdom из ваших игровых файлов. Занимает много времени и выполняется один раз.",
|
||||
"ui.notice": "Папка, которую создаёт установка, содержит игру. Она предназначена только для личного использования: не передавайте и не выкладывайте её.",
|
||||
"ui.keys_private": "Файл ключей читается на месте. Его содержимое не показывается, не копируется и не сохраняется.",
|
||||
"ui.base": "Базовая игра (NSP или XCI)",
|
||||
"ui.update": "Обновление 1.2.1 или 1.4.3 (NSP)",
|
||||
"ui.base": "Базовая игра",
|
||||
"ui.update": "Обновление",
|
||||
"ui.keys": "prod.keys",
|
||||
"ui.firmware": "Прошивка (необязательно)",
|
||||
"ui.game_language": "Язык игры",
|
||||
"ui.dest": "Папка установки",
|
||||
"ui.browse": "Обзор...",
|
||||
"ui.pick_game": "Выберите файл базовой игры",
|
||||
"ui.pick_update": "Выберите файл обновления 1.2.1 или 1.4.3",
|
||||
"ui.pick_update": "Выберите файл обновления 1.1.0 или 1.2.1 или 1.4.3",
|
||||
"ui.pick_keys": "Выберите prod.keys",
|
||||
"ui.pick_firmware": "Выберите папку прошивки Switch (Contents/registered)",
|
||||
"ui.pick_dest": "Выберите папку установки",
|
||||
"ui.type_game": "Файлы игры (NSP, XCI)",
|
||||
"ui.type_nsp": "Файлы NSP",
|
||||
"ui.firmware_help": "Для текста на китайском и корейском: папка Contents/registered прошивки, например из Ryujinx или Yuzu. Установка скопирует из неё системные шрифты Switch в папку установки.",
|
||||
"ui.dlss": "Загрузить NVIDIA DLSS (nvngx_dlss.dll) для видеокарт NVIDIA RTX",
|
||||
"ui.dlss_help": "Из DLSS SDK от NVIDIA на GitHub, по лицензии NVIDIA RTX SDK (github.com/NVIDIA/DLSS). Без него настройки dlaa и DLSS ничего не делают.",
|
||||
"ui.compressed_help": "Сжатые файлы NSZ и XCZ подходят как есть: установка сама их распакует (для этого, пока извлекаются данные игры, нужно столько свободного места, сколько занимают распакованные файлы).",
|
||||
"ui.section_files": "Файлы игры",
|
||||
"ui.section_install": "Установка",
|
||||
"ui.more_details": "▸ Подробнее",
|
||||
"ui.fewer_details": "▾ Скрыть подробности",
|
||||
"ui.formats_help": "Базовая игра: NSP, XCI, NSZ или XCZ. Обновление: 1.1.0, 1.2.1 или 1.4.3, в NSP или NSZ.",
|
||||
"ui.type_game": "Файлы игры (NSP, XCI, NSZ, XCZ)",
|
||||
"ui.type_keys": "Файлы ключей (*.keys)",
|
||||
"ui.type_all": "Все файлы",
|
||||
"ui.start": "Начать",
|
||||
@@ -114,12 +161,13 @@
|
||||
"ui.update_mode": "В этой папке уже есть установка. Программа продолжит или обновит её; файлы игры понадобятся, только если их снова придётся читать.",
|
||||
"ui.need_dest": "Выберите папку установки.",
|
||||
"ui.need_base": "Выберите файл базовой игры.",
|
||||
"ui.need_update": "Выберите файл обновления 1.2.1 или 1.4.3.",
|
||||
"ui.need_update": "Выберите файл обновления 1.1.0 или 1.2.1 или 1.4.3.",
|
||||
"ui.need_keys": "Выберите файл prod.keys.",
|
||||
"ui.need_lang": "Выберите язык игры.",
|
||||
"ui.missing_base": "Файл базовой игры не найден.",
|
||||
"ui.missing_update": "Файл обновления не найден.",
|
||||
"ui.missing_keys": "Файл ключей не найден.",
|
||||
"ui.missing_firmware": "Папки прошивки нет.",
|
||||
"ui.running_install": "Установка",
|
||||
"ui.running_resume": "Продолжение прерванной установки",
|
||||
"ui.running_update": "Обновление установки",
|
||||
@@ -136,7 +184,7 @@
|
||||
"ui.result_ok": "Игра готова",
|
||||
"ui.result_failed": "Установка не удалась",
|
||||
"ui.result_cancelled": "Установка отменена",
|
||||
"ui.done_text": "Запустите totk.exe из папки {dest}. Программа установки и выбранные игровые файлы больше не нужны.",
|
||||
"ui.done_text": "Запустите {game_exe} из папки {dest}. Программа установки и выбранные игровые файлы больше не нужны.",
|
||||
"ui.cancelled_text": "Завершённые шаги сохранены. Чтобы продолжить, снова запустите установку с той же папкой.",
|
||||
"ui.log_file": "Файл журнала: {path}",
|
||||
"ui.process_died": "Установка неожиданно остановилась (код выхода {code}).",
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
{
|
||||
"step.check": "检查电脑和游戏文件",
|
||||
"step.kit": "正在把构建工具包复制到游戏文件夹",
|
||||
"step.fonts": "正在提取系统字体",
|
||||
"step.extract": "解包游戏",
|
||||
"step.lift": "将游戏代码转换为 C 代码",
|
||||
"step.compile": "编译 {game_exe}",
|
||||
"step.prepare": "准备着色器",
|
||||
"step.pc_prompts": "绘制键盘和鼠标按键提示",
|
||||
"step.shapes": "为你的显示器调整游戏画面布局",
|
||||
"step.dlss": "下载 NVIDIA DLSS",
|
||||
"step.cleanup": "清理",
|
||||
|
||||
"phase.check.host": "检查处理器和显卡",
|
||||
"phase.check.verify": "检查已安装的文件",
|
||||
"phase.check.verify_romfs": "检查已安装的游戏数据",
|
||||
"phase.check.inputs": "用密钥打开游戏文件",
|
||||
"phase.check.unpack_base": "正在解压压缩的游戏本体",
|
||||
"phase.check.unpack_update": "正在解压压缩的更新",
|
||||
"phase.check.versions": "检查游戏版本",
|
||||
"phase.kit.copy": "正在复制游戏为代码模组重新构建自身所用的工具",
|
||||
"phase.fonts.extract": "正在从固件中提取共享字体",
|
||||
"phase.fonts.copy": "正在将共享字体复制到安装文件夹",
|
||||
"phase.extract.hash_base": "计算游戏本体的校验和",
|
||||
"phase.extract.hash_update": "计算更新的校验和",
|
||||
"phase.extract.exefs": "解包游戏代码",
|
||||
"phase.extract.copy": "复制游戏数据",
|
||||
"phase.extract.merge": "将更新应用到游戏数据",
|
||||
"phase.extract.diagnose": "查找损坏的游戏文件",
|
||||
"phase.extract.index": "校验游戏数据",
|
||||
"phase.lift.discover": "查找函数",
|
||||
"phase.lift.emit": "生成 C 代码",
|
||||
"phase.compile.compile": "编译",
|
||||
"phase.compile.link": "链接 {game_exe}",
|
||||
"phase.prepare.romfs_patches": "写入 60 帧游戏数据补丁",
|
||||
"phase.pc_prompts.draw": "根据 totk.ini 中的按键绑定绘制键盘和鼠标按键提示",
|
||||
"phase.prepare.seed": "从游戏数据中读取着色器",
|
||||
"phase.prepare.translate": "转译着色器",
|
||||
"phase.prepare.libraries": "为显卡驱动构建着色器",
|
||||
"phase.prepare.pack": "将着色器缓存打包成一个文件",
|
||||
"phase.shapes.layouts": "为每种显示器比例写入画面布局和按键提示",
|
||||
"phase.dlss.download": "从 NVIDIA 的 DLSS SDK 下载 nvngx_dlss.dll",
|
||||
"phase.cleanup.ini": "写入 totk.ini",
|
||||
"phase.cleanup.temp": "删除临时文件",
|
||||
|
||||
"cli.usage": "命令行无效:{detail}",
|
||||
"internal": "意外错误({exception}):{detail}",
|
||||
"state.unreadable": "无法读取 {path}。请选择其他文件夹,或删除该文件。",
|
||||
"state.newer_format": "{path} 是由更新版本的安装程序写入的。请使用那个安装程序,或选择其他文件夹。",
|
||||
"state.output_changed": "步骤“{step}”生成的已安装文件在生成后被改动过;该步骤将重新运行。",
|
||||
|
||||
"check.release_incomplete": "安装程序文件夹不完整,缺少:{paths}。请重新解压发布包。",
|
||||
"check.dest_not_folder": "安装位置 {path} 是一个文件,而不是文件夹。",
|
||||
"check.dest_not_empty": "安装文件夹 {path} 不是空的,其中也没有之前的安装。请选择一个空文件夹。",
|
||||
"check.lang_missing": "请选择游戏语言。",
|
||||
"check.lang_unknown": "未知语言“{lang}”。可用语言:{known}。",
|
||||
"check.toolchain_broken": "自带的编译器无法工作:{detail}",
|
||||
"check.glibc_old": "此系统的 C 库为 glibc {version};安装程序的编译器需要 {need} 或更新版本(Ubuntu 22.04、Debian 12、Fedora 35、SteamOS 3 及更新版本都满足)。更新系统即可解决。",
|
||||
"check.host_probe_failed": "电脑检查未能运行(退出代码 {code})。",
|
||||
"check.cpu_too_old": "此处理器不支持 x86-64-v2(SSE4.2、POPCNT 和 CMPXCHG16B),这是游戏所需的最低指令集。Intel Nehalem(2008 年)或 AMD Bulldozer(2011 年)及更新的处理器都支持。",
|
||||
"check.vulkan_missing": "未安装 Vulkan 驱动。请为你的显卡安装最新的驱动程序。",
|
||||
"check.vulkan_no_device": "Vulkan 找不到显卡。请为你的显卡安装最新的驱动程序。",
|
||||
"check.vulkan_too_old": "游戏需要支持 Vulkan 1.3 的显卡;检测到:{devices}。请更新显卡驱动程序。",
|
||||
"check.no_display": "准备着色器需要显示器。请在桌面会话中运行安装程序,或执行 export DISPLAY=:0(Steam Deck 游戏模式下还需 XDG_RUNTIME_DIR=/run/user/1000)。",
|
||||
"check.inputs_needed": "需要游戏文件:请选择游戏本体、1.1.0、1.2.1 或 1.4.3 更新以及 prod.keys。",
|
||||
"check.input_missing": "找不到文件({input}):{path}",
|
||||
"check.keys_unreadable": "无法读取密钥文件。请选择一个 prod.keys 文件。",
|
||||
"check.keys_no_header_key": "密钥文件中没有 header_key。请从你的主机重新导出 prod.keys。",
|
||||
"check.keys_wrong": "这些密钥无法打开{input}文件。请使用你自己主机的 prod.keys。",
|
||||
"check.keys_too_old": "密钥文件对{input}文件来说太旧(需要密钥代数 {generation})。请从固件更新的主机导出 prod.keys。",
|
||||
"check.not_game_file": "{input}文件不是 XCI、NSP、XCZ 或 NSZ 游戏文件。",
|
||||
"check.file_unreadable": "无法读取{input}文件:{detail}",
|
||||
"check.unpack_failed": "无法解压压缩的{input}文件:{detail}",
|
||||
"check.ticket_personalized": "{input}文件带有个人化票据(personalized ticket);需要通用票据(common ticket)。",
|
||||
"check.ticket_missing": "{input}文件缺少其内容所需的票据(ticket)。",
|
||||
"check.base_not_totk": "游戏本体文件不是《塞尔达传说 王国之泪》({detail})。",
|
||||
"check.base_is_update": "基础游戏文件是一个更新。请在这里选择基础游戏的 NSP 或 XCI(版本 1.0.0),并把此文件选为更新。",
|
||||
"check.base_combined": "基础游戏文件包含多个内容包(基础游戏、更新或 DLC 合在一个文件中)。请选择只包含游戏本体的基础游戏转储。",
|
||||
"check.update_not_nsp": "更新必须是 NSP 或 NSZ 文件。",
|
||||
"check.update_is_base": "更新文件里是游戏本体。请选择 1.1.0、1.2.1 或 1.4.3 的更新 NSP。",
|
||||
"check.update_not_totk": "更新文件不是《王国之泪》的更新({detail})。",
|
||||
"check.exefs_failed": "{input}文件的游戏代码未通过检查;详见 {log}。",
|
||||
"check.input_damaged": "{input}文件已损坏或不完整:{path}({detail})。请从来源重新复制该文件或重新导出,然后再次运行安装程序。",
|
||||
"check.base_wrong_version": "游戏本体不是 1.0.0 版本({modules} 不一致)。",
|
||||
"check.update_wrong_version": "更新的版本是 {found};此发布版需要 {wanted}。",
|
||||
"check.disk_space": "{path} 的可用空间不足:需要 {need_gb} GB,可用 {free_gb} GB。",
|
||||
"check.firmware_missing": "固件文件夹 {path} 不存在。请选择固件的 Contents/registered 文件夹。",
|
||||
"check.firmware_empty": "固件文件夹 {path} 中没有 NCA 文件。请选择固件的 Contents/registered 文件夹。",
|
||||
"check.fonts_keys_needed": "此语言的共享字体尚未安装;请选择 prod.keys,以便安装程序从固件中提取它们。",
|
||||
|
||||
"extract.exefs_mismatch": "解包出的游戏代码与 {version} 版本不符({modules})。",
|
||||
"extract.romfs_merge_failed": "将更新应用到游戏数据失败:{detail}。详情:{log}",
|
||||
"extract.romfs_mismatch": "解包出的游戏数据与 {version} 版本不符(大小 {size},校验和 {sha256}...)。",
|
||||
"fonts.failed": "提取共享字体失败(退出代码 {code}):{detail}。详情:{log}",
|
||||
"fonts.incomplete": "共享字体提取没有写出全部文件({files})。",
|
||||
"fonts.copy_failed": "无法将共享字体复制到 {path}:{detail}",
|
||||
"lift.failed": "游戏代码转换失败(退出代码 {code})。详情:{log}",
|
||||
"compile.failed": "编译 {game_exe} 失败(退出代码 {code})。详情:{log}",
|
||||
"compile.exe_in_use": "{path} 正在使用中。请关闭游戏后重新运行安装程序。",
|
||||
"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": "缺少着色器列表。",
|
||||
"prepare.romfs_patches_failed": "写入游戏数据补丁失败(退出代码 {code})。详情:{log}",
|
||||
"prepare.shaders_failed": "准备着色器失败(退出代码 {code})。详情:{log}",
|
||||
"cleanup.romfs_unreadable": "安装完成后,{path} 中的游戏数据缺失或无法读取。请重启 Windows,然后对同一文件夹再次运行安装程序:它会重新提取游戏数据,其余内容保留。",
|
||||
"prepare.pack_failed": "打包着色器缓存失败(退出代码 {code})。详情:{log}",
|
||||
"cleanup.ini_failed": "无法写入 totk.ini:{detail}",
|
||||
|
||||
"warn.lang_needs_fonts": "{lang}文本需要 Switch 系统字体,但未提供。在添加这些字体之前,游戏无法以该语言启动。请选择固件文件夹(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、PlayStation 或 PC 按键提示(退出代码 {code});游戏将继续使用 Switch 按键提示。详情:{log}",
|
||||
"warn.shaders_skipped": "显卡驱动在编译部分着色器时崩溃,因此有 {count} 个着色器未被预先准备。游戏会在首次需要时编译它们,驱动在那时也可能崩溃;更新驱动可能会解决。详情:{log}",
|
||||
"warn.kernel_old": "Linux {version} 缺少游戏依赖的写入跟踪功能(需要 6.7 或更新版本);游戏可能运行得很慢。更新系统即可解决。",
|
||||
"warn.dlss_kept": "安装文件夹中已有 DLSS 库({path});安装程序将保留它。",
|
||||
"warn.dlss_download_failed": "无法从 {url} 下载 NVIDIA DLSS:{detail}。游戏无需它也能运行;下次运行安装程序时会重试。",
|
||||
|
||||
"ui.title": "TotK 安装程序",
|
||||
"ui.rebuild_title": "正在为你的模组重新构建游戏",
|
||||
"ui.start_game": "启动游戏",
|
||||
"ui.version": "版本 {version}",
|
||||
"ui.intro": "用你自己的游戏文件构建一个可以游玩的《王国之泪》文件夹。耗时较长,只需运行一次。",
|
||||
"ui.notice": "此安装程序构建的文件夹包含游戏本身,仅供你个人使用;请勿分享或上传。",
|
||||
"ui.keys_private": "密钥文件只在原位置读取,其内容绝不会被显示、复制或保存。",
|
||||
"ui.base": "游戏本体",
|
||||
"ui.update": "更新",
|
||||
"ui.keys": "prod.keys",
|
||||
"ui.firmware": "固件(可选)",
|
||||
"ui.game_language": "游戏语言",
|
||||
"ui.dest": "安装文件夹",
|
||||
"ui.browse": "浏览...",
|
||||
"ui.pick_game": "选择游戏本体文件",
|
||||
"ui.pick_update": "选择 1.1.0、1.2.1 或 1.4.3 更新文件",
|
||||
"ui.pick_keys": "选择 prod.keys",
|
||||
"ui.pick_firmware": "选择 Switch 固件文件夹(Contents/registered)",
|
||||
"ui.pick_dest": "选择安装文件夹",
|
||||
"ui.firmware_help": "用于中文、韩文和繁体中文文本:固件的 Contents/registered 文件夹,例如来自 Ryujinx 或 Yuzu。安装程序会从中把 Switch 系统字体复制到安装文件夹。",
|
||||
"ui.dlss": "为 NVIDIA RTX 显卡下载 NVIDIA DLSS(nvngx_dlss.dll)",
|
||||
"ui.dlss_help": "来自 GitHub 上 NVIDIA 的 DLSS SDK,遵循 NVIDIA RTX SDK 许可(github.com/NVIDIA/DLSS)。没有它,dlaa 和 DLSS 设置不起作用。",
|
||||
"ui.compressed_help": "压缩的 NSZ 和 XCZ 文件可以直接使用:安装程序会自行解压(在游戏数据提取完成之前,需要与解压后文件大小相同的可用空间)。",
|
||||
"ui.section_files": "游戏文件",
|
||||
"ui.section_install": "安装",
|
||||
"ui.more_details": "▸ 更多说明",
|
||||
"ui.fewer_details": "▾ 收起说明",
|
||||
"ui.formats_help": "游戏本体:NSP、XCI、NSZ 或 XCZ。更新:1.1.0、1.2.1 或 1.4.3,NSP 或 NSZ 格式。",
|
||||
"ui.type_game": "游戏文件(NSP、XCI、NSZ、XCZ)",
|
||||
"ui.type_keys": "密钥文件(*.keys)",
|
||||
"ui.type_all": "所有文件",
|
||||
"ui.start": "开始",
|
||||
"ui.cancel": "取消",
|
||||
"ui.cancelling": "正在取消...",
|
||||
"ui.show_log": "显示日志",
|
||||
"ui.hide_log": "隐藏日志",
|
||||
"ui.close": "关闭",
|
||||
"ui.back": "返回",
|
||||
"ui.open_folder": "打开文件夹",
|
||||
"ui.update_mode": "此文件夹中已有之前的安装。安装程序会继续或更新它;只有在需要时才会再次要求提供游戏文件。",
|
||||
"ui.need_dest": "请选择安装文件夹。",
|
||||
"ui.need_base": "请选择游戏本体文件。",
|
||||
"ui.need_update": "请选择 1.1.0、1.2.1 或 1.4.3 更新文件。",
|
||||
"ui.need_keys": "请选择 prod.keys 文件。",
|
||||
"ui.need_lang": "请选择游戏语言。",
|
||||
"ui.missing_base": "游戏本体文件不存在。",
|
||||
"ui.missing_update": "更新文件不存在。",
|
||||
"ui.missing_keys": "密钥文件不存在。",
|
||||
"ui.missing_firmware": "固件文件夹不存在。",
|
||||
"ui.running_install": "正在安装",
|
||||
"ui.running_resume": "正在继续之前的安装",
|
||||
"ui.running_update": "正在更新安装",
|
||||
"ui.state_started": "已开始",
|
||||
"ui.state_done": "完成",
|
||||
"ui.state_skipped": "已跳过",
|
||||
"ui.state_pending": "等待中",
|
||||
"ui.state_running": "进行中",
|
||||
"ui.state_failed": "失败",
|
||||
"ui.log_warning": "警告",
|
||||
"ui.log_error": "错误",
|
||||
"ui.log_space": "所需空间:{need} GB,可用:{free} GB",
|
||||
"ui.log_end": "已结束",
|
||||
"ui.result_ok": "游戏已准备就绪",
|
||||
"ui.result_failed": "安装失败",
|
||||
"ui.result_cancelled": "安装已取消",
|
||||
"ui.done_text": "从 {dest} 启动 {game_exe}。安装程序和你选择的游戏文件都不再需要了。",
|
||||
"ui.cancelled_text": "已完成的步骤会保留。用同一个文件夹再次运行安装程序即可继续。",
|
||||
"ui.log_file": "日志文件:{path}",
|
||||
"ui.process_died": "安装程序意外停止(退出代码 {code})。",
|
||||
"ui.confirm_cancel": "安装正在进行。要取消安装并关闭窗口吗?",
|
||||
"ui.space_one": "{path} 需要的可用空间:{need} GB(可用:{free} GB)。",
|
||||
"ui.space_two": "{path} 需要的可用空间:{need} GB(可用:{free} GB);{temp} 需要:{temp_need} GB(可用:{temp_free} GB)。",
|
||||
"ui.amount_bytes": "{done} / {total} GB",
|
||||
"ui.amount_chunks": "{done} / {total} 部分",
|
||||
"ui.amount_objects": "{done} / {total} 个文件",
|
||||
"ui.amount_shaders": "{done} / {total} 个着色器",
|
||||
"ui.amount_other": "{done} / {total} {unit}",
|
||||
"ui.seconds": "{n} 秒",
|
||||
"param.input.base": "游戏本体",
|
||||
"param.input.update": "更新",
|
||||
"param.input.keys": "密钥",
|
||||
|
||||
"launcher.title": "TotK 安装程序",
|
||||
"launcher.python_missing": "安装文件不完整:TotK-Setup.exe 旁边缺少 python 文件夹。请重新解压整个压缩包,然后从解压出的文件夹中启动 TotK-Setup.exe。",
|
||||
|
||||
"lang.ja": "日语",
|
||||
"lang.en-US": "英语(美国)",
|
||||
"lang.en-GB": "英语(英国)",
|
||||
"lang.fr": "法语",
|
||||
"lang.fr-CA": "法语(加拿大)",
|
||||
"lang.de": "德语",
|
||||
"lang.it": "意大利语",
|
||||
"lang.es": "西班牙语",
|
||||
"lang.es-419": "西班牙语(拉丁美洲)",
|
||||
"lang.nl": "荷兰语",
|
||||
"lang.pt": "葡萄牙语",
|
||||
"lang.pt-BR": "葡萄牙语(巴西)",
|
||||
"lang.ru": "俄语",
|
||||
"lang.ko": "韩语",
|
||||
"lang.zh-Hans": "中文(简体)",
|
||||
"lang.zh-Hant": "中文(繁体)"
|
||||
}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) rdbende <rdbende@proton.me>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+130
@@ -0,0 +1,130 @@
|
||||
package require Tk 8.6-
|
||||
|
||||
source [file join [file dirname [info script]] theme light.tcl]
|
||||
source [file join [file dirname [info script]] theme dark.tcl]
|
||||
|
||||
|
||||
if {[tk windowingsystem] == "win32"} {
|
||||
set static ""
|
||||
} else {
|
||||
set static " static"
|
||||
}
|
||||
|
||||
font create SunValleyCaptionFont -family "Segoe UI Variable$static Small" -size -12
|
||||
font create SunValleyBodyFont -family "Segoe UI Variable$static Text" -size -14
|
||||
font create SunValleyBodyStrongFont -family "Segoe UI Variable$static Text Semibold" -size -14
|
||||
font create SunValleyBodyLargeFont -family "Segoe UI Variable$static Text" -size -18
|
||||
font create SunValleySubtitleFont -family "Segoe UI Variable$static Display Semibold" -size -20
|
||||
font create SunValleyTitleFont -family "Segoe UI Variable$static Display Semibold" -size -28
|
||||
font create SunValleyTitleLargeFont -family "Segoe UI Variable$static Display Semibold" -size -40
|
||||
font create SunValleyDisplayFont -family "Segoe UI Variable$static Display Semibold" -size -68
|
||||
|
||||
|
||||
proc config_entry_font {w} {
|
||||
set font_config [$w config -font]
|
||||
if {[lindex $font_config 3] != [lindex $font_config 4]} {
|
||||
return
|
||||
}
|
||||
if {[ttk::style theme use] in {"sun-valley-dark" "sun-valley-light"}} {
|
||||
$w configure -font SunValleyBodyFont
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
proc config_menus {w} {
|
||||
if {[tk windowingsystem] == "aqua" || [tk windowingsystem] == "win32"} {
|
||||
return
|
||||
}
|
||||
|
||||
set theme [ttk::style theme use]
|
||||
if {$theme == "sun-valley-dark"} {
|
||||
$w configure \
|
||||
-relief solid \
|
||||
-borderwidth 1 \
|
||||
-activeborderwidth 0 \
|
||||
-background "#292929" \
|
||||
-activebackground $ttk::theme::sv_dark::colors(-selbg) \
|
||||
-activeforeground $ttk::theme::sv_dark::colors(-selfg) \
|
||||
-selectcolor $ttk::theme::sv_dark::colors(-selfg)
|
||||
} elseif {$theme == "sun-valley-light"} {
|
||||
$w configure \
|
||||
-relief solid \
|
||||
-borderwidth 1 \
|
||||
-activeborderwidth 0 \
|
||||
-background "#e7e7e7" \
|
||||
-activebackground $ttk::theme::sv_light::colors(-selbg) \
|
||||
-activeforeground $ttk::theme::sv_light::colors(-selfg) \
|
||||
-selectcolor $ttk::theme::sv_light::colors(-selfg)
|
||||
}
|
||||
|
||||
if {[[winfo toplevel $w] cget -menu] != $w} {
|
||||
if {$theme == "sun-valley-dark"} {
|
||||
$w configure -borderwidth 0 -background $ttk::theme::sv_dark::colors(-bg)
|
||||
} elseif {$theme == "sun-valley-light"} {
|
||||
$w configure -borderwidth 0 -background $ttk::theme::sv_light::colors(-bg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
proc configure_colors {} {
|
||||
set theme [ttk::style theme use]
|
||||
if {$theme == "sun-valley-dark"} {
|
||||
ttk::style configure . \
|
||||
-background $ttk::theme::sv_dark::colors(-bg) \
|
||||
-foreground $ttk::theme::sv_dark::colors(-fg) \
|
||||
-troughcolor $ttk::theme::sv_dark::colors(-bg) \
|
||||
-focuscolor $ttk::theme::sv_dark::colors(-selbg) \
|
||||
-selectbackground $ttk::theme::sv_dark::colors(-selbg) \
|
||||
-selectforeground $ttk::theme::sv_dark::colors(-selfg) \
|
||||
-insertwidth 1 \
|
||||
-insertcolor $ttk::theme::sv_dark::colors(-fg) \
|
||||
-fieldbackground $ttk::theme::sv_dark::colors(-bg) \
|
||||
-font SunValleyBodyFont \
|
||||
-borderwidth 0 \
|
||||
-relief flat
|
||||
|
||||
tk_setPalette \
|
||||
background $ttk::theme::sv_dark::colors(-bg) \
|
||||
foreground $ttk::theme::sv_dark::colors(-fg) \
|
||||
highlightColor $ttk::theme::sv_dark::colors(-selbg) \
|
||||
selectBackground $ttk::theme::sv_dark::colors(-selbg) \
|
||||
selectForeground $ttk::theme::sv_dark::colors(-selfg) \
|
||||
activeBackground $ttk::theme::sv_dark::colors(-selbg) \
|
||||
activeForeground $ttk::theme::sv_dark::colors(-selfg)
|
||||
|
||||
ttk::style map . -foreground [list disabled $ttk::theme::sv_dark::colors(-disfg)]
|
||||
} elseif {$theme == "sun-valley-light"} {
|
||||
ttk::style configure . \
|
||||
-background $ttk::theme::sv_light::colors(-bg) \
|
||||
-foreground $ttk::theme::sv_light::colors(-fg) \
|
||||
-troughcolor $ttk::theme::sv_light::colors(-bg) \
|
||||
-focuscolor $ttk::theme::sv_light::colors(-selbg) \
|
||||
-selectbackground $ttk::theme::sv_light::colors(-selbg) \
|
||||
-selectforeground $ttk::theme::sv_light::colors(-selfg) \
|
||||
-insertwidth 1 \
|
||||
-insertcolor $ttk::theme::sv_light::colors(-fg) \
|
||||
-fieldbackground $ttk::theme::sv_light::colors(-bg) \
|
||||
-font SunValleyBodyFont \
|
||||
-borderwidth 0 \
|
||||
-relief flat
|
||||
|
||||
tk_setPalette \
|
||||
background $ttk::theme::sv_light::colors(-bg) \
|
||||
foreground $ttk::theme::sv_light::colors(-fg) \
|
||||
highlightColor $ttk::theme::sv_light::colors(-selbg) \
|
||||
selectBackground $ttk::theme::sv_light::colors(-selbg) \
|
||||
selectForeground $ttk::theme::sv_light::colors(-selfg) \
|
||||
activeBackground $ttk::theme::sv_light::colors(-selbg) \
|
||||
activeForeground $ttk::theme::sv_light::colors(-selfg)
|
||||
|
||||
ttk::style map . -foreground [list disabled $ttk::theme::sv_light::colors(-disfg)]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bind [winfo class .] <<ThemeChanged>> {+configure_colors}
|
||||
bind TEntry <<ThemeChanged>> {+config_entry_font %W}
|
||||
bind TCombobox <<ThemeChanged>> {+config_entry_font %W}
|
||||
bind TSpinbox <<ThemeChanged>> {+config_entry_font %W}
|
||||
bind Menu <<ThemeChanged>> {+config_menus %W}
|
||||
+465
@@ -0,0 +1,465 @@
|
||||
source [file join [file dirname [info script]] sprites_dark.tcl]
|
||||
|
||||
namespace eval ttk::theme::sv_dark {
|
||||
package provide ttk::theme::sv_dark 2.5
|
||||
|
||||
array set colors {
|
||||
-fg "#fafafa"
|
||||
-bg "#1c1c1c"
|
||||
-disfg "#595959"
|
||||
-selfg "#ffffff"
|
||||
-selbg "#2f60d8"
|
||||
-accent "#57c8ff"
|
||||
}
|
||||
|
||||
proc load_images {imgfile} {
|
||||
variable I
|
||||
image create photo spritesheet -file $imgfile -format png
|
||||
foreach {name x y width height} $::spriteinfo {
|
||||
set I($name) [image create photo -width $width -height $height]
|
||||
$I($name) copy spritesheet -from $x $y [expr {$x+$width}] [expr {$y+$height}]
|
||||
}
|
||||
}
|
||||
|
||||
load_images [file join [file dirname [info script]] spritesheet_dark.png]
|
||||
|
||||
ttk::style theme create sun-valley-dark -parent clam -settings {
|
||||
|
||||
# Button
|
||||
ttk::style layout TButton {
|
||||
Button.button -children {
|
||||
Button.padding -children {
|
||||
Button.label -side left -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TButton -padding {8 2 8 3} -anchor center -foreground $colors(-fg)
|
||||
ttk::style map TButton -foreground [list disabled "#7a7a7a" pressed "#d0d0d0"]
|
||||
|
||||
ttk::style element create Button.button image \
|
||||
[list $I(button-rest) \
|
||||
{selected disabled} $I(button-dis) \
|
||||
disabled $I(button-dis) \
|
||||
selected $I(button-rest) \
|
||||
pressed $I(button-pressed) \
|
||||
{active focus} $I(button-focus-hover) \
|
||||
active $I(button-hover) \
|
||||
focus $I(button-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
# Toolbutton
|
||||
ttk::style layout Toolbutton {
|
||||
Toolbutton.button -children {
|
||||
Toolbutton.padding -children {
|
||||
Toolbutton.label -side left -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure Toolbutton -padding {8 2 8 3} -anchor center
|
||||
|
||||
ttk::style element create Toolbutton.button image \
|
||||
[list $I(empty) \
|
||||
disabled $I(button-dis) \
|
||||
pressed $I(button-pressed) \
|
||||
{active focus} $I(button-focus-hover) \
|
||||
active $I(button-hover) \
|
||||
focus $I(button-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
# Accent.TButton
|
||||
ttk::style layout Accent.TButton {
|
||||
AccentButton.button -children {
|
||||
AccentButton.padding -children {
|
||||
AccentButton.label -side left -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure Accent.TButton -padding {8 2 8 3} -anchor center -foreground "#000000"
|
||||
ttk::style map Accent.TButton -foreground [list pressed "#25536a" disabled "#a5a5a5"]
|
||||
|
||||
ttk::style element create AccentButton.button image \
|
||||
[list $I(button-accent-rest) \
|
||||
{selected disabled} $I(button-accent-dis) \
|
||||
disabled $I(button-accent-dis) \
|
||||
selected $I(button-accent-rest) \
|
||||
pressed $I(button-accent-pressed) \
|
||||
{active focus} $I(button-accent-focus-hover) \
|
||||
active $I(button-accent-hover) \
|
||||
focus $I(button-accent-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
# Menubutton
|
||||
ttk::style layout TMenubutton {
|
||||
Menubutton.button -children {
|
||||
Menubutton.padding -children {
|
||||
Menubutton.label -side left -expand 1
|
||||
Menubutton.indicator -side right -sticky nsew
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TMenubutton -padding {8 2 13 3}
|
||||
|
||||
ttk::style element create Menubutton.button image \
|
||||
[list $I(button-rest) \
|
||||
disabled $I(button-dis) \
|
||||
pressed $I(button-pressed) \
|
||||
{active focus} $I(button-focus-hover) \
|
||||
active $I(button-hover) \
|
||||
focus $I(button-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
ttk::style element create Menubutton.indicator image $I(down) -width 10 -sticky e
|
||||
|
||||
# OptionMenu
|
||||
ttk::style layout TOptionMenu {
|
||||
OptionMenu.button -children {
|
||||
OptionMenu.padding -children {
|
||||
OptionMenu.label -side left -expand 1
|
||||
OptionMenu.indicator -side right -sticky nsew
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TOptionMenu -padding {8 2 13 3}
|
||||
|
||||
ttk::style element create OptionMenu.button image \
|
||||
[list $I(button-rest) \
|
||||
disabled $I(button-dis) \
|
||||
pressed $I(button-pressed) \
|
||||
{active focus} $I(button-focus-hover) \
|
||||
active $I(button-hover) \
|
||||
focus $I(button-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
ttk::style element create OptionMenu.indicator image $I(down) -width 10 -sticky e
|
||||
|
||||
# Checkbutton
|
||||
ttk::style layout TCheckbutton {
|
||||
Checkbutton.button -children {
|
||||
Checkbutton.padding -children {
|
||||
Checkbutton.indicator -side left
|
||||
Checkbutton.label -side right -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TCheckbutton -padding 4
|
||||
|
||||
ttk::style element create Checkbutton.indicator image \
|
||||
[list $I(check-unsel-rest) \
|
||||
{alternate disabled} $I(check-tri-dis) \
|
||||
{selected disabled} $I(check-dis) \
|
||||
disabled $I(check-unsel-dis) \
|
||||
{pressed alternate} $I(check-tri-hover) \
|
||||
{active focus alternate} $I(check-tri-focus-hover) \
|
||||
{active alternate} $I(check-tri-hover) \
|
||||
{focus alternate} $I(check-tri-focus) \
|
||||
alternate $I(check-tri-rest) \
|
||||
{pressed selected} $I(check-hover) \
|
||||
{active focus selected} $I(check-focus-hover) \
|
||||
{active selected} $I(check-hover) \
|
||||
{focus selected} $I(check-focus) \
|
||||
selected $I(check-rest) \
|
||||
{pressed !selected} $I(check-unsel-pressed) \
|
||||
{active focus} $I(check-unsel-focus-hover) \
|
||||
active $I(check-unsel-hover) \
|
||||
focus $I(check-unsel-focus) \
|
||||
] -width 26 -sticky w
|
||||
|
||||
# Switch.TCheckbutton
|
||||
ttk::style layout Switch.TCheckbutton {
|
||||
Switch.button -children {
|
||||
Switch.padding -children {
|
||||
Switch.indicator -side left
|
||||
Switch.label -side right -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style element create Switch.indicator image \
|
||||
[list $I(switch-off-rest) \
|
||||
{selected disabled} $I(switch-dis) \
|
||||
disabled $I(switch-off-dis) \
|
||||
{pressed selected} $I(switch-pressed) \
|
||||
{active focus selected} $I(switch-focus-hover) \
|
||||
{active selected} $I(switch-hover) \
|
||||
{focus selected} $I(switch-focus) \
|
||||
selected $I(switch-rest) \
|
||||
{pressed !selected} $I(switch-off-pressed) \
|
||||
{active focus} $I(switch-off-focus-hover) \
|
||||
active $I(switch-off-hover) \
|
||||
focus $I(switch-off-focus) \
|
||||
] -width 46 -sticky w
|
||||
|
||||
# Toggle.TButton
|
||||
ttk::style layout Toggle.TButton {
|
||||
ToggleButton.button -children {
|
||||
ToggleButton.padding -children {
|
||||
ToggleButton.label -side left -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure Toggle.TButton -padding {8 2 8 3} -anchor center -foreground $colors(-fg)
|
||||
|
||||
ttk::style map Toggle.TButton -foreground \
|
||||
[list {selected disabled} "#a5a5a5" \
|
||||
{selected pressed} "#d0d0d0" \
|
||||
selected "#000000" \
|
||||
pressed "#25536a" \
|
||||
disabled "#7a7a7a"
|
||||
]
|
||||
|
||||
ttk::style element create ToggleButton.button image \
|
||||
[list $I(button-rest) \
|
||||
{selected disabled} $I(button-accent-dis) \
|
||||
disabled $I(button-dis) \
|
||||
{pressed selected} $I(button-rest) \
|
||||
{active focus selected} $I(button-accent-focus-hover) \
|
||||
{active selected} $I(button-accent-hover) \
|
||||
{focus selected} $I(button-accent-focus) \
|
||||
selected $I(button-accent-rest) \
|
||||
{pressed !selected} $I(button-accent-rest) \
|
||||
{active focus} $I(button-focus-hover) \
|
||||
active $I(button-hover) \
|
||||
focus $I(button-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
# Radiobutton
|
||||
ttk::style layout TRadiobutton {
|
||||
Radiobutton.button -children {
|
||||
Radiobutton.padding -children {
|
||||
Radiobutton.indicator -side left
|
||||
Radiobutton.label -side right -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TRadiobutton -padding 4
|
||||
|
||||
ttk::style element create Radiobutton.indicator image \
|
||||
[list $I(radio-unsel-rest) \
|
||||
{selected disabled} $I(radio-dis) \
|
||||
disabled $I(radio-unsel-dis) \
|
||||
{pressed selected} $I(radio-pressed) \
|
||||
{active focus selected} $I(radio-focus-hover) \
|
||||
{active selected} $I(radio-hover) \
|
||||
{focus selected} $I(radio-focus) \
|
||||
selected $I(radio-rest) \
|
||||
{pressed !selected} $I(radio-unsel-pressed) \
|
||||
{active focus} $I(radio-unsel-focus-hover) \
|
||||
active $I(radio-unsel-hover) \
|
||||
focus $I(radio-unsel-focus) \
|
||||
] -width 26 -sticky w
|
||||
|
||||
# Entry
|
||||
ttk::style configure TEntry -foreground $colors(-fg) -padding {6 1 4 2}
|
||||
ttk::style map TEntry -foreground [list disabled "#757575" pressed "#cfcfcf"]
|
||||
|
||||
ttk::style element create Entry.field image \
|
||||
[list $I(textbox-rest) \
|
||||
{focus hover !invalid} $I(textbox-focus) \
|
||||
invalid $I(textbox-error) \
|
||||
disabled $I(textbox-dis) \
|
||||
{focus !invalid} $I(textbox-focus) \
|
||||
hover $I(textbox-hover) \
|
||||
] -border 5 -sticky nsew
|
||||
|
||||
# Combobox
|
||||
ttk::style layout TCombobox {
|
||||
Combobox.field -sticky nsew -children {
|
||||
Combobox.arrow -side right -sticky ns
|
||||
Combobox.padding -sticky nsew -children {
|
||||
Combobox.textarea -sticky nsew
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TCombobox -foreground $colors(-fg) -padding {6 1 0 2}
|
||||
ttk::style configure ComboboxPopdownFrame -borderwidth 1 -relief solid
|
||||
ttk::style map TCombobox -foreground [list disabled "#757575" pressed "#cfcfcf"]
|
||||
|
||||
ttk::style map TCombobox -selectbackground [list \
|
||||
{readonly hover} $colors(-selbg) \
|
||||
{readonly focus} $colors(-selbg) \
|
||||
] -selectforeground [list \
|
||||
{readonly hover} $colors(-selfg) \
|
||||
{readonly focus} $colors(-selfg) \
|
||||
]
|
||||
|
||||
ttk::style element create Combobox.field image \
|
||||
[list $I(textbox-rest) \
|
||||
{readonly focus} $I(button-focus) \
|
||||
{readonly disabled} $I(button-dis) \
|
||||
{readonly pressed} $I(button-pressed) \
|
||||
{readonly hover} $I(button-hover) \
|
||||
readonly $I(button-rest) \
|
||||
{focus hover !invalid} $I(textbox-focus) \
|
||||
invalid $I(textbox-error) \
|
||||
disabled $I(textbox-dis) \
|
||||
focus $I(textbox-focus) \
|
||||
{focus !invalid} $I(textbox-focus) \
|
||||
hover $I(textbox-hover) \
|
||||
] -border 5
|
||||
|
||||
ttk::style element create Combobox.arrow image $I(down) -width 34 -sticky {}
|
||||
|
||||
# Spinbox
|
||||
ttk::style layout TSpinbox {
|
||||
Spinbox.field -side top -sticky we -children {
|
||||
Spinbox.downarrow -side right -sticky ns
|
||||
Spinbox.uparrow -side right -sticky ns
|
||||
Spinbox.padding -sticky nswe -children {
|
||||
Spinbox.textarea -sticky nsew
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TSpinbox -foreground $colors(-fg) -padding {6 1 0 2}
|
||||
ttk::style map TSpinbox -foreground [list disabled "#757575" pressed "#cfcfcf"]
|
||||
|
||||
ttk::style element create Spinbox.field image \
|
||||
[list $I(textbox-rest) \
|
||||
{focus hover !invalid} $I(textbox-focus) \
|
||||
invalid $I(textbox-error) \
|
||||
disabled $I(textbox-dis) \
|
||||
focus $I(textbox-focus) \
|
||||
{focus !invalid} $I(textbox-focus) \
|
||||
hover $I(textbox-hover) \
|
||||
] -border 5 -sticky nsew
|
||||
|
||||
ttk::style element create Spinbox.uparrow image $I(up) -width 34 -height 16 -sticky {}
|
||||
ttk::style element create Spinbox.downarrow image $I(down) -width 34 -height 16 -sticky {}
|
||||
|
||||
# Progressbar
|
||||
ttk::style element create Horizontal.Progressbar.trough image $I(progressbar-trough-hor) -border 1 -sticky ew
|
||||
ttk::style element create Horizontal.Progressbar.pbar image $I(progressbar-bar-hor) -border 2 -sticky ew
|
||||
|
||||
ttk::style element create Vertical.Progressbar.trough image $I(progressbar-trough-vert) -border 1 -sticky ns
|
||||
ttk::style element create Vertical.Progressbar.pbar image $I(progressbar-bar-vert) -border 2 -sticky ns
|
||||
|
||||
# Scale
|
||||
ttk::style element create Horizontal.Scale.trough image $I(slider-trough-hor) \
|
||||
-border 5 -padding 0 -sticky {ew}
|
||||
|
||||
ttk::style element create Vertical.Scale.trough image $I(slider-trough-vert) \
|
||||
-border 5 -padding 0 -sticky {ns}
|
||||
|
||||
ttk::style element create Scale.slider image \
|
||||
[list $I(slider-thumb-rest) \
|
||||
disabled $I(slider-thumb-dis) \
|
||||
pressed $I(slider-thumb-pressed) \
|
||||
{active focus} $I(slider-thumb-focus-hover) \
|
||||
active $I(slider-thumb-hover) \
|
||||
focus $I(slider-thumb-focus) \
|
||||
] -sticky {}
|
||||
|
||||
# Scrollbar
|
||||
ttk::style layout Vertical.TScrollbar {
|
||||
Vertical.Scrollbar.trough -sticky ns -children {
|
||||
Vertical.Scrollbar.uparrow -side top
|
||||
Vertical.Scrollbar.downarrow -side bottom
|
||||
Vertical.Scrollbar.thumb -expand 1
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style layout Horizontal.TScrollbar {
|
||||
Horizontal.Scrollbar.trough -sticky ew -children {
|
||||
Horizontal.Scrollbar.leftarrow -side left
|
||||
Horizontal.Scrollbar.rightarrow -side right
|
||||
Horizontal.Scrollbar.thumb -expand 1
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style element create Horizontal.Scrollbar.trough image $I(scrollbar-trough-hor) -sticky ew -border {6 0}
|
||||
ttk::style element create Horizontal.Scrollbar.thumb image $I(scrollbar-thumb-hor) -sticky ew -border {3 0}
|
||||
|
||||
ttk::style element create Horizontal.Scrollbar.rightarrow image $I(scrollbar-right) -sticky e -width 13
|
||||
ttk::style element create Horizontal.Scrollbar.leftarrow image $I(scrollbar-left) -sticky w -width 13
|
||||
|
||||
ttk::style element create Vertical.Scrollbar.trough image $I(scrollbar-trough-vert) -sticky ns -border {0 6}
|
||||
ttk::style element create Vertical.Scrollbar.thumb image $I(scrollbar-thumb-vert) -sticky ns -border {0 3}
|
||||
|
||||
ttk::style element create Vertical.Scrollbar.uparrow image $I(scrollbar-up) -sticky n -height 13
|
||||
ttk::style element create Vertical.Scrollbar.downarrow image $I(scrollbar-down) -sticky s -height 13
|
||||
|
||||
# Separator
|
||||
ttk::style element create Separator.separator image $I(sep) -width 1 -height 1
|
||||
|
||||
# Sizegrip
|
||||
ttk::style element create Sizegrip.sizegrip image $I(grip) -sticky nsew
|
||||
|
||||
# Card
|
||||
ttk::style layout Card.TFrame {
|
||||
Card.field {
|
||||
Card.padding -expand 1
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style element create Card.field image $I(card) -border 10 -padding 4 -sticky nsew
|
||||
|
||||
# Labelframe
|
||||
ttk::style layout TLabelframe {
|
||||
Labelframe.border {
|
||||
Labelframe.padding -expand 1 -children {
|
||||
Labelframe.label -side left
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style element create Labelframe.border image $I(card) -border 5 -padding 4 -sticky nsew
|
||||
ttk::style configure TLabelframe.Label -font SunValleyCaptionFont
|
||||
|
||||
# Notebook
|
||||
ttk::style layout TNotebook {
|
||||
Notebook.border -children {
|
||||
TNotebook.Tab -expand 1
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TNotebook -padding 1
|
||||
ttk::style configure TNotebook.Tab -focuscolor $colors(-accent)
|
||||
ttk::style element create Notebook.border image $I(notebook-border) -border 5 -padding 5
|
||||
|
||||
ttk::style element create Notebook.tab image \
|
||||
[list $I(tab-rest) \
|
||||
selected $I(tab-selected) \
|
||||
active $I(tab-hover) \
|
||||
] -border 13 -padding {16 14 16 6} -height 32
|
||||
|
||||
# Treeview
|
||||
ttk::style configure Heading -font SunValleyCaptionFont
|
||||
ttk::style configure Treeview \
|
||||
-background $colors(-bg) \
|
||||
-rowheight [expr {[font metrics SunValleyBodyFont -linespace] + 3}] \
|
||||
-font SunValleyBodyFont
|
||||
|
||||
ttk::style map Treeview -background {selected "#292929"} -foreground "selected $colors(-selfg)"
|
||||
|
||||
ttk::style element create Treeview.field image $I(card) -border 5 -width 0 -height 0
|
||||
|
||||
ttk::style element create Treeheading.cell image \
|
||||
[list $I(heading-rest) \
|
||||
pressed $I(heading-pressed) \
|
||||
active $I(heading-hover)
|
||||
] -border 5 -padding 14 -sticky nsew
|
||||
|
||||
ttk::style element create Treeitem.indicator image \
|
||||
[list $I(right) \
|
||||
user2 $I(empty) \
|
||||
user1 $I(down) \
|
||||
] -width 26 -sticky {}
|
||||
|
||||
# Panedwindow
|
||||
ttk::style configure Sash \
|
||||
-lightcolor "#9e9e9e" \
|
||||
-darkcolor "#9e9e9e" \
|
||||
-bordercolor "#9e9e9e" \
|
||||
-sashthickness 4 \
|
||||
-gripcount 20
|
||||
}
|
||||
}
|
||||
+469
@@ -0,0 +1,469 @@
|
||||
source [file join [file dirname [info script]] sprites_light.tcl]
|
||||
|
||||
namespace eval ttk::theme::sv_light {
|
||||
package provide ttk::theme::sv_light 2.5
|
||||
|
||||
array set colors {
|
||||
-fg "#1c1c1c"
|
||||
-bg "#fafafa"
|
||||
-disfg "#a0a0a0"
|
||||
-selfg "#ffffff"
|
||||
-selbg "#2f60d8"
|
||||
-accent "#005fb8"
|
||||
}
|
||||
|
||||
proc load_images {imgfile} {
|
||||
variable I
|
||||
image create photo spritesheet -file $imgfile -format png
|
||||
foreach {name x y width height} $::spriteinfo {
|
||||
set I($name) [image create photo -width $width -height $height]
|
||||
$I($name) copy spritesheet -from $x $y [expr {$x+$width}] [expr {$y+$height}]
|
||||
}
|
||||
}
|
||||
|
||||
load_images [file join [file dirname [info script]] spritesheet_light.png]
|
||||
|
||||
ttk::style theme create sun-valley-light -parent clam -settings {
|
||||
|
||||
# Button
|
||||
ttk::style layout TButton {
|
||||
Button.button -children {
|
||||
Button.padding -children {
|
||||
Button.label -side left -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TButton -padding {8 2 8 3} -anchor center -foreground $colors(-fg)
|
||||
ttk::style map TButton -foreground [list disabled "#a2a2a2" pressed "#636363" active "#1a1a1a"]
|
||||
|
||||
ttk::style element create Button.button image \
|
||||
[list $I(button-rest) \
|
||||
{selected disabled} $I(button-dis) \
|
||||
disabled $I(button-dis) \
|
||||
selected $I(button-rest) \
|
||||
pressed $I(button-pressed) \
|
||||
{active focus} $I(button-focus-hover) \
|
||||
active $I(button-hover) \
|
||||
focus $I(button-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
# Toolbutton
|
||||
ttk::style layout Toolbutton {
|
||||
Toolbutton.button -children {
|
||||
Toolbutton.padding -children {
|
||||
Toolbutton.label -side left -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure Toolbutton -padding {8 2 8 3} -anchor center
|
||||
|
||||
ttk::style element create Toolbutton.button image \
|
||||
[list $I(empty) \
|
||||
disabled $I(button-dis) \
|
||||
pressed $I(button-pressed) \
|
||||
{active focus} $I(button-focus-hover) \
|
||||
active $I(button-hover) \
|
||||
focus $I(button-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
# Accent.TButton
|
||||
ttk::style layout Accent.TButton {
|
||||
AccentButton.button -children {
|
||||
AccentButton.padding -children {
|
||||
AccentButton.label -side left -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure Accent.TButton -padding {8 2 8 3} -anchor center -foreground "#ffffff"
|
||||
ttk::style map Accent.TButton -foreground [list pressed "#c1d8ee" disabled "#ffffff"]
|
||||
|
||||
ttk::style element create AccentButton.button image \
|
||||
[list $I(button-accent-rest) \
|
||||
{selected disabled} $I(button-accent-dis) \
|
||||
disabled $I(button-accent-dis) \
|
||||
selected $I(button-accent-rest) \
|
||||
pressed $I(button-accent-pressed) \
|
||||
{active focus} $I(button-accent-focus-hover) \
|
||||
active $I(button-accent-hover) \
|
||||
focus $I(button-accent-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
# Menubutton
|
||||
ttk::style layout TMenubutton {
|
||||
Menubutton.button -children {
|
||||
Menubutton.padding -children {
|
||||
Menubutton.label -side left -expand 1
|
||||
Menubutton.indicator -side right -sticky nsew
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TMenubutton -padding {8 2 13 3}
|
||||
|
||||
ttk::style element create Menubutton.button image \
|
||||
[list $I(button-rest) \
|
||||
disabled $I(button-dis) \
|
||||
pressed $I(button-pressed) \
|
||||
{active focus} $I(button-focus-hover) \
|
||||
active $I(button-hover) \
|
||||
focus $I(button-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
ttk::style element create Menubutton.indicator image $I(down) -width 10 -sticky e
|
||||
|
||||
# OptionMenu
|
||||
ttk::style layout TOptionMenu {
|
||||
OptionMenu.button -children {
|
||||
OptionMenu.padding -children {
|
||||
OptionMenu.label -side left -expand 1
|
||||
OptionMenu.indicator -side right -sticky nsew
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TOptionMenu -padding {8 2 13 3}
|
||||
|
||||
ttk::style element create OptionMenu.button image \
|
||||
[list $I(button-rest) \
|
||||
disabled $I(button-dis) \
|
||||
pressed $I(button-pressed) \
|
||||
{active focus} $I(button-focus-hover) \
|
||||
active $I(button-hover) \
|
||||
focus $I(button-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
ttk::style element create OptionMenu.indicator image $I(down) -width 10 -sticky e
|
||||
|
||||
# Checkbutton
|
||||
ttk::style layout TCheckbutton {
|
||||
Checkbutton.button -children {
|
||||
Checkbutton.padding -children {
|
||||
Checkbutton.indicator -side left
|
||||
Checkbutton.label -side right -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TCheckbutton -padding 4
|
||||
|
||||
ttk::style element create Checkbutton.indicator image \
|
||||
[list $I(check-unsel-rest) \
|
||||
{alternate disabled} $I(check-tri-dis) \
|
||||
{selected disabled} $I(check-dis) \
|
||||
disabled $I(check-unsel-dis) \
|
||||
{pressed alternate} $I(check-tri-hover) \
|
||||
{active focus alternate} $I(check-tri-focus-hover) \
|
||||
{active alternate} $I(check-tri-hover) \
|
||||
{focus alternate} $I(check-tri-focus) \
|
||||
alternate $I(check-tri-rest) \
|
||||
{pressed selected} $I(check-hover) \
|
||||
{active focus selected} $I(check-focus-hover) \
|
||||
{active selected} $I(check-hover) \
|
||||
{focus selected} $I(check-focus) \
|
||||
selected $I(check-rest) \
|
||||
{pressed !selected} $I(check-unsel-pressed) \
|
||||
{active focus} $I(check-unsel-focus-hover) \
|
||||
active $I(check-unsel-hover) \
|
||||
focus $I(check-unsel-focus) \
|
||||
] -width 26 -sticky w
|
||||
|
||||
# Switch.TCheckbutton
|
||||
ttk::style layout Switch.TCheckbutton {
|
||||
Switch.button -children {
|
||||
Switch.padding -children {
|
||||
Switch.indicator -side left
|
||||
Switch.label -side right -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style element create Switch.indicator image \
|
||||
[list $I(switch-off-rest) \
|
||||
{selected disabled} $I(switch-dis) \
|
||||
disabled $I(switch-off-dis) \
|
||||
{pressed selected} $I(switch-pressed) \
|
||||
{active focus selected} $I(switch-focus-hover) \
|
||||
{active selected} $I(switch-hover) \
|
||||
{focus selected} $I(switch-focus) \
|
||||
selected $I(switch-rest) \
|
||||
{pressed !selected} $I(switch-off-pressed) \
|
||||
{active focus} $I(switch-off-focus-hover) \
|
||||
active $I(switch-off-hover) \
|
||||
focus $I(switch-off-focus) \
|
||||
] -width 46 -sticky w
|
||||
|
||||
# Toggle.TButton
|
||||
ttk::style layout Toggle.TButton {
|
||||
ToggleButton.button -children {
|
||||
ToggleButton.padding -children {
|
||||
ToggleButton.label -side left -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure Toggle.TButton -padding {8 2 8 3} -anchor center -foreground $colors(-fg)
|
||||
|
||||
ttk::style map Toggle.TButton -foreground \
|
||||
[list {selected disabled} "#ffffff" \
|
||||
{selected pressed} "#636363" \
|
||||
selected "#ffffff" \
|
||||
pressed "#c1d8ee" \
|
||||
disabled "#a2a2a2" \
|
||||
active "#1a1a1a"
|
||||
]
|
||||
|
||||
ttk::style element create ToggleButton.button image \
|
||||
[list $I(button-rest) \
|
||||
{selected disabled} $I(button-accent-dis) \
|
||||
disabled $I(button-dis) \
|
||||
{pressed selected} $I(button-rest) \
|
||||
{active focus selected} $I(button-accent-focus-hover) \
|
||||
{active selected} $I(button-accent-hover) \
|
||||
{focus selected} $I(button-accent-focus) \
|
||||
selected $I(button-accent-rest) \
|
||||
{pressed !selected} $I(button-accent-rest) \
|
||||
{active focus} $I(button-focus-hover) \
|
||||
active $I(button-hover) \
|
||||
focus $I(button-focus) \
|
||||
] -border 4 -sticky nsew
|
||||
|
||||
# Radiobutton
|
||||
ttk::style layout TRadiobutton {
|
||||
Radiobutton.button -children {
|
||||
Radiobutton.padding -children {
|
||||
Radiobutton.indicator -side left
|
||||
Radiobutton.label -side right -expand 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TRadiobutton -padding 4
|
||||
|
||||
ttk::style element create Radiobutton.indicator image \
|
||||
[list $I(radio-unsel-rest) \
|
||||
{selected disabled} $I(radio-dis) \
|
||||
disabled $I(radio-unsel-dis) \
|
||||
{pressed selected} $I(radio-pressed) \
|
||||
{active focus selected} $I(radio-focus-hover) \
|
||||
{active selected} $I(radio-hover) \
|
||||
{focus selected} $I(radio-focus) \
|
||||
selected $I(radio-rest) \
|
||||
{pressed !selected} $I(radio-unsel-pressed) \
|
||||
{active focus} $I(radio-unsel-focus-hover) \
|
||||
active $I(radio-unsel-hover) \
|
||||
focus $I(radio-unsel-focus) \
|
||||
] -width 26 -sticky w
|
||||
|
||||
# Entry
|
||||
ttk::style configure TEntry -foreground $colors(-fg) -padding {6 1 4 2}
|
||||
ttk::style map TEntry -foreground [list disabled $colors(-disfg) pressed "#636363" active "#626262"]
|
||||
|
||||
ttk::style element create Entry.field image \
|
||||
[list $I(textbox-rest) \
|
||||
{focus hover !invalid} $I(textbox-focus) \
|
||||
invalid $I(textbox-error) \
|
||||
disabled $I(textbox-dis) \
|
||||
{focus !invalid} $I(textbox-focus) \
|
||||
hover $I(textbox-hover) \
|
||||
] -border 5 -sticky nsew
|
||||
|
||||
# Combobox
|
||||
ttk::style layout TCombobox {
|
||||
Combobox.field -sticky nsew -children {
|
||||
Combobox.arrow -side right -sticky ns
|
||||
Combobox.padding -sticky nsew -children {
|
||||
Combobox.textarea -sticky nsew
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TCombobox -foreground $colors(-fg) -padding {6 1 0 2}
|
||||
ttk::style configure ComboboxPopdownFrame -borderwidth 1 -relief solid
|
||||
ttk::style map TCombobox -foreground [list disabled $colors(-disfg) pressed "#636363" active "#626262"]
|
||||
|
||||
ttk::style map TCombobox -selectbackground [list \
|
||||
{readonly hover} $colors(-selbg) \
|
||||
{readonly focus} $colors(-selbg) \
|
||||
] -selectforeground [list \
|
||||
{readonly hover} $colors(-selfg) \
|
||||
{readonly focus} $colors(-selfg) \
|
||||
]
|
||||
|
||||
ttk::style element create Combobox.field image \
|
||||
[list $I(textbox-rest) \
|
||||
{readonly focus} $I(button-focus) \
|
||||
{readonly disabled} $I(button-dis) \
|
||||
{readonly pressed} $I(button-pressed) \
|
||||
{readonly hover} $I(button-hover) \
|
||||
readonly $I(button-rest) \
|
||||
{focus hover !invalid} $I(textbox-focus) \
|
||||
invalid $I(textbox-error) \
|
||||
disabled $I(textbox-dis) \
|
||||
focus $I(textbox-focus) \
|
||||
{focus !invalid} $I(textbox-focus) \
|
||||
hover $I(textbox-hover) \
|
||||
] -border 5
|
||||
|
||||
ttk::style element create Combobox.arrow image $I(down) -width 34 -sticky {}
|
||||
|
||||
# Spinbox
|
||||
ttk::style layout TSpinbox {
|
||||
Spinbox.field -side top -sticky we -children {
|
||||
Spinbox.downarrow -side right -sticky ns
|
||||
Spinbox.uparrow -side right -sticky ns
|
||||
Spinbox.padding -sticky nswe -children {
|
||||
Spinbox.textarea -sticky nsew
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TSpinbox -foreground $colors(-fg) -padding {6 1 0 2}
|
||||
ttk::style map TSpinbox -foreground [list disabled $colors(-disfg) pressed "#636363" active "#626262"]
|
||||
|
||||
ttk::style element create Spinbox.field image \
|
||||
[list $I(textbox-rest) \
|
||||
{focus hover !invalid} $I(textbox-focus) \
|
||||
invalid $I(textbox-error) \
|
||||
disabled $I(textbox-dis) \
|
||||
focus $I(textbox-focus) \
|
||||
{focus !invalid} $I(textbox-focus) \
|
||||
hover $I(textbox-hover) \
|
||||
] -border 5 -sticky nsew
|
||||
|
||||
ttk::style element create Spinbox.uparrow image $I(up) -width 34 -height 16 -sticky {}
|
||||
ttk::style element create Spinbox.downarrow image $I(down) -width 34 -height 16 -sticky {}
|
||||
|
||||
# Progressbar
|
||||
ttk::style element create Horizontal.Progressbar.trough image $I(progressbar-trough-hor) \
|
||||
-border 1 -sticky ew
|
||||
ttk::style element create Horizontal.Progressbar.pbar image $I(progressbar-bar-hor) \
|
||||
-border 2 -sticky ew
|
||||
|
||||
ttk::style element create Vertical.Progressbar.trough image $I(progressbar-trough-vert) \
|
||||
-border 1 -sticky ns
|
||||
ttk::style element create Vertical.Progressbar.pbar image $I(progressbar-bar-vert) \
|
||||
-border 2 -sticky ns
|
||||
|
||||
# Scale
|
||||
ttk::style element create Horizontal.Scale.trough image $I(slider-trough-hor) \
|
||||
-border 5 -padding 0 -sticky {ew}
|
||||
|
||||
ttk::style element create Vertical.Scale.trough image $I(slider-trough-vert) \
|
||||
-border 5 -padding 0 -sticky {ns}
|
||||
|
||||
ttk::style element create Scale.slider image \
|
||||
[list $I(slider-thumb-rest) \
|
||||
disabled $I(slider-thumb-dis) \
|
||||
pressed $I(slider-thumb-pressed) \
|
||||
{active focus} $I(slider-thumb-focus-hover) \
|
||||
active $I(slider-thumb-hover) \
|
||||
focus $I(slider-thumb-focus) \
|
||||
] -sticky {}
|
||||
|
||||
# Scrollbar
|
||||
ttk::style layout Vertical.TScrollbar {
|
||||
Vertical.Scrollbar.trough -sticky ns -children {
|
||||
Vertical.Scrollbar.uparrow -side top
|
||||
Vertical.Scrollbar.downarrow -side bottom
|
||||
Vertical.Scrollbar.thumb -expand 1
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style layout Horizontal.TScrollbar {
|
||||
Horizontal.Scrollbar.trough -sticky ew -children {
|
||||
Horizontal.Scrollbar.leftarrow -side left
|
||||
Horizontal.Scrollbar.rightarrow -side right
|
||||
Horizontal.Scrollbar.thumb -expand 1
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style element create Horizontal.Scrollbar.trough image $I(scrollbar-trough-hor) -sticky ew -border {6 0}
|
||||
ttk::style element create Horizontal.Scrollbar.thumb image $I(scrollbar-thumb-hor) -sticky ew -border {3 0}
|
||||
|
||||
ttk::style element create Horizontal.Scrollbar.rightarrow image $I(scrollbar-right) -sticky e -width 13
|
||||
ttk::style element create Horizontal.Scrollbar.leftarrow image $I(scrollbar-left) -sticky w -width 13
|
||||
|
||||
ttk::style element create Vertical.Scrollbar.trough image $I(scrollbar-trough-vert) -sticky ns -border {0 6}
|
||||
ttk::style element create Vertical.Scrollbar.thumb image $I(scrollbar-thumb-vert) -sticky ns -border {0 3}
|
||||
|
||||
ttk::style element create Vertical.Scrollbar.uparrow image $I(scrollbar-up) -sticky n -height 13
|
||||
ttk::style element create Vertical.Scrollbar.downarrow image $I(scrollbar-down) -sticky s -height 13
|
||||
|
||||
# Separator
|
||||
ttk::style element create Separator.separator image $I(sep) -width 1 -height 1
|
||||
|
||||
# Sizegrip
|
||||
ttk::style element create Sizegrip.sizegrip image $I(grip) -sticky nsew
|
||||
|
||||
# Card
|
||||
ttk::style layout Card.TFrame {
|
||||
Card.field {
|
||||
Card.padding -expand 1
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style element create Card.field image $I(card) -border 10 -padding 4 -sticky nsew
|
||||
|
||||
# Labelframe
|
||||
ttk::style layout TLabelframe {
|
||||
Labelframe.border {
|
||||
Labelframe.padding -expand 1 -children {
|
||||
Labelframe.label -side left
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style element create Labelframe.border image $I(card) -border 5 -padding 4 -sticky nsew
|
||||
ttk::style configure TLabelframe.Label -font SunValleyCaptionFont
|
||||
|
||||
# Notebook
|
||||
ttk::style layout TNotebook {
|
||||
Notebook.border -children {
|
||||
TNotebook.Tab -expand 1
|
||||
}
|
||||
}
|
||||
|
||||
ttk::style configure TNotebook -padding 1
|
||||
ttk::style configure TNotebook.Tab -focuscolor $colors(-accent)
|
||||
ttk::style element create Notebook.border image $I(notebook-border) -border 5 -padding 5
|
||||
|
||||
ttk::style element create Notebook.tab image \
|
||||
[list $I(tab-rest) \
|
||||
selected $I(tab-selected) \
|
||||
active $I(tab-hover) \
|
||||
] -border 13 -padding {16 14 16 6} -height 32
|
||||
|
||||
# Treeview
|
||||
ttk::style configure Heading -font SunValleyCaptionFont
|
||||
ttk::style configure Treeview \
|
||||
-background $colors(-bg) \
|
||||
-rowheight [expr {[font metrics SunValleyBodyFont -linespace] + 3}] \
|
||||
-font SunValleyBodyFont
|
||||
|
||||
ttk::style map Treeview -background {selected "#e7e7e7"} -foreground {selected "#191919"}
|
||||
|
||||
ttk::style element create Treeview.field image $I(card) -border 5 -width 0 -height 0
|
||||
ttk::style element create Treeheading.cell image \
|
||||
[list $I(heading-rest) \
|
||||
pressed $I(heading-pressed) \
|
||||
active $I(heading-hover)
|
||||
] -border 5 -padding 14 -sticky nsew
|
||||
|
||||
ttk::style element create Treeitem.indicator image \
|
||||
[list $I(right) \
|
||||
user2 $I(empty) \
|
||||
user1 $I(down) \
|
||||
] -width 26 -sticky {}
|
||||
|
||||
# Panedwindow
|
||||
ttk::style configure Sash \
|
||||
-lightcolor "#676767" \
|
||||
-darkcolor "#676767" \
|
||||
-bordercolor "#676767" \
|
||||
-sashthickness 4 \
|
||||
-gripcount 20
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
set ::spriteinfo [list \
|
||||
card 0 0 50 50 \
|
||||
notebook-border 50 0 40 40 \
|
||||
switch-dis 50 40 40 20 \
|
||||
switch-focus-hover 0 50 40 20 \
|
||||
switch-focus 0 70 40 20 \
|
||||
switch-hover 40 60 40 20 \
|
||||
switch-off-dis 90 0 40 20 \
|
||||
switch-off-focus-hover 90 20 40 20 \
|
||||
switch-off-focus 90 40 40 20 \
|
||||
switch-off-hover 80 60 40 20 \
|
||||
switch-off-pressed 0 90 40 20 \
|
||||
switch-off-rest 40 80 40 20 \
|
||||
switch-pressed 80 80 40 20 \
|
||||
switch-rest 0 110 40 20 \
|
||||
tab-hover 130 0 32 32 \
|
||||
tab-rest 130 32 32 32 \
|
||||
tab-selected 120 64 32 32 \
|
||||
heading-hover 40 100 22 22 \
|
||||
heading-pressed 62 100 22 22 \
|
||||
heading-rest 84 100 22 22 \
|
||||
slider-thumb-dis 106 100 22 22 \
|
||||
slider-thumb-focus-hover 128 96 22 22 \
|
||||
slider-thumb-focus 0 130 22 22 \
|
||||
slider-thumb-hover 22 130 22 22 \
|
||||
slider-thumb-pressed 44 122 22 22 \
|
||||
slider-thumb-rest 66 122 22 22 \
|
||||
slider-trough-hor 88 122 22 22 \
|
||||
slider-trough-vert 110 122 22 22 \
|
||||
button-accent-dis 132 118 20 20 \
|
||||
button-accent-focus-hover 0 152 20 20 \
|
||||
button-accent-focus 20 152 20 20 \
|
||||
button-accent-hover 40 152 20 20 \
|
||||
button-accent-pressed 60 144 20 20 \
|
||||
button-accent-rest 80 144 20 20 \
|
||||
button-dis 100 144 20 20 \
|
||||
button-focus-hover 120 144 20 20 \
|
||||
button-focus 140 138 20 20 \
|
||||
button-hover 162 0 20 20 \
|
||||
button-pressed 162 20 20 20 \
|
||||
button-rest 162 40 20 20 \
|
||||
check-dis 162 60 20 20 \
|
||||
check-focus-hover 150 96 20 20 \
|
||||
check-focus 152 116 20 20 \
|
||||
check-hover 160 136 20 20 \
|
||||
check-pressed 0 172 20 20 \
|
||||
check-rest 20 172 20 20 \
|
||||
check-tri-dis 40 172 20 20 \
|
||||
check-tri-focus-hover 160 156 20 20 \
|
||||
check-tri-focus 140 158 20 20 \
|
||||
check-tri-hover 60 164 20 20 \
|
||||
check-tri-pressed 80 164 20 20 \
|
||||
check-tri-rest 100 164 20 20 \
|
||||
check-unsel-dis 120 164 20 20 \
|
||||
check-unsel-focus-hover 182 0 20 20 \
|
||||
check-unsel-focus 182 20 20 20 \
|
||||
check-unsel-hover 182 40 20 20 \
|
||||
check-unsel-pressed 182 60 20 20 \
|
||||
check-unsel-rest 180 80 20 20 \
|
||||
progressbar-bar-hor 180 100 20 5 \
|
||||
progressbar-bar-vert 172 80 5 20 \
|
||||
progressbar-trough-hor 152 80 20 5 \
|
||||
progressbar-trough-vert 172 100 5 20 \
|
||||
radio-dis 180 105 20 20 \
|
||||
radio-focus-hover 180 125 20 20 \
|
||||
radio-focus 180 145 20 20 \
|
||||
radio-hover 180 165 20 20 \
|
||||
radio-pressed 160 176 20 20 \
|
||||
radio-rest 140 178 20 20 \
|
||||
radio-unsel-dis 0 192 20 20 \
|
||||
radio-unsel-focus-hover 20 192 20 20 \
|
||||
radio-unsel-focus 40 192 20 20 \
|
||||
radio-unsel-hover 180 185 20 20 \
|
||||
radio-unsel-pressed 60 184 20 20 \
|
||||
radio-unsel-rest 80 184 20 20 \
|
||||
scrollbar-thumb-hor 160 196 20 12 \
|
||||
scrollbar-thumb-vert 100 184 12 20 \
|
||||
scrollbar-trough-hor 112 198 20 12 \
|
||||
scrollbar-trough-vert 202 0 12 20 \
|
||||
textbox-dis 0 212 20 20 \
|
||||
textbox-error 20 212 20 20 \
|
||||
textbox-focus 40 212 20 20 \
|
||||
textbox-hover 60 210 20 20 \
|
||||
textbox-rest 80 210 20 20 \
|
||||
down 40 50 10 5 \
|
||||
empty 152 64 10 10 \
|
||||
grip 152 85 10 10 \
|
||||
right 162 85 5 10 \
|
||||
sep 202 20 10 10 \
|
||||
up 40 55 10 5 \
|
||||
scrollbar-down 132 138 8 6 \
|
||||
scrollbar-left 44 144 6 8 \
|
||||
scrollbar-right 50 144 6 8 \
|
||||
scrollbar-up 172 120 8 6 \
|
||||
]
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
set ::spriteinfo [list \
|
||||
card 0 0 50 50 \
|
||||
notebook-border 50 0 40 40 \
|
||||
switch-dis 50 40 40 20 \
|
||||
switch-focus-hover 0 50 40 20 \
|
||||
switch-focus 0 70 40 20 \
|
||||
switch-hover 40 60 40 20 \
|
||||
switch-off-dis 90 0 40 20 \
|
||||
switch-off-focus-hover 90 20 40 20 \
|
||||
switch-off-focus 90 40 40 20 \
|
||||
switch-off-hover 80 60 40 20 \
|
||||
switch-off-pressed 0 90 40 20 \
|
||||
switch-off-rest 40 80 40 20 \
|
||||
switch-pressed 80 80 40 20 \
|
||||
switch-rest 0 110 40 20 \
|
||||
tab-hover 130 0 32 32 \
|
||||
tab-rest 130 32 32 32 \
|
||||
tab-selected 120 64 32 32 \
|
||||
heading-hover 40 100 22 22 \
|
||||
heading-pressed 62 100 22 22 \
|
||||
heading-rest 84 100 22 22 \
|
||||
slider-thumb-dis 106 100 22 22 \
|
||||
slider-thumb-focus-hover 128 96 22 22 \
|
||||
slider-thumb-focus 0 130 22 22 \
|
||||
slider-thumb-hover 22 130 22 22 \
|
||||
slider-thumb-pressed 44 122 22 22 \
|
||||
slider-thumb-rest 66 122 22 22 \
|
||||
slider-trough-hor 88 122 22 22 \
|
||||
slider-trough-vert 110 122 22 22 \
|
||||
button-accent-dis 132 118 20 20 \
|
||||
button-accent-focus-hover 0 152 20 20 \
|
||||
button-accent-focus 20 152 20 20 \
|
||||
button-accent-hover 40 152 20 20 \
|
||||
button-accent-pressed 60 144 20 20 \
|
||||
button-accent-rest 80 144 20 20 \
|
||||
button-dis 100 144 20 20 \
|
||||
button-focus-hover 120 144 20 20 \
|
||||
button-focus 140 138 20 20 \
|
||||
button-hover 162 0 20 20 \
|
||||
button-pressed 162 20 20 20 \
|
||||
button-rest 162 40 20 20 \
|
||||
check-dis 162 60 20 20 \
|
||||
check-focus-hover 150 96 20 20 \
|
||||
check-focus 152 116 20 20 \
|
||||
check-hover 160 136 20 20 \
|
||||
check-pressed 0 172 20 20 \
|
||||
check-rest 20 172 20 20 \
|
||||
check-tri-dis 40 172 20 20 \
|
||||
check-tri-focus-hover 160 156 20 20 \
|
||||
check-tri-focus 140 158 20 20 \
|
||||
check-tri-hover 60 164 20 20 \
|
||||
check-tri-pressed 80 164 20 20 \
|
||||
check-tri-rest 100 164 20 20 \
|
||||
check-unsel-dis 120 164 20 20 \
|
||||
check-unsel-focus-hover 182 0 20 20 \
|
||||
check-unsel-focus 182 20 20 20 \
|
||||
check-unsel-hover 182 40 20 20 \
|
||||
check-unsel-pressed 182 60 20 20 \
|
||||
check-unsel-rest 180 80 20 20 \
|
||||
progressbar-bar-hor 180 100 20 5 \
|
||||
progressbar-bar-vert 172 80 5 20 \
|
||||
progressbar-trough-hor 152 80 20 5 \
|
||||
progressbar-trough-vert 172 100 5 20 \
|
||||
radio-dis 180 105 20 20 \
|
||||
radio-focus-hover 180 125 20 20 \
|
||||
radio-focus 180 145 20 20 \
|
||||
radio-hover 180 165 20 20 \
|
||||
radio-pressed 160 176 20 20 \
|
||||
radio-rest 140 178 20 20 \
|
||||
radio-unsel-dis 0 192 20 20 \
|
||||
radio-unsel-focus-hover 20 192 20 20 \
|
||||
radio-unsel-focus 40 192 20 20 \
|
||||
radio-unsel-hover 180 185 20 20 \
|
||||
radio-unsel-pressed 60 184 20 20 \
|
||||
radio-unsel-rest 80 184 20 20 \
|
||||
scrollbar-thumb-hor 160 196 20 12 \
|
||||
scrollbar-thumb-vert 100 184 12 20 \
|
||||
scrollbar-trough-hor 112 198 20 12 \
|
||||
scrollbar-trough-vert 202 0 12 20 \
|
||||
textbox-dis 0 212 20 20 \
|
||||
textbox-error 20 212 20 20 \
|
||||
textbox-focus 40 212 20 20 \
|
||||
textbox-hover 60 210 20 20 \
|
||||
textbox-rest 80 210 20 20 \
|
||||
down 40 50 10 5 \
|
||||
empty 152 64 10 10 \
|
||||
grip 152 85 10 10 \
|
||||
right 162 85 5 10 \
|
||||
sep 202 20 10 10 \
|
||||
up 40 55 10 5 \
|
||||
scrollbar-down 132 138 8 6 \
|
||||
scrollbar-left 44 144 6 8 \
|
||||
scrollbar-right 50 144 6 8 \
|
||||
scrollbar-up 172 120 8 6 \
|
||||
]
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
+493
-87
@@ -2,13 +2,22 @@
|
||||
"""Generate C for the ExeFS modules: function discovery, then parallel emission into chunked C files.
|
||||
|
||||
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]
|
||||
[--limit N] [--chunk-fns N] [--chunk-bytes B] [--big-fn B] [--patches FILE] [--v-locals K [--v-trust]]
|
||||
[--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)
|
||||
<mod>/<mod>_NNNN.c one `void f_<addr>(Cpu *c)` per guest function, about --chunk-bytes of C per file
|
||||
<mod>/<mod>_table.c sorted <mod>_fn_addrs[] / <mod>_fn_ptrs[] / <mod>_fn_count for rt_dispatch
|
||||
<mod>/manifest.json chunk list, function count, statistics and timings
|
||||
<mod>/lift_cache.json per chunk: the key of its inputs, its file's SHA-256, size and mtime, and its results
|
||||
<mod>/folded.txt the module's bytes the generated code took as constants: what the jump tables read at
|
||||
lift time, as module offsets [start, end); tools/exefs_patches.py keeps a mod's data
|
||||
writes off them
|
||||
patches.h code patch sets for the runtime (recomp/patches.py; no sets without --patches)
|
||||
|
||||
Function discovery runs in this process, vectorised over the module's .text words. Function starts are the module
|
||||
@@ -21,8 +30,20 @@ Emission runs in worker processes, one chunk per task. Each worker loads the mod
|
||||
time and resolves its jump tables (recomp/jumptables.py), so memory per worker does not grow with the module.
|
||||
Chunks are sized from a per-instruction estimate of the C they produce, so their names and contents only depend on
|
||||
the input; a chunk whose text did not change is not rewritten and keeps its mtime.
|
||||
|
||||
A chunk is not lifted again when its inputs did not change. Its text depends only on the generator (recomp/*.py,
|
||||
GENERATED_MARKER, the Emitter options), the module (its file, its base, and the function starts discovered from it),
|
||||
the chunk's number and functions, and the patch sites, spin waits and function hooks inside the chunk's address
|
||||
range (and whether the patch table has hooks at all): the per-module caches of recomp/jumptables.py are derived from
|
||||
the module's bytes and base, and its per-function state is reset for each function. The SHA-256 of all of these is the chunk's key. <mod>/lift_cache.json records the key of each chunk
|
||||
with the SHA-256, size and mtime of the file it wrote and the results the manifest and folded.txt need, under a
|
||||
digest of the entry. A chunk whose entry is intact, whose key matches and whose file still has that size, mtime and
|
||||
hash is reused as it is; any other chunk is lifted. So a rebuild after a change to one cheat lifts only the chunks
|
||||
holding its sites. --no-cache, or TOTK_LIFT_CACHE=0 in the environment, lifts every chunk.
|
||||
"""
|
||||
import argparse
|
||||
import bisect
|
||||
import hashlib
|
||||
import json
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
@@ -30,6 +51,7 @@ import re
|
||||
import sys
|
||||
import time
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
@@ -43,9 +65,10 @@ import hostmem # noqa: E402
|
||||
import jumptables # noqa: E402
|
||||
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')
|
||||
@@ -58,7 +81,7 @@ MUSTTAIL = '__attribute__((musttail)) return'
|
||||
EST_INT = 62
|
||||
EST_SIMD = 75
|
||||
EST_SIMD_LDST = 48
|
||||
EST_FN = 38 # per function: signature, FN_ENTER, closing brace
|
||||
EST_FN = 38 # per function: signature, FN_ENTER (recomp/patches.py `hook`), closing brace
|
||||
EST_BR_LABELS = 10 # per instruction of a function with a `br`: switch cases, or labels if it falls back
|
||||
|
||||
|
||||
@@ -66,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'
|
||||
|
||||
@@ -206,16 +253,25 @@ def partition(est, max_fns, max_bytes, big_fn):
|
||||
# ------------------------------------------------------------------------------------------------ emission
|
||||
|
||||
class Emitter:
|
||||
"""C for the functions of one module. starts is the set of every function start of the module."""
|
||||
"""C for the functions of one module. starts is the set of every function start of the module. A new input of
|
||||
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):
|
||||
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, picks=None, origs=None):
|
||||
self.mod = mod
|
||||
self.starts = starts
|
||||
self.patched = patched or {} # {address: (set index, [replacement words])} (recomp/patches.py)
|
||||
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)
|
||||
self.v_trust = v_trust # with v_locals: V8-V15 are not reloaded after a call
|
||||
# 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()
|
||||
|
||||
@@ -250,33 +306,57 @@ class Emitter:
|
||||
self.unsupported[re.sub(r'\b[0-9a-f]{8}\b', '', msg).strip()] += 1
|
||||
elif k == 'asm':
|
||||
raise ValueError(f'{entry + 4 * i:#x}: asm instruction from the portable lifter')
|
||||
for a in self.patched: # a replacement's branch into the function needs its label
|
||||
if entry <= a < end:
|
||||
for words in self.replacements(a):
|
||||
r = words[-1]
|
||||
if r.kind in ('b', 'bcond') and entry <= r.target < end:
|
||||
labels.add(r.target)
|
||||
return labels, tables
|
||||
|
||||
def replacements(self, a):
|
||||
"""Lifted replacement words of the patched site a."""
|
||||
return [self.mod.lifter.lift(w, a) for w in self.patched[a][1]]
|
||||
"""The lifted words of each alternative of the patched site a, in set order. Only the last word of an
|
||||
alternative may branch (bl, b, b.cond / cbz / tbz, ret)."""
|
||||
out = []
|
||||
for _, words in self.patched[a]:
|
||||
# ('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)
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def flow(insns, entry, end, tables):
|
||||
def flow(self, insns, entry, end, tables):
|
||||
"""Successors of each instruction inside the function [entry, end). Index len(insns) stands for falling
|
||||
through into the next function and has none."""
|
||||
through into the next function and has none. A patched site has the successors of all its alternatives."""
|
||||
def idx(t):
|
||||
return [(t - entry) // 4] if entry <= t < end else []
|
||||
|
||||
succ = []
|
||||
for i, ins in enumerate(insns):
|
||||
def of(ins, i):
|
||||
k = ins.kind
|
||||
if k in ('op', 'bl', 'blr'):
|
||||
succ.append([i + 1])
|
||||
elif k == 'b':
|
||||
succ.append(idx(ins.target))
|
||||
elif k == 'bcond':
|
||||
succ.append(idx(ins.target) + [i + 1])
|
||||
elif k == 'br':
|
||||
return [i + 1]
|
||||
if k == 'b':
|
||||
return idx(ins.target)
|
||||
if k == 'bcond':
|
||||
return idx(ins.target) + [i + 1]
|
||||
if k == 'br':
|
||||
jt = tables.get(entry + 4 * i)
|
||||
succ.append([t for x in jt for t in idx(x)] if jt and jt != 'all' else [])
|
||||
else: # ret, trap
|
||||
succ.append([])
|
||||
return [t for x in jt for t in idx(x)] if jt and jt != 'all' else []
|
||||
return [] # ret, trap
|
||||
|
||||
succ = []
|
||||
for i, ins in enumerate(insns):
|
||||
s = of(ins, i)
|
||||
a = entry + 4 * i
|
||||
if a in self.patched:
|
||||
for words in self.replacements(a):
|
||||
s += [t for t in of(words[-1], i) if t not in s]
|
||||
succ.append(s)
|
||||
succ.append([])
|
||||
return succ
|
||||
|
||||
@@ -294,27 +374,50 @@ class Emitter:
|
||||
exits.add(i) # through rt_dispatch, also a table's default
|
||||
if a in self.patched:
|
||||
effects.append(self.patched_effect(ins, a))
|
||||
if any(r.kind == 'bl' for r in self.replacements(a)):
|
||||
calls.add(i)
|
||||
for words in self.replacements(a):
|
||||
r = words[-1]
|
||||
if r.kind == 'bl':
|
||||
calls.add(i)
|
||||
elif r.kind in ('b', 'bcond') and not entry <= r.target < end:
|
||||
exits.add(i)
|
||||
else:
|
||||
effects.append(flags.effect(ins.cond if k == 'bcond' else ins.code or ''))
|
||||
effects.append((False, None))
|
||||
return flags.plan(effects, succ, calls, exits)
|
||||
|
||||
def patched_effect(self, ins, a):
|
||||
"""Flag effect of a patched site: both alternatives must have the same one, in at most one word each."""
|
||||
"""Flag effect of a patched site: every alternative (the original and each replacement) must write the same
|
||||
flags, in at most one word each; the site reads flags when any alternative does (a b.cond reads them)."""
|
||||
alts = []
|
||||
for words in ([ins], self.replacements(a)):
|
||||
fx = [flags.effect(w.code or '') for w in words if w.kind == 'op']
|
||||
for words in [[ins]] + self.replacements(a):
|
||||
fx = [flags.effect(w.code or '') if w.kind == 'op' else flags.effect(w.cond) for w in words
|
||||
if w.kind in ('op', 'bcond')]
|
||||
fx = [e for e in fx if e[0] or e[1]]
|
||||
if len(fx) > 1:
|
||||
raise patches.PatchError(f'{a:#x}: several flag-using words in one alternative')
|
||||
alts.append(fx[0] if fx else (False, None))
|
||||
if alts[0][1] != alts[1][1]:
|
||||
raise patches.PatchError(f'{a:#x}: the alternatives write different flags ({alts[0][1]}, {alts[1][1]})')
|
||||
if (alts[0][1] or alts[0][0] or alts[1][0]) and ins.kind == 'bl':
|
||||
if any(e[1] != alts[0][1] for e in alts):
|
||||
raise patches.PatchError(f'{a:#x}: the alternatives write different flags ({[e[1] for e in alts]})')
|
||||
reads = any(e[0] for e in alts)
|
||||
if (alts[0][1] or reads) and (ins.kind == 'bl' or any(w[-1].kind == 'bl' for w in self.replacements(a))):
|
||||
raise patches.PatchError(f'{a:#x}: a patched call that uses flags')
|
||||
return alts[0][0] or alts[1][0], alts[0][1]
|
||||
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)."""
|
||||
@@ -356,6 +459,7 @@ class Emitter:
|
||||
self.stats['external_branches'] += 1
|
||||
return f'{publish(i)}{spill}c->pc = {hx(t)}; {MUSTTAIL} rt_dispatch(c);'
|
||||
|
||||
enter = [f' FN_ENTER({hx(entry)});'] if self.hooks is None or entry in self.hooks else []
|
||||
if all_labels:
|
||||
# An unresolved computed br re-enters the function through fb_<entry>, which switches on c->pc to any
|
||||
# instruction. A goto to a shared dispatch block inside the body instead turns every instruction into
|
||||
@@ -364,13 +468,13 @@ class Emitter:
|
||||
cases = ' '.join(f'case {hx(t)}: goto L_{t:x};' for t in range(entry, end, 4))
|
||||
redispatch = f'{MUSTTAIL} {fb}(c);'
|
||||
out = [f'static void {fb}(Cpu *c);',
|
||||
f'void {fname(entry)}(Cpu *c) {{', f' FN_ENTER({hx(entry)});', f' c->pc = {hx(entry)};',
|
||||
f'void {fname(entry)}(Cpu *c) {{', *enter, f' c->pc = {hx(entry)};',
|
||||
f' {redispatch}', '}',
|
||||
f'static void {fb}(Cpu *c) {{', f' switch (c->pc) {{ {cases} default: break; }}',
|
||||
f' {MUSTTAIL} rt_dispatch(c);']
|
||||
else:
|
||||
redispatch = f'{MUSTTAIL} rt_dispatch(c);'
|
||||
out = [f'void {fname(entry)}(Cpu *c) {{', f' FN_ENTER({hx(entry)});']
|
||||
out = [f'void {fname(entry)}(Cpu *c) {{', *enter]
|
||||
if fp.used:
|
||||
out.append(' ' + fp.decl())
|
||||
|
||||
@@ -385,23 +489,40 @@ class Emitter:
|
||||
code = fx(i, code)
|
||||
return f'{spill}{code}{reload}' if regs.ESCAPE.search(code) else code
|
||||
|
||||
def one(i, r, a):
|
||||
"""C of one lifted word of a patched site."""
|
||||
if r.kind == 'op':
|
||||
return op(i, r.code)
|
||||
if r.kind == 'bl':
|
||||
return call(r.target, a)
|
||||
if r.kind == 'b':
|
||||
return jump(r.target, i)
|
||||
if r.kind == 'bcond':
|
||||
return f'if ({fx(i, r.cond)}) {{ {jump(r.target, i)} }}'
|
||||
if r.kind == 'ret':
|
||||
return f'{spill}return;'
|
||||
if r.kind == '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 { original } for a patched site (recomp/patches.py)."""
|
||||
k, words = self.patched[a]
|
||||
if ins.kind not in ('op', 'bl'):
|
||||
"""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}')
|
||||
repl = []
|
||||
for j, (w, r) in enumerate(zip(words, self.replacements(a))):
|
||||
if r.kind == 'op':
|
||||
repl.append(op(i, r.code))
|
||||
elif r.kind == 'bl' and j == len(words) - 1:
|
||||
repl.append(call(r.target, a))
|
||||
else:
|
||||
raise patches.PatchError(f'{a:#x}: replacement word {w:08x} is a {r.kind}')
|
||||
orig = op(i, ins.code) if ins.kind == 'op' else call(ins.target, a)
|
||||
line = ' '
|
||||
n, values = self.picks.get(a, (None, {}))
|
||||
for (k, _), words in zip(self.patched[a], self.replacements(a)):
|
||||
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' if (rt_patch_on[{k}]) {{ {" ".join(repl)} }} else {{ {orig} }}'
|
||||
return f'{line} {{ {one(i, ins, a)} }}'
|
||||
|
||||
body = [] # (instruction index or None for a label, line); a line belongs to the instruction it lifts
|
||||
|
||||
@@ -445,7 +566,7 @@ class Emitter:
|
||||
else:
|
||||
raise ValueError(f'{a:#x}: unknown instruction kind {k!r}')
|
||||
n = len(insns)
|
||||
if k not in TERMINATORS: # falls through into the next function
|
||||
if k not in TERMINATORS or end - 4 in self.patched: # falls through into the next function
|
||||
if end < mod.hi:
|
||||
emit(n, ' ' + jump(end, n))
|
||||
else:
|
||||
@@ -466,6 +587,8 @@ class Emitter:
|
||||
else:
|
||||
out += [line for _, line in body]
|
||||
out.append('}')
|
||||
if self.v_locals:
|
||||
out = vlocals.rewrite('\n'.join(out), self.v_locals, self.v_trust, self.stats).split('\n')
|
||||
self.stats['functions'] += 1
|
||||
self.stats['instructions'] += len(insns)
|
||||
return out, refs
|
||||
@@ -474,22 +597,28 @@ 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'
|
||||
return (header(f'{name} chunk {number:04d}') + '#include "cpu.h"\n#include "simd.h"\n\n' + protos + '\n'
|
||||
+ '\n\n'.join(body) + '\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')
|
||||
|
||||
|
||||
def write_if_changed(path, text):
|
||||
def write_if_changed(path, text, wait=True):
|
||||
"""Returns True if the file was written. An unchanged file keeps its mtime, so the build skips it. A changed one
|
||||
is written under a temporary name and renamed into place, so a reader never sees it half written."""
|
||||
is written under a temporary name and renamed into place, so a reader never sees it half written. wait: retry
|
||||
the rename while another process holds the file (_retry); without it the first failure raises."""
|
||||
data = text.encode()
|
||||
try:
|
||||
if path.stat().st_size == len(data) and path.read_bytes() == data:
|
||||
@@ -499,7 +628,10 @@ def write_if_changed(path, text):
|
||||
tmp = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
|
||||
tmp.write_bytes(data)
|
||||
try:
|
||||
_retry(os.replace, tmp, path)
|
||||
if wait:
|
||||
_retry(os.replace, tmp, path)
|
||||
else:
|
||||
os.replace(tmp, path)
|
||||
except OSError:
|
||||
tmp.unlink(missing_ok=True)
|
||||
raise
|
||||
@@ -520,59 +652,108 @@ def _retry(fn, *args):
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ workers
|
||||
|
||||
_W = {} # worker state: 'mods' {name: (path, base)}, 'starts' {name: sorted array}, 'emitters' {name: Emitter}
|
||||
_W = {} # worker state: 'mods' {name: (path, base)}, 'starts' {name: sorted array}, 'emitters' {name: Emitter},
|
||||
# 'reads' {name: [(start, end)]} module bytes read since the last chunk
|
||||
|
||||
|
||||
def _worker_init(mods, starts, table, opts):
|
||||
def _worker_init(mods, starts, table, opts, jobs):
|
||||
_W['jobs'] = jobs
|
||||
_W['mods'] = mods
|
||||
_W['starts'] = starts
|
||||
_W['patches'] = table
|
||||
_W['opts'] = opts # Emitter keyword arguments
|
||||
_W['emitters'] = {}
|
||||
_W['reads'] = {}
|
||||
|
||||
|
||||
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, [])
|
||||
|
||||
def recorded(a, n, signed=False):
|
||||
reads.append((a - base, a - base + n))
|
||||
return read(a, n, signed=signed)
|
||||
mod.read = recorded
|
||||
e = _W['emitters'][name] = Emitter(mod, set(_W['starts'][name].tolist()),
|
||||
_W['patches'].for_module(name, base),
|
||||
spins=_W['patches'].spins_for(name, base), **_W['opts'])
|
||||
spins=_W['patches'].spins_for(name, base),
|
||||
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
|
||||
|
||||
|
||||
def merge_ranges(ranges):
|
||||
"""Sorted [start, end) ranges with overlapping and touching ones joined."""
|
||||
out = []
|
||||
for s, e in sorted(ranges):
|
||||
if out and s <= out[-1][1]:
|
||||
out[-1][1] = max(out[-1][1], e)
|
||||
else:
|
||||
out.append([s, e])
|
||||
return out
|
||||
|
||||
|
||||
def _emit_chunk(task):
|
||||
"""Worker: write one chunk. Returns its statistics."""
|
||||
name, number, path, fns = task
|
||||
"""Worker: write one chunk. Returns its statistics, and the SHA-256, size and mtime of its file for the cache."""
|
||||
name, number, path, fns, key = task
|
||||
t0 = time.perf_counter()
|
||||
# Test hook: a pool wider than this raises the MemoryError a busy machine does, so the retry can be exercised.
|
||||
limit = os.environ.get('TOTK_LIFT_TEST_OOM_ABOVE')
|
||||
if limit and _W['jobs'] > int(limit) and number % 2 == 1:
|
||||
raise MemoryError
|
||||
e = _emitter(name)
|
||||
e.stats.clear()
|
||||
e.unsupported.clear()
|
||||
text = chunk_text(name, number, e, fns)
|
||||
error = None
|
||||
error, st = None, None
|
||||
try:
|
||||
written = write_if_changed(Path(path), text)
|
||||
st = os.stat(path)
|
||||
except OSError as ex:
|
||||
written, error = False, f'{path}: {ex}'
|
||||
reads = _W['reads'].get(name, [])
|
||||
folded = merge_ranges(reads)
|
||||
reads.clear()
|
||||
return {'module': name, 'number': number, 'file': Path(path).name, 'functions': len(fns), 'bytes': len(text),
|
||||
'written': written, 'error': error, 'seconds': time.perf_counter() - t0, 'stats': dict(e.stats),
|
||||
'unsupported': dict(e.unsupported)}
|
||||
'written': written, 'reused': False, 'error': error, 'seconds': time.perf_counter() - t0,
|
||||
'stats': dict(e.stats), 'unsupported': dict(e.unsupported), 'folded': folded, 'key': key,
|
||||
'sha256': _sha256(text.encode()), 'size': st.st_size if st else None,
|
||||
'mtime_ns': st.st_mtime_ns if st else None}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ 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)
|
||||
|
||||
|
||||
def folded_text(name, ranges):
|
||||
"""<mod>/folded.txt: the module offsets [start, end) of the bytes the jump tables read at lift time, in hex."""
|
||||
lines = [f'# {GENERATED_MARKER}: {name} bytes the generated code took as constants (jump tables), module offsets '
|
||||
f'[start, end), generated by recomp/gen.py from game code. Do not edit or commit.']
|
||||
lines += [f'{s:x} {e:x}' for s, e in ranges]
|
||||
return '\n'.join(lines) + '\n'
|
||||
|
||||
|
||||
def remove_stale(moddir, name, nchunks, errors):
|
||||
"""Delete chunks an earlier run wrote beyond this run's count, and temporary files an interrupted run left."""
|
||||
pat = re.compile(re.escape(name) + r'_(\d{4})\.c')
|
||||
@@ -588,6 +769,129 @@ def remove_stale(moddir, name, nchunks, errors):
|
||||
return removed
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ lift cache
|
||||
|
||||
CACHE_FILE = 'lift_cache.json'
|
||||
CACHE_VERSION = 1 # raise when the cache's format or the meaning of its key changes
|
||||
# Per-chunk results the cache keeps beside the key: what the manifest, folded.txt and the reuse check need.
|
||||
CACHED = ('functions', 'bytes', 'stats', 'unsupported', 'folded', 'sha256', 'size', 'mtime_ns')
|
||||
|
||||
|
||||
def _sha256(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _key(*parts):
|
||||
"""SHA-256 of JSON-encodable parts."""
|
||||
return _sha256(json.dumps(parts, separators=(',', ':')).encode())
|
||||
|
||||
|
||||
def generator_key(opts):
|
||||
"""Key of everything the chunk text depends on besides the module and the patches: the generator's sources
|
||||
(recomp/*.py, not the patch tables beside them), the marker in each header, the Emitter options, the Python
|
||||
version that runs them."""
|
||||
srcs = [[p.name, _sha256(p.read_bytes())] for p in sorted((ROOT / 'recomp').glob('*.py'))]
|
||||
return _key('gen', CACHE_VERSION, list(sys.version_info[:2]), GENERATED_MARKER, sorted(opts.items()), srcs)
|
||||
|
||||
|
||||
def module_key(gen_key, name, path, base, abs_starts):
|
||||
"""Key of one module's inputs: the generator, the module's file and base, and the function starts discovered
|
||||
from them (they decide which branches become direct calls)."""
|
||||
return _key(gen_key, name, _sha256(Path(path).read_bytes()), base, _sha256(abs_starts.tobytes()))
|
||||
|
||||
|
||||
def in_span(addrs, lo, hi):
|
||||
"""The addresses of the sorted list addrs in [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, 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), 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]
|
||||
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)
|
||||
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):
|
||||
"""Digest of a cache entry: its chunk file name, key and results. The results go into the manifest and folded.txt
|
||||
as they are, so a changed value in the cache file must not be taken (tools/exefs_patches.py --folded keeps a
|
||||
mod's data writes off the folded bytes)."""
|
||||
return _key(file, entry['key'], [entry[k] for k in CACHED])
|
||||
|
||||
|
||||
def load_cache(moddir):
|
||||
"""{chunk file name: entry} from <mod>/lift_cache.json: the entries whose digest matches; empty when the file is
|
||||
missing or unreadable."""
|
||||
try:
|
||||
data = json.loads((moddir / CACHE_FILE).read_text())
|
||||
if data.get('version') != CACHE_VERSION or not isinstance(data.get('chunks'), dict):
|
||||
return {}
|
||||
out = {}
|
||||
for file, e in data['chunks'].items():
|
||||
try:
|
||||
if e['check'] == _entry_check(file, e):
|
||||
out[file] = e
|
||||
except (KeyError, TypeError):
|
||||
pass
|
||||
return out
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return {}
|
||||
|
||||
|
||||
def _intact(path, entry):
|
||||
"""True when the file at path still is the one the entry recorded: same size and mtime, then same SHA-256 (a bit
|
||||
flipped in a kept file would otherwise stay forever, as tools/build_game.py check_objects says of objects)."""
|
||||
try:
|
||||
st = path.stat()
|
||||
if st.st_size != entry['size'] or st.st_mtime_ns != entry['mtime_ns']:
|
||||
return False
|
||||
return _sha256(path.read_bytes()) == entry['sha256']
|
||||
except (OSError, KeyError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def reuse(tasks, caches):
|
||||
"""The results of the tasks whose chunk can be reused: its recorded key equals the task's and its file is intact.
|
||||
The files are hashed on threads (hashlib releases the GIL), about 1 GB in all for the three modules."""
|
||||
cands = []
|
||||
for name, number, path, fns, key in tasks:
|
||||
e = caches.get(name, {}).get(Path(path).name)
|
||||
if e is not None and e['key'] == key:
|
||||
cands.append((name, number, Path(path), key, e))
|
||||
with ThreadPoolExecutor(min(16, os.cpu_count() or 4)) as ex:
|
||||
ok = list(ex.map(lambda c: _intact(c[2], c[4]), cands))
|
||||
out = []
|
||||
for (name, number, path, key, e), good in zip(cands, ok):
|
||||
if good:
|
||||
out.append({'module': name, 'number': number, 'file': path.name, 'written': False, 'reused': True,
|
||||
'error': None, 'seconds': 0.0, 'key': key, **{k: e[k] for k in CACHED}})
|
||||
return out
|
||||
|
||||
|
||||
def cache_text(name, results):
|
||||
"""<mod>/lift_cache.json for this run's chunks; a chunk that could not be written gets no entry. Keys keep their
|
||||
order (no sort_keys), so a reused chunk's `unsupported` merges into the census as it did when it was lifted."""
|
||||
chunks = {}
|
||||
for r in results:
|
||||
if not r['error'] and r['size'] is not None:
|
||||
e = {'key': r['key'], **{k: r[k] for k in CACHED}}
|
||||
chunks[r['file']] = {**e, 'check': _entry_check(r['file'], e)}
|
||||
return json.dumps({'module': name, 'marker': GENERATED_MARKER, 'version': CACHE_VERSION, 'chunks': chunks},
|
||||
separators=(',', ':')) + '\n'
|
||||
|
||||
|
||||
# Peak memory of one emit worker on 1.4.3 is 1.3 GiB (1.5 GiB with margin); the parent holds about 0.7 GiB.
|
||||
WORKER_MEM = 1536 << 20
|
||||
MEM_SHARE = 0.8 # of the free memory the workers may take, the rest is for the system and other programs
|
||||
@@ -597,6 +901,14 @@ def pick_jobs(requested):
|
||||
"""Worker count and the reason for it: --jobs if given, else the CPU count capped by the free memory."""
|
||||
if requested:
|
||||
return requested, '--jobs'
|
||||
env = os.environ.get('TOTK_LIFT_JOBS', '').strip()
|
||||
if env:
|
||||
try:
|
||||
if int(env) >= 1:
|
||||
return int(env), 'TOTK_LIFT_JOBS'
|
||||
except ValueError:
|
||||
pass
|
||||
print(f'ignoring TOTK_LIFT_JOBS={env!r}: not a positive integer', file=sys.stderr, flush=True)
|
||||
cpus = os.cpu_count() or 4
|
||||
free = hostmem.available_ram()
|
||||
if free is None:
|
||||
@@ -609,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')
|
||||
@@ -622,15 +937,34 @@ def main():
|
||||
ap.add_argument('--no-callee-saved-trust', action='store_true',
|
||||
help='reload X19-X29 and SP after every call too, instead of trusting AAPCS64 (slower; for '
|
||||
'telling a broken callee from a generator bug)')
|
||||
ap.add_argument('--v-locals', type=int, default=vlocals.LOCALS,
|
||||
help='V registers per function kept in C locals that clang holds in XMM registers, the most used '
|
||||
f'ones (recomp/vlocals.py; default {vlocals.LOCALS}, 0: all in the Cpu)')
|
||||
ap.add_argument('--v-trust', action='store_true',
|
||||
help='with --v-locals: do not reload V8-V15 after a call (AAPCS64: the callee preserves their low '
|
||||
'64 bits)')
|
||||
ap.add_argument('--fn-enter-all', action='store_true',
|
||||
help='FN_ENTER (runtime/cpu.h) in every function, also with hook lines in the patch table '
|
||||
'(recomp/patches.py `hook`): a whole-game function-entry profile')
|
||||
ap.add_argument('--no-cache', action='store_true',
|
||||
help=f'lift every chunk, also those whose inputs match <mod>/{CACHE_FILE} (it is written anew); '
|
||||
'so does the environment variable TOTK_LIFT_CACHE=0')
|
||||
args = ap.parse_args()
|
||||
opts = {'reg_locals': args.reg_locals, 'callee_saved': not args.no_callee_saved_trust}
|
||||
# The installer's lift step passes no --no-cache; the environment reaches it, as TOTK_LIFT_JOBS does (pick_jobs)
|
||||
no_cache = ('--no-cache' if args.no_cache else
|
||||
'TOTK_LIFT_CACHE=0' if os.environ.get('TOTK_LIFT_CACHE', '').strip() == '0' else None)
|
||||
opts = {'reg_locals': args.reg_locals, 'callee_saved': not args.no_callee_saved_trust, 'v_locals': args.v_locals,
|
||||
'v_trust': args.v_trust, 'fn_enter_all': args.fn_enter_all}
|
||||
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))}')
|
||||
@@ -640,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)
|
||||
@@ -651,12 +985,39 @@ 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)
|
||||
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()))
|
||||
if stray:
|
||||
raise SystemExit(f'{args.patches}: hook {", ".join(f"{name}+{a - base:#x}" for a in stray)} is no function '
|
||||
f'start of {name}')
|
||||
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()))
|
||||
tasks.append((int(est[i0:i1].sum()), (name, number, str(moddir / f'{name}_{number:04d}.c'), fns)))
|
||||
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), '
|
||||
@@ -666,20 +1027,52 @@ def main():
|
||||
# Largest chunks first, so the pool does not end on a long tail.
|
||||
tasks.sort(key=lambda t: -t[0])
|
||||
results = {name: [] for name in info}
|
||||
folded = {name: [] for name in info}
|
||||
done_at, errors = {}, []
|
||||
t_emit = time.perf_counter()
|
||||
ctx = mp.get_context('spawn')
|
||||
jobs, why = pick_jobs(args.jobs)
|
||||
print(f'emitting with {jobs} workers ({why})', file=sys.stderr, flush=True)
|
||||
with ctx.Pool(jobs, initializer=_worker_init, initargs=(paths, starts_abs, table, opts)) as pool:
|
||||
for i, r in enumerate(pool.imap_unordered(_emit_chunk, [t for _, t in tasks], chunksize=1)):
|
||||
results[r['module']].append(r)
|
||||
if r['error']:
|
||||
errors.append(r['error'])
|
||||
done_at[r['module']] = time.perf_counter() - t_emit
|
||||
if (i + 1) % 200 == 0 or i + 1 == len(tasks):
|
||||
print(f'emitted {i + 1}/{len(tasks)} chunks, {time.perf_counter() - t_emit:.0f}s', file=sys.stderr,
|
||||
flush=True)
|
||||
pending = [t for _, t in tasks]
|
||||
reused = [] if no_cache else reuse(pending, {name: load_cache(d['moddir']) for name, d in info.items()})
|
||||
for r in reused:
|
||||
results[r['module']].append(r)
|
||||
folded[r['module']] += r['folded']
|
||||
skip = {(r['module'], r['number']) for r in reused}
|
||||
pending = [t for t in pending if (t[0], t[1]) not in skip]
|
||||
emitted = len(reused)
|
||||
print(f'reusing {len(reused)} of {len(tasks)} chunks (inputs unchanged), {time.perf_counter() - t_emit:.1f}s'
|
||||
if not no_cache else f'lifting every chunk ({no_cache})', file=sys.stderr, flush=True)
|
||||
if reused or not pending:
|
||||
# installer/steps.py EMITTED reads these lines for its progress bar: the reused chunks count as done, and a
|
||||
# run with nothing to lift still reaches M/M
|
||||
print(f'emitted {emitted}/{len(tasks)} chunks, 0s', file=sys.stderr, flush=True)
|
||||
if len(pending) < jobs:
|
||||
jobs, why = max(1, len(pending)), f'{len(pending)} chunk{"s" if len(pending) != 1 else ""} to lift'
|
||||
while pending:
|
||||
print(f'emitting with {jobs} worker{"s" if jobs != 1 else ""} ({why})', file=sys.stderr, flush=True)
|
||||
try:
|
||||
# Chunk writes are atomic and idempotent, so a chunk lost with a failed pool is simply emitted again.
|
||||
# Its folded bytes come with its result: a chunk emitted again reads them again in its new worker.
|
||||
with ctx.Pool(jobs, initializer=_worker_init, initargs=(paths, starts_abs, table, opts, jobs)) as pool:
|
||||
for r in pool.imap_unordered(_emit_chunk, pending, chunksize=1):
|
||||
results[r['module']].append(r)
|
||||
folded[r['module']] += r['folded']
|
||||
if r['error']:
|
||||
errors.append(r['error'])
|
||||
done_at[r['module']] = time.perf_counter() - t_emit
|
||||
emitted += 1
|
||||
if emitted % 200 == 0 or emitted == len(tasks):
|
||||
print(f'emitted {emitted}/{len(tasks)} chunks, {time.perf_counter() - t_emit:.0f}s',
|
||||
file=sys.stderr, flush=True)
|
||||
break
|
||||
except MemoryError:
|
||||
if jobs == 1:
|
||||
raise
|
||||
smaller = jobs // 2
|
||||
print(f'emit: out of memory with {jobs} workers, retrying with {smaller}', file=sys.stderr, flush=True)
|
||||
jobs, why = smaller, 'after out of memory'
|
||||
done = {(r['module'], r['number']) for rs in results.values() for r in rs}
|
||||
pending = [t for t in pending if (t[0], t[1]) not in done]
|
||||
|
||||
for name, d in info.items():
|
||||
rs = sorted(results[name], key=lambda r: r['number'])
|
||||
@@ -689,7 +1082,9 @@ 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 = {
|
||||
'module': name,
|
||||
@@ -725,7 +1120,9 @@ def main():
|
||||
'c_bytes': sum(r['bytes'] for r in rs),
|
||||
'largest_chunk_bytes': max((r['bytes'] for r in rs), default=0),
|
||||
'chunks_written': sum(r['written'] for r in rs) + table_written,
|
||||
'chunks_reused': sum(r['reused'] for r in rs),
|
||||
'stale_chunks_removed': removed,
|
||||
**{k: v for k, v in sorted(stats.items()) if k.startswith('v_')}, # --v-locals only
|
||||
},
|
||||
'unsupported_census': dict(unsupported.most_common(50)),
|
||||
'timings': {
|
||||
@@ -736,8 +1133,17 @@ def main():
|
||||
},
|
||||
}
|
||||
write_if_changed(moddir / 'manifest.json', json.dumps(manifest, indent=1) + '\n')
|
||||
# The cache goes last, after every output it describes. It only saves time, so a failed write warns and the
|
||||
# lift still succeeds, without waiting for a holder of the file: the previous cache stays, and its entries
|
||||
# for the chunks this run rewrote no longer match their files' size, mtime and hash. A run stopped before
|
||||
# here leaves it the same way.
|
||||
try:
|
||||
write_if_changed(moddir / CACHE_FILE, cache_text(name, rs), wait=False)
|
||||
except OSError as ex:
|
||||
print(f'{name}: {CACHE_FILE} not written, the next lift reuses less: {ex}', file=sys.stderr, flush=True)
|
||||
s = manifest['stats']
|
||||
print(f'{name}: {s["emitted_functions"]} functions, {len(rs)} chunks, {s["c_bytes"] / 1e6:.0f} MB of C, '
|
||||
print(f'{name}: {s["emitted_functions"]} functions, {len(rs)} chunks ({s["chunks_reused"]} reused), '
|
||||
f'{s["c_bytes"] / 1e6:.0f} MB of C, '
|
||||
f'{s["jump_tables"]} jump tables, {s["all_label_fallbacks"]} all-label fallbacks, '
|
||||
f'{s["br_dispatch"]} br via dispatch, {s["traps"]} traps ({s["unsupported"]} unsupported)',
|
||||
file=sys.stderr)
|
||||
|
||||
+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]
|
||||
+2
-1
@@ -352,7 +352,8 @@ class Lifter:
|
||||
dst = {
|
||||
(3, 3, 13, 0, 2): 'c->tpidr = {v};',
|
||||
(3, 3, 4, 2, 0): 'c->nzcv = {v} & 0xf0000000ull;',
|
||||
(3, 3, 4, 4, 0): 'c->fpcr = {v} & 0x7c00000ull; rt_fpcr_sync(c);' if self.sc else 'rt_set_fpcr({v});',
|
||||
(3, 3, 4, 4, 0): ('c->fpcr = {v} & 0x7c00000ull; rt_fpcr_sync(c); RT_FPCR_NOTE(c, c->x[30]);' if self.sc
|
||||
else 'rt_set_fpcr({v});'),
|
||||
(3, 3, 4, 4, 1): 'c->fpsr = {v} & 0xf800009full;' if self.sc else 'rt_set_fpsr({v});',
|
||||
}.get(key)
|
||||
if dst is None:
|
||||
|
||||
+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
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -9,6 +9,9 @@ set cloth TOTK_CLOTH_REALTIME 1
|
||||
set bounce TOTK_HIGHFPS_FIX 1
|
||||
set output TOTK_PATCH_OUTPUT 0
|
||||
set scene TOTK_PATCH_SCENE 0
|
||||
set 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)
|
||||
@@ -32,6 +35,12 @@ site realtime main 8f2398 1e2c1001 bd400120 # fmov s1, #0.5 -> ldr s0, [x9] (g
|
||||
site realtime main 8f23a8 5e21d800 d503201f # scvtf s0, s0 -> nop
|
||||
site realtime main 8f23ac 1e210800 d503201f # fmul s0, s0, s1 -> nop
|
||||
|
||||
# Equipment-switch cooldown (issue #18, found by JieML1100 on 1.4.3): the player update (main+0x852d24) steps the
|
||||
# countdown at player state +0x109c through the timer step (main+0xec98cc) only while it is above FLT_EPSILON, but the
|
||||
# equipment gate (main+0xcae6f8) blocks weapon, shield and bow changes while it is above 0. A measured ratio can leave
|
||||
# a remainder in (0, FLT_EPSILON] that is never stepped again; stepping while above 0 takes it below 0.
|
||||
site realtime main 852d28 1e270101 1e2703e1 # fmov s1, w8 (FLT_EPSILON) -> fmov s1, wzr
|
||||
|
||||
# Hair and cloth (upstream 290ec9f, 8f8022f): the actor animation update builds a second clock {seconds = factor / 30,
|
||||
# ratio = factor} per rendered frame. Three inlined places: at the fmul, seconds = measured seconds * factor; at the
|
||||
# store of the factor into the ratio slot, measured ratio * factor. The call of the shared update (main+0x89822c)
|
||||
@@ -48,6 +57,47 @@ site cloth main 8222f0 9401d7cf @page:x8 bd400104 1e240842 1e240863 9401d7cf #
|
||||
# 100; compare +0x28 * +0x38 (30 / time scale) instead, the same value at 30 Hz and independent of the frame rate.
|
||||
site bounce main bda798 bd402900 bd402900 bd403901 1e210800 # ldr s0, [x8, #0x28]; ldr s1, [x8, #0x38]; fmul s0, s0, s1
|
||||
|
||||
# Climbing (issues #35, #276, #1001): the climb controller's velocity step (main+0x1918220, the same code as 1.4.3
|
||||
# main+0x1f49754) multiplies the requested velocity by a factor that makes up for a movement loss growing with the
|
||||
# frame rate: 1.272 - 0.362 (r - 1) clamped to [0.5, 1.5] (r = VFR +0, the 30 Hz ratio times the time scale). Right at
|
||||
# 30 fps, 78% of the speed at 60 and 30% at 240. Below r = 1 use 1.4.3's factor, 1.272 + 1.189 (1 - r) at most 2
|
||||
# (Nintendo's 60 fps fit), and below r = 0.5 the 1.4.3 set climb's g(r) = 0.66265 / r + 0.4982 + 0.0848 r, at most 8.
|
||||
# Without flags: h = max(min(1.4.3 factor, 2), g - 16 max(r - 0.5, 0)), s0 = max(s0, h), s1 = max(1.5, h), and the
|
||||
# following fmin s1, s0, s1 gives max(min(s0, 1.5), h). For r >= 1 h is at most the shipping value, so 30 fps and
|
||||
# slower keep the factor bit for bit. x8 is dead after the load at 0x19182c0; s5-s7 and s16 are written before any
|
||||
# later read in this function.
|
||||
# g takes u = max(page +0, r): the patch page's 30 Hz frame ratio without the time scale (runtime/frame_rate.c), so
|
||||
# slow motion at 30 or 60 fps keeps the shipping factor and only a real frame rate above 60 raises it; the runtime
|
||||
# switches the set off without the real-time step, where the page is not written.
|
||||
set climb TOTK_CLIMB_FIX 1
|
||||
site climb main 19182cc 1e2f1001 @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 # fmov s1, #1.5 -> s5 = h(r); s0 = max(s0, s5); s1 = max(1.5, s5)
|
||||
|
||||
# Cursor and aim steps (upstream game_patches.c patch_cursor_speed, 363a6eb). These updates read the game's 30 Hz frame
|
||||
# ratio for their smoothing but leave it out of the step itself, so the map cursor and the vertical Ultrahand aim moved
|
||||
# 2x as fast at 60 fps and 4x at 120 as at the shipping 30 fps (issue #44). Each site multiplies the step by that ratio,
|
||||
# so the speed is the shipping one at any frame rate. x9 and s16 are free: the next read of x9 follows a write, the
|
||||
# function does not touch s16, and x20 keeps the update's frame object for the whole function.
|
||||
set cursor TOTK_HIGHFPS_FIX 1
|
||||
site cursor main ec3d9c bd400361 f94002e9 bd400930 1e300800 bd400361 # map pan speed s0 *= [[x23] + 8], then ldr s1, [x27]
|
||||
site cursor main 1d48d64 1e2a198c 1e2a198c bd400a90 1e30098c # fdiv s12, s12, s10, then s12 *= [x20 + 8]: vertical Ultrahand aim
|
||||
site cursor main 1d484e4 1e200923 1e200923 bd400a90 1e300863 # fmul s3, s9, s0, then s3 *= [x20 + 8]: vertical gyro aim (Recall)
|
||||
|
||||
# Gear rotation check (issues #330, #984). The update of ActorCheckRotateModule (main+0x21350c0; vtable +0x110, called
|
||||
# by the AI node dispatchers main+0x11f5a40 / 0x2adbcf8 with x1 = the update context) reports a gear or water wheel as
|
||||
# turning when the angle it turned since the previous update is above RotateStartDeg / 30, the angle of one 30 Hz
|
||||
# frame. Above 30 fps a gear turns less per update than that, reads as stopped, and the shrine doors that wait on it
|
||||
# (Riogok, Turakamik, the Wind Temple) never open. 1.4.3 (main+0x273d080) divides the angle by the context's +8, the
|
||||
# frame delta in 30 Hz frames (the AI root sets it from its owner's virtual +0x30, main+0x106acc4, and the frame
|
||||
# counter node SelectorGenericFrameCounter, main+0x10b66f8, adds it up per update). 1.2.1 gets the same context and
|
||||
# ignores it: the update overwrites x1 with its first instruction. The first site keeps ctx+8 in s12 (the prologue has
|
||||
# saved d12, the function first writes it at the second site, and callees preserve it); the second multiplies the
|
||||
# threshold by it, which is 1.4.3's test with both sides multiplied by the delta. s4 is free after the fdiv: the next
|
||||
# read follows a write in the callee main+0x11c2014. The context follows the measured step with the set realtime and is
|
||||
# the whole-vsync ratio without it (0.25 at 120 fps, 0.5 at 60 fps measured), so the set works either way.
|
||||
set gears TOTK_HIGHFPS_FIX 1
|
||||
site gears main 21350e0 f9402001 bd40082c f9402001 # ldr x1, [x0, #0x40], after ldr s12, [x1, #8] (frame delta)
|
||||
site gears main 21352d0 1e24180c 1e241804 1e2c088c # fdiv s12, s0, s4 -> fdiv s4, s0, s4; fmul s12, s4, s12
|
||||
|
||||
# Output size (upstream games/totk/runtime/game_patches.c patch_output_res; runtime/resolution.c switches the set on).
|
||||
# The swapchain size nnMain writes before NvInitializeGraphics comes from page +48 ({w, h} as one 64-bit value), and
|
||||
# the output size the renderer lays out its canvas, crop and UI in (main+0xcc3f00, read from the graphics parameters
|
||||
@@ -64,6 +114,161 @@ site scene main cc3f68 5e21d900 @page:x9 # scvtf s0, s8 -> adrp x9, page
|
||||
site scene main cc3f70 bd0cc660 2d420520 # str s0, [x19, #0xcc4] -> ldp s0, s1, [x9, #16]
|
||||
site scene main cc3f74 5e21d921 bd0cc660 # scvtf s1, s9 -> str s0, [x19, #0xcc4]
|
||||
|
||||
# Fixed scene size (MacNativeGames game_patches_v143.c patch_fixed_res, 1.4.3 main+0x5848a8; runtime/resolution.c
|
||||
# res_dynres_live switches the set on unless TOTK_DYNAMIC_RES=1). The game's dynamic resolution controller
|
||||
# (main+0xcc26f4, called once per frame from the renderer at main+0xcc0fa0) steps the scene through tiers of 100, 90 and
|
||||
# 80 % by a cost model that grows with the scene width squared (runtime/resolution.c res_dynres_live), and the renderer stores scene width * tier / output width at +0xccc (main+0xcc1150).
|
||||
# Every path leaves through one epilogue, where the tier's scale moves into the result: 1.0 there makes every tier 100 %.
|
||||
set fixres TOTK_FIXED_RES_PATCH 0
|
||||
site fixres main cc2c00 2a1703e9 52a7f009 # mov w9, w23 -> mov w9, #0x3f800000 (1.0f)
|
||||
|
||||
# Camera aspect ratio for a game resolution that is not 16:9 (upstream game_patches.c, the 1.2.1 sites of aspect_install;
|
||||
# runtime/resolution.c res_init writes the output's width / height to page +56 and switches the set on). The same four
|
||||
# sites as patches-v143.txt, with the same original words: two camera sites (update and setup) load the camera's copy of
|
||||
# DefaultAspect 1.777778, two viewport routines divide width by height. The replacement loads the ratio from the page
|
||||
# instead (Hor+). x10 is kept on the stack, so no register liveness is assumed.
|
||||
set aspect TOTK_ASPECT_PATCH 0
|
||||
site aspect main cb4b10 bd414260 f81f0fea @page:x10 bd403940 f84107ea # ldr s0, [x19, #0x140] (camera update)
|
||||
site aspect main 12521cc bd414260 f81f0fea @page:x10 bd403940 f84107ea # ldr s0, [x19, #0x140] (camera setup)
|
||||
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
|
||||
# shipped heap table keeps every pool far below 2 GiB; a texture pack's heap table with TOTK_APP_POOL raised can make
|
||||
# one larger (MacNativeGames saw a 3.58 GiB pool), and every texture past 2 GiB then got storage 4 GiB below its pool.
|
||||
# The offset is widened unsigned instead, the same value below 2 GiB, right up to 4 GiB. 1.4.3 needs no patch: its
|
||||
# loaders (main+0x583c34, main+0x27ed214) keep the offset in 64 bits.
|
||||
set pooloff TOTK_POOL_OFFSET_PATCH 1
|
||||
site pooloff main ad43f0 93407f22 2a1903e2 # sxtw x2, w25 -> mov w2, w25 (SetStorage offset)
|
||||
site pooloff main ad440c 8b39c101 8b394101 # add x1, x8, w25, sxtw -> add x1, x8, w25, uxtw (packaged data source)
|
||||
|
||||
# Load-dependent quality, after the emulator mod "Disable LOD Quality Reduction" (main-1.2.1.pchtxt), which turns a
|
||||
# conditional branch into an unconditional one; the generator patches only plain instructions (recomp/gen.py, the
|
||||
# emitter's patch), so the site feeds the branch instead. The graphics settings setup (main+0xc7e9xx, it also reads the
|
||||
# FSR and FXAA switches) walks a
|
||||
# list at its +0x120 and passes three floats of each entry to virtual setters, which the mod describes as the drop of
|
||||
# model and texture detail when the frame rate falls; it skips all of it, to the epilogue, when the value it reads at
|
||||
# main+0xc7eb24 is above 8. Reading 9 there skips it as the mod does; w21 is not read again on that path (the epilogue
|
||||
# restores it).
|
||||
set steady TOTK_LOD_STEADY 0
|
||||
site steady main c7eb24 b9400815 52800135 # ldr w21, [x0, #8] -> mov w21, #9 (b.gt 0xc7ee4c taken)
|
||||
|
||||
# Direct mouse camera (runtime/mouse_direct.c; the same hooks as patches-v143.txt, mapped by enclosing function to the
|
||||
# 1.2.1 main, each original word checked). The camera input update (main+0xd18088, 1.4.3 0x874c1c) after its dead zone,
|
||||
# clamp and StickExponent keeps x in s11 (1.4.3 s9); the host callback performs the displaced store and adds raw mouse
|
||||
# counts. The free orbit (main+0xae28b8) keeps its final angles at [sp+0x3c] / [sp+0x40], Ultrahand's curve results
|
||||
# (main+0x1768ebc) are s9 and s15. The host functions are at page +0xfd0 .. +0xf80; the page is main+0x472b000.
|
||||
set mouse_direct TOTK_MOUSE_DIRECT_PATCH 1
|
||||
site mouse_direct main d18140 bd04228b 94e84fa4 # camera input: str s11, [x20, #0x420]
|
||||
site mouse_direct main d181fc 6d4123e9 94e84f71 # camera input activity: ldp d9, d8, [sp, #0x10]
|
||||
site mouse_direct main ae28e8 f9400408 94f125b2 # free orbit begin: ldr x8, [x0, #8]
|
||||
site mouse_direct main ae355c bd403fed 94f12291 # free orbit angles: ldr s13, [sp, #0x3c]
|
||||
site mouse_direct main 176949c b9001be9 94bf0abd # Ultrahand input: str w9, [sp, #0x18]
|
||||
# The aiming, scope, ability, horse and Purah Pad cameras: per axis, the stick load and the angle the turn is added to,
|
||||
# each a bl to page +0xf80 told apart by the return address (runtime/mouse_direct.c load_sites_121). Where 1.2.1 adds
|
||||
# the turn in a shared helper (main+0x1bb70e8, 0x1bd0d00: *p = wrap(*p + s0)), the hook is on the turn the helper takes
|
||||
# (Horse) or on the store of the helper's result (Aiming's pitch target). Every enclosing function saves x30 in its
|
||||
# prologue and reads it only to return.
|
||||
site mouse_direct main 1d34338 bd4426c1 94a7df12 # Aiming: ldr s1, [x22, #0x424] (stick y)
|
||||
site mouse_direct main 1d34374 bd015660 94a7df03 # Aiming: str s0, [x19, #0x154] (pitch target: +0x15c + turn from a helper)
|
||||
site mouse_direct main 1d34584 bd4422c1 94a7de7f # Aiming: ldr s1, [x22, #0x420] (stick x)
|
||||
site mouse_direct main 1d345d0 bc5b83a1 94a7de6c # Aiming: ldur s1, [x29, #-0x48] (yaw)
|
||||
site mouse_direct main 1d35fd4 bd4422e0 94a7d7eb # AimingTelescope: ldr s0, [x23, #0x420] (stick x)
|
||||
site mouse_direct main 1d35fe0 bd4426e9 94a7d7e8 # AimingTelescope: ldr s9, [x23, #0x424] (stick y)
|
||||
site mouse_direct main 1d36280 bd416260 94a7d740 # AimingTelescope: ldr s0, [x19, #0x160] (pitch)
|
||||
site mouse_direct main 1d36224 bd405be1 94a7d757 # AimingTelescope: ldr s1, [sp, #0x58] (yaw)
|
||||
site mouse_direct main 1d48478 bd4422cf 94a78ec2 # SpecialPower: ldr s15, [x22, #0x420] (stick x)
|
||||
site mouse_direct main 1d48480 bd4426cc 94a78ec0 # SpecialPower: ldr s12, [x22, #0x424] (stick y)
|
||||
site mouse_direct main 1d48bb4 bd416262 94a78cf3 # SpecialPower: ldr s2, [x19, #0x160] (pitch)
|
||||
site mouse_direct main 1d48b38 bc5a83a1 94a78d12 # SpecialPower: ldur s1, [x29, #-0x58] (yaw)
|
||||
site mouse_direct main 1d4070c bd442288 94a7ae1d # Horse: ldr s8, [x20, #0x420] (stick x)
|
||||
site mouse_direct main 1d40740 bd401be0 94a7ae10 # Horse: ldr s0, [sp, #0x18] (yaw turn, which a helper adds to +0x68)
|
||||
site mouse_direct main 1d408f8 bd4426a8 94a7ada2 # Horse: ldr s8, [x21, #0x424] (stick y)
|
||||
site mouse_direct main 1d409ac bd406661 94a7ad75 # Horse: ldr s1, [x19, #0x64] (pitch)
|
||||
site mouse_direct main 1d48ccc bd4422c9 94a78cad # SpecialPower offset mode: ldr s9, [x22, #0x420] (stick x)
|
||||
site mouse_direct main 1d48cf0 bd41da61 94a78ca4 # SpecialPower offset mode: ldr s1, [x19, #0x1d8] (offset x)
|
||||
site mouse_direct main 1d48cfc bd4426c9 94a78ca1 # SpecialPower offset mode: ldr s9, [x22, #0x424] (stick y)
|
||||
site mouse_direct main 1d48d18 bd41de61 94a78c9a # SpecialPower offset mode: ldr s1, [x19, #0x1dc] (offset y)
|
||||
site mouse_direct main 1d485f8 bd400400 94a78e62 # SpecialPower: ldr s0, [x0, #0x4] (offset scale, read only)
|
||||
site mouse_direct main 1d37b44 bd4426ad 94a7d10f # CameraFinder: ldr s13, [x21, #0x424] (stick y)
|
||||
site mouse_direct main 1d37b68 bd405261 94a7d106 # CameraFinder: ldr s1, [x19, #0x50] (pitch)
|
||||
site mouse_direct main 1d37bcc bd4422ad 94a7d0ed # CameraFinder: ldr s13, [x21, #0x420] (stick x)
|
||||
site mouse_direct main 1d37bf4 bd405be1 94a7d0e3 # CameraFinder: ldr s1, [sp, #0x58] (yaw)
|
||||
# The other player cameras. ClimbObj, EventMultiTalk and EventTalkManual load an angle with a pre-indexed load whose
|
||||
# write-back the code after it needs; the mov before it adds the offset instead and the hook loads [base] (no register
|
||||
# between the two words, no branch into them). Wakeboard, ShieldSurfing and Tail read the stick twice, once for its
|
||||
# length and once for its angle: the first pair gives the same values without degrees of its own (REPEAT).
|
||||
site mouse_direct main 1d38e08 bd442301 94a7cc5e # ClimbObj: ldr s1, [x24, #0x420]
|
||||
site mouse_direct main 1d38e10 bd409261 94a7cc5c # ClimbObj: ldr s1, [x19, #0x90] (yaw)
|
||||
site mouse_direct main 1d38dac bd442701 94a7cc75 # ClimbObj: ldr s1, [x24, #0x424]
|
||||
site mouse_direct main 1d38da4 aa1303f6 91022276 # ClimbObj: mov x22, x19 -> add x22, x19, #0x88
|
||||
site mouse_direct main 1d38db8 bc488ec1 94a7cc72 # ClimbObj: ldr s1, [x22, #0x88]! (pitch), as ldr s1, [x22]
|
||||
site mouse_direct main 1d50738 bd4422c0 94a76e12 # Wakeboard: ldr s0, [x22, #0x420] (x for the length, REPEAT)
|
||||
site mouse_direct main 1d50740 bd4426c1 94a76e10 # Wakeboard: ldr s1, [x22, #0x424] (y for the length, REPEAT)
|
||||
site mouse_direct main 1d50768 bd4426c0 94a76e06 # Wakeboard: ldr s0, [x22, #0x424] (stick y, kept)
|
||||
site mouse_direct main 1d5076c bd4422c1 94a76e05 # Wakeboard: ldr s1, [x22, #0x420]
|
||||
site mouse_direct main 1d50e5c bd40da60 94a76c49 # Wakeboard: ldr s0, [x19, #0xd8] (pitch)
|
||||
site mouse_direct main 1d508bc bd401fa0 94a76db1 # Wakeboard: ldr s0, [x29, #0x1c] (pitch turn, cut to the pad)
|
||||
site mouse_direct main 1d50f20 bd403bec 94a76c18 # Wakeboard: ldr s12, [sp, #0x38] (yaw)
|
||||
site mouse_direct main 1d51e10 bd4422cd 94a7685c # WaterfallClimb: ldr s13, [x22, #0x420]
|
||||
site mouse_direct main 1d51fb8 b9403be8 94a767f2 # WaterfallClimb: ldr w8, [sp, #0x38] (yaw)
|
||||
site mouse_direct main 1d51f48 bd4426c9 94a7680e # WaterfallClimb: ldr s9, [x22, #0x424]
|
||||
site mouse_direct main 1d4a11c bd442280 94a78799 # Tail: ldr s0, [x20, #0x420] (x for the length, REPEAT)
|
||||
site mouse_direct main 1d4a124 bd442681 94a78797 # Tail: ldr s1, [x20, #0x424] (y for the length, REPEAT)
|
||||
site mouse_direct main 1d4a14c bd442680 94a7878d # Tail (climbing): ldr s0, [x20, #0x424] (stick y)
|
||||
site mouse_direct main 1d4a150 bd442281 94a7878c # Tail: ldr s1, [x20, #0x420]
|
||||
site mouse_direct main 1d4a4a0 bd40c260 94a786b8 # Tail (climbing): ldr s0, [x19, #0xc0] (yaw)
|
||||
site mouse_direct main 1d4a514 bd40b661 94a7869b # Tail (climbing): ldr s1, [x19, #0xb4] (pitch)
|
||||
site mouse_direct main 1d4c930 bd442320 94a77d94 # LockOn / Target: ldr s0, [x25, #0x420]
|
||||
site mouse_direct main 1d4c958 bd442321 94a77d8a # LockOn / Target: ldr s1, [x25, #0x420] (stick x)
|
||||
site mouse_direct main 1d4c97c bd402be0 94a77d81 # LockOn / Target: ldr s0, [sp, #0x28] (yaw turn)
|
||||
site mouse_direct main 1d4c98c bd402be9 94a77d7d # LockOn / Target: ldr s9, [sp, #0x28] (yaw turn)
|
||||
site mouse_direct main 1d4cd5c bd442721 94a77c89 # LockOn / Target: ldr s1, [x25, #0x424] (stick y)
|
||||
site mouse_direct main 1d4cd80 bd402be0 94a77c80 # LockOn / Target: ldr s0, [sp, #0x28] (pitch turn)
|
||||
site mouse_direct main 1d4cd90 bd402beb 94a77c7c # LockOn / Target: ldr s11, [sp, #0x28] (pitch turn)
|
||||
site mouse_direct main 1d443e8 bd4426a9 94a79ee6 # LockOnAimingAt: ldr s9, [x21, #0x424] (stick y)
|
||||
site mouse_direct main 1d44430 bd419a61 94a79ed4 # LockOnAimingAt: ldr s1, [x19, #0x198] (pitch offset)
|
||||
site mouse_direct main 1d44444 bd4422a9 94a79ecf # LockOnAimingAt: ldr s9, [x21, #0x420] (stick x)
|
||||
site mouse_direct main 1d44490 bd419e61 94a79ebc # LockOnAimingAt: ldr s1, [x19, #0x19c] (yaw offset)
|
||||
site mouse_direct main 1d418dc bd44234b 94a7a9a9 # HorseLockOnEmpty: ldr s11, [x26, #0x420]
|
||||
site mouse_direct main 1d3a484 bd44230b 94a7c6bf # EventMultiTalk: ldr s11, [x24, #0x420]
|
||||
site mouse_direct main 1d3a3f8 bd44270b 94a7c6e2 # EventMultiTalk: ldr s11, [x24, #0x424] (stick y)
|
||||
site mouse_direct main 1d3a418 aa1303f7 91017277 # EventMultiTalk: mov x23, x19 -> add x23, x19, #0x5c
|
||||
site mouse_direct main 1d3a420 bc45cee1 94a7c6d8 # EventMultiTalk: ldr s1, [x23, #0x5c]! (pitch), as ldr s1, [x23]
|
||||
site mouse_direct main 1d3a4dc aa1303f6 91019276 # EventMultiTalk: mov x22, x19 -> add x22, x19, #0x64
|
||||
site mouse_direct main 1d3a4e4 bc464ec1 94a7c6a7 # EventMultiTalk: ldr s1, [x22, #0x64]! (yaw), as ldr s1, [x22]
|
||||
site mouse_direct main 1d3e2b0 bd442729 94a7b734 # EventTalkManual: ldr s9, [x25, #0x424] (stick y)
|
||||
site mouse_direct main 1d3e2d4 aa1303f8 9101d278 # EventTalkManual: mov x24, x19 -> add x24, x19, #0x74
|
||||
site mouse_direct main 1d3e2d8 bc474f01 94a7b72a # EventTalkManual: ldr s1, [x24, #0x74]! (pitch), as ldr s1, [x24]
|
||||
site mouse_direct main 1d3e33c bd442329 94a7b711 # EventTalkManual: ldr s9, [x25, #0x420] (stick x)
|
||||
site mouse_direct main 1d3e360 aa1303f6 9101f276 # EventTalkManual: mov x22, x19 -> add x22, x19, #0x7c
|
||||
site mouse_direct main 1d3e364 bc47cec1 94a7b707 # EventTalkManual: ldr s1, [x22, #0x7c]! (yaw), as ldr s1, [x22]
|
||||
site mouse_direct main 1d46108 bd4422e0 94a7979e # ShieldSurfing: ldr s0, [x23, #0x420] (x for the length, REPEAT)
|
||||
site mouse_direct main 1d46110 bd4426e1 94a7979c # ShieldSurfing: ldr s1, [x23, #0x424] (y for the length, REPEAT)
|
||||
site mouse_direct main 1d46138 bd4426e0 94a79792 # ShieldSurfing: ldr s0, [x23, #0x424] (stick y, kept)
|
||||
site mouse_direct main 1d4613c bd4422e1 94a79791 # ShieldSurfing: ldr s1, [x23, #0x420] (stick x)
|
||||
site mouse_direct main 1d46788 bd40de60 94a795fe # ShieldSurfing: ldr s0, [x19, #0xdc] (pitch)
|
||||
site mouse_direct main 1d46910 bd401fa0 94a7959c # ShieldSurfing: ldr s0, [x29, #0x1c] (pitch turn, cut to the pad)
|
||||
site mouse_direct main 1d467b4 bd403bec 94a795f3 # ShieldSurfing: ldr s12, [sp, #0x38] (yaw)
|
||||
|
||||
# Spin waits, from tools/spin_waits.py --exefs build/extracted/v121/exefs --patches recomp/patches-v121.txt: loops that only
|
||||
# another thread can end; their back-edges pass rt_spin_gate (runtime/kernel.c), TOTK_SPIN=0 keeps the core.
|
||||
spin main ac600 ac620 ac630 # 13 instructions; loads
|
||||
@@ -930,3 +1135,77 @@ spin sdk 23a590 23a5d8 # 19 instructions; loads
|
||||
spin sdk 23a658 23a6a0 # 19 instructions; loads
|
||||
spin sdk 23a7fc 23a918 # 19 instructions; loads
|
||||
spin sdk 3d3250 3d3270 # 9 instructions; loads
|
||||
|
||||
# Sun shadow map size (runtime/resolution.c shadow_init switches the set on). Each frame the engine sizes its shadow
|
||||
# cascades (a D16 4-layer array) in main+0xcebdf4: a base size (960 in the field), interpolated down by how close the
|
||||
# cover is, rounded up to 8 at main+0xcec22c and stored as the width (+0x3d8 of the cascade set) and, through the packed
|
||||
# store at +0xe4, the height (+0x3f8). Near the ground it falls to about 400, which draws foliage shadows blocky, and
|
||||
# every change of size moves the shadow texels, so leaf shadows jump instead of sliding. The page's fixed size (+92)
|
||||
# goes in just before the rounding, as the community's shadow resolution mods do (1.1.0: mov w11, #1024 over the
|
||||
# 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.
|
||||
site grass main fe58b4 52a84f48 @page:x8 b9408108 # mov w8, #62.5 -> ldr w8, [page+128]
|
||||
site grass main fe58c0 52a80f48 @page:x8 b9408508 # mov w8, #3.90625 -> ldr w8, [page+132]
|
||||
site grass main fe58ec 52802002 @page:x2 b9408842 # mov w2, #0x100 -> ldr w2, [page+136]
|
||||
site grass main fe5950 52801002 @page:x2 b9408c42 # mov w2, #0x80 -> ldr w2, [page+140]
|
||||
site grass main 1a30a8c 52a84f48 @page:x8 b9408108 # mov w8, #62.5 -> ldr w8, [page+128]
|
||||
site grass main 1a30a98 52a83f48 @page:x8 b9409108 # mov w8, #31.25 -> ldr w8, [page+144]
|
||||
|
||||
|
||||
# Optional reference with an invalid value (#1005). The same guard as set optref in patches-v143.txt (main+0x1bd01c0),
|
||||
# here for 1.2.1's main+0x1622bec: ldr x8, [x19, #0x6b0]; cbz x8; ldr x21, [x8]. A negative value counts as absent.
|
||||
# x8 and x9 are dead at the branch target 0x1622c1c, which loads x8 again.
|
||||
set optref TOTK_OPTREF_GUARD 1
|
||||
site optref main 1622bec b4000188 937ffd09 8a290108 b4000188 # cbz x8 -> asr x9, x8, #63; bic x8, x8, x9; cbz x8
|
||||
|
||||
# Recall and Ultrahand target that is stale memory: set ability in patches-v143.txt, here for 1.2.1's main+0x1622bf0
|
||||
# (function main+0x1622b60; the callees main+0x809ecc, 0x842aa4 and 0x842d10 read the same actor offsets). The model
|
||||
# scene report-row guard (set report there) has no 1.2.1 site: this version does not have that loop's code shape.
|
||||
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
|
||||
@@ -10,6 +10,16 @@ set cloth TOTK_CLOTH_REALTIME 1
|
||||
set bounce TOTK_HIGHFPS_FIX 1
|
||||
set output TOTK_PATCH_OUTPUT 0
|
||||
set scene TOTK_PATCH_SCENE 0
|
||||
set shadow TOTK_PATCH_SHADOW 0
|
||||
set cascade TOTK_PATCH_CASCADE 0
|
||||
set grass TOTK_PATCH_GRASS 0
|
||||
# Load-dependent quality (patches-v121.txt, set steady). The graphics settings setup (main+0x5868c4) inlines the
|
||||
# three getters 1.2.1 calls: the value 1.2.1 reads at
|
||||
# main+0xc7eb24 is the ldr w10, [x10, #0x38] at main+0x58692c, and the getters' slow paths (main+0x586bc8, 0x586c18,
|
||||
# 0x586f44) come back before the compare. So the site is the compare, which every path reaches: w10 = 9 skips the
|
||||
# list walk to the epilogue (main+0x58729c), which does not read w10.
|
||||
set steady TOTK_LOD_STEADY 0
|
||||
site steady main 586954 7100215f 5280012a 7100215f # cmp w10, #8 -> mov w10, #9; cmp w10, #8 (b.gt 0x58729c taken)
|
||||
|
||||
# 60 fps: the adaptive present-interval controller (main+0x2db174, 1.2.1 0x8f26c8) gets the minimum interval 1.
|
||||
site fps60 main 2db204 6b08015f 7100055f # clamp: cmp w10, #1 (was cmp w10, w8 = minimum)
|
||||
@@ -32,6 +42,23 @@ site realtime main 2daa70 1e201820 d503201f # fdiv s0, s1, s0 -> nop
|
||||
site realtime main 2daa74 1e2c1001 d503201f # fmov s1, #0.5 -> nop
|
||||
site realtime main 2daa78 1e210800 d503201f # fmul s0, s0, s1 -> nop
|
||||
|
||||
# Equipment-switch cooldown (issue #18, found by JieML1100): the player update (main+0x2b0368) steps the countdown at
|
||||
# player state +0x109c through the timer step (main+0x1b0834, value += ratio * rate) only while it is above FLT_EPSILON,
|
||||
# but the equipment gate (main+0x31cc7c) blocks weapon, shield and bow changes while it is above 0. Whole 30 Hz steps
|
||||
# reach exactly 0; a measured ratio leaves a rounding remainder, and one in (0, FLT_EPSILON] is never stepped again and
|
||||
# keeps equipment locked until a load. Stepping while above 0 takes the remainder below 0 like any other last step.
|
||||
site realtime main 2b036c 0f016681 0f000401 # movi v1.2s, #0x34, lsl #24 (FLT_EPSILON) -> movi v1.2s, #0
|
||||
|
||||
# Attack hit processing (main+0x2906a24) builds a list of this frame's hit records on its stack (count at [sp], slots
|
||||
# at [sp+8] -> an inline array that is never cleared). The record insert (main+0x86e1d8) returns null when the
|
||||
# attacker's record map (+0x190) is full, so a full map leaves the list empty. After its two loops the function
|
||||
# passes slot 0 to the hit handler (main+0x870158, which dereferences it) unconditionally at main+0x2906de0 and only
|
||||
# then checks count == 0 at main+0x2906df0; with an empty list slot 0 is stale stack data and the handler faults.
|
||||
# Charged spear hits above 60 fps fill the map. Both count == 0 branches go to the check instead, which reloads the
|
||||
# count and leaves through main+0x2906ce8; x19 and x20 are the only registers read there. A non-empty list is unchanged.
|
||||
site realtime main 2906d98 34000248 340002c8 # cbz w8, 0x2906de0 -> 0x2906df0 (first loop's empty check)
|
||||
site realtime main 2906dc0 34000108 34000188 # cbz w8, 0x2906de0 -> 0x2906df0 (second loop's empty check)
|
||||
|
||||
# Hair and cloth: the actor animation update builds a second clock {seconds = factor / 30, ratio = factor} per
|
||||
# rendered frame. 1.4.3 inlines it in two actor paths, where the factor was just stored to the ratio slot: the
|
||||
# replacement stores measured ratio * factor there and computes measured seconds * factor. Two other callers share the
|
||||
@@ -73,6 +100,13 @@ site scene main 585e50 bd0cc660 2d420460 # str s0, [x19, #0xcc4] -> ldp s0, s
|
||||
site scene main 585e54 1e220140 bd0cc660 # scvtf s0, w10 -> str s0, [x19, #0xcc4]
|
||||
site scene main 585e60 bd0cca60 bd0cca61 # str s0, [x19, #0xcc8] -> str s1, [x19, #0xcc8]
|
||||
|
||||
# Fixed scene size (MacNativeGames game_patches_v143.c patch_fixed_res; runtime/resolution.c res_dynres_live switches
|
||||
# the set on unless TOTK_DYNAMIC_RES=1). The dynamic resolution controller (main+0x584300, 1.2.1 0xcc26f4) steps the
|
||||
# scene through tiers of 100, 90 and 80 % by a cost model that grows with the scene width squared; at its one epilogue the tier's scale moves into
|
||||
# the result, and 1.0 there makes every tier 100 %. The original word is MacNativeGames' check against 1.4.3.
|
||||
set fixres TOTK_FIXED_RES_PATCH 0
|
||||
site fixres main 5848a8 2a1703e9 52a7f009 # mov w9, w23 -> mov w9, #0x3f800000 (1.0f)
|
||||
|
||||
# Camera aspect ratio for a game resolution that is not 16:9 (upstream game_patches_v143.c and aspect_patch.h
|
||||
# aspect_install / aspect_stub; runtime/resolution.c res_init writes the output's width / height to page +56 and
|
||||
# switches the set on). Each site leaves the ratio sead's perspective projection (+0xb0) takes in s0: two camera sites
|
||||
@@ -85,6 +119,103 @@ site aspect main b43460 bd406ac0 f81f0fea @page:x10 bd403940 f84107ea # ldr s0
|
||||
site aspect main 1ff04f4 1e211800 f81f0fea @page:x10 bd403940 f84107ea # fdiv s0, s0, s1 (viewport)
|
||||
site aspect main 253fbb0 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 load the camera's vertical view angle (radians) a few words before the ratio and
|
||||
# hand it to sead's perspective projection (+0xa0, then sin / cos / tan of half of it at +0xa4..+0xac). The replacement
|
||||
# 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. Zooms the game makes itself (the bow, the scope) scale with it.
|
||||
set fov TOTK_FOV_PATCH 0
|
||||
site fov main 628c3c bd413e60 f81f0fea @page:x10 bd413e60 bd403d48 1e280800 f84107ea # ldr s0, [x19, #0x13c] (camera update)
|
||||
site fov main b4342c bd4066c0 f81f0fea @page:x10 bd4066c0 bd403d48 1e280800 f84107ea # ldr s0, [x22, #0x64] (camera setup)
|
||||
|
||||
# The camera input update, after its stick dead zone, unit-radius clamp and StickExponent. The host callback
|
||||
# performs the displaced store and adds raw mouse counts to s9/s10 (runtime/mouse_direct.c camera_input).
|
||||
# Its address is page +0xfd0; the page is main+0x3adf000 on this verified build.
|
||||
set mouse_direct TOTK_MOUSE_DIRECT_PATCH 1
|
||||
site mouse_direct main 874cb4 bd042289 94c9acc7
|
||||
site mouse_direct main 874d7c 6d40a3e9 94c9ac91
|
||||
site mouse_direct main 18e444 f9400408 94e546db
|
||||
site mouse_direct main 18f108 bd4047ec 94e543a6
|
||||
# Keep native camera-distance easing when direct mouse orbit bypasses the stick integrators.
|
||||
site mouse_direct main 18ea34 b9418a88 94e5454f # orbit state: ldr w8, [x20, #0x188]
|
||||
site mouse_direct main 1d59460 b9004be8 94761acc
|
||||
# The aiming, scope, ability, horse and Purah Pad camera cameras: per axis, the float load the stick turn is computed
|
||||
# from (the gamepad's part only) and the load of the angle it is added to (plus the mouse's degrees), each a bl to page
|
||||
# +0xf80, told apart by the return address (runtime/mouse_direct.c camera_load, load_sites). Every enclosing function
|
||||
# saves x30 in its prologue, so the bl's link register write is harmless.
|
||||
site mouse_direct main 23beb94 bd4426c1 945c84fb # Aiming: ldr s1, [x22, #0x424] (stick y)
|
||||
site mouse_direct main 23bebc8 bd415e61 945c84ee # Aiming: ldr s1, [x19, #0x15c] (pitch)
|
||||
site mouse_direct main 23bee2c bd4422c1 945c8455 # Aiming: ldr s1, [x22, #0x420] (stick x)
|
||||
site mouse_direct main 23beeec bc5b83a1 945c8425 # Aiming: ldur s1, [x29, #-0x48] (yaw)
|
||||
site mouse_direct main 23c0a10 bd4422e0 945c7d5c # AimingTelescope: ldr s0, [x23, #0x420] (stick x)
|
||||
site mouse_direct main 23c0a1c bd4426eb 945c7d59 # AimingTelescope: ldr s11, [x23, #0x424] (stick y)
|
||||
site mouse_direct main 23c0b00 bd416260 945c7d20 # AimingTelescope: ldr s0, [x19, #0x160] (pitch)
|
||||
site mouse_direct main 23c0e80 bd405be1 945c7c40 # AimingTelescope: ldr s1, [sp, #0x58] (yaw)
|
||||
site mouse_direct main 23d2eec bd4422e8 945c3425 # SpecialPower: ldr s8, [x23, #0x420] (stick x)
|
||||
site mouse_direct main 23d2ef4 bd4426ee 945c3423 # SpecialPower: ldr s14, [x23, #0x424] (stick y)
|
||||
site mouse_direct main 23d3158 bd416260 945c338a # SpecialPower: ldr s0, [x19, #0x160] (pitch)
|
||||
site mouse_direct main 23d34cc bc5b03a1 945c32ad # SpecialPower: ldur s1, [x29, #-0x50] (yaw)
|
||||
site mouse_direct main 23cb274 bd442288 945c5343 # Horse: ldr s8, [x20, #0x420] (stick x)
|
||||
site mouse_direct main 23cb2a0 bd406a61 945c5338 # Horse: ldr s1, [x19, #0x68] (yaw)
|
||||
site mouse_direct main 23cb3f8 bd4426a8 945c52e2 # Horse: ldr s8, [x21, #0x424] (stick y)
|
||||
site mouse_direct main 23cb424 bd406661 945c52d7 # Horse: ldr s1, [x19, #0x64] (pitch)
|
||||
site mouse_direct main 23d2f30 bd4422e8 945c3414 # SpecialPower offset mode: ldr s8, [x23, #0x420] (stick x)
|
||||
site mouse_direct main 23d2f5c bd41da62 945c3409 # SpecialPower offset mode: ldr s2, [x19, #0x1d8] (offset x)
|
||||
site mouse_direct main 23d2f6c bd4426e8 945c3405 # SpecialPower offset mode: ldr s8, [x23, #0x424] (stick y)
|
||||
site mouse_direct main 23d2f98 bd41de62 945c33fa # SpecialPower offset mode: ldr s2, [x19, #0x1dc] (offset y)
|
||||
site mouse_direct main 23d3210 bd400400 945c335c # SpecialPower: ldr s0, [x0, #0x4] (offset scale, read only)
|
||||
site mouse_direct main 23c2890 bd4426ad 945c75bc # CameraFinder: ldr s13, [x21, #0x424] (stick y)
|
||||
site mouse_direct main 23c28b4 bd405261 945c75b3 # CameraFinder: ldr s1, [x19, #0x50] (pitch)
|
||||
site mouse_direct main 23c2934 bd4422ad 945c7593 # CameraFinder: ldr s13, [x21, #0x420] (stick x)
|
||||
site mouse_direct main 23c2964 bd404be1 945c7587 # CameraFinder: ldr s1, [sp, #0x48] (yaw)
|
||||
# The other player cameras (runtime/mouse_direct.c load_sites; a ROLE_WATCH load stays the game's and only names its
|
||||
# mode in the log when the mouse was in it):
|
||||
site mouse_direct main 23c3dd0 bd442301 945c706c # ClimbObj: ldr s1, [x24, #0x420]
|
||||
site mouse_direct main 23c3dd8 bd409261 945c706a # ClimbObj: ldr s1, [x19, #0x90] (yaw)
|
||||
site mouse_direct main 23c3d64 bd442701 945c7087 # ClimbObj: ldr s1, [x24, #0x424]
|
||||
# ClimbObj's pitch is a pre-indexed load, ldr s1, [x22, #0x88]!, whose write-back the code after it needs (ldp and
|
||||
# str through x22). A host call cannot write x22: the lifter keeps X19-X29 in locals across a call. So the mov before
|
||||
# it adds the 0x88 instead (x22 = x19 + 0x88) and the hook loads [x22] with no write-back.
|
||||
site mouse_direct main 23c3d5c aa1303f6 91022276 # ClimbObj: mov x22, x19 -> add x22, x19, #0x88
|
||||
site mouse_direct main 23c3d70 bc488ec1 945c7084 # ClimbObj: ldr s1, [x22, #0x88]! (pitch), as ldr s1, [x22]
|
||||
site mouse_direct main 23da694 bd4422c1 945c163b # Wakeboard: ldr s1, [x22, #0x420]
|
||||
site mouse_direct main 23da698 bd4426c0 945c163a # Wakeboard: ldr s0, [x22, #0x424] (stick y, kept)
|
||||
site mouse_direct main 23da840 bd40da60 945c15d0 # Wakeboard: ldr s0, [x19, #0xd8] (pitch)
|
||||
site mouse_direct main 23da894 bd4017e0 945c15bb # Wakeboard: ldr s0, [sp, #0x14] (pitch turn, cut to the pad)
|
||||
site mouse_direct main 23daed8 bd403fe9 945c142a # Wakeboard: ldr s9, [sp, #0x3c] (yaw)
|
||||
site mouse_direct main 23dced8 bd4422cd 945c0c2a # WaterfallClimb: ldr s13, [x22, #0x420]
|
||||
site mouse_direct main 23dd070 b85cc3a8 945c0bc4 # WaterfallClimb: ldur w8, [x29, #-0x34] (yaw)
|
||||
site mouse_direct main 23dd008 bd4426c9 945c0bde # WaterfallClimb: ldr s9, [x22, #0x424]
|
||||
site mouse_direct main 23d4b14 bd44228c 945c2d1b # Tail: ldr s12, [x20, #0x420]
|
||||
site mouse_direct main 23d4b1c bd44268d 945c2d19 # Tail (climbing): ldr s13, [x20, #0x424] (stick y)
|
||||
site mouse_direct main 23d4f34 bd40c260 945c2c13 # Tail (climbing): ldr s0, [x19, #0xc0] (yaw)
|
||||
site mouse_direct main 23d5028 bd40b661 945c2bd6 # Tail (climbing): ldr s1, [x19, #0xb4] (pitch)
|
||||
site mouse_direct main 23d756c bd442300 945c2285 # LockOn / Target: ldr s0, [x24, #0x420]
|
||||
site mouse_direct main 23d7594 bd442301 945c227b # LockOn / Target: ldr s1, [x24, #0x420] (stick x)
|
||||
site mouse_direct main 23d75b4 bd4023e0 945c2273 # LockOn / Target: ldr s0, [sp, #0x20] (yaw turn)
|
||||
site mouse_direct main 23d75c4 bd4023e9 945c226f # LockOn / Target: ldr s9, [sp, #0x20] (yaw turn)
|
||||
site mouse_direct main 23d7998 bd442701 945c217a # LockOn / Target: ldr s1, [x24, #0x424] (stick y)
|
||||
site mouse_direct main 23d79b8 bd4023e0 945c2172 # LockOn / Target: ldr s0, [sp, #0x20] (pitch turn)
|
||||
site mouse_direct main 23d79c8 bd4023ea 945c216e # LockOn / Target: ldr s10, [sp, #0x20] (pitch turn)
|
||||
site mouse_direct main 23cecb4 bd4426a9 945c44b3 # LockOnAimingAt: ldr s9, [x21, #0x424] (stick y)
|
||||
site mouse_direct main 23cecf8 bd419a61 945c44a2 # LockOnAimingAt: ldr s1, [x19, #0x198] (pitch offset)
|
||||
site mouse_direct main 23ced0c bd4422a9 945c449d # LockOnAimingAt: ldr s9, [x21, #0x420] (stick x)
|
||||
site mouse_direct main 23ced4c bd419e61 945c448d # LockOnAimingAt: ldr s1, [x19, #0x19c] (yaw offset)
|
||||
site mouse_direct main 23cc4b4 bd44232b 945c4eb3 # HorseLockOnEmpty: ldr s11, [x25, #0x420]
|
||||
site mouse_direct main 23c54d4 bd4422eb 945c6aab # EventMultiTalk: ldr s11, [x23, #0x420]
|
||||
site mouse_direct main 23c542c bd4426eb 945c6ad5 # EventMultiTalk: ldr s11, [x23, #0x424] (stick y)
|
||||
site mouse_direct main 23c546c bd405e61 945c6ac5 # EventMultiTalk: ldr s1, [x19, #0x5c] (pitch)
|
||||
site mouse_direct main 23c5554 bd406661 945c6a8b # EventMultiTalk: ldr s1, [x19, #0x64] (yaw)
|
||||
site mouse_direct main 23c90ac bd442709 945c5bb5 # EventTalkManual: ldr s9, [x24, #0x424] (stick y)
|
||||
site mouse_direct main 23c90d8 bd407661 945c5baa # EventTalkManual: ldr s1, [x19, #0x74] (pitch)
|
||||
site mouse_direct main 23c9140 bd442309 945c5b90 # EventTalkManual: ldr s9, [x24, #0x420] (stick x)
|
||||
site mouse_direct main 23c9170 bd407e61 945c5b84 # EventTalkManual: ldr s1, [x19, #0x7c] (yaw)
|
||||
site mouse_direct main 23d0100 bd4422c1 945c3fa0 # ShieldSurfing: ldr s1, [x22, #0x420] (stick x)
|
||||
site mouse_direct main 23d0104 bd4426c0 945c3f9f # ShieldSurfing: ldr s0, [x22, #0x424] (stick y, kept)
|
||||
site mouse_direct main 23d02ac bd40de60 945c3f35 # ShieldSurfing: ldr s0, [x19, #0xdc] (pitch)
|
||||
site mouse_direct main 23d0a34 bd4013e0 945c3d53 # ShieldSurfing: ldr s0, [sp, #0x10] (pitch turn, cut to the pad)
|
||||
site mouse_direct main 23d087c bd403fe9 945c3dc1 # ShieldSurfing: ldr s9, [sp, #0x3c] (yaw)
|
||||
|
||||
# The game's zstd decoder (BSD zstd, statically linked into main) through the host's libzstd (runtime/ov_zstd.c):
|
||||
# every call of ZSTD_decompressMultiFrame (main+0x3a1f0: dctx, dst, capacity, src, size, dict, dict size, ddict) and of
|
||||
# its wrapper ZSTD_decompress_usingDDict (main+0x3a1e0, which tail-branches to it) goes to a host function on the patch
|
||||
@@ -960,3 +1091,163 @@ spin subsdk0 1c4e54 1c4e60 # 4 instructions; loads
|
||||
spin sdk 2d3654 2d3668 # 6 instructions; loads
|
||||
spin sdk 443864 443884 # 9 instructions; loads
|
||||
spin sdk 541e54 541f98 # 32 instructions; loads
|
||||
|
||||
# Sun shadow map size (patches-v121.txt explains the set and the page). 1.4.3 interpolates the size between a minimum
|
||||
# and the base and rounds it up to 8 at main+0x683604; the rounded value is the width (+0x3d8) and, through the packed
|
||||
# store at +0xf4, the height (+0x3f8). The page's size goes in just before the rounding.
|
||||
site shadow main 683604 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). The depth shadow parameter
|
||||
# object (main+0x6fa3c0) registers depth_shadow_near_0_1..3 = 20, 40, 80 m and depth_shadow_far_0 = 160 m as
|
||||
# immediates, and the field's .bgsdw files do not override them; with the set on they come from page +64..+76.
|
||||
site cascade main 6fabb8 52a83408 @page:x8 b9404108 # mov w8, #20.0 -> ldr w8, [page+64]
|
||||
site cascade main 6fac40 52a84408 @page:x8 b9404508 # mov w8, #40.0 -> ldr w8, [page+68]
|
||||
site cascade main 6facc8 52a85408 @page:x8 b9404908 # mov w8, #80.0 -> ldr w8, [page+72]
|
||||
site cascade main 6fad4c 52a86408 @page:x8 b9404d08 # mov w8, #160.0 -> ldr w8, [page+76]
|
||||
# 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
|
||||
# growing with the frame rate. Below ratio 1 the factor is 1.272 + 1.189 (1 - r) clamped to [1, 2] (r = VFR +0, the
|
||||
# 30 Hz ratio times the time scale): Nintendo's fit for 30 and 60 fps, flat at 2 from about 77 fps, so Link climbs at
|
||||
# 63% of the speed at 120 fps and 34% at 240. Below r = 0.5 take g(r) = 0.66265 / r + 0.4982 + 0.0848 r instead,
|
||||
# fitted to the replayed ladder climb at 120 and 240 fps and equal to the shipping 1.8665 at r = 0.5; at most 8. The
|
||||
# site computes g with 16 * max(r - 0.5, 0) subtracted, so g stays under the shipping factor for r >= 0.5, and folds it
|
||||
# into the existing clamp without flags: s0 = max(s0, g) (the value clamped), s1 = max(2, g) (the bound). r >= 0.5
|
||||
# keeps the shipping factor bit for bit. x8 is dead after the constant load at 0x1f497e8, s2-s4 are loaded again at
|
||||
# 0x1f49844 before any read.
|
||||
# g takes u = max(page +0, r): the patch page's 30 Hz frame ratio without the time scale (runtime/frame_rate.c), so
|
||||
# slow motion at 30 or 60 fps keeps the shipping factor and only a real frame rate above 60 raises it; the runtime
|
||||
# switches the set off without the real-time step, where the page is not written.
|
||||
set climb TOTK_CLIMB_FIX 1
|
||||
site climb main 1f497f4 1e201001 @page:x8 bd400104 1e286884 52946dc8 72a7e528 1e270102 1e241842 52828248 72a7dfe8 1e270103 1e232842 529573e8 72a7b5a8 1e270103 1f040862 1e2a3883 2f00e404 1e246863 1e261004 1f048862 1e241004 1e247842 1e226800 1e201001 1e226821 # fmov s1, #2.0 -> s2 = g(u); s0 = max(s0, s2); s1 = max(2.0, s2)
|
||||
|
||||
|
||||
# Grass range (runtime/resolution.c res_grass_range switches the set on). Grass blades grow from the near grass map, a
|
||||
# square texture the game draws around the camera (GrassShader.sharcb). Its constructor (main+0xa38e58) gives it a
|
||||
# 62.5 m extent, a 3.90625 m step (1/16 of it) and 256x256 and 128x128 textures; main+0x206340c later sets the extent
|
||||
# to 62.5 or 31.25 m. With the set on all of them come from page +128..+144, scaled together so the map keeps its
|
||||
# texels per metre; resolution.c grows the grass heap of the HeapDef for the larger textures.
|
||||
site grass main a38e58 52a84f48 @page:x8 b9408108 # mov w8, #62.5 -> ldr w8, [page+128]
|
||||
site grass main a38e64 52a80f48 @page:x8 b9408508 # mov w8, #3.90625 -> ldr w8, [page+132]
|
||||
site grass main a38e94 52802002 @page:x2 b9408842 # mov w2, #0x100 -> ldr w2, [page+136]
|
||||
site grass main a38ef4 52801002 @page:x2 b9408c42 # mov w2, #0x80 -> ldr w2, [page+140]
|
||||
site grass main 2063454 52a84f48 @page:x8 b9408108 # mov w8, #62.5 -> ldr w8, [page+128]
|
||||
site grass main 2063460 52a83f48 @page:x8 b9409108 # mov w8, #31.25 -> ldr w8, [page+144]
|
||||
|
||||
|
||||
# Optional reference with an invalid value (#1005). main+0x1bd0138 reads an optional reference at object +0x6b0 (null or
|
||||
# a holder whose first word is the target, bit 0 a tag) and checks it only for null: ldr x8, [x19, #0x6b0]; cbz x8;
|
||||
# ldr x21, [x8]. Players' crash reports show the field holding 0xffffffffffffffff after minutes to hours of play, and
|
||||
# the load of the holder faults. MacNativeGames (games/totk/runtime/loader.c, crash) met the same field holding
|
||||
# 0xffff0000ffffffff during a save load and treats the reference as absent there. Every valid holder is a heap address
|
||||
# below 2^63, so the cbz becomes a test for null or negative: x9 = x8 >> 63 (arithmetic, all ones when negative),
|
||||
# x8 &= ~x9, cbz x8. Both x8 and x9 are dead at the branch target 0x1bd01f0, which loads x8 again and writes x9 before
|
||||
# any read; on the fall-through path x8 is unchanged.
|
||||
set optref TOTK_OPTREF_GUARD 1
|
||||
site optref main 1bd01c0 b4000188 937ffd09 8a290108 b4000188 # cbz x8 -> asr x9, x8, #63; bic x8, x8, x9; cbz x8
|
||||
|
||||
# Recall and Ultrahand target that is stale memory. The same function reads the target actor from the holder
|
||||
# (ldr x21, [x8]) and follows it into main+0x155ec, main+0x9a89d4 and main+0x2b8464 (an atomic write at +0x90). The
|
||||
# holder can be reused memory by then, so the actor points into .rodata, outside the address space or at other heap
|
||||
# data, and the game crashes reading 0xffffffffffffffff. UltraTears (kuraeow/ultratears, ability target guard) found
|
||||
# the class. The load becomes a call to runtime/ov_ability.c host_ability_target (page+0xf60): x21 is the holder's
|
||||
# first word, or 0 where the game's own code would fault on the target (holder, actor or component unreadable, the
|
||||
# reference word not writable), which the game's cbz x21 skips for this frame. Every other target goes on unchanged.
|
||||
# The answer comes back in x9 and the cbz site moves it to x21: the lifted code keeps x21 (callee-saved) in a C local
|
||||
# across the call. x9 is dead after 0x1bd01c8 on every path (written or clobbered by a bl before any read); x30 is saved by the
|
||||
# prologue and clobbered by the next bl anyway.
|
||||
set ability TOTK_ABILITY_GUARD 1
|
||||
site ability main 1bd01c4 f9400115 947c3f67 # ldr x21, [x8] -> bl page+0xf60
|
||||
site ability main 1bd01c8 b4000155 aa0903f5 b4000155 # cbz x21 -> mov x21, x9; cbz x21
|
||||
|
||||
# Model scene report rows (WoE, daniel-madrid-07/weeping-of-the-empire, MIT, games/totk/patches/sites_v143.py
|
||||
# reportguard; their #52 and #73: crashes while using Ultrahand and aiming). gsys::ModelScene::calcGPU_ is inlined in
|
||||
# main+0xa1f84; its per-object loop (0xa22bc..0xa234c) takes the object's report handle h (int16 at obj+0x98 + 2 * side),
|
||||
# exits for -1 only, reads row 2h+1 and then u32 n from row 2h, and follows n to row 2n with no bound (WoE's crash had
|
||||
# n = the float 0.05, a read 32 GB past the rows). n indexes a row pair as h does, so a valid one is below 0x8000.
|
||||
# A negative h (other than -1) or n >= 0x8000 goes to 0xa2340, where the game resets the handle to -1 after every use:
|
||||
# the object has coverage 0 this frame (stored at 0xa22cc) and the game asks for a new report, as after a normal read.
|
||||
# WoE's veneers exit at 0xa2344 instead, which keeps the bad handle for the next frames. No flags change; w4 is never
|
||||
# used in main+0xa1f84; x1, x16, x15 and w13, which 0xa2340 reads, hold what they hold on the game's own path there.
|
||||
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
|
||||
|
||||
# Free camera (runtime/freecam.c freecam_hook, page +0xf50). The camera component update (main+0x628460, the routine of
|
||||
# the first fov and aspect sites) copies the component's eye, target and up into its sead camera; every path to that
|
||||
# copy runs this load of the component's link first. The hook performs the load and, while the free camera is on,
|
||||
# writes the component's one-shot eye and target overrides (+0x180, +0x198). The function saves x30 in its prologue, so
|
||||
# the bl's link write is harmless. Off by default (freecam_patch, the Free camera row of the Controls tab, read at start):
|
||||
# with it off the site runs the game's load and nothing else. It sits at the end of the table, so the sets before it
|
||||
# keep their numbers.
|
||||
set freecam TOTK_FREECAM_PATCH 0
|
||||
site freecam main 6286d4 f9400e68 94d2de1f # ldr x8, [x19, #0x18]
|
||||
+212
-22
@@ -1,32 +1,86 @@
|
||||
"""Code patch table for the generator: guest instructions replaced in the lifted C, switchable at run time.
|
||||
|
||||
Lifted code cannot be byte-patched when the game runs, so a patch is applied when the C is generated. A patch file
|
||||
(gen.py --patches) has two kinds of lines; `#` starts a comment, fields are separated by whitespace:
|
||||
(gen.py --patches) has these kinds of lines; `#` starts a comment, fields are separated by whitespace:
|
||||
|
||||
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
|
||||
of the 2 MiB-aligned module slot free); the runtime commits it and owns its contents.
|
||||
of the 2 MiB-aligned module slot free); the runtime commits it and owns its contents. Words in use, by byte offset:
|
||||
+0..15 the frame-rate step (runtime/frame_rate.c), +16..55 the output, swapchain and scene sizes
|
||||
(runtime/resolution.c res_init), +56..59 the camera's aspect ratio (runtime/resolution.c res_init, set aspect), +60..63
|
||||
the field-of-view factor (runtime/resolution.c res_fov_live, set fov), +92..95 the sun shadow map size
|
||||
(runtime/resolution.c shadow_init, set shadow). A new set takes words outside these.
|
||||
|
||||
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. Replacement
|
||||
words must not branch except a final `bl` (lifted with the site's return address); the original must not be a branch
|
||||
other than `bl`. So the function's control flow, labels and jump tables are the original's. The generator writes
|
||||
patches.h (set names, switches, the page address) next to layout.h for the runtime.
|
||||
`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.
|
||||
|
||||
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, 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
|
||||
without any keeps it in every function, as does gen.py --fn-enter-all (a whole-game function-entry profile).
|
||||
"""
|
||||
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):
|
||||
@@ -42,40 +96,107 @@ def adrp(pc, target, rd):
|
||||
|
||||
|
||||
class Table:
|
||||
"""sets: [(name, env, default)]; sites: {module: {offset: (set index, [word | ('page', reg)], original)}}; page."""
|
||||
"""sets: [(name, env, default)]; sites: {module: {offset: [(set index, [word | ('page', reg)], original)]}} (the
|
||||
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):
|
||||
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
|
||||
(FN_ENTER in every function)."""
|
||||
if not self.hooks:
|
||||
return None
|
||||
return {base + o for o in self.hooks.get(name, ())}
|
||||
|
||||
def spins_for(self, name, base):
|
||||
"""{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 = {}
|
||||
for off, (k, repl, _) in self.sites.get(name, {}).items():
|
||||
|
||||
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])
|
||||
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 = [], {}, {}, {}
|
||||
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:
|
||||
@@ -87,12 +208,19 @@ 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))
|
||||
mod = sites.setdefault(f[2], {})
|
||||
if off in mod:
|
||||
raise PatchError(f'{where}: {f[2]}+{off:#x} patched twice')
|
||||
mod[off] = (index[f[1]], repl, orig)
|
||||
alts = sites.setdefault(f[2], {}).setdefault(off, [])
|
||||
if any(k == index[f[1]] for k, _, _ in alts):
|
||||
raise PatchError(f'{where}: {f[2]}+{off:#x} patched twice by set {f[1]}')
|
||||
if alts and alts[0][2] != orig:
|
||||
raise PatchError(f'{where}: {f[2]}+{off:#x} expects {orig:08x}, an earlier line {alts[0][2]:08x}')
|
||||
alts.append((index[f[1]], repl, orig))
|
||||
elif f[0] == 'spin' and len(f) >= 4:
|
||||
if f[1] not in bases:
|
||||
raise PatchError(f'{where}: module {f[1]} not in the layout')
|
||||
@@ -102,6 +230,19 @@ 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')
|
||||
hooks.setdefault(f[1], set()).update(int(o, 16) for o in f[2:])
|
||||
else:
|
||||
raise PatchError(f'{where}: cannot parse {raw!r}')
|
||||
base, size = bases['main'][0], bases['main'][1]
|
||||
@@ -109,12 +250,41 @@ 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)
|
||||
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):
|
||||
"""Stops on a site whose original word differs from the module's."""
|
||||
for off, (_, _, want) in table.sites.get(name, {}).items():
|
||||
for off, [(_, _, want), *_] in table.sites.get(name, {}).items():
|
||||
a = mod.base + off
|
||||
if not mod.in_text(a):
|
||||
raise PatchError(f'{name}+{off:#x}: patch site outside .text')
|
||||
@@ -145,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)
|
||||
@@ -0,0 +1,246 @@
|
||||
"""V registers in C locals (gen.py --v-locals K): a rewrite of one emitted function's C.
|
||||
|
||||
The lifter writes V registers as `c->v[n]`, lane forms `((T *)&c->v[n])[i]`, the register macros of runtime/simd.h
|
||||
(VREG, VQ, VW, VS32, ...) and helper calls that name registers by number (fp_op_s(c, op, d, n, m), ...). A chunk
|
||||
generated with K > 0 defines RT_VLOCALS, under which those macros and helpers reach a register through a local array
|
||||
`u128 vr[32]` when its bit in the function's VMASK is set, else through c->v; every access is a whole-vector load or
|
||||
store, so clang's SROA keeps each local register in an XMM register. This module
|
||||
|
||||
- turns the direct forms into the accessors (c->v[n] = e -> VSET, c->v[n] -> VGET, lane forms -> VLANE/VLSET),
|
||||
- picks the K registers the function names most often (VMASK),
|
||||
- loads them at entry; before every call, rt_dispatch, rt_svc/rt_udf/rt_brk, rt_spin_gate and exit stores the ones
|
||||
the function writes (VSYNC_OUT_D: only if the dirty mask may have the bit; the mask folds to a constant on most
|
||||
paths); after a call reloads them, except V8-V15 with trust (AAPCS64: a callee preserves their low 64 bits, and a
|
||||
conforming caller does not read their upper halves after the call).
|
||||
|
||||
Why the cap: 32 guest registers on 16 XMM registers spill (all 32 cost +20% instructions, the stack traffic tripled),
|
||||
while K = 6..8 removed a quarter of the c->v traffic and kept dependent FP chains in registers; build/v143-vloc
|
||||
NOTES.md has the measurements.
|
||||
"""
|
||||
import re
|
||||
from collections import Counter
|
||||
|
||||
# Default K: 8 cut guest time 3.9-6.2% in the town on a 7900X against K = 0 (build/v143-vloc NOTES.md, series s1 and g1).
|
||||
LOCALS = 8
|
||||
|
||||
# runtime/simd.h helpers that take VCTX, with their parameters after c. Register-number parameters are d (written,
|
||||
# also read by some), n, m, a (read) and t (the first of up to 4 consecutive registers; written by the sl_ld* loads).
|
||||
HELPERS = {
|
||||
'fp_op_s': ['op', 'd', 'n', 'm'],
|
||||
'fp_op_d': ['op', 'd', 'n', 'm'],
|
||||
'fp_fma_s': ['na', 'nn', 'd', 'n', 'm', 'a'],
|
||||
'fp_fma_d': ['na', 'nn', 'd', 'n', 'm', 'a'],
|
||||
'sl_gen': ['op', 'sz', 'ne', 'd', 'szd', 'offd', 'keep', 'n', 'szn', 'offn', 'm', 'szm', 'offm', 'bidx', 'bimm'],
|
||||
'sl_addlp': ['u', 'acc', 'Q', 'sz', 'd', 'n'],
|
||||
'sl_across': ['op', 'u', 'Q', 'sz', 'd', 'n'],
|
||||
'sl_pmull64': ['part', 'd', 'n', 'm'],
|
||||
'sv_fred_s': ['op', 'd', 'n'],
|
||||
'sv_fcvtl': ['sz', 'part', 'd', 'n'],
|
||||
'sv_fcvtn': ['sz', 'part', 'odd', 'd', 'n'],
|
||||
'sv_tbl': ['Q', 'len', 'tbx', 'd', 'n', 'm'],
|
||||
'sv_aes': ['op', 'd', 'n'],
|
||||
'sv_sha1hash': ['op', 'd', 'n', 'm'],
|
||||
'sv_sha256hash': ['part1', 'd', 'n', 'm'],
|
||||
'sv_sha_misc': ['op', 'd', 'n', 'm'],
|
||||
'sl_ldm': ['Q', 'sz', 'selem', 'rpt', 't', 'ea'],
|
||||
'sl_stm': ['Q', 'sz', 'selem', 'rpt', 't', 'ea'],
|
||||
'sl_lds': ['sz', 'selem', 'idx', 't', 'ea'],
|
||||
'sl_sts': ['sz', 'selem', 'idx', 't', 'ea'],
|
||||
'sl_ldr': ['Q', 'sz', 'selem', 't', 'ea'],
|
||||
}
|
||||
REG_PARAMS = ('d', 'n', 'm', 'a', 't')
|
||||
LANE_T = {'sa16': 'vu16', 'sa32': 'vu32', 'sa64': 'vu64', 'saf32': 'vf32', 'saf64': 'vf64', 'uint8_t': 'vu8',
|
||||
'uint16_t': 'vu16', 'uint32_t': 'vu32', 'uint64_t': 'vu64', 'float': 'vf32', 'double': 'vf64'}
|
||||
CALLEE_SAVED = frozenset(range(8, 16))
|
||||
PLAIN = '\n const unsigned VMASK = 0; u128 *const vr = c->v; unsigned vd_ = 0, *const vdp = &vd_; (void)vr; (void)vdp;'
|
||||
|
||||
FN = re.compile(r'^(?:static )?void (?:f|fb)_[0-9a-f]+\(Cpu \*c\) \{$', re.M)
|
||||
CALL = re.compile(r'\b(?:f|fb)_[0-9a-f]+\(c\);|\brt_dispatch\(c\);|\brt_(?:svc|udf|brk|spin_gate)\(c,[^;]*;')
|
||||
RET = re.compile(r'(?:__attribute__\(\(musttail\)\)\s*)?\breturn\b[^;]*;')
|
||||
RET_BLOCK = re.compile(r'(\{ [^{}]*?(?:__attribute__\(\(musttail\)\) )?return\b[^;]*; \})')
|
||||
LANE = re.compile(r'\(\((\w+) \*\)&c->v\[')
|
||||
WHOLE = re.compile(r'c->v\[')
|
||||
USES = re.compile(r'\b(' + '|'.join(['VSET', 'VLSET', 'VGET', 'VLANE', 'VS8', 'VS16', 'VS32', 'VS64', 'VSF32', 'VSF64',
|
||||
'VHI64', 'VREG', 'VQ', 'VW', 'FP_SETS', 'FP_SETD', 'SV_FOP_S', 'SV_FOP_D']
|
||||
+ sorted(HELPERS)) + r')\(')
|
||||
|
||||
|
||||
class Unsupported(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _close(s, i):
|
||||
"""s[i-1] opens a bracket; the index after its match"""
|
||||
d = 1
|
||||
while d:
|
||||
d += {'[': 1, ']': -1}.get(s[i], 0)
|
||||
i += 1
|
||||
return i
|
||||
|
||||
|
||||
def _stmt_end(s, i):
|
||||
"""index of the ';' that ends the expression starting at s[i]"""
|
||||
d = 0
|
||||
while True:
|
||||
ch = s[i]
|
||||
if ch in '([{':
|
||||
d += 1
|
||||
elif ch in ')]}':
|
||||
d -= 1
|
||||
elif ch == ';' and d == 0:
|
||||
return i
|
||||
i += 1
|
||||
|
||||
|
||||
def _args(s, i):
|
||||
"""arguments of the call whose '(' is s[i]"""
|
||||
d, cur, out = 0, '', []
|
||||
while True:
|
||||
ch = s[i]
|
||||
if ch == '(':
|
||||
d += 1
|
||||
if d == 1:
|
||||
i += 1
|
||||
continue
|
||||
elif ch == ')':
|
||||
d -= 1
|
||||
if d == 0:
|
||||
out.append(cur.strip())
|
||||
return out
|
||||
elif ch == ',' and d == 1:
|
||||
out.append(cur.strip())
|
||||
cur = ''
|
||||
i += 1
|
||||
continue
|
||||
cur += ch
|
||||
i += 1
|
||||
|
||||
|
||||
def accessors(t):
|
||||
"""c->v forms of emitted C -> the RT_VLOCALS accessors of runtime/simd.h"""
|
||||
out, i = [], 0
|
||||
while True:
|
||||
m1, m2 = LANE.search(t, i), WHOLE.search(t, i)
|
||||
m = min((x for x in (m1, m2) if x), key=lambda x: x.start(), default=None)
|
||||
if not m:
|
||||
out.append(t[i:])
|
||||
return ''.join(out)
|
||||
out.append(t[i:m.start()])
|
||||
if m is m1:
|
||||
e = _close(t, m.end())
|
||||
if m.group(1) not in LANE_T or t[e:e + 2] != ')[':
|
||||
raise Unsupported(f'V register pointer form {t[m.start():e + 10]!r}')
|
||||
je = _close(t, e + 2)
|
||||
reg, lane, vt = accessors(t[m.end():e - 1]), t[e + 2:je - 1], LANE_T[m.group(1)]
|
||||
a = re.match(r'\s*=(?!=)', t[je:])
|
||||
if a:
|
||||
se = _stmt_end(t, je + a.end())
|
||||
out.append(f'VLSET({reg}, {vt}, {lane}, {accessors(t[je + a.end():se]).strip()})')
|
||||
i = se
|
||||
else:
|
||||
out.append(f'VLANE({reg}, {vt}, {lane})')
|
||||
i = je
|
||||
continue
|
||||
if t[m.start() - 1:m.start()] == '&':
|
||||
raise Unsupported(f'V register address {t[m.start() - 1:m.start() + 20]!r}')
|
||||
e = _close(t, m.end())
|
||||
reg = accessors(t[m.end():e - 1])
|
||||
a = re.match(r'\s*=(?!=)', t[e:])
|
||||
if a:
|
||||
se = _stmt_end(t, e + a.end())
|
||||
out.append(f'VSET({reg}, {accessors(t[e + a.end():se]).strip()})')
|
||||
i = se
|
||||
else:
|
||||
out.append(f'VGET({reg})')
|
||||
i = e
|
||||
|
||||
|
||||
def _lit(a):
|
||||
a = a.strip().rstrip('uUlL')
|
||||
if re.fullmatch(r'-\d+', a):
|
||||
return -1
|
||||
return int(a, 0) if re.fullmatch(r'0x[0-9a-fA-F]+|\d+', a) else None
|
||||
|
||||
|
||||
def registers(body):
|
||||
"""(Counter of register uses, set of written registers) of a body in accessor form"""
|
||||
used, wr = Counter(), set()
|
||||
for m in USES.finditer(body):
|
||||
name = m.group(1)
|
||||
args = _args(body, m.end() - 1)
|
||||
if name in HELPERS:
|
||||
for p, a in zip(['c'] + HELPERS[name], args):
|
||||
if p not in REG_PARAMS:
|
||||
continue
|
||||
v = _lit(a)
|
||||
if v == -1:
|
||||
continue
|
||||
if v is None:
|
||||
raise Unsupported(f'register argument {a!r} of {name}')
|
||||
span = 4 if p == 't' or (name == 'sv_tbl' and p == 'n') else 1
|
||||
rs = [(v + k) & 31 for k in range(span)]
|
||||
used.update(rs)
|
||||
if p == 'd' or (p == 't' and name.startswith('sl_ld')):
|
||||
wr.update(rs)
|
||||
continue
|
||||
pos, write = {'VREG': (1, False), 'VQ': (2, False), 'VW': (2, True), 'SV_FOP_S': (2, True),
|
||||
'SV_FOP_D': (2, True), 'VSET': (0, True), 'VLSET': (0, True), 'FP_SETS': (0, True),
|
||||
'FP_SETD': (0, True)}.get(name, (0, False))
|
||||
v = _lit(args[pos])
|
||||
if v is None or v < 0:
|
||||
raise Unsupported(f'register {args[pos]!r} of {name}')
|
||||
used[v] += 1
|
||||
if write:
|
||||
wr.add(v)
|
||||
return used, wr
|
||||
|
||||
|
||||
def rewrite_one(body, k, trust, stats):
|
||||
"""Body of one C function (text between its braces)."""
|
||||
try:
|
||||
new = accessors(body)
|
||||
cnt, written = registers(new)
|
||||
except Unsupported:
|
||||
# a form this rewrite does not know: every register stays in c->v (VMASK 0)
|
||||
stats['v_unsupported_functions'] += 1
|
||||
return PLAIN + body
|
||||
body = new
|
||||
if not cnt:
|
||||
return body
|
||||
local = {r for r, _ in sorted(cnt.items(), key=lambda x: (-x[1], x[0]))[:k]}
|
||||
written &= local
|
||||
load = ''.join(f'VSYNC_IN({r}); ' for r in sorted(local))
|
||||
reload = ''.join(f'VSYNC_IN({r}); ' for r in sorted(local - (CALLEE_SAVED if trust else set())))
|
||||
store = ''.join(f'VSYNC_OUT_D({r}); ' for r in sorted(written))
|
||||
stats['v_local_functions'] += 1
|
||||
stats['v_local_registers'] += len(local)
|
||||
|
||||
def at_ret(m):
|
||||
stats['v_exit_syncs'] += 1
|
||||
return '{ ' + store + m.group(0) + ' }'
|
||||
|
||||
def at_call(m):
|
||||
stats['v_call_syncs'] += 1
|
||||
return '{ ' + store + m.group(0) + ' ' + reload + 'vd_ = 0; }'
|
||||
|
||||
body = RET.sub(at_ret, body)
|
||||
parts = RET_BLOCK.split(body)
|
||||
body = ''.join(p if i % 2 else CALL.sub(at_call, p) for i, p in enumerate(parts))
|
||||
mask = sum(1 << r for r in local)
|
||||
return (f'\n const unsigned VMASK = {mask:#x}u; u128 vr[32]; unsigned vd_ = 0, *const vdp = &vd_; {load.rstrip()}'
|
||||
+ body + ('\n ' + store.rstrip() if store else ''))
|
||||
|
||||
|
||||
def rewrite(text, k, trust, stats):
|
||||
"""C text of one emitted guest function (an f_ and, for a computed branch, its fb_) with K registers local."""
|
||||
out, pos = [], 0
|
||||
for m in FN.finditer(text):
|
||||
d, i = 1, m.end()
|
||||
while d:
|
||||
d += {'{': 1, '}': -1}.get(text[i], 0)
|
||||
i += 1
|
||||
out.append(text[pos:m.end()])
|
||||
out.append(rewrite_one(text[m.end():i - 1], k, trust, stats) + text[i - 1])
|
||||
pos = i
|
||||
out.append(text[pos:])
|
||||
return ''.join(out)
|
||||
@@ -0,0 +1,400 @@
|
||||
// Amiibo dump loader and Horizon OS NFP state emulation.
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "amiibo.h"
|
||||
#include "host.h"
|
||||
#include "platform/platform.h"
|
||||
|
||||
static PlatMutex g_amiibo_lock = PLAT_MUTEX_INIT;
|
||||
|
||||
// 540-byte raw NTAG215 binary dump
|
||||
static uint8_t g_dump[AMIIBO_DUMP_SIZE];
|
||||
static bool g_has_dump = false;
|
||||
static AmiiboInfo g_info;
|
||||
|
||||
static bool g_device_present = true;
|
||||
static bool g_detecting = false;
|
||||
static bool g_tag_present = false;
|
||||
static bool g_mounted = false;
|
||||
static bool g_auto_remove = true;
|
||||
static float g_auto_remove_delay_s = 2.5f;
|
||||
|
||||
static uint64_t g_tap_timestamp_ns = 0;
|
||||
static bool g_timer_active = false;
|
||||
|
||||
static bool amiibo_validate_dump(const uint8_t *data, uint64_t size) {
|
||||
if (size != AMIIBO_DUMP_SIZE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// NTAG215 Capability Container (CC) at page 3 (offset 0x0C). An amiibo's is F1 10 FF EE, not the E1 of a plain
|
||||
// NDEF tag (3dbrew, "Amiibo"); the CC is not encrypted, so encrypted dumps carry it too.
|
||||
static const uint8_t amiibo_cc[4] = {0xF1, 0x10, 0xFF, 0xEE};
|
||||
if (memcmp(data + 0x0C, amiibo_cc, sizeof amiibo_cc)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// UID sanity: UID (bytes 0..2 and 4..7) cannot be all zeroes or all 0xFF.
|
||||
if ((data[0] == 0 && data[1] == 0 && data[2] == 0 && data[4] == 0 &&
|
||||
data[5] == 0 && data[6] == 0 && data[7] == 0) ||
|
||||
(data[0] == 0xFF && data[1] == 0xFF && data[2] == 0xFF && data[4] == 0xFF &&
|
||||
data[5] == 0xFF && data[6] == 0xFF && data[7] == 0xFF)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// ISO 14443-3 / NTAG215 Bit Check Character (BCC) verification.
|
||||
// Page 0 byte 3 (BCC0) = 0x88 ^ UID[0] ^ UID[1] ^ UID[2]
|
||||
// Page 2 byte 0 (BCC1) = UID[3] ^ UID[4] ^ UID[5] ^ UID[6]
|
||||
uint8_t bcc0 = (uint8_t)(0x88 ^ data[0] ^ data[1] ^ data[2]);
|
||||
uint8_t bcc1 = (uint8_t)(data[4] ^ data[5] ^ data[6] ^ data[7]);
|
||||
if (data[3] != bcc0 || data[8] != bcc1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// The 7-byte UID of an NTAG215 dump: bytes 0..2, then 4..7. Byte 3 is the check byte BCC0.
|
||||
static void copy_uid(uint8_t out[7], const uint8_t *dump) {
|
||||
memcpy(out, dump, 3);
|
||||
memcpy(out + 3, dump + 4, 4);
|
||||
}
|
||||
|
||||
static void parse_dump_info(const char *path) {
|
||||
memset(&g_info, 0, sizeof(g_info));
|
||||
if (path) {
|
||||
snprintf(g_info.path, sizeof(g_info.path), "%s", path);
|
||||
const char *slash = strrchr(path, '\\');
|
||||
const char *fslash = strrchr(path, '/');
|
||||
const char *name = slash ? slash + 1 : (fslash ? fslash + 1 : path);
|
||||
if (slash && fslash) {
|
||||
name = (slash > fslash ? slash : fslash) + 1;
|
||||
}
|
||||
snprintf(g_info.filename, sizeof(g_info.filename), "%s", name);
|
||||
}
|
||||
|
||||
copy_uid(g_info.uuid, g_dump);
|
||||
g_info.uuid_len = 7;
|
||||
|
||||
// Amiibo ID at offset 0x54 (8 bytes, 3dbrew "Amiibo"): character ID and variant, figure type, model number
|
||||
// (big-endian), series, format version 02
|
||||
memcpy(g_info.character_id, g_dump + 0x54, 3);
|
||||
g_info.nfp_type = g_dump[0x57];
|
||||
g_info.numbering_id = ((uint16_t)g_dump[0x58] << 8) | g_dump[0x59];
|
||||
g_info.series_id = g_dump[0x5A];
|
||||
g_info.version = g_dump[0x5B];
|
||||
}
|
||||
|
||||
void amiibo_init(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
g_device_present = true;
|
||||
g_detecting = false;
|
||||
g_tag_present = false;
|
||||
g_mounted = false;
|
||||
g_has_dump = false;
|
||||
g_timer_active = false;
|
||||
memset(g_dump, 0, sizeof(g_dump));
|
||||
memset(&g_info, 0, sizeof(g_info));
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
void amiibo_set_device_present(bool present) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
g_device_present = present;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
bool amiibo_is_device_present(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
bool res = g_device_present;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return res;
|
||||
}
|
||||
|
||||
// While the game waits for a tag it stops and starts detection again several times a second (tens with the menu open),
|
||||
// so the log names the first few and then a count every 200th start.
|
||||
static uint64_t g_detect_starts;
|
||||
static uint64_t g_detect_stop_ns; // the last stop: the menu holds "searching" across the game's restarts
|
||||
|
||||
void amiibo_start_detection(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
g_detecting = true;
|
||||
uint64_t n = ++g_detect_starts;
|
||||
if (n <= 3) rt_log("amiibo: start detection");
|
||||
else if (n % 200 == 0) rt_log("amiibo: detection started %llu times so far", (unsigned long long)n);
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
void amiibo_stop_detection(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
if (g_detecting) g_detect_stop_ns = plat_now_ns();
|
||||
g_detecting = false;
|
||||
if (g_detect_starts <= 3) rt_log("amiibo: stop detection");
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
bool amiibo_is_detecting(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
bool res = g_detecting;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return res;
|
||||
}
|
||||
|
||||
bool amiibo_mount(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
if (!g_device_present || !g_tag_present) {
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return false;
|
||||
}
|
||||
g_mounted = true;
|
||||
rt_log("amiibo: mounted tag '%s'", g_info.filename[0] ? g_info.filename : "unknown");
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return true;
|
||||
}
|
||||
|
||||
void amiibo_unmount(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
g_mounted = false;
|
||||
rt_log("amiibo: unmounted tag");
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
bool amiibo_is_mounted(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
bool res = g_mounted;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return res;
|
||||
}
|
||||
|
||||
AmiiboDeviceState amiibo_get_device_state(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
if (!g_device_present) {
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return AMIIBO_DEV_STATE_UNAVAILABLE;
|
||||
}
|
||||
if (g_mounted) {
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return AMIIBO_DEV_STATE_TAG_MOUNTED;
|
||||
}
|
||||
if (g_tag_present) {
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return AMIIBO_DEV_STATE_TAG_FOUND;
|
||||
}
|
||||
if (g_detecting) {
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return AMIIBO_DEV_STATE_SEARCHING;
|
||||
}
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return AMIIBO_DEV_STATE_INITIALIZED;
|
||||
}
|
||||
|
||||
AmiiboDeviceState amiibo_get_reader_state(void) {
|
||||
AmiiboDeviceState state = amiibo_get_device_state();
|
||||
if (state != AMIIBO_DEV_STATE_INITIALIZED) return state;
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
bool recent = g_detect_stop_ns && plat_now_ns() - g_detect_stop_ns < 1000000000ull;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return recent ? AMIIBO_DEV_STATE_SEARCHING : state;
|
||||
}
|
||||
|
||||
bool amiibo_load_file(const char *path) {
|
||||
if (!path || !*path) return false;
|
||||
uint64_t size = 0;
|
||||
uint8_t *data = plat_file_read(path, &size);
|
||||
if (!data) {
|
||||
rt_log("amiibo: failed to read file: %s", path);
|
||||
return false;
|
||||
}
|
||||
if (size != AMIIBO_DUMP_SIZE) {
|
||||
rt_log("amiibo: invalid dump size (%llu bytes, expected exactly %d): %s",
|
||||
(unsigned long long)size, AMIIBO_DUMP_SIZE, path);
|
||||
free(data);
|
||||
return false;
|
||||
}
|
||||
if (!amiibo_validate_dump(data, size)) {
|
||||
rt_log("amiibo: dump failed NTAG215 structure sanity checks: %s", path);
|
||||
free(data);
|
||||
return false;
|
||||
}
|
||||
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
memcpy(g_dump, data, AMIIBO_DUMP_SIZE);
|
||||
g_has_dump = true;
|
||||
parse_dump_info(path);
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
|
||||
free(data);
|
||||
rt_log("amiibo: loaded dump '%s' (char_id: %02x%02x%02x, series: %02x, num: %04x)",
|
||||
g_info.filename, g_info.character_id[0], g_info.character_id[1], g_info.character_id[2],
|
||||
g_info.series_id, g_info.numbering_id);
|
||||
return true;
|
||||
}
|
||||
|
||||
void amiibo_tap_tag(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
if (!g_has_dump) {
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return;
|
||||
}
|
||||
g_tag_present = true;
|
||||
g_tap_timestamp_ns = plat_now_ns();
|
||||
if (g_auto_remove) {
|
||||
g_timer_active = true;
|
||||
}
|
||||
rt_log("amiibo: tag tapped on reader ('%s')", g_info.filename);
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
bool amiibo_scan_and_tap(const char *path) {
|
||||
if (!amiibo_load_file(path)) return false;
|
||||
amiibo_tap_tag();
|
||||
return true;
|
||||
}
|
||||
|
||||
void amiibo_remove_tag(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
if (g_tag_present || g_mounted) {
|
||||
g_tag_present = false;
|
||||
g_mounted = false;
|
||||
g_timer_active = false;
|
||||
rt_log("amiibo: tag removed from reader");
|
||||
}
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
void amiibo_tick(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
if (g_timer_active && g_tag_present) {
|
||||
uint64_t now = plat_now_ns();
|
||||
uint64_t diff = now > g_tap_timestamp_ns ? now - g_tap_timestamp_ns : 0;
|
||||
uint64_t limit_ns = (uint64_t)(g_auto_remove_delay_s * 1000000000.0f);
|
||||
if (diff >= limit_ns) {
|
||||
g_tag_present = false;
|
||||
g_mounted = false;
|
||||
g_timer_active = false;
|
||||
rt_log("amiibo: auto-removed tag after %.1fs timeout", (double)g_auto_remove_delay_s);
|
||||
}
|
||||
}
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
void amiibo_set_auto_remove(bool enable) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
g_auto_remove = enable;
|
||||
if (!enable) g_timer_active = false;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
bool amiibo_get_auto_remove(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
bool res = g_auto_remove;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return res;
|
||||
}
|
||||
|
||||
void amiibo_set_auto_remove_delay_s(float seconds) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
if (seconds >= 0.5f && seconds <= 10.0f) g_auto_remove_delay_s = seconds;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
float amiibo_get_auto_remove_delay_s(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
float res = g_auto_remove_delay_s;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return res;
|
||||
}
|
||||
|
||||
bool amiibo_has_tag(void) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
bool res = g_has_dump && g_tag_present;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return res;
|
||||
}
|
||||
|
||||
const AmiiboInfo *amiibo_get_current_info(void) {
|
||||
return &g_info;
|
||||
}
|
||||
|
||||
const uint8_t *amiibo_get_raw_data(void) {
|
||||
return g_dump;
|
||||
}
|
||||
|
||||
void amiibo_get_tag_info(void *out_tag_info) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
uint8_t *out = (uint8_t *)out_tag_info;
|
||||
memset(out, 0, 0x58);
|
||||
// UUID: offset 0x00, 10 bytes max
|
||||
copy_uid(out, g_dump);
|
||||
out[0x0A] = 7; // UUID length
|
||||
// Protocol at offset 0x20: TypeA = 1
|
||||
*(uint32_t *)(out + 0x20) = 1;
|
||||
// TagType at offset 0x24: Type2 / NTAG215 = 2
|
||||
*(uint32_t *)(out + 0x24) = 2;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
void amiibo_get_model_info(void *out_model_info) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
uint8_t *out = (uint8_t *)out_model_info;
|
||||
memset(out, 0, 0x40);
|
||||
// nn::nfp::ModelInfo from the amiibo ID at 0x54: character ID and variant in the tag's byte order, series, model
|
||||
// number little-endian (big-endian on the tag), figure type. The game tells figures of one character apart by the
|
||||
// model number.
|
||||
memcpy(out + 0x00, g_dump + 0x54, 3); // character ID, variant
|
||||
out[0x03] = g_dump[0x5A]; // series
|
||||
out[0x04] = g_dump[0x59]; // model number
|
||||
out[0x05] = g_dump[0x58];
|
||||
out[0x06] = g_dump[0x57]; // figure type
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
void amiibo_get_common_info(void *out_common_info) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
uint8_t *out = (uint8_t *)out_common_info;
|
||||
memset(out, 0, 0x40);
|
||||
// Last write date: 0x00..0x03
|
||||
out[0x00] = 0xE7; out[0x01] = 0x07; // 2023, u16 little-endian
|
||||
out[0x02] = 0x05; out[0x03] = 0x0C; // May 12
|
||||
// Write counter: 0x04..0x05
|
||||
out[0x04] = 0x00; out[0x05] = 0x01;
|
||||
// Version: 0x06
|
||||
out[0x06] = 0x02;
|
||||
// Application area size: 0x08..0x0B = 0xD8 (216 bytes)
|
||||
*(uint32_t *)(out + 0x08) = 0xD8;
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
void amiibo_get_register_info(void *out_register_info) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
uint8_t *out = (uint8_t *)out_register_info;
|
||||
memset(out, 0, 0x100);
|
||||
// Mii CharInfo at 0x00..0x57 (dummy valid mii)
|
||||
out[0x00] = 0x03; // version 3
|
||||
// First write date at 0x58..0x5B
|
||||
out[0x58] = 0xE7; out[0x59] = 0x07; // 2023, u16 little-endian
|
||||
out[0x5A] = 0x05; out[0x5B] = 0x0C;
|
||||
// Amiibo Name at 0x5C: copy up to 40 bytes NUL-terminated
|
||||
const char *name = g_info.filename[0] ? g_info.filename : "Amiibo";
|
||||
snprintf((char *)(out + 0x5C), 0x29, "%s", name);
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
}
|
||||
|
||||
int amiibo_get_application_area(void *out_buf, uint32_t max_size) {
|
||||
plat_mutex_lock(&g_amiibo_lock);
|
||||
if (!g_has_dump || !out_buf) {
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return 0;
|
||||
}
|
||||
uint32_t to_copy = max_size < 0xD8 ? max_size : 0xD8;
|
||||
// Decrypted/payload application area starts at offset 0xDC (or 0x0A0..0x178 in raw dump)
|
||||
if (0xDC + to_copy <= AMIIBO_DUMP_SIZE) {
|
||||
memcpy(out_buf, g_dump + 0xDC, to_copy);
|
||||
} else {
|
||||
memset(out_buf, 0, to_copy);
|
||||
}
|
||||
plat_mutex_unlock(&g_amiibo_lock);
|
||||
return (int)to_copy;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// Amiibo loader and state management subsystem (540-byte NTAG215 binary dumps).
|
||||
#pragma once
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define AMIIBO_DUMP_SIZE 540
|
||||
|
||||
// Device state corresponding to nn::nfp / nn::nfc DeviceState
|
||||
typedef enum {
|
||||
AMIIBO_DEV_STATE_INITIALIZED = 0,
|
||||
AMIIBO_DEV_STATE_SEARCHING = 1,
|
||||
AMIIBO_DEV_STATE_TAG_FOUND = 2,
|
||||
AMIIBO_DEV_STATE_TAG_REMOVED = 3,
|
||||
AMIIBO_DEV_STATE_TAG_MOUNTED = 4,
|
||||
AMIIBO_DEV_STATE_UNAVAILABLE = 5
|
||||
} AmiiboDeviceState;
|
||||
|
||||
// Amiibo identification info
|
||||
typedef struct {
|
||||
uint8_t uuid[10];
|
||||
uint8_t uuid_len;
|
||||
uint8_t character_id[3];
|
||||
uint8_t series_id;
|
||||
uint16_t numbering_id;
|
||||
uint8_t nfp_type;
|
||||
uint8_t version;
|
||||
char path[512];
|
||||
char filename[128];
|
||||
} AmiiboInfo;
|
||||
|
||||
// Subsystem lifecycle
|
||||
void amiibo_init(void);
|
||||
|
||||
// Hardware / device emulation status
|
||||
void amiibo_set_device_present(bool present);
|
||||
bool amiibo_is_device_present(void);
|
||||
|
||||
// Tag detection & lifecycle
|
||||
void amiibo_start_detection(void);
|
||||
void amiibo_stop_detection(void);
|
||||
bool amiibo_is_detecting(void);
|
||||
|
||||
// Tag mounting
|
||||
bool amiibo_mount(void);
|
||||
void amiibo_unmount(void);
|
||||
bool amiibo_is_mounted(void);
|
||||
|
||||
// State query
|
||||
AmiiboDeviceState amiibo_get_device_state(void);
|
||||
// The state the menu shows: searching also within a second after a stop, since the game restarts detection many times
|
||||
// a second while it waits for a tag. The game reads amiibo_get_device_state.
|
||||
AmiiboDeviceState amiibo_get_reader_state(void);
|
||||
|
||||
// File loading & triggering actions
|
||||
bool amiibo_load_file(const char *path);
|
||||
bool amiibo_scan_and_tap(const char *path);
|
||||
void amiibo_tap_tag(void);
|
||||
void amiibo_remove_tag(void);
|
||||
|
||||
// Timer tick called during menu / frame updates
|
||||
void amiibo_tick(void);
|
||||
|
||||
// Options
|
||||
void amiibo_set_auto_remove(bool enable);
|
||||
bool amiibo_get_auto_remove(void);
|
||||
void amiibo_set_auto_remove_delay_s(float seconds);
|
||||
float amiibo_get_auto_remove_delay_s(void);
|
||||
|
||||
// Tag inspection
|
||||
bool amiibo_has_tag(void);
|
||||
const AmiiboInfo *amiibo_get_current_info(void);
|
||||
const uint8_t *amiibo_get_raw_data(void);
|
||||
|
||||
// Horizon OS buffers extraction (called by NFP IPC/override services)
|
||||
void amiibo_get_tag_info(void *out_tag_info);
|
||||
void amiibo_get_model_info(void *out_model_info);
|
||||
void amiibo_get_common_info(void *out_common_info);
|
||||
void amiibo_get_register_info(void *out_register_info);
|
||||
int amiibo_get_application_area(void *out_buf, uint32_t max_size);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -10,8 +10,8 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <windows.h>
|
||||
|
||||
#include "platform/platform.h"
|
||||
#include "host.h"
|
||||
#include "tex.h"
|
||||
#include "vk.h"
|
||||
@@ -112,11 +112,7 @@ static void to_general(VkCommandBuffer cb, VkImage img) {
|
||||
vkCmdPipelineBarrier2(cb, &di);
|
||||
}
|
||||
|
||||
static double now_ms(void) {
|
||||
LARGE_INTEGER t, f;
|
||||
QueryPerformanceCounter(&t), QueryPerformanceFrequency(&f);
|
||||
return (double)t.QuadPart * 1e3 / (double)f.QuadPart;
|
||||
}
|
||||
static double now_ms(void) { return (double)plat_now_ns() / 1e6; }
|
||||
|
||||
// Decodes regions (w0 x h0 at level 0, w1 x h1 at level 1) of blk on the GPU; out_rb: the decoder's texels, out_img:
|
||||
// the image's two levels read back. 0 on a Vulkan failure.
|
||||
@@ -359,7 +355,7 @@ static void timing(VkCtx *c, uint32_t bw, uint32_t bh) {
|
||||
}
|
||||
|
||||
int probe_astc(void) {
|
||||
_putenv_s("TOTK_ASTC_BC", "1"); // also builds the BC3 encoder; the RGBA8 cases pass bc 0 and do not use it
|
||||
plat_setenv("TOTK_ASTC_BC", "1"); // also builds the BC3 encoder; the RGBA8 cases pass bc 0 and do not use it
|
||||
if (!vk_init()) { printf("probe-astc: FAIL vk_init\n"); return 1; }
|
||||
VkCtx *c = vk_ctx();
|
||||
printf("probe-astc: GPU %s, textureCompressionASTC_LDR %d, mode %d\n", c->props.deviceName, c->has_astc_ldr,
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
// Sound categories (music, effects, voices) for the volume_music / volume_sfx / volume_voice settings.
|
||||
//
|
||||
// The audio renderer only sees sample memory, so the category is learned where the game loads its sounds:
|
||||
// - RomFS opens and reads of Sound/Resource/ files (romfs.c romfs_open / romfs_read): the file name gives the
|
||||
// category (BGM_* music, NV_* and *_Vo_* / *Voice* voices, the rest effects);
|
||||
// - zstd decodes of BARS banks (ov_zstd.c decode): each bank entry's AMTA name refines the bank's category;
|
||||
// - Opus decodes (ov_media.c ov_decode): the decoded PCM inherits the category of the packet it came from.
|
||||
// Two tables answer the mixer (audio_mixer.c voice_category):
|
||||
// - DSP-ADPCM coefficient tables, by a hash of their 32 bytes, read from each BWAV channel header. The game copies
|
||||
// these coefficients next to the voice, so a voice's own table names its sound wherever its samples live;
|
||||
// - guest address ranges of loaded or decoded audio, newest first, for PCM voices (Opus output).
|
||||
// Everything here runs only while one of the three settings is below 100 (audio_cat_active): at the defaults no table
|
||||
// is written or read. A setting moved during play classifies what loads from then on; sounds loaded before (an area's
|
||||
// effect banks, a stream opened earlier) are found when their next stream read lands, otherwise they count as effects.
|
||||
#include "audio_cat.h"
|
||||
#include "cfg.h"
|
||||
#include "host.h"
|
||||
#include "platform/platform.h"
|
||||
|
||||
#include <stdatomic.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
|
||||
#define RANGE_CAP 4096 // address ranges, a ring: the oldest go first. Lookups scan it, so it stays small
|
||||
#define COEF_CAP 65536 // coefficient tables, open addressing; a full probe run drops the new table (it counts as SFX)
|
||||
#define COEF_PROBES 64
|
||||
|
||||
typedef struct {
|
||||
uint64_t start, end;
|
||||
uint8_t cat;
|
||||
} Range;
|
||||
|
||||
static Range ranges[RANGE_CAP];
|
||||
static uint32_t range_head; // ranges written so far; under range_lock
|
||||
static PlatMutex range_lock = PLAT_MUTEX_INIT;
|
||||
|
||||
typedef struct {
|
||||
_Atomic uint64_t hash; // 0 = free; a slot is claimed once and never freed
|
||||
_Atomic uint8_t cat;
|
||||
} Coef;
|
||||
|
||||
static Coef coefs[COEF_CAP];
|
||||
|
||||
typedef struct {
|
||||
uint64_t guest;
|
||||
uint8_t cat;
|
||||
} Decoder;
|
||||
|
||||
static Decoder decoders[64]; // the category each Opus decoder produced last; under decoder_lock
|
||||
static unsigned decoder_next;
|
||||
static PlatMutex decoder_lock = PLAT_MUTEX_INIT;
|
||||
|
||||
static _Atomic uint64_t coef_count[4], range_count, bars_count;
|
||||
|
||||
int audio_cat_active(void) {
|
||||
static _Atomic unsigned seen = ~0u;
|
||||
static _Atomic int on;
|
||||
unsigned ver = cfg_version();
|
||||
if (atomic_load_explicit(&seen, memory_order_acquire) != ver) {
|
||||
int a = cfg_double("TOTK_VOLUME_MUSIC") < 100 || cfg_double("TOTK_VOLUME_SFX") < 100 ||
|
||||
cfg_double("TOTK_VOLUME_VOICE") < 100;
|
||||
atomic_store_explicit(&on, a, memory_order_relaxed);
|
||||
atomic_store_explicit(&seen, ver, memory_order_release);
|
||||
}
|
||||
return atomic_load_explicit(&on, memory_order_relaxed);
|
||||
}
|
||||
|
||||
static int ci_str_has(const char *haystack, const char *needle) {
|
||||
size_t nlen = strlen(needle);
|
||||
for (; *haystack; haystack++)
|
||||
if (strncasecmp(haystack, needle, nlen) == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int all_zero32(const uint8_t *p) {
|
||||
for (int i = 0; i < 32; i++)
|
||||
if (p[i]) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static uint64_t fnv1a32(const uint8_t *p) {
|
||||
uint64_t h = 14695981039346656037ULL;
|
||||
for (int i = 0; i < 32; i++) {
|
||||
h ^= p[i];
|
||||
h *= 1099511628211ULL;
|
||||
}
|
||||
return h ? h : 1;
|
||||
}
|
||||
|
||||
// A table seen under several categories keeps music or voice over effects: one sample shared by a voice line and an
|
||||
// effect bank follows the voice setting.
|
||||
static void register_coef32(const uint8_t *coef, int cat) {
|
||||
if (cat <= AUDIO_CAT_UNKNOWN || cat > AUDIO_CAT_VOICE || all_zero32(coef)) return;
|
||||
uint64_t h = fnv1a32(coef);
|
||||
for (uint32_t step = 0; step < COEF_PROBES; step++) {
|
||||
Coef *e = &coefs[((uint32_t)h + step) & (COEF_CAP - 1)];
|
||||
uint64_t cur = atomic_load_explicit(&e->hash, memory_order_acquire);
|
||||
if (cur == 0 && atomic_compare_exchange_strong_explicit(&e->hash, &cur, h, memory_order_acq_rel,
|
||||
memory_order_acquire)) {
|
||||
atomic_store_explicit(&e->cat, (uint8_t)cat, memory_order_release);
|
||||
atomic_fetch_add_explicit(&coef_count[cat], 1, memory_order_relaxed);
|
||||
return;
|
||||
}
|
||||
if (cur == h) {
|
||||
if (cat != AUDIO_CAT_SFX) atomic_store_explicit(&e->cat, (uint8_t)cat, memory_order_release);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int audio_cat_lookup_coef(uint64_t extra_addr, uint64_t extra_size) {
|
||||
if (!extra_addr || extra_size < 32 || extra_addr >= RT_ADDRESS_LIMIT || !mem_guest_readable(extra_addr, 32))
|
||||
return AUDIO_CAT_UNKNOWN;
|
||||
const uint8_t *p = (const uint8_t *)(uintptr_t)extra_addr;
|
||||
if (all_zero32(p)) return AUDIO_CAT_UNKNOWN;
|
||||
uint64_t h = fnv1a32(p);
|
||||
for (uint32_t step = 0; step < COEF_PROBES; step++) {
|
||||
Coef *e = &coefs[((uint32_t)h + step) & (COEF_CAP - 1)];
|
||||
uint64_t cur = atomic_load_explicit(&e->hash, memory_order_acquire);
|
||||
if (cur == h) return atomic_load_explicit(&e->cat, memory_order_acquire); // 0 while the writer is midway
|
||||
if (cur == 0) break;
|
||||
}
|
||||
return AUDIO_CAT_UNKNOWN;
|
||||
}
|
||||
|
||||
// BWAV: "BWAV", channel count at 0x0E, then 0x4C-byte channel infos from 0x10: codec u16 (1 = DSP-ADPCM) and the 16
|
||||
// ADPCM coefficients at +0x10.
|
||||
void audio_cat_scan_bwav(const void *data, uint64_t size, int cat) {
|
||||
if (!data || size < 0x40 || cat <= AUDIO_CAT_UNKNOWN) return;
|
||||
const uint8_t *b = data;
|
||||
uint32_t magic;
|
||||
uint16_t nch;
|
||||
memcpy(&magic, b, 4);
|
||||
memcpy(&nch, b + 0x0E, 2);
|
||||
if (magic != 0x56415742u || nch == 0 || nch > 16) return;
|
||||
for (uint16_t ch = 0; ch < nch; ch++) {
|
||||
uint64_t at = 0x10ull + ch * 0x4Cull;
|
||||
if (at + 0x30 > size) break;
|
||||
uint16_t codec;
|
||||
memcpy(&codec, b + at, 2);
|
||||
if (codec == 1) register_coef32(b + at + 0x10, cat);
|
||||
}
|
||||
}
|
||||
|
||||
// Every sound bank and stream of the game is under Sound/Resource/ (Sound/Resource/*.bars.zs, Sound/Resource/Stream/
|
||||
// *.bwav); everything else is not audio. Creature and player vocal banks (Bokoblin_Voice0, Player_Voice, *_Vo_*)
|
||||
// count as voices, as do the NV_* character voice lines.
|
||||
int audio_cat_from_path(const char *path) {
|
||||
if (!path || strncmp(path, "Sound/Resource/", 15)) return AUDIO_CAT_UNKNOWN;
|
||||
const char *name = strrchr(path, '/') + 1;
|
||||
if (!strncasecmp(name, "nv_", 3) || !strncasecmp(name, "vo_", 3)) return AUDIO_CAT_VOICE;
|
||||
if (ci_str_has(name, "bgm_")) return AUDIO_CAT_MUSIC;
|
||||
if (ci_str_has(name, "_voice") || ci_str_has(name, "voice_") || ci_str_has(name, "_vo_") ||
|
||||
ci_str_has(name, "shoutvoice") || ci_str_has(name, "shoutmsg"))
|
||||
return AUDIO_CAT_VOICE;
|
||||
return AUDIO_CAT_SFX;
|
||||
}
|
||||
|
||||
void audio_cat_tag_range(uint64_t addr, uint64_t size, int cat) {
|
||||
if (!addr || !size || cat <= AUDIO_CAT_UNKNOWN || cat > AUDIO_CAT_VOICE) return;
|
||||
plat_mutex_lock(&range_lock);
|
||||
// A stream refills the same buffers: the same range read again only changes its category.
|
||||
uint32_t depth = range_head < 64 ? range_head : 64;
|
||||
for (uint32_t k = 0; k < depth; k++) {
|
||||
Range *r = &ranges[(range_head - 1 - k) & (RANGE_CAP - 1)];
|
||||
if (r->start == addr && r->end == addr + size) {
|
||||
r->cat = (uint8_t)cat;
|
||||
plat_mutex_unlock(&range_lock);
|
||||
return;
|
||||
}
|
||||
}
|
||||
Range *r = &ranges[range_head & (RANGE_CAP - 1)];
|
||||
r->start = addr;
|
||||
r->end = addr + size;
|
||||
r->cat = (uint8_t)cat;
|
||||
range_head++;
|
||||
plat_mutex_unlock(&range_lock);
|
||||
atomic_fetch_add_explicit(&range_count, 1, memory_order_relaxed);
|
||||
}
|
||||
|
||||
// The newest range holding addr; newer loads into reused memory win over older ones.
|
||||
int audio_cat_lookup(uint64_t addr) {
|
||||
if (!addr) return AUDIO_CAT_UNKNOWN;
|
||||
int cat = AUDIO_CAT_UNKNOWN;
|
||||
plat_mutex_lock_shared(&range_lock);
|
||||
uint32_t n = range_head < RANGE_CAP ? range_head : RANGE_CAP;
|
||||
for (uint32_t k = 0; k < n; k++) {
|
||||
const Range *r = &ranges[(range_head - 1 - k) & (RANGE_CAP - 1)];
|
||||
if (addr >= r->start && addr < r->end) {
|
||||
cat = r->cat;
|
||||
break;
|
||||
}
|
||||
}
|
||||
plat_mutex_unlock_shared(&range_lock);
|
||||
return cat;
|
||||
}
|
||||
|
||||
// BARS: "BARS", entry count at 0x0C, then count CRC32 name hashes and count (AMTA offset, BWAV offset) pairs. The AMTA
|
||||
// block holds the entry's name; music and voice names inside an effects bank (a boss bank with its BGM) get their own
|
||||
// category. ADPCM entries register their coefficients; other entries tag their bytes.
|
||||
void audio_cat_scan_bars(uint64_t dst, uint64_t size, int fallback_cat) {
|
||||
if (!dst || size < 16) return;
|
||||
atomic_fetch_add_explicit(&bars_count, 1, memory_order_relaxed);
|
||||
if (fallback_cat != AUDIO_CAT_UNKNOWN) audio_cat_tag_range(dst, size, fallback_cat);
|
||||
const uint8_t *base = (const uint8_t *)(uintptr_t)dst;
|
||||
uint32_t count;
|
||||
memcpy(&count, base + 0x0C, 4);
|
||||
if (count > 16384 || 0x10ull + (uint64_t)count * 12ull > size) return;
|
||||
const uint8_t *pairs = base + 0x10 + (uint64_t)count * 4;
|
||||
for (uint32_t k = 0; k < count; k++) {
|
||||
uint32_t amta_off, bwav_off;
|
||||
memcpy(&amta_off, pairs + k * 8ull, 4);
|
||||
memcpy(&bwav_off, pairs + k * 8ull + 4, 4);
|
||||
if (bwav_off >= size) continue;
|
||||
int cat = fallback_cat != AUDIO_CAT_UNKNOWN ? fallback_cat : AUDIO_CAT_SFX;
|
||||
if (amta_off < size) {
|
||||
uint64_t limit = size - amta_off < 512 ? size - amta_off : 512;
|
||||
const char *a = (const char *)(base + amta_off);
|
||||
for (uint64_t s = 0; s + 4 <= limit; s++) {
|
||||
if (!memcmp(a + s, "BGM_", 4)) { cat = AUDIO_CAT_MUSIC; break; }
|
||||
if (!memcmp(a + s, "Vo_", 3) || !memcmp(a + s, "NV_", 3)) { cat = AUDIO_CAT_VOICE; break; }
|
||||
if (s + 5 <= limit && !memcmp(a + s, "Voice", 5)) { cat = AUDIO_CAT_VOICE; break; }
|
||||
}
|
||||
}
|
||||
const uint8_t *w = base + bwav_off;
|
||||
uint32_t magic = 0;
|
||||
uint16_t codec = 0;
|
||||
if (bwav_off + 0x40 <= size) {
|
||||
memcpy(&magic, w, 4);
|
||||
memcpy(&codec, w + 0x10, 2);
|
||||
}
|
||||
if (magic == 0x56415742u) audio_cat_scan_bwav(w, size - bwav_off, cat);
|
||||
if (cat == fallback_cat || (magic == 0x56415742u && codec == 1)) continue;
|
||||
// The entry ends where the next BWAV starts: one pass over the offsets, only for the few entries tagged here.
|
||||
uint64_t next = size;
|
||||
for (uint32_t j = 0; j < count; j++) {
|
||||
uint32_t o;
|
||||
memcpy(&o, pairs + j * 8ull + 4, 4);
|
||||
if (o > bwav_off && o < next) next = o;
|
||||
}
|
||||
audio_cat_tag_range(dst + bwav_off, next - bwav_off, cat);
|
||||
}
|
||||
}
|
||||
|
||||
// The PCM out of one Opus packet takes the packet's category, else the decoder's last one, else effects. Consecutive
|
||||
// packets of one decoder fill one buffer, so the output grows the newest matching range instead of adding one each.
|
||||
void audio_cat_on_opus_decode(uint64_t decoder_guest, uint64_t in_addr, uint64_t out_addr, uint64_t out_size) {
|
||||
if (!out_addr || !out_size) return;
|
||||
int cat = audio_cat_lookup(in_addr);
|
||||
plat_mutex_lock(&decoder_lock);
|
||||
int slot = -1;
|
||||
for (int i = 0; i < 64 && decoder_guest; i++)
|
||||
if (decoders[i].guest == decoder_guest) slot = i;
|
||||
if (cat == AUDIO_CAT_UNKNOWN && slot >= 0) cat = decoders[slot].cat;
|
||||
if (cat == AUDIO_CAT_UNKNOWN) cat = AUDIO_CAT_SFX;
|
||||
if (decoder_guest) {
|
||||
if (slot < 0) {
|
||||
slot = (int)(decoder_next++ & 63);
|
||||
decoders[slot].guest = decoder_guest;
|
||||
}
|
||||
decoders[slot].cat = (uint8_t)cat;
|
||||
}
|
||||
plat_mutex_unlock(&decoder_lock);
|
||||
|
||||
plat_mutex_lock(&range_lock);
|
||||
uint32_t depth = range_head < 32 ? range_head : 32;
|
||||
for (uint32_t k = 0; k < depth; k++) {
|
||||
Range *r = &ranges[(range_head - 1 - k) & (RANGE_CAP - 1)];
|
||||
if (r->cat != (uint8_t)cat) continue;
|
||||
uint64_t lo = r->start > 65536 ? r->start - 65536 : 0, hi = r->end + 65536;
|
||||
if (out_addr >= lo && out_addr + out_size <= hi) {
|
||||
if (out_addr < r->start) r->start = out_addr;
|
||||
if (out_addr + out_size > r->end) r->end = out_addr + out_size;
|
||||
plat_mutex_unlock(&range_lock);
|
||||
return;
|
||||
}
|
||||
}
|
||||
plat_mutex_unlock(&range_lock);
|
||||
audio_cat_tag_range(out_addr, out_size, cat);
|
||||
}
|
||||
|
||||
void audio_cat_log_tables(void) {
|
||||
rt_log("audio: categories known: coefficient tables music %llu, sfx %llu, voice %llu; address ranges %llu "
|
||||
"(ring %d); BARS banks scanned %llu",
|
||||
(unsigned long long)atomic_load(&coef_count[AUDIO_CAT_MUSIC]),
|
||||
(unsigned long long)atomic_load(&coef_count[AUDIO_CAT_SFX]),
|
||||
(unsigned long long)atomic_load(&coef_count[AUDIO_CAT_VOICE]), (unsigned long long)atomic_load(&range_count),
|
||||
RANGE_CAP, (unsigned long long)atomic_load(&bars_count));
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Sound categories for the music / effects / voice volume settings (audio_cat.c).
|
||||
#ifndef TOTK_AUDIO_CAT_H
|
||||
#define TOTK_AUDIO_CAT_H
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
enum {
|
||||
AUDIO_CAT_UNKNOWN = 0,
|
||||
AUDIO_CAT_MUSIC = 1,
|
||||
AUDIO_CAT_SFX = 2,
|
||||
AUDIO_CAT_VOICE = 3,
|
||||
};
|
||||
|
||||
int audio_cat_active(void); // one of volume_music / volume_sfx / volume_voice is below 100
|
||||
int audio_cat_from_path(const char *path); // a RomFS-relative path; UNKNOWN outside Sound/Resource/
|
||||
void audio_cat_tag_range(uint64_t addr, uint64_t size, int cat);
|
||||
void audio_cat_scan_bars(uint64_t dst, uint64_t size, int fallback_cat);
|
||||
void audio_cat_scan_bwav(const void *data, uint64_t size, int cat);
|
||||
void audio_cat_on_opus_decode(uint64_t decoder_guest, uint64_t in_addr, uint64_t out_addr, uint64_t out_size);
|
||||
int audio_cat_lookup(uint64_t addr);
|
||||
int audio_cat_lookup_coef(uint64_t extra_addr, uint64_t extra_size);
|
||||
void audio_cat_log_tables(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -22,8 +22,11 @@ struct AudioEffectDsp {
|
||||
};
|
||||
static int channel_ok(unsigned n) { return n==1 || n==2 || n==4 || n==6; }
|
||||
static unsigned sample_count(unsigned rate, float ms) { return (unsigned)nearbyintf(rate*ms); }
|
||||
/* The reference DelayLine wraps at CurrentSampleCount-1, including when its
|
||||
backing allocation is larger. Preserve this timing for sample comparisons. */
|
||||
/* The ring has `count` slots. The reference DelayLine wraps its cursor at
|
||||
CurrentSampleCount-1 while its taps index modulo CurrentSampleCount, so once
|
||||
per turn every tap reads a slot that is never written (a one-sample dropout
|
||||
per tap, audible as grain). The cursor and the taps share one ring length here;
|
||||
each delay is one sample longer than the reference. */
|
||||
static void line_set(DelayLine *d, unsigned n) { d->count=n<d->max?n:d->max; d->at=0; }
|
||||
static void line_init(DelayLine *d, unsigned rate, float ms) {
|
||||
d->max=sample_count(rate,ms); d->data=calloc((size_t)d->max+1,sizeof(float));
|
||||
@@ -32,12 +35,12 @@ static void line_init(DelayLine *d, unsigned rate, float ms) {
|
||||
static float line_read(const DelayLine *d) { return d->data[d->at]; }
|
||||
static float line_update(DelayLine *d,float v) {
|
||||
float old=line_read(d);d->data[d->at++]=v;
|
||||
if(d->at >= (d->count?d->count-1:0))d->at=0;
|
||||
if(d->at >= d->count)d->at=0;
|
||||
return old;
|
||||
}
|
||||
static float line_tap(const DelayLine *d,unsigned sample,int offset) {
|
||||
int at=(int)d->at-(int)sample-offset;
|
||||
if(at<0)at+=(int)d->count;
|
||||
if(d->count){at%=(int)d->count;if(at<0)at+=(int)d->count;}
|
||||
if(at<0 || (unsigned)at>d->max)rt_fatal("audio effect delay tap bounds");
|
||||
return d->data[at];
|
||||
}
|
||||
|
||||
+348
-61
@@ -5,10 +5,11 @@
|
||||
//
|
||||
// Per 5 ms frame the render thread (audren.c, renderer lock held) decodes every started voice (PCM8/16/24/32, float,
|
||||
// DSP-ADPCM) along the sample path the voice clock consumes, resamples it linearly, runs the voice biquads, scales it
|
||||
// into its destination mix, folds the submixes, runs the mix effects and writes the device sink's stereo mix into a
|
||||
// single-producer single-consumer ring. The SDL audio thread drains that ring without taking any lock: an empty ring
|
||||
// into its destination mix, folds the submixes, runs the mix effects and writes the device sink's mix (stereo, or 5.1
|
||||
// with TOTK_AUDIO_CHANNELS, output_channels) into a single-producer single-consumer ring. The SDL audio thread drains
|
||||
// that ring without taking any lock: an empty ring
|
||||
// plays silence and never blocks the render thread or the guest. TOTK_AUDIO=none (or TOTK_AUDIO_OFF) mixes without a
|
||||
// device; TOTK_AUDIO_PREFILL_MS (0..500, default 20) is the queued audio the output waits for after start or underrun.
|
||||
// device; TOTK_AUDIO_PREFILL_MS (0..500, default 20, 60 on Linux) is the queued audio the output waits for after start or underrun.
|
||||
// The device's clock paces the render thread, as the audio hardware paces the Switch's DSP (audio_mixer_pace_ns): a
|
||||
// frame is rendered when the ring holds less than the output target, max(prefill, two device periods), so the queue and
|
||||
// the delay from the game to the speakers stay there and the host and device clocks cannot drift apart. LASRecomp and
|
||||
@@ -27,12 +28,14 @@
|
||||
#include "cfg.h"
|
||||
#include "audio_effects.h"
|
||||
#include "audio_reverb.h"
|
||||
#include "audio_cat.h"
|
||||
#include "audren.h"
|
||||
#include "host.h"
|
||||
#include "ipc.h"
|
||||
|
||||
#define MAX_FRAME 1024
|
||||
#define RING_FRAMES 16384 // stereo frames, about 340 ms at 48 kHz
|
||||
#define RING_FRAMES 16384 // output frames, about 340 ms at 48 kHz
|
||||
#define OUT_MAX 6 // output channels at most: 5.1
|
||||
#define QUEUE_SLACK_MS 40 // queued audio above the target plus the device's request that ring_pull skips
|
||||
#define STALL_MS 50 // the device took nothing this long (at least 4 periods): the timer paces
|
||||
#define SPLITTER_UNUSED 0xffffffffu
|
||||
@@ -50,8 +53,12 @@ typedef struct Mixer {
|
||||
float *buf; int nbuf, frame;
|
||||
int *offset; // first mix buffer of each mix id
|
||||
SplitInfo *split; int nsplit; SplitDest *dest; int ndest;
|
||||
SDL_AudioStream *stream; int device_ok, rate;
|
||||
float ring[RING_FRAMES * 2];
|
||||
SDL_AudioStream *stream; int device_ok, rate; // stream: output_open's, then the output worker's alone
|
||||
SDL_AudioDeviceID open_id, failed_id; // the device the stream plays on; the last one that failed to open
|
||||
PlatThread *worker; PlatEvent wake; // output_worker, NULL until a device is chosen; wake: a cfg change
|
||||
_Atomic int worker_quit; unsigned watch_ver; // watch_ver: the render thread's last cfg_version (output_watch)
|
||||
int channels; // output channels, 2 or 6 (output_channels)
|
||||
float ring[RING_FRAMES * OUT_MAX];
|
||||
_Atomic uint64_t wr, rd, underruns, overruns, missing_frames, callback_frames, callback_nonzero, skipped_frames;
|
||||
_Atomic int playing; int ready; // ready: the callback's own state
|
||||
int target, period; // output target and device period, frames (output_open)
|
||||
@@ -61,7 +68,7 @@ typedef struct Mixer {
|
||||
EffectState *effect; int *effect_order; unsigned effect_reported;
|
||||
uint64_t *sink_address; uint32_t *sink_size, *sink_offset, *sink_old, *sink_written;
|
||||
unsigned reported; // one-time reports
|
||||
float voice_scratch[6][MAX_FRAME], filter_scratch[MAX_FRAME], output_scratch[MAX_FRAME * 2];
|
||||
float voice_scratch[6][MAX_FRAME], filter_scratch[MAX_FRAME], output_scratch[MAX_FRAME * OUT_MAX];
|
||||
double level_sum, level_peak; uint64_t level_count, level_frames; int first_sound_logged;
|
||||
int prefill; // render blocks
|
||||
} Mixer;
|
||||
@@ -80,6 +87,64 @@ static float host_volume(void) {
|
||||
v = (float)((pct < 0 ? 0 : pct > 100 ? 100 : pct) / 100);
|
||||
return v;
|
||||
}
|
||||
|
||||
// TOTK_VOLUME_MUSIC / _SFX / _VOICE: per-category volumes in percent on top of TOTK_VOLUME, live like it. Render thread
|
||||
// only.
|
||||
static float category_volume(int cat) {
|
||||
static const char *const names[4] = {NULL, "TOTK_VOLUME_MUSIC", "TOTK_VOLUME_SFX", "TOTK_VOLUME_VOICE"};
|
||||
static float v[4] = {1, 1, 1, 1};
|
||||
static unsigned seen = ~0u;
|
||||
unsigned ver = cfg_version();
|
||||
if (ver != seen) {
|
||||
seen = ver;
|
||||
for (int k = 1; k < 4; k++) {
|
||||
double pct = cfg_double(names[k]);
|
||||
v[k] = (float)((pct < 0 ? 0 : pct > 100 ? 100 : pct) / 100);
|
||||
}
|
||||
}
|
||||
return v[cat >= AUDIO_CAT_MUSIC && cat <= AUDIO_CAT_VOICE ? cat : AUDIO_CAT_SFX];
|
||||
}
|
||||
|
||||
// What the voice plays (audio_cat.c): an ADPCM voice by its coefficient table, any voice by the newest loaded or decoded
|
||||
// range holding its current wave buffer, else effects. Kept per voice until it moves to another buffer or table, so a
|
||||
// table lookup runs once per wave buffer, not once per frame. The counts feed category_report.
|
||||
static uint64_t cat_counts[4], cat_by_coef, cat_by_range, cat_ns;
|
||||
static int voice_category(ServerVoice *v) {
|
||||
uint64_t addr = v->buffers[v->index].address, extra = v->in.extra_address;
|
||||
if (v->cat && v->cat_address == addr && v->cat_extra == extra) return v->cat;
|
||||
uint64_t t0 = kern_now_ns();
|
||||
int cat = AUDIO_CAT_UNKNOWN;
|
||||
if (v->in.sample_format == FMT_ADPCM) cat = audio_cat_lookup_coef(extra, v->in.extra_size);
|
||||
if (cat != AUDIO_CAT_UNKNOWN) cat_by_coef++;
|
||||
else if ((cat = audio_cat_lookup(addr)) != AUDIO_CAT_UNKNOWN) cat_by_range++;
|
||||
else cat = AUDIO_CAT_SFX;
|
||||
cat_counts[cat]++;
|
||||
v->cat = (uint8_t)cat;
|
||||
v->cat_address = addr;
|
||||
v->cat_extra = extra;
|
||||
cat_ns += kern_now_ns() - t0;
|
||||
return cat;
|
||||
}
|
||||
|
||||
// While a category volume is set, once a minute: how the wave buffers played were classified and what it cost.
|
||||
static void category_report(void) {
|
||||
static uint64_t next;
|
||||
uint64_t now = kern_now_ns();
|
||||
if (!next) next = now + 60000000000ull;
|
||||
if (now < next) return;
|
||||
next = now + 60000000000ull;
|
||||
uint64_t n = cat_counts[AUDIO_CAT_MUSIC] + cat_counts[AUDIO_CAT_SFX] + cat_counts[AUDIO_CAT_VOICE];
|
||||
rt_log("audio: categories over the last minute: %llu wave buffers, music %llu, sfx %llu, voice %llu; by coefficients "
|
||||
"%llu, by address %llu, unmatched (played as sfx) %llu; %.1f us classifying",
|
||||
(unsigned long long)n, (unsigned long long)cat_counts[AUDIO_CAT_MUSIC],
|
||||
(unsigned long long)cat_counts[AUDIO_CAT_SFX], (unsigned long long)cat_counts[AUDIO_CAT_VOICE],
|
||||
(unsigned long long)cat_by_coef, (unsigned long long)cat_by_range,
|
||||
(unsigned long long)(n - cat_by_coef - cat_by_range), cat_ns / 1000.0);
|
||||
audio_cat_log_tables();
|
||||
memset(cat_counts, 0, sizeof cat_counts);
|
||||
cat_by_coef = cat_by_range = cat_ns = 0;
|
||||
}
|
||||
|
||||
static unsigned audio_revision(const AudioRenderer *r) { unsigned byte = r->revision >> 24; return byte >= '0' ? byte - '0' : 0; }
|
||||
static void report_once(Mixer *m, unsigned bit, const char *msg, int value) {
|
||||
if (m->reported & (1u << bit)) return;
|
||||
@@ -90,16 +155,82 @@ static void report_once(Mixer *m, unsigned bit, const char *msg, int value) {
|
||||
// ---- output: SDL3 audio stream fed from the ring
|
||||
// How much audio the output waits for before it starts, and again after an underrun: TOTK_AUDIO_PREFILL_MS rounded up
|
||||
// to whole 5 ms render blocks. Returns -1 for a value outside 0..500 ms.
|
||||
// The Linux default is higher: at 20 ms PipeWire's queue (max(prefill, two 1024-sample periods)) underran
|
||||
// thousands of times within minutes in busy scenes, and 60 ms removed the underruns.
|
||||
#ifdef __linux__
|
||||
#define PREFILL_DEFAULT_MS 60
|
||||
#else
|
||||
#define PREFILL_DEFAULT_MS 20
|
||||
#endif
|
||||
static int prefill_blocks_for(const char *e) {
|
||||
if (!e || !*e) return 4;
|
||||
if (!e || !*e) return PREFILL_DEFAULT_MS / 5;
|
||||
char *end;
|
||||
double ms = strtod(e, &end);
|
||||
if (end == e || *end || !(ms >= 0) || ms > 500) return -1;
|
||||
return (int)ceil(ms / 5.0);
|
||||
}
|
||||
|
||||
// Fills `frames` stereo frames from the ring (zeros for what is missing). Lock-free; runs on SDL's audio thread.
|
||||
// TOTK_AUDIO_DEVICE: the playback device by the name SDL reports (SDL_GetAudioDeviceName), since SDL's device ids
|
||||
// change between runs. Unset, empty or "default": the system default, which SDL follows when Windows changes it.
|
||||
static int device_is_default(const char *want) { return !want || !*want || !strcmp(want, "default"); }
|
||||
|
||||
// The device for `want`: the first playback device of that name, *found 1; else the system default, *found 0 for a name
|
||||
// SDL does not list (unplugged). The default asks SDL nothing.
|
||||
static SDL_AudioDeviceID device_pick(const char *want, int *found) {
|
||||
*found = 1;
|
||||
if (device_is_default(want)) return SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK;
|
||||
int n = 0;
|
||||
SDL_AudioDeviceID *ids = SDL_GetAudioPlaybackDevices(&n), id = 0;
|
||||
for (int i = 0; ids && i < n && !id; i++) {
|
||||
const char *name = SDL_GetAudioDeviceName(ids[i]);
|
||||
if (name && !strcmp(name, want)) id = ids[i];
|
||||
}
|
||||
SDL_free(ids);
|
||||
*found = id != 0;
|
||||
return id ? id : SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK;
|
||||
}
|
||||
|
||||
int audio_output_devices(char (*names)[AUDIO_DEVICE_NAME_MAX], int max) {
|
||||
if (!SDL_WasInit(SDL_INIT_AUDIO)) return 0; // TOTK_AUDIO=none or no output: nothing to pick
|
||||
int n = 0, k = 0;
|
||||
SDL_AudioDeviceID *ids = SDL_GetAudioPlaybackDevices(&n);
|
||||
for (int i = 0; ids && i < n && k < max; i++) {
|
||||
const char *name = SDL_GetAudioDeviceName(ids[i]);
|
||||
if (name && *name && strlen(name) < AUDIO_DEVICE_NAME_MAX) snprintf(names[k++], AUDIO_DEVICE_NAME_MAX, "%s", name);
|
||||
}
|
||||
SDL_free(ids);
|
||||
return k;
|
||||
}
|
||||
|
||||
// TOTK_AUDIO_CHANNELS: the output channels of this run, decided once. stereo gives 2; 5.1 gives 6 (FL FR C LFE RL RR,
|
||||
// the device sink's order and SDL's); auto gives 6 when the chosen playback device (TOTK_AUDIO_DEVICE at start, the
|
||||
// system default without one) has at least six channels (a 5.1
|
||||
// or 7.1 speaker setup in Windows; SDL places 5.1 on 7.1) and 2 otherwise. IAudioDevice reports the same count to the
|
||||
// game (GetActiveChannelCount), which picks its sink layout from it. TOTK_AUDIO=none: 2, without touching SDL.
|
||||
static int output_channels(void) {
|
||||
static _Atomic int decided;
|
||||
int n = atomic_load(&decided);
|
||||
if (n) return n;
|
||||
const char *want = cfg_value("TOTK_AUDIO_CHANNELS"), *mode = cfg_get("TOTK_AUDIO");
|
||||
if ((mode && !strcmp(mode, "none")) || cfg_get("TOTK_AUDIO_OFF")) n = 2;
|
||||
else if (!strcmp(want, "5.1")) n = 6;
|
||||
else if (!strcmp(want, "stereo")) n = 2;
|
||||
else {
|
||||
SDL_AudioSpec dev = {0};
|
||||
int found, ok = SDL_InitSubSystem(SDL_INIT_AUDIO);
|
||||
SDL_AudioDeviceID id = ok ? device_pick(cfg_get("TOTK_AUDIO_DEVICE"), &found) : 0;
|
||||
n = ok && SDL_GetAudioDeviceFormat(id, &dev, NULL) && dev.channels >= 6 ? 6 : 2;
|
||||
const char *name = ok ? SDL_GetAudioDeviceName(id) : NULL;
|
||||
rt_log("audio: TOTK_AUDIO_CHANNELS=auto: device '%s' has %d channels, output %s", name ? name : "?",
|
||||
dev.channels, n == 6 ? "5.1" : "stereo");
|
||||
}
|
||||
int expected = 0;
|
||||
return atomic_compare_exchange_strong(&decided, &expected, n) ? n : expected;
|
||||
}
|
||||
|
||||
// Fills `frames` output frames from the ring (zeros for what is missing). Lock-free; runs on SDL's audio thread.
|
||||
static void ring_pull(Mixer *m, float *out, uint32_t frames) {
|
||||
const int oc = m->channels;
|
||||
atomic_fetch_add(&m->callback_frames, frames);
|
||||
unsigned epoch = atomic_load_explicit(&m->stop_epoch, memory_order_acquire);
|
||||
uint64_t rd = atomic_load(&m->rd), wr = atomic_load_explicit(&m->wr, memory_order_acquire), have = wr - rd;
|
||||
@@ -114,7 +245,7 @@ static void ring_pull(Mixer *m, float *out, uint32_t frames) {
|
||||
m->ready = 0;
|
||||
}
|
||||
if (!atomic_load_explicit(&m->playing, memory_order_acquire)) {
|
||||
memset(out, 0, (size_t)frames * 2 * sizeof(float));
|
||||
memset(out, 0, (size_t)frames * oc * sizeof(float));
|
||||
m->ready = 0;
|
||||
atomic_store_explicit(&m->rd, wr, memory_order_release);
|
||||
return;
|
||||
@@ -124,7 +255,7 @@ static void ring_pull(Mixer *m, float *out, uint32_t frames) {
|
||||
if (prefill > RING_FRAMES) prefill = RING_FRAMES;
|
||||
if (!m->ready) {
|
||||
if (have < prefill) {
|
||||
memset(out, 0, (size_t)frames * 2 * sizeof(float));
|
||||
memset(out, 0, (size_t)frames * oc * sizeof(float));
|
||||
return;
|
||||
}
|
||||
m->ready = 1;
|
||||
@@ -140,13 +271,16 @@ static void ring_pull(Mixer *m, float *out, uint32_t frames) {
|
||||
uint64_t nonzero = 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
uint64_t k = (rd + i) % RING_FRAMES;
|
||||
out[2 * i] = m->ring[2 * k];
|
||||
out[2 * i + 1] = m->ring[2 * k + 1];
|
||||
if (out[2 * i] != 0 || out[2 * i + 1] != 0) nonzero++;
|
||||
int sound = 0;
|
||||
for (int c = 0; c < oc; c++) {
|
||||
out[oc * i + c] = m->ring[oc * k + c];
|
||||
sound |= out[oc * i + c] != 0;
|
||||
}
|
||||
nonzero += sound;
|
||||
}
|
||||
atomic_fetch_add(&m->callback_nonzero, nonzero);
|
||||
if (n < frames) {
|
||||
memset(out + 2 * n, 0, (size_t)(frames - n) * 2 * sizeof(float));
|
||||
memset(out + (size_t)oc * n, 0, (size_t)(frames - n) * oc * sizeof(float));
|
||||
atomic_fetch_add(&m->underruns, 1);
|
||||
atomic_fetch_add(&m->missing_frames, frames - n);
|
||||
m->ready = 0;
|
||||
@@ -157,18 +291,41 @@ static void ring_pull(Mixer *m, float *out, uint32_t frames) {
|
||||
static void SDLCALL sdl_pull(void *user, SDL_AudioStream *stream, int additional, int total) {
|
||||
(void)total;
|
||||
Mixer *m = user;
|
||||
float tmp[2 * 1024];
|
||||
float tmp[OUT_MAX * 1024];
|
||||
const uint32_t frame_bytes = (uint32_t)m->channels * sizeof(float);
|
||||
atomic_store_explicit(&m->pulled_ns, kern_now_ns(), memory_order_release);
|
||||
while (additional > 0) {
|
||||
uint32_t frames = (uint32_t)additional / (2 * sizeof(float));
|
||||
uint32_t frames = (uint32_t)additional / frame_bytes;
|
||||
if (!frames) break;
|
||||
if (frames > 1024) frames = 1024;
|
||||
ring_pull(m, tmp, frames);
|
||||
if (!SDL_PutAudioStreamData(stream, tmp, (int)(frames * 2 * sizeof(float)))) break;
|
||||
additional -= (int)(frames * 2 * sizeof(float));
|
||||
if (!SDL_PutAudioStreamData(stream, tmp, (int)(frames * frame_bytes))) break;
|
||||
additional -= (int)(frames * frame_bytes);
|
||||
}
|
||||
}
|
||||
|
||||
// The pacing figures of the stream's device: its period, the output target and the stall time. Set before the stream
|
||||
// is resumed; the render thread reads target and stall_ns while a switch sets them (audio_mixer_pace_ns).
|
||||
static void output_timing(Mixer *m, SDL_AudioSpec *dev) {
|
||||
int period = 0;
|
||||
if (!SDL_GetAudioDeviceFormat(SDL_GetAudioStreamDevice(m->stream), dev, &period) || period <= 0) period = m->frame;
|
||||
m->period = period;
|
||||
int target = m->frame * m->prefill > 2 * period ? m->frame * m->prefill : 2 * period;
|
||||
__atomic_store_n(&m->target, target > RING_FRAMES / 2 ? RING_FRAMES / 2 : target, __ATOMIC_RELAXED);
|
||||
uint64_t period_ns = (uint64_t)period * 1000000000ull / (uint64_t)m->rate;
|
||||
__atomic_store_n(&m->stall_ns, 4 * period_ns > STALL_MS * 1000000ull ? 4 * period_ns : STALL_MS * 1000000ull,
|
||||
__ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
static void output_log(Mixer *m, const char *what, const SDL_AudioSpec *dev) {
|
||||
const char *name = SDL_GetAudioDeviceName(SDL_GetAudioStreamDevice(m->stream));
|
||||
rt_log("audio: SDL device '%s' %s, %d Hz %s float (device %d channels), prefill %d ms, device period %d frames; "
|
||||
"the device paces rendering at %.1f ms queued", name ? name : "?", what, m->rate,
|
||||
m->channels == 6 ? "5.1" : "stereo", dev->channels, m->prefill * 5, m->period, m->target * 1000.0 / m->rate);
|
||||
}
|
||||
|
||||
static void output_worker_start(Mixer *m);
|
||||
|
||||
static void output_open(Mixer *m, int rate) {
|
||||
const char *mode = cfg_get("TOTK_AUDIO");
|
||||
if ((mode && !strcmp(mode, "none")) || cfg_get("TOTK_AUDIO_OFF")) {
|
||||
@@ -179,12 +336,18 @@ static void output_open(Mixer *m, int rate) {
|
||||
rt_log("audio: SDL audio init failed (%s): mixing without sound", SDL_GetError());
|
||||
return;
|
||||
}
|
||||
SDL_AudioSpec spec = {SDL_AUDIO_F32, 2, rate};
|
||||
m->stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec, sdl_pull, m);
|
||||
const char *want = cfg_get("TOTK_AUDIO_DEVICE");
|
||||
int found;
|
||||
m->open_id = device_pick(want, &found);
|
||||
if (!found) rt_log("audio: TOTK_AUDIO_DEVICE '%s' is not connected: the system default plays", want);
|
||||
SDL_AudioSpec spec = {SDL_AUDIO_F32, m->channels, rate};
|
||||
m->stream = SDL_OpenAudioDeviceStream(m->open_id, &spec, sdl_pull, m);
|
||||
if (!m->stream) {
|
||||
rt_log("audio: no output device (%s): mixing without sound", SDL_GetError());
|
||||
return;
|
||||
}
|
||||
SDL_AudioSpec dev = {0};
|
||||
output_timing(m, &dev);
|
||||
if (!SDL_ResumeAudioStreamDevice(m->stream)) {
|
||||
rt_log("audio: starting the output failed (%s): mixing without sound", SDL_GetError());
|
||||
SDL_DestroyAudioStream(m->stream);
|
||||
@@ -192,32 +355,90 @@ static void output_open(Mixer *m, int rate) {
|
||||
return;
|
||||
}
|
||||
m->device_ok = 1;
|
||||
SDL_AudioSpec dev;
|
||||
int period = 0;
|
||||
if (!SDL_GetAudioDeviceFormat(SDL_GetAudioStreamDevice(m->stream), &dev, &period) || period <= 0) period = m->frame;
|
||||
m->period = period;
|
||||
m->target = m->frame * m->prefill > 2 * period ? m->frame * m->prefill : 2 * period;
|
||||
if (m->target > RING_FRAMES / 2) m->target = RING_FRAMES / 2;
|
||||
uint64_t period_ns = (uint64_t)period * 1000000000ull / (uint64_t)rate;
|
||||
m->stall_ns = 4 * period_ns > STALL_MS * 1000000ull ? 4 * period_ns : STALL_MS * 1000000ull;
|
||||
const char *name = SDL_GetAudioDeviceName(SDL_GetAudioStreamDevice(m->stream));
|
||||
rt_log("audio: SDL device '%s' opened, %d Hz stereo float, prefill %d ms, device period %d frames; the device paces "
|
||||
"rendering at %.1f ms queued", name ? name : "?", rate, m->prefill * 5, period, m->target * 1000.0 / rate);
|
||||
output_log(m, "opened", &dev);
|
||||
m->watch_ver = cfg_version();
|
||||
if (!device_is_default(want)) output_worker_start(m); // watches the chosen device from the start
|
||||
}
|
||||
|
||||
// ---- switching the output device while the game plays (TOTK_AUDIO_DEVICE is live)
|
||||
// One worker thread per mixer, started when a device is first chosen, owns the stream from then on: it opens the new
|
||||
// device (tens of ms) off the render thread, so the game's audio never waits for it. Once a second, and at once when
|
||||
// cfg changes, it resolves the setting again: a chosen device that disappears falls back to the system default, and the
|
||||
// output returns to it within a second of it being plugged in again. SDL's device events are not used: on Windows
|
||||
// nothing pumps SDL's event queue (the window is Win32, gfx_window_win.c), while SDL's device list stays current.
|
||||
|
||||
// Moves the output to device `id` with the same spec; SDL converts to the device's own format and channels.
|
||||
static void output_switch(Mixer *m, SDL_AudioDeviceID id) {
|
||||
SDL_AudioSpec spec = {SDL_AUDIO_F32, m->channels, m->rate};
|
||||
SDL_AudioStream *s = SDL_OpenAudioDeviceStream(id, &spec, sdl_pull, m); // opens paused: no callback yet
|
||||
if (!s) {
|
||||
const char *name = SDL_GetAudioDeviceName(id);
|
||||
rt_log("audio: opening device '%s' failed (%s): the output stays where it was", name ? name : "?",
|
||||
SDL_GetError());
|
||||
m->failed_id = id; // not tried again until the setting or the device list leads elsewhere
|
||||
return;
|
||||
}
|
||||
SDL_DestroyAudioStream(m->stream); // closes the old device; returns once its callback has finished
|
||||
m->stream = s;
|
||||
m->open_id = id;
|
||||
m->failed_id = 0;
|
||||
// No callback runs until the resume: its prefill starts over, and the render thread paces by its timer (pulled_ns
|
||||
// 0) until the new device asks for audio. The ring and the game go on; ring_pull trims what piled up meanwhile.
|
||||
m->ready = 0;
|
||||
atomic_store_explicit(&m->pulled_ns, 0, memory_order_release);
|
||||
SDL_AudioSpec dev = {0};
|
||||
output_timing(m, &dev);
|
||||
if (!SDL_ResumeAudioStreamDevice(s)) rt_log("audio: starting the output failed (%s)", SDL_GetError());
|
||||
output_log(m, "switched to", &dev);
|
||||
}
|
||||
|
||||
static void output_worker(void *p) {
|
||||
Mixer *m = p;
|
||||
while (!atomic_load(&m->worker_quit)) {
|
||||
const char *want = cfg_get("TOTK_AUDIO_DEVICE");
|
||||
int found;
|
||||
SDL_AudioDeviceID id = device_pick(want, &found);
|
||||
if (id != m->open_id && id != m->failed_id) {
|
||||
if (!found) rt_log("audio: TOTK_AUDIO_DEVICE '%s' is not connected: switching to the system default", want);
|
||||
output_switch(m, id);
|
||||
}
|
||||
if (id == m->open_id) m->failed_id = 0;
|
||||
plat_event_wait_ns(&m->wake, 1000000000ull);
|
||||
}
|
||||
}
|
||||
|
||||
static void output_worker_start(Mixer *m) {
|
||||
plat_event_init(&m->wake, 0, 0);
|
||||
m->worker = plat_thread_new(output_worker, m, "audio-out");
|
||||
if (!m->worker) rt_log("audio: no output worker thread: the device stays as it is until the next start");
|
||||
}
|
||||
|
||||
// Render thread: wakes the worker when cfg changed, or starts it when a device is chosen for the first time. Until the
|
||||
// worker runs the stream plays on the system default (output_open), so an unset setting costs this check alone.
|
||||
static void output_watch(Mixer *m) {
|
||||
unsigned ver = cfg_version();
|
||||
if (ver == m->watch_ver) return;
|
||||
m->watch_ver = ver;
|
||||
if (m->worker) plat_event_set(&m->wake);
|
||||
else if (!device_is_default(cfg_get("TOTK_AUDIO_DEVICE"))) output_worker_start(m);
|
||||
}
|
||||
|
||||
int64_t audio_mixer_pace_ns(AudioRenderer *r, uint64_t now) {
|
||||
Mixer *m = r->mixer;
|
||||
if (m && m->device_ok) output_watch(m);
|
||||
if (!m || !m->device_ok || !atomic_load_explicit(&m->playing, memory_order_acquire)) return -1;
|
||||
uint64_t pulled = atomic_load_explicit(&m->pulled_ns, memory_order_acquire);
|
||||
if (!pulled || (now > pulled && now - pulled > m->stall_ns)) return -1;
|
||||
if (!pulled || (now > pulled && now - pulled > __atomic_load_n(&m->stall_ns, __ATOMIC_RELAXED))) return -1;
|
||||
uint64_t have = atomic_load(&m->wr) - atomic_load_explicit(&m->rd, memory_order_acquire);
|
||||
if (have < (uint64_t)m->target) return 0;
|
||||
int64_t ns = (int64_t)((have - (uint64_t)m->target + 1) * 1000000000ull / (uint64_t)m->rate);
|
||||
uint64_t target = (uint64_t)__atomic_load_n(&m->target, __ATOMIC_RELAXED);
|
||||
if (have < target) return 0;
|
||||
int64_t ns = (int64_t)((have - target + 1) * 1000000000ull / (uint64_t)m->rate);
|
||||
return ns < 500000 ? 500000 : ns; // until the device has taken it below the target
|
||||
}
|
||||
|
||||
// Render thread only.
|
||||
static void output_push(Mixer *m, const float *lr, int frames) {
|
||||
static void output_push(Mixer *m, const float *out, int frames) {
|
||||
const int oc = m->channels;
|
||||
uint64_t wr = atomic_load(&m->wr), rd = atomic_load_explicit(&m->rd, memory_order_acquire);
|
||||
if (m->device_ok && wr + (uint64_t)frames - rd > RING_FRAMES) { // device stalled: drop this frame
|
||||
atomic_fetch_add(&m->overruns, 1);
|
||||
@@ -225,24 +446,51 @@ static void output_push(Mixer *m, const float *lr, int frames) {
|
||||
}
|
||||
for (int i = 0; i < frames; i++) {
|
||||
uint64_t k = (wr + (uint64_t)i) % RING_FRAMES;
|
||||
m->ring[2 * k] = lr[2 * i];
|
||||
m->ring[2 * k + 1] = lr[2 * i + 1];
|
||||
memcpy(&m->ring[oc * k], &out[oc * i], (size_t)oc * sizeof(float));
|
||||
}
|
||||
atomic_store_explicit(&m->wr, wr + (uint64_t)frames, memory_order_release);
|
||||
if (!m->device_ok) atomic_store(&m->rd, wr + (uint64_t)frames); // no device: the ring only keeps the latest frames
|
||||
}
|
||||
|
||||
// TOTK_AUDIO_DUMP=<path>: the sink mix before the clamp as raw interleaved float32 stereo, and every 5 s one log line with
|
||||
// how many frames were rendered less than 1 ms after the one before (a burst refill). File writes on the render thread:
|
||||
// for diagnosis only.
|
||||
static void sink_dump(const float *raw, int frames) {
|
||||
static FILE *f;
|
||||
static int opened;
|
||||
static uint64_t last, window_start, total, bursts;
|
||||
if (!opened) {
|
||||
opened = 1;
|
||||
const char *path = cfg_get("TOTK_AUDIO_DUMP");
|
||||
if (path && *path) f = fopen(path, "wb");
|
||||
}
|
||||
if (!f) return;
|
||||
fwrite(raw, sizeof(float), (size_t)frames * 2, f);
|
||||
uint64_t now = kern_now_ns();
|
||||
total++;
|
||||
if (last && now - last < 1000000ull) bursts++;
|
||||
last = now;
|
||||
if (!window_start) window_start = now;
|
||||
if (now - window_start >= 5000000000ull) {
|
||||
rt_log("audio: dump: %llu frames in %.1f s, %llu rendered under 1 ms after the previous", (unsigned long long)total,
|
||||
(now - window_start) / 1e9, (unsigned long long)bursts);
|
||||
total = bursts = 0;
|
||||
window_start = now;
|
||||
fflush(f);
|
||||
}
|
||||
}
|
||||
|
||||
// Level meter (TOTK_TRACE=audio): one line per 5 s of output, and the first nonzero frame.
|
||||
static void level_note(AudioRenderer *r, Mixer *m, const float *lr, int frames) {
|
||||
static void level_note(AudioRenderer *r, Mixer *m, const float *out, int frames) {
|
||||
if (!(rt_trace & RT_TRACE_AUDIO)) return;
|
||||
int sound = 0;
|
||||
for (int k = 0; k < 2 * frames; k++) {
|
||||
double x = lr[k];
|
||||
for (int k = 0; k < m->channels * frames; k++) {
|
||||
double x = out[k];
|
||||
m->level_sum += x * x;
|
||||
if (fabs(x) > m->level_peak) m->level_peak = fabs(x);
|
||||
if (x != 0) sound = 1;
|
||||
}
|
||||
m->level_count += 2 * (uint64_t)frames;
|
||||
m->level_count += (uint64_t)m->channels * (uint64_t)frames;
|
||||
m->level_frames += (uint64_t)frames;
|
||||
if (sound && !m->first_sound_logged) {
|
||||
m->first_sound_logged = 1;
|
||||
@@ -290,9 +538,10 @@ void audio_mixer_open(AudioRenderer *r) {
|
||||
const char *pe = cfg_get("TOTK_AUDIO_PREFILL_MS");
|
||||
m->prefill = prefill_blocks_for(pe);
|
||||
if (m->prefill < 0) {
|
||||
rt_log("audio: TOTK_AUDIO_PREFILL_MS=%s is not 0..500 ms: using 20", pe);
|
||||
m->prefill = 4;
|
||||
rt_log("audio: TOTK_AUDIO_PREFILL_MS=%s is not 0..500 ms: using %d", pe, PREFILL_DEFAULT_MS);
|
||||
m->prefill = PREFILL_DEFAULT_MS / 5;
|
||||
}
|
||||
m->channels = output_channels();
|
||||
r->mixer = m;
|
||||
atomic_store(&m->playing, r->state == 0);
|
||||
output_open(m, r->param.sample_rate);
|
||||
@@ -311,6 +560,11 @@ void audio_mixer_set_running(AudioRenderer *r, int running) {
|
||||
void audio_mixer_close(AudioRenderer *r) {
|
||||
Mixer *m = r->mixer;
|
||||
if (!m) return;
|
||||
if (m->worker) { // the render thread is joined: nothing wakes or starts the worker any more
|
||||
atomic_store(&m->worker_quit, 1);
|
||||
plat_event_set(&m->wake);
|
||||
plat_thread_join(m->worker);
|
||||
}
|
||||
if (m->stream) { // destroying the stream closes the device and waits for the callback to finish
|
||||
SDL_DestroyAudioStream(m->stream);
|
||||
SDL_QuitSubSystem(SDL_INIT_AUDIO);
|
||||
@@ -505,8 +759,25 @@ static void walk_step(Walk *w) { /* the same transitions as advance_voice in a
|
||||
walk_skip_empty(w);
|
||||
}
|
||||
/* Decodes `frames` output samples per channel into out[c][k]; the renderer advances the voice afterwards by the same amount. */
|
||||
static double voice_step(const AudioRenderer *r, const ServerVoice *v) {
|
||||
return v->in.sample_rate * (v->in.pitch > 0 ? v->in.pitch : 1.0) / r->param.sample_rate;
|
||||
}
|
||||
/* Source samples the voice consumes over `frames` output samples, counted with the exact accumulation voice_render steps by
|
||||
(float rounding makes `fraction + seconds * rate * pitch` differ from it by one sample on some frames, a seam click);
|
||||
leaves the fractional position in v->fraction. */
|
||||
uint64_t audio_voice_consumed(const AudioRenderer *r, ServerVoice *v, int frames) {
|
||||
const double step = voice_step(r, v);
|
||||
double frac = v->fraction;
|
||||
uint64_t consumed = 0;
|
||||
for (int k = 0; k < frames; k++) {
|
||||
frac += step;
|
||||
while (frac >= 1.0) { frac -= 1.0; consumed++; }
|
||||
}
|
||||
v->fraction = frac;
|
||||
return consumed;
|
||||
}
|
||||
static void voice_render(AudioRenderer *r, ServerVoice *v, float out[6][MAX_FRAME], int frames) {
|
||||
const double step = v->in.sample_rate * (v->in.pitch > 0 ? v->in.pitch : 1.0) / r->param.sample_rate;
|
||||
const double step = voice_step(r, v);
|
||||
Walk w = {v, v->index, v->offset, v->loops_done, {0}, 0, v->adpcm.history[0], v->adpcm.history[1], v->adpcm.buffer, v->adpcm.at};
|
||||
memcpy(w.valid, v->valid, sizeof w.valid);
|
||||
walk_skip_empty(&w);
|
||||
@@ -545,6 +816,7 @@ static void mix_aux(AudioRenderer *r, int mix, const AudrenEffectIn *e) {
|
||||
uint8_t *send=ipc_guest(p.send_info,128+(uint64_t)p.capacity*4), *ret=ipc_guest(p.return_info,128+(uint64_t)p.capacity*4);
|
||||
uint32_t *sh=(uint32_t *)(send+64),*rh=(uint32_t *)(ret+64); int32_t *sd=(int32_t *)(send+128),*rd=(int32_t *)(ret+128);
|
||||
uint32_t wr=sh[1],read=rh[0],total=p.channels*(uint32_t)m->frame;
|
||||
if(e->enabled) report_once(m,6,"auxiliary effect in use, channels",(int)p.channels);
|
||||
for(unsigned c=0;c<p.channels;c++) {
|
||||
if(p.input[c]>=r->mixes[mix].buffer_count || p.output[c]>=r->mixes[mix].buffer_count)rt_fatal("auxiliary effect mix buffer");
|
||||
float *input=mixbuf(m,m->offset[mix]+p.input[c]),*output=mixbuf(m,m->offset[mix]+p.output[c]);
|
||||
@@ -726,10 +998,13 @@ void audio_mixer_render(AudioRenderer *r, double seconds) {
|
||||
if (at > m->nbuf) { rt_log("audio: mixes use %d buffers, renderer has %d", at, m->nbuf); rt_fatal("audio mix buffer layout"); }
|
||||
|
||||
float (*vs)[MAX_FRAME]=m->voice_scratch,*filtered=m->filter_scratch;
|
||||
const int by_category = audio_cat_active(); // the defaults (all 100) skip the category lookups
|
||||
if (by_category) category_report();
|
||||
for (int i = 0; i < r->param.voice_count; i++) {
|
||||
ServerVoice *v = &r->voices[i];
|
||||
if (!v->in.in_use || v->state != SV_STARTED || !v->in.sample_rate || !v->valid[v->index]) continue;
|
||||
int cc = (int)v->in.channel_count; if (cc < 1 || cc > 6) { report_once(m, 2, "voice channel count unsupported", cc); continue; }
|
||||
const float vvol = by_category ? v->in.volume * category_volume(voice_category(v)) : v->in.volume;
|
||||
voice_render(r, v, vs, frames);
|
||||
for (int f = 0; f < 2; f++) if (v->in.biquads[f].enable) {
|
||||
const AudrenBiquad *b = &v->in.biquads[f];
|
||||
@@ -755,13 +1030,13 @@ void audio_mixer_render(AudioRenderer *r, double seconds) {
|
||||
SplitDest *d = &m->dest[s->ids[k]];
|
||||
if (!d->used || !mix_valid(r, d->dest)) continue;
|
||||
const float *source=splitter_filter(d,vs[c],filtered,frames);
|
||||
for (int b = 0; b < r->mixes[d->dest].buffer_count && b < 24; b++) accumulate(m, m->offset[d->dest] + b, source, d->vol[b] * v->in.volume, frames);
|
||||
for (int b = 0; b < r->mixes[d->dest].buffer_count && b < 24; b++) accumulate(m, m->offset[d->dest] + b, source, d->vol[b] * vvol, frames);
|
||||
}
|
||||
} else if (mix_valid(r, v->in.mix_id)) {
|
||||
for (int c = 0; c < cc; c++) {
|
||||
int32_t id = v->in.channel_ids[c]; if (id < 0 || id >= r->param.voice_count * 6) continue;
|
||||
const AudrenChannelIn *ch = &r->channels[id];
|
||||
for (int b = 0; b < r->mixes[v->in.mix_id].buffer_count && b < 24; b++) accumulate(m, m->offset[v->in.mix_id] + b, vs[c], ch->mix[b] * v->in.volume, frames);
|
||||
for (int b = 0; b < r->mixes[v->in.mix_id].buffer_count && b < 24; b++) accumulate(m, m->offset[v->in.mix_id] + b, vs[c], ch->mix[b] * vvol, frames);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -793,30 +1068,42 @@ void audio_mixer_render(AudioRenderer *r, double seconds) {
|
||||
if (r->sinks[i].type == SINK_DEVICE && !sink) sink = &r->sinks[i];
|
||||
else if (r->sinks[i].type == SINK_CIRCULAR){mix_circular_sink(r,i);circular=1;}
|
||||
} else {m->sink_address[i]=0;m->sink_size[i]=m->sink_offset[i]=m->sink_old[i]=m->sink_written[i]=0;}
|
||||
float *lr=m->output_scratch;
|
||||
memset(lr, 0, sizeof(float) * 2 * (size_t)frames);
|
||||
const int oc = m->channels;
|
||||
float *out=m->output_scratch;
|
||||
memset(out, 0, sizeof(float) * (size_t)oc * (size_t)frames);
|
||||
if (sink && sink->input_count >= 1 && sink->input_count <= 6) {
|
||||
if (!(m->reported & (1u << 6))) {
|
||||
m->reported |= 1u << 6;
|
||||
rt_log("audio: device sink has %u inputs, output %s", sink->input_count, oc == 6 ? "5.1" : "stereo");
|
||||
}
|
||||
const float gain = host_volume() * atomic_load(&device_volume) * (r->mixes[0].in_use ? r->mixes[0].volume : 1.0f);
|
||||
const float *ch[6] = {0};
|
||||
float raw[2 * MAX_FRAME];
|
||||
for (uint32_t c = 0; c < sink->input_count; c++) if (sink->inputs[c] >= 0 && sink->inputs[c] < m->nbuf) ch[c] = mixbuf(m, sink->inputs[c]);
|
||||
for (int k = 0; k < frames; k++) {
|
||||
float l, rr;
|
||||
if (sink->input_count >= 6) { /* FL FR C LFE RL RR -> stereo */
|
||||
float s[OUT_MAX] = {0}; /* FL FR C LFE RL RR */
|
||||
if (sink->input_count >= 6 && oc == 6) {
|
||||
for (int c = 0; c < 6; c++) s[c] = ch[c] ? ch[c][k] : 0;
|
||||
} else if (sink->input_count >= 6) { /* 5.1 -> stereo; the LFE is left out, as the Switch's downmix does */
|
||||
float ff = sink->downmix_enabled ? sink->downmix[0] : 1.0f, cf = sink->downmix_enabled ? sink->downmix[1] : 0.7071f, sf = sink->downmix_enabled ? sink->downmix[2] : 0.7071f;
|
||||
float C = ch[2] ? ch[2][k] : 0;
|
||||
l = ff * (ch[0] ? ch[0][k] : 0) + cf * C + sf * (ch[4] ? ch[4][k] : 0);
|
||||
rr = ff * (ch[1] ? ch[1][k] : 0) + cf * C + sf * (ch[5] ? ch[5][k] : 0);
|
||||
} else if (sink->input_count >= 2) { l = ch[0] ? ch[0][k] : 0; rr = ch[1] ? ch[1][k] : 0; }
|
||||
else l = rr = ch[0] ? ch[0][k] : 0;
|
||||
l *= gain; rr *= gain;
|
||||
lr[2 * k] = l > 1 ? 1 : l < -1 ? -1 : l; lr[2 * k + 1] = rr > 1 ? 1 : rr < -1 ? -1 : rr;
|
||||
s[0] = ff * (ch[0] ? ch[0][k] : 0) + cf * C + sf * (ch[4] ? ch[4][k] : 0);
|
||||
s[1] = ff * (ch[1] ? ch[1][k] : 0) + cf * C + sf * (ch[5] ? ch[5][k] : 0);
|
||||
} else if (sink->input_count >= 2) { s[0] = ch[0] ? ch[0][k] : 0; s[1] = ch[1] ? ch[1][k] : 0; }
|
||||
else s[0] = s[1] = ch[0] ? ch[0][k] : 0;
|
||||
raw[2 * k] = s[0] * gain; raw[2 * k + 1] = s[1] * gain; /* TOTK_AUDIO_DUMP: the front pair before clipping */
|
||||
for (int c = 0; c < oc; c++) {
|
||||
float x = s[c] * gain;
|
||||
out[oc * k + c] = x > 1 ? 1 : x < -1 ? -1 : x;
|
||||
}
|
||||
}
|
||||
sink_dump(raw, frames);
|
||||
} else if (!sink && !circular) report_once(m, 5, "no device sink in use", r->param.sink_count);
|
||||
level_note(r, m, lr, frames);
|
||||
output_push(m, lr, frames);
|
||||
level_note(r, m, out, frames);
|
||||
output_push(m, out, frames);
|
||||
}
|
||||
|
||||
// ---- IAudioDevice: one stereo output device
|
||||
// ---- IAudioDevice: one output device, stereo or 5.1 (output_channels)
|
||||
static const char device_name[] = "AudioTvOutput";
|
||||
|
||||
static void put_name(const IpcBuffer *b, IpcResponse *rs, int pointer) {
|
||||
@@ -855,7 +1142,7 @@ void audio_device_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *rs)
|
||||
put_name(&b, rs, pointer);
|
||||
return;
|
||||
}
|
||||
case 5: { int32_t n = 2; IPC_OUT(rs, n); return; } // GetActiveChannelCount
|
||||
case 5: { int32_t n = output_channels(); IPC_OUT(rs, n); return; } // GetActiveChannelCount
|
||||
case 4: case 11: case 12: { // QueryAudioDeviceSystemEvent, ...InputEvent, ...OutputEvent
|
||||
uint32_t ev = __atomic_load_n(&change_event, __ATOMIC_ACQUIRE);
|
||||
if (!ev) {
|
||||
|
||||
@@ -24,8 +24,8 @@ static void delay_set(Delay *d, unsigned n) { if (n > d->cap) rt_fatal("reverb d
|
||||
static void delay_init(Delay *d, unsigned khz, float ms) { d->cap = samples(khz, ms); d->data = calloc(d->cap + 1, sizeof(float)); if (!d->data) rt_fatal("reverb delay allocation"); delay_set(d, d->cap); }
|
||||
static float delay_update(Delay *d, float v) {
|
||||
d->data[d->write++] = v; float out = d->data[d->read++];
|
||||
if (d->read >= d->cap) d->read = 0;
|
||||
if (d->write >= d->cap) d->write = 0;
|
||||
if (d->read > d->cap) d->read = 0;
|
||||
if (d->write > d->cap) d->write = 0;
|
||||
return out;
|
||||
}
|
||||
static float delay_tap(const Delay *d, unsigned at) { int i = (int)d->write - (int)at - 1; if (i < 0) i += (int)d->cap + 1; return d->data[i]; }
|
||||
|
||||
+45
-41
@@ -5,7 +5,6 @@
|
||||
// service validates every section against the header, keeps server-side voice state, advances it in real time (one
|
||||
// frame of sample_count / sample_rate seconds per render tick, signalling the renderer's event) and writes the output
|
||||
// status the client expects. The mixer behind it is audio_mixer.c.
|
||||
#include <windows.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -14,10 +13,11 @@
|
||||
#include "audren.h"
|
||||
#include "host.h"
|
||||
#include "ipc.h"
|
||||
#include "platform/platform.h"
|
||||
|
||||
static volatile long g_live;
|
||||
static volatile int32_t g_live;
|
||||
|
||||
long audren_renderers_live(void) { return InterlockedCompareExchange(&g_live, 0, 0); }
|
||||
long audren_renderers_live(void) { return plat_cas32(&g_live, 0, 0); }
|
||||
|
||||
static int revision_number(uint32_t rev) { return (int)(rev >> 24) - '0'; }
|
||||
|
||||
@@ -44,7 +44,7 @@ static AudioRenderer *renderer_new(const AudrenParameter *p) {
|
||||
r->effects = calloc((size_t)(p->effect_count ? p->effect_count : 1), sizeof *r->effects);
|
||||
r->channels = calloc((size_t)p->voice_count * 6, sizeof *r->channels);
|
||||
need(r->voices && r->pools && r->mixes && r->sinks && r->effects && r->channels, "renderer tables");
|
||||
InitializeSRWLock(&r->lock);
|
||||
plat_mutex_init(&r->lock);
|
||||
r->event = kern_event_new();
|
||||
r->state = 1; // stopped
|
||||
return r;
|
||||
@@ -86,6 +86,7 @@ static void voice_reset(ServerVoice *v) {
|
||||
v->loops_done = 0;
|
||||
memset(&v->adpcm, 0, sizeof v->adpcm);
|
||||
memset(v->biquad_state, 0, sizeof v->biquad_state);
|
||||
v->cat = 0;
|
||||
}
|
||||
|
||||
static void update_voice(AudioRenderer *r, const AudrenVoiceIn *in) {
|
||||
@@ -195,7 +196,7 @@ static void request_update(AudioRenderer *r, const uint8_t *input, uint64_t in_s
|
||||
memcpy(&h, input, sizeof h);
|
||||
need(h.total <= in_size, "update total size");
|
||||
Reader in = {input + sizeof h, input + h.total};
|
||||
AcquireSRWLockExclusive(&r->lock);
|
||||
plat_mutex_lock(&r->lock);
|
||||
r->revision = h.revision;
|
||||
const int vc = r->param.voice_count, ec = r->param.effect_count, sc = r->param.sink_count,
|
||||
mc = r->param.submix_count + 1;
|
||||
@@ -313,16 +314,14 @@ static void request_update(AudioRenderer *r, const uint8_t *input, uint64_t in_s
|
||||
w += 0x10; // performance: nothing written
|
||||
w += AUDREN_BEHAVIOR_OUT; // behavior: no errors
|
||||
memcpy(w, &r->elapsed_frames, 8);
|
||||
ReleaseSRWLockExclusive(&r->lock);
|
||||
plat_mutex_unlock(&r->lock);
|
||||
}
|
||||
|
||||
// ---- render tick: one frame each time the output device has taken the ring below its target (audio_mixer_pace_ns),
|
||||
// or every sample_count / sample_rate seconds of the host clock without a device, while stopped or while it stalls
|
||||
static void advance_voice(AudioRenderer *r, ServerVoice *v, double out_seconds) {
|
||||
static void advance_voice(AudioRenderer *r, ServerVoice *v) {
|
||||
if (!v->in.in_use || v->state != SV_STARTED || !v->in.sample_rate) return;
|
||||
double want = v->fraction + out_seconds * v->in.sample_rate * (v->in.pitch > 0 ? v->in.pitch : 1.0);
|
||||
uint64_t samples = (uint64_t)want;
|
||||
v->fraction = want - (double)samples;
|
||||
uint64_t samples = audio_voice_consumed(r, v, (int)r->param.sample_count);
|
||||
while (samples && v->valid[v->index]) {
|
||||
AudrenWaveBuffer *b = &v->buffers[v->index];
|
||||
uint64_t length = (uint64_t)(b->end - b->start), left = length - v->offset;
|
||||
@@ -349,40 +348,48 @@ static void advance_voice(AudioRenderer *r, ServerVoice *v, double out_seconds)
|
||||
}
|
||||
}
|
||||
|
||||
static void wait_ns(HANDLE timer, uint64_t ns) {
|
||||
LARGE_INTEGER due = {.QuadPart = -(LONGLONG)((ns + 99) / 100)}; // relative, 100 ns units
|
||||
if (!SetWaitableTimer(timer, &due, 0, NULL, NULL, FALSE)) rt_fatal("audren: SetWaitableTimer failed (error %lu)", GetLastError());
|
||||
WaitForSingleObject(timer, INFINITE);
|
||||
}
|
||||
|
||||
static DWORD WINAPI render_thread(void *p) {
|
||||
static void render_thread(void *p) {
|
||||
AudioRenderer *r = p;
|
||||
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
|
||||
HANDLE timer = CreateWaitableTimerExW(NULL, NULL, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS);
|
||||
if (!timer) timer = CreateWaitableTimerExW(NULL, NULL, 0, TIMER_ALL_ACCESS);
|
||||
if (!timer) rt_fatal("audren: CreateWaitableTimerExW failed (error %lu)", GetLastError());
|
||||
plat_thread_priority(PLAT_PRIO_HIGHEST);
|
||||
const uint64_t frame_ns = (uint64_t)r->param.sample_count * 1000000000ull / (uint64_t)r->param.sample_rate;
|
||||
const double frame = (double)r->param.sample_count / r->param.sample_rate;
|
||||
uint64_t next = kern_now_ns();
|
||||
while (InterlockedCompareExchange(&r->running, 0, 0)) {
|
||||
// When the device pulls a period (1024 samples on PipeWire, 4-5 frames) the ring drops below its target
|
||||
// and the frames would otherwise render back to back. On hardware the DSP renders one frame every 5 ms and
|
||||
// the game's audio thread works in between; AUX effects need that time to fill the return ring, or mix_aux
|
||||
// reads stale samples and the frame clicks at its seams. Device-paced frames stay at least 4/5 of a frame
|
||||
// apart, which still refills a period well before the device drains it. Linux only: on Windows SDL pulls
|
||||
// 480-sample periods, and a sink dump (TOTK_AUDIO_DUMP) of the bursts there showed no more seam spikes than
|
||||
// chance, so a wait on this thread buys nothing.
|
||||
#ifdef __linux__
|
||||
const uint64_t gap_ns = frame_ns * 4 / 5;
|
||||
#else
|
||||
const uint64_t gap_ns = 0;
|
||||
#endif
|
||||
uint64_t next = kern_now_ns(), last = 0;
|
||||
while (plat_cas32(&r->running, 0, 0)) {
|
||||
uint64_t now = kern_now_ns();
|
||||
int64_t pace = audio_mixer_pace_ns(r, now);
|
||||
if (pace > 0) {
|
||||
wait_ns(timer, (uint64_t)pace);
|
||||
plat_wait_ns((uint64_t)pace);
|
||||
continue;
|
||||
}
|
||||
if (pace == 0 && last && now - last < gap_ns) {
|
||||
plat_wait_ns(gap_ns - (now - last));
|
||||
continue;
|
||||
}
|
||||
if (pace == 0) {
|
||||
next = now + frame_ns; // where the timer goes on if the device stops pacing
|
||||
} else {
|
||||
if (next > now) wait_ns(timer, next - now);
|
||||
if (next > now) plat_wait_ns(next - now);
|
||||
else if (now - next > 100000000ull) next = now; // fell far behind (debugger, sleep): resynchronise
|
||||
next += frame_ns;
|
||||
}
|
||||
AcquireSRWLockExclusive(&r->lock);
|
||||
last = kern_now_ns();
|
||||
plat_mutex_lock(&r->lock);
|
||||
if (r->state == 0) {
|
||||
voices_prepare(r);
|
||||
audio_mixer_render(r, frame);
|
||||
for (int i = 0; i < r->param.voice_count; i++) advance_voice(r, &r->voices[i], frame);
|
||||
for (int i = 0; i < r->param.voice_count; i++) advance_voice(r, &r->voices[i]);
|
||||
r->elapsed_frames++;
|
||||
uint64_t given = r->stop_released + r->empty_played + r->flushed;
|
||||
if ((rt_trace & RT_TRACE_IPC) && given != r->logged_released && r->elapsed_frames % 1000 == 0) {
|
||||
@@ -392,11 +399,9 @@ static DWORD WINAPI render_thread(void *p) {
|
||||
(unsigned long long)r->flushed);
|
||||
}
|
||||
}
|
||||
ReleaseSRWLockExclusive(&r->lock);
|
||||
plat_mutex_unlock(&r->lock);
|
||||
kern_event_signal(r->event);
|
||||
}
|
||||
CloseHandle(timer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- IAudioRenderer
|
||||
@@ -428,16 +433,16 @@ static void renderer_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *r
|
||||
return;
|
||||
}
|
||||
case 5: // Start
|
||||
AcquireSRWLockExclusive(&r->lock);
|
||||
plat_mutex_lock(&r->lock);
|
||||
r->state = 0;
|
||||
audio_mixer_set_running(r, 1);
|
||||
ReleaseSRWLockExclusive(&r->lock);
|
||||
plat_mutex_unlock(&r->lock);
|
||||
return;
|
||||
case 6: // Stop
|
||||
AcquireSRWLockExclusive(&r->lock);
|
||||
plat_mutex_lock(&r->lock);
|
||||
r->state = 1;
|
||||
audio_mixer_set_running(r, 0);
|
||||
ReleaseSRWLockExclusive(&r->lock);
|
||||
plat_mutex_unlock(&r->lock);
|
||||
return;
|
||||
case 7: rs->copy[rs->ncopy++] = kern_event_readable(r->event); return; // QuerySystemEvent
|
||||
case 8: r->time_limit = IPC_ARG(rq, uint32_t, 0); return; // SetRenderingTimeLimit
|
||||
@@ -448,12 +453,11 @@ static void renderer_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *r
|
||||
|
||||
static void renderer_close(void *p) {
|
||||
AudioRenderer *r = p;
|
||||
InterlockedExchange(&r->running, 0);
|
||||
plat_xchg32(&r->running, 0);
|
||||
int away = kern_core_away();
|
||||
WaitForSingleObject(r->thread, INFINITE);
|
||||
plat_thread_join(r->thread);
|
||||
kern_core_back(&away);
|
||||
CloseHandle(r->thread);
|
||||
InterlockedDecrement(&g_live);
|
||||
plat_dec32(&g_live);
|
||||
audio_mixer_close(r);
|
||||
kern_handle_close(r->event);
|
||||
rt_log("audren: renderer closed after %llu frames", (unsigned long long)r->elapsed_frames);
|
||||
@@ -472,9 +476,9 @@ void audren_manager_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *rs
|
||||
AudioRenderer *r = renderer_new(&p);
|
||||
r->running = 1;
|
||||
audio_mixer_open(r);
|
||||
r->thread = CreateThread(NULL, 0, render_thread, r, 0, NULL);
|
||||
if (!r->thread) rt_fatal("audren: render thread CreateThread failed (error %lu)", GetLastError());
|
||||
InterlockedIncrement(&g_live);
|
||||
r->thread = plat_thread_new(render_thread, r, "audren");
|
||||
if (!r->thread) rt_fatal("audren: cannot start the render thread");
|
||||
plat_inc32(&g_live);
|
||||
rt_log("audren: renderer open %d Hz x%d, mix buffers %d, voices %d, effects %d, submixes %d, sinks %d, "
|
||||
"splitters %d/%d, REV%d, work buffer %#llx+%#llx",
|
||||
p.sample_rate, p.sample_count, p.mix_buffer_count, p.voice_count, p.effect_count, p.submix_count,
|
||||
|
||||
+11
-4
@@ -3,10 +3,10 @@
|
||||
// audren:u, the audio renderer service: RequestUpdate wire formats, the server-side
|
||||
// renderer state, and the mixer interface (audio_mixer.c: the real mixer with SDL3 output).
|
||||
#pragma once
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "ipc.h"
|
||||
#include "platform/platform.h"
|
||||
|
||||
typedef struct {
|
||||
int32_t sample_rate, sample_count, mix_buffer_count, submix_count, voice_count, sink_count, effect_count,
|
||||
@@ -145,14 +145,16 @@ typedef struct {
|
||||
uint32_t consumed, drops;
|
||||
struct { int16_t history[2]; int32_t buffer; uint64_t at; } adpcm; // DSP-ADPCM decode cursor (buffer slot, next sample) and history
|
||||
float biquad_state[2][6][2]; // filter, channel: transposed direct-form II delays
|
||||
uint64_t cat_address, cat_extra; // the wave buffer and coefficients voice_category (audio_mixer.c) last classified
|
||||
uint8_t cat; // their AUDIO_CAT_*, 0 until classified; voice_reset clears it
|
||||
} ServerVoice;
|
||||
enum { SV_STOPPED, SV_STARTED, SV_PAUSED, SV_STOPPING };
|
||||
|
||||
typedef struct AudioRenderer {
|
||||
AudrenParameter param;
|
||||
SRWLOCK lock;
|
||||
HANDLE thread;
|
||||
volatile long running;
|
||||
PlatMutex lock;
|
||||
PlatThread *thread;
|
||||
volatile int32_t running;
|
||||
uint32_t state, revision, time_limit, event; // state 0 started, 1 stopped; event: writable handle
|
||||
int logged;
|
||||
uint64_t behavior_flags, elapsed_frames;
|
||||
@@ -184,5 +186,10 @@ void audio_mixer_render(AudioRenderer *r, double seconds); // after audio_voic
|
||||
// many ns (the ring is at its target), -1 leaves the pace to the render thread's timer (no device, renderer stopped,
|
||||
// device stalled).
|
||||
int64_t audio_mixer_pace_ns(AudioRenderer *r, uint64_t now);
|
||||
// The playback devices SDL lists now, by name (TOTK_AUDIO_DEVICE takes one), at most max; 0 while SDL audio is not up
|
||||
// (TOTK_AUDIO=none). Any thread; the Sound tab of the menu lists them.
|
||||
enum { AUDIO_DEVICE_NAME_MAX = 256 };
|
||||
int audio_output_devices(char (*names)[AUDIO_DEVICE_NAME_MAX], int max);
|
||||
uint64_t audio_voice_consumed(const AudioRenderer *r, ServerVoice *v, int frames); // source samples over one frame; advances v->fraction
|
||||
int audio_buffer_empty(const AudrenWaveBuffer *b); // no samples to decode: played as soon as it is reached
|
||||
void audio_device_handler(IpcSession *s, const IpcRequest *rq, IpcResponse *rs); // IAudioDevice
|
||||
@@ -0,0 +1,111 @@
|
||||
// Generated by tools/build_shaders.py from runtime/shaders/bl_deswizzle.comp; do not edit.
|
||||
// source sha256 bd2065290e315e85d2fcdb609d812c15ba9a109d7506b3105850a5860677b0ef
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
static const uint32_t bl_deswizzle_spv[] = {
|
||||
0x07230203, 0x00010300, 0x000d000b, 0x000000d0, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
|
||||
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
|
||||
0x0007000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x0000001f, 0x00060010,
|
||||
0x00000004, 0x00000011, 0x00000040, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b,
|
||||
0x0000001a, 0x00030047, 0x00000010, 0x00000002, 0x00050048, 0x00000010, 0x00000000, 0x00000023,
|
||||
0x00000000, 0x00050048, 0x00000010, 0x00000001, 0x00000023, 0x00000004, 0x00050048, 0x00000010,
|
||||
0x00000002, 0x00000023, 0x00000008, 0x00050048, 0x00000010, 0x00000003, 0x00000023, 0x0000000c,
|
||||
0x00050048, 0x00000010, 0x00000004, 0x00000023, 0x00000010, 0x00050048, 0x00000010, 0x00000005,
|
||||
0x00000023, 0x00000014, 0x00050048, 0x00000010, 0x00000006, 0x00000023, 0x00000018, 0x00050048,
|
||||
0x00000010, 0x00000007, 0x00000023, 0x0000001c, 0x00050048, 0x00000010, 0x00000008, 0x00000023,
|
||||
0x00000020, 0x00050048, 0x00000010, 0x00000009, 0x00000023, 0x00000024, 0x00050048, 0x00000010,
|
||||
0x0000000a, 0x00000023, 0x00000028, 0x00040047, 0x0000001f, 0x0000000b, 0x0000001b, 0x00040047,
|
||||
0x000000ad, 0x00000006, 0x00000010, 0x00030047, 0x000000ae, 0x00000002, 0x00040048, 0x000000ae,
|
||||
0x00000000, 0x00000019, 0x00050048, 0x000000ae, 0x00000000, 0x00000023, 0x00000000, 0x00030047,
|
||||
0x000000b0, 0x00000019, 0x00040047, 0x000000b0, 0x00000021, 0x00000001, 0x00040047, 0x000000b0,
|
||||
0x00000022, 0x00000000, 0x00040047, 0x000000c1, 0x00000006, 0x00000010, 0x00030047, 0x000000c2,
|
||||
0x00000002, 0x00040048, 0x000000c2, 0x00000000, 0x00000018, 0x00050048, 0x000000c2, 0x00000000,
|
||||
0x00000023, 0x00000000, 0x00030047, 0x000000c4, 0x00000018, 0x00040047, 0x000000c4, 0x00000021,
|
||||
0x00000000, 0x00040047, 0x000000c4, 0x00000022, 0x00000000, 0x00040047, 0x000000cd, 0x0000000b,
|
||||
0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006,
|
||||
0x00000020, 0x00000000, 0x00040017, 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a,
|
||||
0x00000001, 0x00000009, 0x0004003b, 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006,
|
||||
0x0000000c, 0x00000001, 0x00040020, 0x0000000d, 0x00000001, 0x00000006, 0x000d001e, 0x00000010,
|
||||
0x00000006, 0x00000006, 0x00000006, 0x00000006, 0x00000006, 0x00000006, 0x00000006, 0x00000006,
|
||||
0x00000006, 0x00000006, 0x00000006, 0x00040020, 0x00000011, 0x00000009, 0x00000010, 0x0004003b,
|
||||
0x00000011, 0x00000012, 0x00000009, 0x00040015, 0x00000013, 0x00000020, 0x00000001, 0x0004002b,
|
||||
0x00000013, 0x00000014, 0x0000000a, 0x00040020, 0x00000015, 0x00000009, 0x00000006, 0x0004002b,
|
||||
0x00000006, 0x00000019, 0x00000000, 0x0004002b, 0x00000006, 0x0000001d, 0x00000040, 0x0004003b,
|
||||
0x0000000a, 0x0000001f, 0x00000001, 0x0004002b, 0x00000013, 0x00000024, 0x00000002, 0x00020014,
|
||||
0x00000027, 0x0004002b, 0x00000013, 0x0000002d, 0x00000006, 0x0004002b, 0x00000013, 0x00000032,
|
||||
0x00000007, 0x0004002b, 0x00000006, 0x00000037, 0x00000020, 0x0004002b, 0x00000006, 0x00000048,
|
||||
0x00000005, 0x0004002b, 0x00000006, 0x0000004c, 0x0000001f, 0x0004002b, 0x00000013, 0x0000004f,
|
||||
0x00000008, 0x0004002b, 0x00000013, 0x00000052, 0x00000009, 0x0004002b, 0x00000006, 0x0000006a,
|
||||
0x00000004, 0x0004002b, 0x00000006, 0x0000006f, 0x00000002, 0x0004002b, 0x00000006, 0x00000078,
|
||||
0x00000008, 0x0004002b, 0x00000006, 0x00000083, 0x00000003, 0x0004002b, 0x00000013, 0x00000093,
|
||||
0x00000003, 0x0004002b, 0x00000013, 0x0000009b, 0x00000004, 0x0004002b, 0x00000013, 0x000000a4,
|
||||
0x00000005, 0x00040017, 0x000000ac, 0x00000006, 0x00000004, 0x0003001d, 0x000000ad, 0x000000ac,
|
||||
0x0003001e, 0x000000ae, 0x000000ad, 0x00040020, 0x000000af, 0x0000000c, 0x000000ae, 0x0004003b,
|
||||
0x000000af, 0x000000b0, 0x0000000c, 0x0004002b, 0x00000013, 0x000000b1, 0x00000000, 0x0004002b,
|
||||
0x00000013, 0x000000b2, 0x00000001, 0x0003001d, 0x000000c1, 0x000000ac, 0x0003001e, 0x000000c2,
|
||||
0x000000c1, 0x00040020, 0x000000c3, 0x0000000c, 0x000000c2, 0x0004003b, 0x000000c3, 0x000000c4,
|
||||
0x0000000c, 0x00040020, 0x000000c9, 0x0000000c, 0x000000ac, 0x0006002c, 0x00000009, 0x000000cd,
|
||||
0x0000001d, 0x0000000c, 0x0000000c, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003,
|
||||
0x000200f8, 0x00000005, 0x000300f7, 0x000000ce, 0x00000000, 0x000300fb, 0x00000019, 0x000000cf,
|
||||
0x000200f8, 0x000000cf, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d,
|
||||
0x00000006, 0x0000000f, 0x0000000e, 0x00050041, 0x00000015, 0x00000016, 0x00000012, 0x00000014,
|
||||
0x0004003d, 0x00000006, 0x00000017, 0x00000016, 0x00050084, 0x00000006, 0x00000018, 0x0000000f,
|
||||
0x00000017, 0x00050041, 0x0000000d, 0x0000001a, 0x0000000b, 0x00000019, 0x0004003d, 0x00000006,
|
||||
0x0000001b, 0x0000001a, 0x00050080, 0x00000006, 0x0000001c, 0x00000018, 0x0000001b, 0x00050084,
|
||||
0x00000006, 0x0000001e, 0x0000001c, 0x0000001d, 0x00050041, 0x0000000d, 0x00000020, 0x0000001f,
|
||||
0x00000019, 0x0004003d, 0x00000006, 0x00000021, 0x00000020, 0x00050080, 0x00000006, 0x00000022,
|
||||
0x0000001e, 0x00000021, 0x00050041, 0x00000015, 0x00000025, 0x00000012, 0x00000024, 0x0004003d,
|
||||
0x00000006, 0x00000026, 0x00000025, 0x000500ae, 0x00000027, 0x00000028, 0x00000022, 0x00000026,
|
||||
0x000300f7, 0x0000002a, 0x00000000, 0x000400fa, 0x00000028, 0x00000029, 0x0000002a, 0x000200f8,
|
||||
0x00000029, 0x000200f9, 0x000000ce, 0x000200f8, 0x0000002a, 0x00050041, 0x00000015, 0x0000002e,
|
||||
0x00000012, 0x0000002d, 0x0004003d, 0x00000006, 0x0000002f, 0x0000002e, 0x000500c4, 0x00000006,
|
||||
0x00000030, 0x0000000c, 0x0000002f, 0x00050041, 0x00000015, 0x00000033, 0x00000012, 0x00000032,
|
||||
0x0004003d, 0x00000006, 0x00000034, 0x00000033, 0x000500c4, 0x00000006, 0x00000035, 0x0000000c,
|
||||
0x00000034, 0x00050080, 0x00000006, 0x0000003c, 0x0000002f, 0x00000034, 0x000500c4, 0x00000006,
|
||||
0x0000003d, 0x00000037, 0x0000003c, 0x00050086, 0x00000006, 0x00000041, 0x00000022, 0x0000003d,
|
||||
0x00050089, 0x00000006, 0x00000045, 0x00000022, 0x0000003d, 0x000500c2, 0x00000006, 0x00000049,
|
||||
0x00000045, 0x00000048, 0x000500c7, 0x00000006, 0x0000004d, 0x00000045, 0x0000004c, 0x00050041,
|
||||
0x00000015, 0x00000050, 0x00000012, 0x0000004f, 0x0004003d, 0x00000006, 0x00000051, 0x00000050,
|
||||
0x00050041, 0x00000015, 0x00000053, 0x00000012, 0x00000052, 0x0004003d, 0x00000006, 0x00000054,
|
||||
0x00000053, 0x00050084, 0x00000006, 0x00000055, 0x00000051, 0x00000054, 0x00050086, 0x00000006,
|
||||
0x00000059, 0x00000041, 0x00000055, 0x00050089, 0x00000006, 0x0000005d, 0x00000041, 0x00000055,
|
||||
0x00050086, 0x00000006, 0x00000062, 0x0000005d, 0x00000051, 0x00050089, 0x00000006, 0x00000067,
|
||||
0x0000005d, 0x00000051, 0x00050084, 0x00000006, 0x0000006b, 0x00000067, 0x0000006a, 0x000500c2,
|
||||
0x00000006, 0x0000006d, 0x0000004d, 0x0000006a, 0x000500c7, 0x00000006, 0x0000006e, 0x0000006d,
|
||||
0x0000000c, 0x00050084, 0x00000006, 0x00000070, 0x0000006e, 0x0000006f, 0x00050080, 0x00000006,
|
||||
0x00000071, 0x0000006b, 0x00000070, 0x000500c2, 0x00000006, 0x00000073, 0x0000004d, 0x0000000c,
|
||||
0x000500c7, 0x00000006, 0x00000074, 0x00000073, 0x0000000c, 0x00050080, 0x00000006, 0x00000075,
|
||||
0x00000071, 0x00000074, 0x00050084, 0x00000006, 0x00000079, 0x00000062, 0x00000078, 0x00050084,
|
||||
0x00000006, 0x0000007b, 0x00000079, 0x00000030, 0x00050089, 0x00000006, 0x0000007e, 0x00000049,
|
||||
0x00000030, 0x00050084, 0x00000006, 0x0000007f, 0x0000007e, 0x00000078, 0x00050080, 0x00000006,
|
||||
0x00000080, 0x0000007b, 0x0000007f, 0x000500c2, 0x00000006, 0x00000082, 0x0000004d, 0x0000006f,
|
||||
0x000500c7, 0x00000006, 0x00000084, 0x00000082, 0x00000083, 0x00050084, 0x00000006, 0x00000085,
|
||||
0x00000084, 0x0000006f, 0x00050080, 0x00000006, 0x00000086, 0x00000080, 0x00000085, 0x000500c7,
|
||||
0x00000006, 0x00000088, 0x00000045, 0x0000000c, 0x00050080, 0x00000006, 0x00000089, 0x00000086,
|
||||
0x00000088, 0x00050084, 0x00000006, 0x0000008d, 0x00000059, 0x00000035, 0x00050086, 0x00000006,
|
||||
0x00000090, 0x00000049, 0x00000030, 0x00050080, 0x00000006, 0x00000091, 0x0000008d, 0x00000090,
|
||||
0x00050041, 0x00000015, 0x00000094, 0x00000012, 0x00000093, 0x0004003d, 0x00000006, 0x00000095,
|
||||
0x00000094, 0x000500ae, 0x00000027, 0x00000096, 0x00000075, 0x00000095, 0x000400a8, 0x00000027,
|
||||
0x00000097, 0x00000096, 0x000300f7, 0x00000099, 0x00000000, 0x000400fa, 0x00000097, 0x00000098,
|
||||
0x00000099, 0x000200f8, 0x00000098, 0x00050041, 0x00000015, 0x0000009c, 0x00000012, 0x0000009b,
|
||||
0x0004003d, 0x00000006, 0x0000009d, 0x0000009c, 0x000500ae, 0x00000027, 0x0000009e, 0x00000089,
|
||||
0x0000009d, 0x000200f9, 0x00000099, 0x000200f8, 0x00000099, 0x000700f5, 0x00000027, 0x0000009f,
|
||||
0x00000096, 0x0000002a, 0x0000009e, 0x00000098, 0x000400a8, 0x00000027, 0x000000a0, 0x0000009f,
|
||||
0x000300f7, 0x000000a2, 0x00000000, 0x000400fa, 0x000000a0, 0x000000a1, 0x000000a2, 0x000200f8,
|
||||
0x000000a1, 0x00050041, 0x00000015, 0x000000a5, 0x00000012, 0x000000a4, 0x0004003d, 0x00000006,
|
||||
0x000000a6, 0x000000a5, 0x000500ae, 0x00000027, 0x000000a7, 0x00000091, 0x000000a6, 0x000200f9,
|
||||
0x000000a2, 0x000200f8, 0x000000a2, 0x000700f5, 0x00000027, 0x000000a8, 0x0000009f, 0x00000099,
|
||||
0x000000a7, 0x000000a1, 0x000300f7, 0x000000aa, 0x00000000, 0x000400fa, 0x000000a8, 0x000000a9,
|
||||
0x000000aa, 0x000200f8, 0x000000a9, 0x000200f9, 0x000000ce, 0x000200f8, 0x000000aa, 0x00050041,
|
||||
0x00000015, 0x000000b3, 0x00000012, 0x000000b2, 0x0004003d, 0x00000006, 0x000000b4, 0x000000b3,
|
||||
0x00050041, 0x00000015, 0x000000b6, 0x00000012, 0x0000009b, 0x0004003d, 0x00000006, 0x000000b7,
|
||||
0x000000b6, 0x00050084, 0x00000006, 0x000000b8, 0x00000091, 0x000000b7, 0x00050080, 0x00000006,
|
||||
0x000000ba, 0x000000b8, 0x00000089, 0x00050084, 0x00000006, 0x000000bd, 0x000000ba, 0x00000095,
|
||||
0x00050080, 0x00000006, 0x000000be, 0x000000b4, 0x000000bd, 0x00050080, 0x00000006, 0x000000c0,
|
||||
0x000000be, 0x00000075, 0x00050041, 0x00000015, 0x000000c5, 0x00000012, 0x000000b1, 0x0004003d,
|
||||
0x00000006, 0x000000c6, 0x000000c5, 0x00050080, 0x00000006, 0x000000c8, 0x000000c6, 0x00000022,
|
||||
0x00060041, 0x000000c9, 0x000000ca, 0x000000c4, 0x000000b1, 0x000000c8, 0x0004003d, 0x000000ac,
|
||||
0x000000cb, 0x000000ca, 0x00060041, 0x000000c9, 0x000000cc, 0x000000b0, 0x000000b1, 0x000000c0,
|
||||
0x0003003e, 0x000000cc, 0x000000cb, 0x000200f9, 0x000000ce, 0x000200f8, 0x000000ce, 0x000100fd,
|
||||
0x00010038,
|
||||
};
|
||||
+84
-43
@@ -3,38 +3,45 @@
|
||||
// da35b83 (MIT, Copyright (c) 2026 Peiikai).
|
||||
// The boot driver: the guest main thread runs the game's own nn::init::Start
|
||||
// with three host callbacks, the second of which runs DT_INIT of main, subsdk0 and sdk; Start then calls nnMain.
|
||||
// --boot checks two checkpoints on the way and ends at the first nvnBootstrapLoader call:
|
||||
// SetFocusHandlingMode called from main+0xe7a954 (1.4.3: +0xbdb48c) in nnMain, every module's constructor flag
|
||||
// reads 2
|
||||
// nvnBootstrapLoader called from main+0xe7eb2c (1.4.3: +0xbe0360) in the graphics bring-up; logs the run
|
||||
// statistics, exits 0
|
||||
// --boot checks two checkpoints on the way and ends at the first nvnBootstrapLoader call, at the return address of
|
||||
// each in main (1.1.0, 1.2.1, 1.4.3):
|
||||
// SetFocusHandlingMode main+0xeb8c14 (1.2.1: +0xe7a954, 1.4.3: +0xbdb48c) in nnMain, every module's constructor
|
||||
// flag reads 2
|
||||
// nvnBootstrapLoader main+0xebcdec (1.2.1: +0xe7eb2c, 1.4.3: +0xbe0360) in the graphics bring-up; logs the
|
||||
// run statistics, exits 0
|
||||
// With --seconds S the run continues past that call; rt_frame_presented ends it once the world clock passed S.
|
||||
#include <windows.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "cfg.h"
|
||||
#include "cheats.h"
|
||||
#include "fs.h"
|
||||
#include "gfx.h"
|
||||
#include "mods.h"
|
||||
#include "nvn_api.h"
|
||||
#include "platform/platform.h"
|
||||
#include "vk.h"
|
||||
#include "gameplay_tweaks.h"
|
||||
|
||||
#define SYM_INIT_START "_ZN2nn4init5StartEmmPFvvES2_S2_"
|
||||
// main: return addresses of nnMain's SetFocusHandlingMode call (1.2.1 from this port's analysis of main; 1.4.3 from
|
||||
// MacNativeGames' scripts/verify_boot.py) and of the first nvnBootstrapLoader call, per game version.
|
||||
#define CHECKPOINT_RET (RT_V143 ? 0xbdb48cull : 0xe7a954ull)
|
||||
#define NVN_RET (RT_V143 ? 0xbe0360ull : 0xe7eb2cull)
|
||||
// main: return addresses of nnMain's SetFocusHandlingMode call (1.1.0 and 1.2.1 from this port's analysis of main;
|
||||
// 1.4.3 from MacNativeGames' scripts/verify_boot.py) and of the first nvnBootstrapLoader call, per game version.
|
||||
#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.2.1: counted in the modules; 1.4.3: DT_INIT_ARRAYSZ); MacNativeGames' boot check expects
|
||||
// the same.
|
||||
// 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.
|
||||
typedef struct { const char *name; uint64_t entries; } InitCount;
|
||||
static const InitCount inits_110[] = {{"main", 10668}, {"subsdk0", 45}, {"sdk", 116}};
|
||||
static const InitCount inits_121[] = {{"main", 10673}, {"subsdk0", 45}, {"sdk", 116}};
|
||||
static const InitCount inits_143[] = {{"main", 10717}, {"subsdk0", 45}, {"sdk", 83}};
|
||||
#define expected_inits (RT_V143 ? inits_143 : inits_121)
|
||||
#define expected_inits (RT_V143 ? inits_143 : RT_V110 ? inits_110 : inits_121)
|
||||
|
||||
static volatile LONG inits_done, checkpoint_seen;
|
||||
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) {
|
||||
@@ -71,21 +78,34 @@ static void cb_loader_ready(Cpu *c) {
|
||||
// DT_INIT registers the module with musl (__nnmusl_init_dso) and runs its init_array; the constructor flag reads 2
|
||||
// afterwards (MacNativeGames loader.c:458-462).
|
||||
static void cb_module_inits(Cpu *c) {
|
||||
if (InterlockedCompareExchange(&inits_done, 0, 0)) rt_fatal("boot: module constructors requested twice");
|
||||
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);
|
||||
}
|
||||
InterlockedExchange(&inits_done, 1);
|
||||
plat_xchg32(&inits_done, 1);
|
||||
}
|
||||
|
||||
static void cb_module_finis(Cpu *c) {
|
||||
@@ -96,8 +116,11 @@ static void cb_module_finis(Cpu *c) {
|
||||
// ---- checkpoints (host.h)
|
||||
static void stats_line(void) {
|
||||
RtStats s = rt_stats();
|
||||
rt_logf("boot: passed (%llu SVCs, %llu threads, %llu host calls)\n", (unsigned long long)s.svcs,
|
||||
(unsigned long long)s.threads, (unsigned long long)s.host_calls);
|
||||
if (rt_trace & (RT_TRACE_HOSTCALL | RT_TRACE_HOSTCOUNT)) // counted only then (hostfn.c hostfn_entry)
|
||||
rt_logf("boot: passed (%llu SVCs, %llu threads, %llu host calls)\n", (unsigned long long)s.svcs,
|
||||
(unsigned long long)s.threads, (unsigned long long)s.host_calls);
|
||||
else
|
||||
rt_logf("boot: passed (%llu SVCs, %llu threads)\n", (unsigned long long)s.svcs, (unsigned long long)s.threads);
|
||||
}
|
||||
|
||||
void rt_boot_event(const char *what, Cpu *c, const char *detail) {
|
||||
@@ -109,12 +132,13 @@ void rt_boot_event(const char *what, Cpu *c, const char *detail) {
|
||||
if (ret != main_mod->base + CHECKPOINT_RET)
|
||||
rt_fatal("boot: checkpoint %s reached from %s, expected main+%#llx", detail, at,
|
||||
(unsigned long long)CHECKPOINT_RET);
|
||||
if (!InterlockedCompareExchange(&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)
|
||||
if (!plat_cas32(&inits_done, 0, 0)) rt_fatal("boot: checkpoint %s before DT_INIT", detail);
|
||||
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)));
|
||||
InterlockedExchange(&checkpoint_seen, 1);
|
||||
plat_xchg32(&checkpoint_seen, 1);
|
||||
rt_logf("boot: checkpoint %s from main+%#llx\n", detail, (unsigned long long)(ret - main_mod->base));
|
||||
return;
|
||||
}
|
||||
@@ -122,7 +146,7 @@ void rt_boot_event(const char *what, Cpu *c, const char *detail) {
|
||||
if (ret != main_mod->base + NVN_RET)
|
||||
rt_fatal("boot: first NVN call %s(\"%s\") from %s, expected main+%#llx", "nvnBootstrapLoader", detail, at,
|
||||
(unsigned long long)NVN_RET);
|
||||
if (!InterlockedCompareExchange(&checkpoint_seen, 0, 0))
|
||||
if (!plat_cas32(&checkpoint_seen, 0, 0))
|
||||
rt_fatal("boot: first NVN call before the SetFocusHandlingMode checkpoint");
|
||||
rt_logf("boot: first NVN call nvnBootstrapLoader(\"%s\") from main+%#llx\n", detail,
|
||||
(unsigned long long)(ret - main_mod->base));
|
||||
@@ -131,7 +155,7 @@ void rt_boot_event(const char *what, Cpu *c, const char *detail) {
|
||||
stats_line();
|
||||
fflush(stdout);
|
||||
fflush(stderr);
|
||||
_exit(0); // other guest threads are still running; nothing of theirs needs an orderly end
|
||||
plat_exit(0); // other guest threads are still running; nothing of theirs needs an orderly end
|
||||
}
|
||||
rt_fatal("boot: unknown boot event %s (%s) from %s", what, detail ? detail : "", at);
|
||||
}
|
||||
@@ -241,7 +265,7 @@ static void series_shot(const tex_t *t, uint64_t n) {
|
||||
step = (unsigned long long)(ws * 1e6), next = lo;
|
||||
else if (!e || sscanf(e, "%llu-%llu:%llu", &lo, &hi, &step) != 3 || !step) hi = 0;
|
||||
dir = cfg_get("TOTK_SHOTS_DIR") ? cfg_get("TOTK_SHOTS_DIR") : ".";
|
||||
if (hi) CreateDirectoryA(dir, NULL);
|
||||
if (hi) plat_file_mkdir_p(dir);
|
||||
parsed = 1;
|
||||
}
|
||||
if (world) { // the first present at or after each step of the world clock
|
||||
@@ -275,7 +299,7 @@ static void series_shot(const tex_t *t, uint64_t n) {
|
||||
for (int c = 0; c < 4; c++) o[c] = (uint8_t)(sum[bgra && c != 3 ? 2 - c : c] / k);
|
||||
o[3] = 255;
|
||||
}
|
||||
char path[MAX_PATH];
|
||||
char path[PLAT_PATH_MAX];
|
||||
snprintf(path, sizeof path, "%s/f%05llu.png", dir, (unsigned long long)n);
|
||||
rt_write_png(path, out, ow, oh);
|
||||
free(out);
|
||||
@@ -302,9 +326,10 @@ void rt_frame_presented(const tex_t *t, uint64_t n) {
|
||||
fflush(stderr);
|
||||
fs_save_flush();
|
||||
vk_pipeline_save(); // no-op without the Vulkan back end
|
||||
playtime_save();
|
||||
prof_write();
|
||||
fflush(stderr);
|
||||
_exit(0);
|
||||
plat_exit(0);
|
||||
}
|
||||
|
||||
// ---- steps 9-14
|
||||
@@ -321,41 +346,57 @@ static void guest_main(Cpu *c) {
|
||||
rt_fatal("boot: nn::init::Start returned");
|
||||
}
|
||||
|
||||
static DWORD WINAPI prewarm_main(void *arg) {
|
||||
static void prewarm_main(void *arg) {
|
||||
(void)arg;
|
||||
vk_pipeline_prewarm();
|
||||
const char *prep = cfg_get("TOTK_TEST_PREPARE_SHADERS"); // Task 2.3 test hook; Task 2.6 builds the preparation
|
||||
if (prep && !strcmp(prep, "1")) {
|
||||
int cpus = (int)GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
|
||||
int cpus = (int)plat_cpu_usable();
|
||||
gfx_shader_prepare_recorded(cpus, cpus / 2 > 16 ? 16 : cpus / 2 < 1 ? 1 : cpus / 2);
|
||||
}
|
||||
return 0;
|
||||
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.
|
||||
HANDLE warm = CreateThread(NULL, 0, prewarm_main, NULL, 0, NULL);
|
||||
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
|
||||
frame_step_init();
|
||||
gameplay_tweaks_init();
|
||||
res_init();
|
||||
cheats_init(); // after the patch sets: a cheat's set follows its setting
|
||||
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();
|
||||
ULONGLONG held = GetTickCount64();
|
||||
if (warm) WaitForSingleObject(warm, INFINITE), CloseHandle(warm);
|
||||
uint64_t held = plat_now_ms();
|
||||
if (warm) plat_thread_join(warm);
|
||||
else vk_pipeline_prewarm();
|
||||
held = GetTickCount64() - held;
|
||||
FILETIME created, x0, x1, x2, now;
|
||||
GetProcessTimes(GetCurrentProcess(), &created, &x0, &x1, &x2);
|
||||
GetSystemTimeAsFileTime(&now);
|
||||
ULARGE_INTEGER c = {.LowPart = created.dwLowDateTime, .HighPart = created.dwHighDateTime},
|
||||
n = {.LowPart = now.dwLowDateTime, .HighPart = now.dwHighDateTime};
|
||||
held = plat_now_ms() - held;
|
||||
rt_log("boot: guest starts %llu ms after process start (%llu ms of it waiting for the prewarm)",
|
||||
(unsigned long long)((n.QuadPart - c.QuadPart) / 10000), (unsigned long long)held);
|
||||
(unsigned long long)(plat_process_uptime_ns() / 1000000), (unsigned long long)held);
|
||||
rt_guest_start_ns = kern_now_ns();
|
||||
kern_run_on_guest_main(guest_main);
|
||||
rt_fatal("boot: the guest main thread ended");
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// Camera speed: TOTK_STICK_SENS (0.1 to 3, default 1, read at start) multiplies the game's own right-stick camera speeds.
|
||||
// The game's Options menu offers five camera sensitivities, Very Low to Very High; their turn rates are the array
|
||||
// StickSensitivity {0.8, 1.2, 1.6, 2.0, 2.4} in Component/PlayerCameraParam/PlayerCamera.game__component__
|
||||
// PlayerCameraParam.bgyml inside Pack/Actor/PlayerCamera.pack.zs. romfs.c serves a copy of that pack with every entry
|
||||
// multiplied (cam_pack_build), so the setting raises the camera's top speed as well as its speed at a partial tilt, at
|
||||
// any of the five sensitivities. The mouse camera reaches the game as a right-stick deflection (input.c, mouse_camera),
|
||||
// which divides it by the same factor (cam_speed_applied), so TOTK_MOUSE_SENS alone sets the mouse's speed.
|
||||
//
|
||||
// The pack is a SARC archive compressed with the dictionary pack.zsdic of Pack/ZsDic.pack.zs. A float in a BYML array
|
||||
// is stored in the array itself, so the multiplied values take the bytes of the old ones and no offset moves.
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <zstd.h>
|
||||
|
||||
#include "cfg.h"
|
||||
#include "host.h"
|
||||
|
||||
#define MEMBER "Component/PlayerCameraParam/PlayerCamera.game__component__PlayerCameraParam.bgyml"
|
||||
#define MAX_RAW (64u << 20)
|
||||
|
||||
static float applied = 1.0f;
|
||||
|
||||
float cam_speed_wanted(void) {
|
||||
double v = cfg_double("TOTK_STICK_SENS");
|
||||
return (float)(v < 0.1 ? 0.1 : v > 3 ? 3 : v);
|
||||
}
|
||||
|
||||
float cam_speed_applied(void) { return applied; }
|
||||
|
||||
static int u32_at(const uint8_t *p, size_t n, size_t off, uint32_t *v) {
|
||||
if (off > n || n - off < 4) return 0;
|
||||
memcpy(v, p + off, 4);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// SARC member `name` of the archive p[0..n): its start and size; 0 when it is not there.
|
||||
static int sarc_member(const uint8_t *p, size_t n, const char *name, size_t *at, size_t *size) {
|
||||
uint32_t data;
|
||||
uint16_t head, count, bom;
|
||||
if (n < 0x14 || memcmp(p, "SARC", 4)) return 0;
|
||||
memcpy(&head, p + 4, 2);
|
||||
memcpy(&bom, p + 6, 2);
|
||||
if (bom != 0xfeff || !u32_at(p, n, 12, &data) || head + 12u > n || memcmp(p + head, "SFAT", 4)) return 0;
|
||||
memcpy(&count, p + head + 6, 2);
|
||||
size_t names = head + 12 + (size_t)count * 16;
|
||||
if (names + 8 > n || memcmp(p + names, "SFNT", 4)) return 0;
|
||||
names += 8;
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
uint32_t attr, lo, hi;
|
||||
size_t e = head + 12 + (size_t)i * 16;
|
||||
if (!u32_at(p, n, e + 4, &attr) || !u32_at(p, n, e + 8, &lo) || !u32_at(p, n, e + 12, &hi)) return 0;
|
||||
size_t s = names + (size_t)(attr & 0xffffff) * 4, len = strlen(name);
|
||||
if (!(attr >> 24) || s + len + 1 > n || memcmp(p + s, name, len + 1)) continue;
|
||||
if (lo > hi || data + (size_t)hi > n) return 0;
|
||||
*at = data + lo;
|
||||
*size = hi - lo;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The StickSensitivity floats of the BYML p[0..n), multiplied by k; their count, 0 when the file has no such array.
|
||||
static int scale_sensitivity(uint8_t *p, size_t n, float k, float was[8]) {
|
||||
uint32_t keys, root, head;
|
||||
if (n < 16 || memcmp(p, "YB", 2) || !u32_at(p, n, 4, &keys) || !u32_at(p, n, 12, &root) ||
|
||||
!u32_at(p, n, root, &head) || (head & 0xff) != 0xc1 || !u32_at(p, n, keys, &head) || (head & 0xff) != 0xc2)
|
||||
return 0;
|
||||
uint32_t nkeys = head >> 8;
|
||||
if (!u32_at(p, n, root, &head)) return 0;
|
||||
for (uint32_t i = 0; i < head >> 8; i++) {
|
||||
uint32_t e, at, arr, ah;
|
||||
if (!u32_at(p, n, root + 4 + 8 * (size_t)i, &e) || (e & 0xffffff) >= nkeys ||
|
||||
!u32_at(p, n, keys + 4 + 4 * (size_t)(e & 0xffffff), &at))
|
||||
return 0;
|
||||
const char *name = (const char *)p + keys + at;
|
||||
if (keys + at + sizeof "StickSensitivity" > n || strcmp(name, "StickSensitivity")) continue;
|
||||
if (e >> 24 != 0xc0 || !u32_at(p, n, root + 8 + 8 * (size_t)i, &arr) || !u32_at(p, n, arr, &ah) ||
|
||||
(ah & 0xff) != 0xc0)
|
||||
return 0;
|
||||
uint32_t count = ah >> 8;
|
||||
size_t vals = arr + 4 + ((count + 3) & ~3u);
|
||||
if (!count || count > 8 || vals + 4 * (size_t)count > n) return 0;
|
||||
for (uint32_t j = 0; j < count; j++)
|
||||
if (p[arr + 4 + j] != 0xd2) return 0;
|
||||
for (uint32_t j = 0; j < count; j++) {
|
||||
float v;
|
||||
memcpy(&v, p + vals + 4 * j, 4);
|
||||
was[j] = v;
|
||||
v *= k;
|
||||
memcpy(p + vals + 4 * j, &v, 4);
|
||||
}
|
||||
return (int)count;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int cam_pack_build(const void *in, size_t n, const void *zsdic, size_t zsdic_n, void **out, size_t *out_n) {
|
||||
float k = cam_speed_wanted();
|
||||
*out = NULL;
|
||||
if (k == 1.0f) return 0;
|
||||
int ok = 0;
|
||||
uint8_t *dics = NULL, *raw = NULL;
|
||||
ZSTD_DDict *dd = NULL;
|
||||
ZSTD_CDict *cd = NULL;
|
||||
void *z = NULL;
|
||||
// The dictionaries: Pack/ZsDic.pack.zs is a SARC compressed without one.
|
||||
unsigned long long dn = ZSTD_getFrameContentSize(zsdic, zsdic_n);
|
||||
size_t dic_at, dic_n;
|
||||
if (dn == ZSTD_CONTENTSIZE_UNKNOWN || dn == ZSTD_CONTENTSIZE_ERROR || dn > MAX_RAW || !(dics = malloc((size_t)dn)) ||
|
||||
ZSTD_decompress(dics, (size_t)dn, zsdic, zsdic_n) != dn ||
|
||||
!sarc_member(dics, (size_t)dn, "pack.zsdic", &dic_at, &dic_n)) {
|
||||
rt_log("camera speed: no pack.zsdic in Pack/ZsDic.pack.zs; the camera keeps its own speed");
|
||||
goto done;
|
||||
}
|
||||
unsigned long long rn = ZSTD_getFrameContentSize(in, n);
|
||||
unsigned id = ZSTD_getDictID_fromFrame(in, n);
|
||||
dd = ZSTD_createDDict(dics + dic_at, dic_n);
|
||||
if (!dd || id != ZSTD_getDictID_fromDDict(dd) || rn == ZSTD_CONTENTSIZE_UNKNOWN ||
|
||||
rn == ZSTD_CONTENTSIZE_ERROR || rn > MAX_RAW || !(raw = malloc((size_t)rn))) {
|
||||
rt_log("camera speed: Pack/Actor/PlayerCamera.pack.zs is not a pack.zsdic frame with a size; the camera keeps its "
|
||||
"own speed");
|
||||
goto done;
|
||||
}
|
||||
ZSTD_DCtx *dctx = ZSTD_createDCtx();
|
||||
size_t got = dctx ? ZSTD_decompress_usingDDict(dctx, raw, (size_t)rn, in, n, dd) : 0;
|
||||
ZSTD_freeDCtx(dctx);
|
||||
size_t at, size;
|
||||
float was[8];
|
||||
int count = !ZSTD_isError(got) && got == rn && sarc_member(raw, (size_t)rn, MEMBER, &at, &size)
|
||||
? scale_sensitivity(raw + at, size, k, was) : 0;
|
||||
if (!count) {
|
||||
rt_log("camera speed: no StickSensitivity array in %s; the camera keeps its own speed", MEMBER);
|
||||
goto done;
|
||||
}
|
||||
cd = ZSTD_createCDict(dics + dic_at, dic_n, 9);
|
||||
size_t cap = ZSTD_compressBound((size_t)rn), zn = 0;
|
||||
ZSTD_CCtx *cctx = cd ? ZSTD_createCCtx() : NULL;
|
||||
if (cctx && (z = malloc(cap))) zn = ZSTD_compress_usingCDict(cctx, z, cap, raw, (size_t)rn, cd);
|
||||
ZSTD_freeCCtx(cctx);
|
||||
if (!z || !zn || ZSTD_isError(zn)) goto done;
|
||||
*out = z;
|
||||
*out_n = zn;
|
||||
z = NULL;
|
||||
ok = 1;
|
||||
rt_log("camera speed: x%.2f, StickSensitivity %.2f %.2f %.2f %.2f %.2f -> %.2f %.2f %.2f %.2f %.2f", k, was[0],
|
||||
count > 1 ? was[1] : 0, count > 2 ? was[2] : 0, count > 3 ? was[3] : 0, count > 4 ? was[4] : 0, was[0] * k,
|
||||
count > 1 ? was[1] * k : 0, count > 2 ? was[2] * k : 0, count > 3 ? was[3] * k : 0,
|
||||
count > 4 ? was[4] * k : 0);
|
||||
done:
|
||||
free(z);
|
||||
free(raw);
|
||||
free(dics);
|
||||
ZSTD_freeDDict(dd);
|
||||
ZSTD_freeCDict(cd);
|
||||
return ok;
|
||||
}
|
||||
|
||||
void cam_pack_served(void) { applied = cam_speed_wanted(); }
|
||||
+356
-58
@@ -7,12 +7,14 @@
|
||||
// cfg_get handed out stays valid) and cfg_save writes only the changed keys back, keeping the rest of the file.
|
||||
// Readers take no lock: an entry is complete before n_entries counts it, and value pointers are swapped atomically.
|
||||
#include <ctype.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "cfg.h"
|
||||
#include "host.h"
|
||||
#include "input_map.h"
|
||||
#include "platform/platform.h"
|
||||
|
||||
#define PREFIX "TOTK_"
|
||||
@@ -28,58 +30,101 @@ static PlatMutex set_lock = PLAT_MUTEX_INIT; // cfg_set, cfg_reset, cfg_save
|
||||
static int save_ok = 1; // the last cfg_save_to wrote (or had nothing to write)
|
||||
|
||||
// Every name the runtime reads (and the patch sets in generated/), without the prefix. A file key outside this list is
|
||||
// logged as unknown. A new variable goes here too, or its ini key logs a harmless "unknown key" line.
|
||||
// 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", "APP_POOL", "ASPECT", "ASPECT_PATCH", "ASSUME_FOCUS", "ASTC", "ASTC_BC", "ASTC_TIME", "ASYNC_PREEMPT", "AUDIO", "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_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y",
|
||||
"BIND_ZL", "BIND_ZR", "BLOCK_VIEWS_3D", "CLOTH_REALTIME", "CORE_DIAG", "CRIT", "CRIT_OUT", "DESC_TEMPLATE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG",
|
||||
"EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS",
|
||||
"FLIGHT_THUMBS", "FPS60", "FPS_LIMIT", "FREEZE_IDLE", "FREE_CORES", "FULLSCREEN", "GPL", "GPL_DRAW_BUILD", "GPU",
|
||||
"GPU_INDEX", "GPU_NAME", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD",
|
||||
"LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "MEMORY", "MENU_LANG", "MENU_TEST",
|
||||
"MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MOTION", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE",
|
||||
"ONE_PER_CORE", "OPERATION_MODE", "OUTPUT_RES", "PAD_LAYOUT", "PATCH_OUTPUT", "PATCH_SCENE", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT",
|
||||
"PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES",
|
||||
"PROFILE_MAIN", "PROFILE_RENDER", "PUSH_SKIP", "PUSH_STAGE", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_END", "REEXEC",
|
||||
"RENDER_SCALE", "REPLAY_ASYNC",
|
||||
"REPLAY_CHECK", "RESOLVE_CHECK", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
|
||||
"ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SHADER_CACHE",
|
||||
"SHADER_MEMO", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "SWKBD_ANSWER",
|
||||
"SWKBD_TEST", "TEST_PAD", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "UBO_SNAPSHOT", "UPSCALER", "VK_DYN_VERTEX", "VK_NO_FLOAT64",
|
||||
"VK_PRESENT", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VOLUME", "VRAM_HEADROOM", "VS_OUTS",
|
||||
"WB_FENCE_LIMIT", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_PROCS", "ZSTD_CHECK", "ZSTD_NATIVE",
|
||||
"BIND_SHAKE",
|
||||
"BIND_INC", "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y",
|
||||
"BIND_ZL", "BIND_ZR", "BARRIER_MERGE", "BLOCK_VIEWS_3D", "CLIMB_FIX", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA",
|
||||
"COLOR_PRESET", "COLOR_SATURATION", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT",
|
||||
"DESC_TEMPLATE", "DESWIZZLE", "DEVICE_PROFILE", "DIALOGUE_CLICK", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_CAM_JITTER", "DLAA_EFFECTS_AFTER", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_FIXED_EXPOSURE", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR",
|
||||
"DUMP_LOG", "DYNAMIC_RES", "DYN_DELTA", "EXEFS", "FEEDBACK", "FG_DEBUG", "FG_OBJECTS", "FG_SHOT", "FG_SHOT_DIR", "FG_TEST", "FG_TIMES", "FIXED_RES_PATCH", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES",
|
||||
"FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FLUSH_SPAN", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FRAME_GEN", "FRAME_QUEUE", "FREECAM_KEY", "FREECAM_PAD", "FREECAM_PATCH",
|
||||
"FREEZE_IDLE", "FREE_CORES", "FSR3_DEBUG", "FSR3_VIEW", "FSR_SHARPNESS",
|
||||
"FULLSCREEN", "FXAA",
|
||||
"GAMEPLAY_DISTANCE_SENSITIVITY", "GAMEPLAY_ITEM_AD", "GAMEPLAY_ITEM_SENSITIVITY", "GAMEPLAY_ITEM_WHEEL",
|
||||
"GAMEPLAY_MAP_ZOOM", "GAMEPLAY_MAP_ZOOM_SENSITIVITY", "GAMEPLAY_ROTATION_SENSITIVITY", "GAMEPLAY_TWEAKS_ENABLED",
|
||||
"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_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_NO_CODE", "MODS_ORDER", "MODS_REBUILD", "MODS_WITHOUT_CODE", "MOTION", "MOUSE_AIM_SCALE", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_ASPECT", "MOVIE_HOST", "MOVIE_PACE",
|
||||
"MVOBJ_ALL", "MVOBJ_BANKS", "MVOBJ_EQUAL", "MVOBJ_EXACT", "MVOBJ_EXEC", "MVOBJ_NOC4", "MVOBJ_ONLY", "MVOBJ_TIMES", "MVPREV_CHECK", "MVPREV_GROW", "MVPREV_SKIP", "MVPREV_TRUST", "MV_CHECK",
|
||||
"MV_SURVEY",
|
||||
"ONE_PER_CORE", "OPERATION_MODE", "OPTREF_GUARD", "OUTPUT_RES", "PAD_LAYOUT", "PASS_CRUMBS", "PATCH_OUTPUT", "PATCH_SCENE", "PCORE", "PCSS", "PCSS_K", "PERF_CENSUS", "PERF_OVERLAY", "PERF_SLOW_MS", "PIPELINE_CACHE", "PIPE_MEMO", "PIPE_PREBUILD", "PIPE_SKIP", "PIPE_SYNC", "PIPE_WAIT", "PLUGIN_TICK_OFFSET", "PLUGIN_TRACE", "POINTER_IMAGE",
|
||||
"PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_BENCH", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES",
|
||||
"PROFILE_MAIN", "PROFILE_RENDER", "PROMPTS", "PUSH_SKIP", "PUSH_STAGE", "QUICKLOAD_KEY", "QUICKSAVE", "QUICKSAVE_KEY", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_ASYNC", "REC_END", "REC_SPIN_US", "REEXEC", "REFLEX",
|
||||
"RENDER_SCALE", "REPLAY_ASYNC", "REPLAY_CHUNKS", "REPLAY_CHUNK_DRAWS", "REPLAY_SKEW_US", "REPLAY_STATE_CHECK", "REPLAY_WORKERS",
|
||||
"REPLAY_CHECK", "REPORT_GUARD", "RESOLVE_CHECK", "RESTART_WAIT", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
|
||||
"ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RSTICK_DEADZONE", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SCENE_UPSCALER", "SHADER_CACHE",
|
||||
"SHADER_MEMO", "SHADOW", "SHADOW_DEFER", "SHADOW_RANGE", "SHADOW_RES", "SHADOW_SCALE", "SHADOW_SNAP", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHUTTER_FIX",
|
||||
"SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "STICK_SENS",
|
||||
"SWKBD_ANSWER", "SYNC_AHEAD",
|
||||
"SWKBD_TEST", "TEST_OOM", "TEST_PAD", "TEST_PAD_RUMBLE_MS", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_BLOCK_MIB", "TEX_HEAP_EXTRA_MB", "TEX_MEMO", "TEX_RELEASED_MIB", "TEX_VRAM_PRESSURE", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "UB_OVERLAY", "UB_OVERLAY_OUT", "UPSCALER", "VB_USED", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NO_FLOAT64",
|
||||
"VK_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",
|
||||
};
|
||||
|
||||
// The totk.ini section a key cfg_set may write goes to when the file lacks it (totk.ini.example's sections).
|
||||
static const struct { const char *key, *section; } sections[] = {
|
||||
{"FPS_LIMIT", "frame rate"}, {"FPS60", "frame rate"},
|
||||
{"FPS_LIMIT", "frame rate"}, {"FPS60", "frame rate"}, {"FRAME_QUEUE", "frame rate"}, {"FRAME_GEN", "frame rate"},
|
||||
{"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"},
|
||||
{"CLIMB_FIX", "frame rate"}, {"AUDIO_DRAIN_FIX", "frame rate"}, {"SHUTTER_FIX", "frame rate"},
|
||||
{"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"},
|
||||
{"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"},
|
||||
{"SHARPNESS", "display"}, {"ASPECT", "display"},
|
||||
{"MENU_LANG", "language"}, {"LANG", "language"}, {"OPERATION_MODE", "language"},
|
||||
{"VOLUME", "audio"},
|
||||
{"MOTION", "input"}, {"RUMBLE_STRENGTH", "input"}, {"RUMBLE_CURVE", "input"}, {"RUMBLE_TRIGGERS", "input"},
|
||||
{"PAD_LAYOUT", "input"}, {"STICK_DEADZONE", "input"}, {"MOUSE_SENS", "input"}, {"INPUT_RECORD", "input"},
|
||||
{"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"},
|
||||
{"SCENE_UPSCALER", "display"}, {"DLAA", "display"}, {"DLSS", "display"}, {"FSR_SHARPNESS", "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_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"}, {"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"}, {"QUICKSAVE", "input"}, {"QUICKSAVE_KEY", "input"}, {"QUICKLOAD_KEY", "input"}, {"MOUSE_MODE", "input"}, {"MOUSE_SENS", "input"}, {"MOUSE_AIM_SCALE", "input"}, {"WALK_KEY", "input"}, {"WALK_SCALE", "input"}, {"FREECAM_PATCH", "input"}, {"FREECAM_PAD", "input"}, {"FREECAM_KEY", "input"}, {"INPUT_RECORD", "input"},
|
||||
{"BIND_A", "input"}, {"BIND_B", "input"}, {"BIND_X", "input"}, {"BIND_Y", "input"}, {"BIND_LCLICK", "input"},
|
||||
{"BIND_RCLICK", "input"}, {"BIND_L", "input"}, {"BIND_R", "input"}, {"BIND_ZL", "input"}, {"BIND_ZR", "input"},
|
||||
{"BIND_PLUS", "input"}, {"BIND_MINUS", "input"}, {"BIND_LEFT", "input"}, {"BIND_UP", "input"},
|
||||
{"BIND_RIGHT", "input"}, {"BIND_DOWN", "input"}, {"BIND_LSTICK_LEFT", "input"}, {"BIND_LSTICK_UP", "input"},
|
||||
{"BIND_LSTICK_RIGHT", "input"}, {"BIND_LSTICK_DOWN", "input"}, {"BIND_RSTICK_LEFT", "input"},
|
||||
{"BIND_RSTICK_UP", "input"}, {"BIND_RSTICK_RIGHT", "input"}, {"BIND_RSTICK_DOWN", "input"},
|
||||
{"ASYNC_PREEMPT", "performance"}, {"REPLAY_ASYNC", "performance"}, {"FREE_CORES", "performance"},
|
||||
{"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"}, {"ASTC_BC", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"},
|
||||
{"BIND_SKIP", "performance"}, {"SHADER_MEMO", "performance"}, {"PIPE_MEMO", "performance"}, {"TEX_MEMO", "performance"}, {"DESC_TEMPLATE", "performance"},
|
||||
{"PUSH_SKIP", "performance"}, {"SPLIT_DRAWS", "performance"}, {"SPLIT_US", "performance"}, {"VK_VALIDATION", "performance"},
|
||||
{"VK_DYN_VERTEX", "performance"}, {"VK_SUBGROUP_PIN", "performance"},
|
||||
{"TRACE", "diagnostics"}, {"FLIGHT", "diagnostics"}, {"FLIGHT_SPIKE_MS", "diagnostics"},
|
||||
{"WB_FENCE_LIMIT", "diagnostics"},
|
||||
{"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"}, {"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"},
|
||||
{"GAMEPLAY_MAP_ZOOM", "gameplay tweaks"}, {"GAMEPLAY_MAP_ZOOM_SENSITIVITY", "gameplay tweaks"},
|
||||
{"GAMEPLAY_ROTATION_SENSITIVITY", "gameplay tweaks"}, {"GAMEPLAY_DISTANCE_SENSITIVITY", "gameplay tweaks"},
|
||||
{"GAMEPLAY_ITEM_SENSITIVITY", "gameplay tweaks"},
|
||||
{"GAMEPLAY_WEAPON_WHEEL", "gameplay tweaks"}, {"GAMEPLAY_WEAPON_SENSITIVITY", "gameplay tweaks"},
|
||||
};
|
||||
|
||||
// The settings the menu shows: the value in effect when the key is unset, and what the key accepts. The only place a
|
||||
@@ -93,49 +138,121 @@ 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},
|
||||
{"ASPECT", "fit", "fit|stretch", LIVE},
|
||||
{"SCENE_UPSCALER", "off", "off|dlss|fsr3", RESTART}, {"DLAA", "0", "0|1", RESTART},
|
||||
{"DLSS", "dlaa", "dlaa|quality|balanced|performance|ultra_performance", LIVE},
|
||||
{"FSR_SHARPNESS", "80", "0..100", LIVE}, // vk_dlaa.c fsr_evaluate
|
||||
{"DLSS_PRESET", "default", "default|k|j", LIVE}, {"DLSS_FIXED_EXPOSURE", "0", "0|1", LIVE}, {"DLAA_EFFECTS_AFTER", "0", "0|1", LIVE},
|
||||
{"DLSS_CHAR_MASK", "65", "0|35|65|100", LIVE}, {"REFLEX", "off", "off|on|boost", RESTART}, {"FXAA", "1", "0|1", LIVE},
|
||||
{"LOD_STEADY", "0", "0|1", RESTART}, // sets steady
|
||||
{"ASPECT", "fit", "fit|stretch", LIVE}, {"MOVIE_ASPECT", "keep", "keep|stretch", LIVE}, {"FOV", "100", "70..140", LIVE},
|
||||
{"ANISO", "game", "game|2|4|8|16", RESTART}, // vk_texture.c sampler_features
|
||||
// colour adjustment (vk_color.c); the preset is the menu's, the four values are what the present uses
|
||||
{"COLOR_PRESET", "default", "default|vivid|clarity|custom", LIVE}, {"COLOR_BRIGHTNESS", "0", "-30..30", LIVE},
|
||||
{"COLOR_CONTRAST", "100", "70..150", LIVE}, {"COLOR_SATURATION", "100", "50..200", LIVE},
|
||||
{"COLOR_GAMMA", "1", "0.8..1.2", LIVE},
|
||||
// HDR output (vk_hdr.c): on at start (the tonemap shader is swapped as shaders load); the nits apply at once
|
||||
{"HDR", "0", "0|1", RESTART}, {"HDR_PEAK_NITS", "1000", "400..10000", LIVE}, {"HDR_GAME_NITS", "203", "80..500", LIVE},
|
||||
{"HDR_UI_NITS", "203", "80..500", LIVE}, {"HDR_HUE", "70", "0..100", LIVE},
|
||||
{"DEVICE_PROFILE", "auto", "auto|desktop|deck", RESTART},
|
||||
{"SHADOW_RES", "game", "game|256|512|768|1024|1536|2048", RESTART},
|
||||
{"SHADOW_SCALE", "1", "1..4", RESTART},
|
||||
{"SHADOW_RANGE", "100", "50..400", RESTART}, {"GRASS_RANGE", "100", "50..400", RESTART}, {"CONTACT_SHADOWS", "0", "0..100", RESTART},
|
||||
{"PCSS", "0", "0..200", RESTART},
|
||||
// Game
|
||||
{"FPS_LIMIT", "60", "30|60|90|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE},
|
||||
{"FPS_LIMIT", "60", "30|40|45|60|90|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"FRAME_QUEUE", "0", "0|1", LIVE},
|
||||
{"FRAME_GEN", "off", "off|fsr3", LIVE}, // the generator; vk_fg.cpp vk_fg_engine maps it
|
||||
{"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART},
|
||||
{"HIGHFPS_FIX", "1", "0|1", RESTART},
|
||||
{"MODS_REBUILD", "auto", "auto|off", RESTART},
|
||||
{"MODS_WITHOUT_CODE", "0", "0|1", RESTART}, // 1: a mod is used without the code module it cannot run (mods.c)
|
||||
{"HIGHFPS_FIX", "1", "0|1", RESTART}, {"CLIMB_FIX", "1", "0|1", RESTART}, {"AUDIO_DRAIN_FIX", "1", "0|1", RESTART},
|
||||
{"SHUTTER_FIX", "1", "0|1", RESTART},
|
||||
{"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},
|
||||
{"MOTION", "1", "0|1", LIVE}, {"RUMBLE_STRENGTH", "130", "0..300", LIVE}, {"RUMBLE_CURVE", "0.6", "0.2..1.5", LIVE},
|
||||
{"RUMBLE_TRIGGERS", "0", "0|1", LIVE}, {"PAD_LAYOUT", "auto", "auto|nintendo|xbox|xbox_prompts", LIVE},
|
||||
{"STICK_DEADZONE", "8", "0..50", LIVE}, {"MOUSE_SENS", "1", "0..10", LIVE},
|
||||
{"MENU_LANG", "", "en|ru", LIVE},
|
||||
{"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}, {"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|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},
|
||||
{"MOUSE_SENS", "1", "0..10", LIVE}, {"MOUSE_AIM_SCALE", "1", "0.1..3", LIVE}, {"MENU_CURSOR", "1", "0|1", LIVE},
|
||||
{"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},
|
||||
// freecam.c: the patch set of its hook (off: the game's camera code as shipped), then the combo and key that step it
|
||||
{"FREECAM_PATCH", "0", "0|1", RESTART}, {"FREECAM_PAD", "none", NULL, LIVE}, {"FREECAM_KEY", "none", NULL, LIVE},
|
||||
// Gameplay Tweaks
|
||||
{"GAMEPLAY_TWEAKS_ENABLED", "0", "0|1", LIVE},
|
||||
{"GAMEPLAY_ULTRAHAND_ROTATE", "1", "0|1", LIVE}, {"GAMEPLAY_ULTRAHAND_C_AXIS", "1", "0|1", LIVE},
|
||||
{"GAMEPLAY_ULTRAHAND_DISTANCE", "1", "0|1", LIVE}, {"GAMEPLAY_ITEM_WHEEL", "1", "0|1", LIVE},
|
||||
{"GAMEPLAY_ITEM_AD", "1", "0|1", LIVE}, {"GAMEPLAY_MAP_ZOOM", "1", "0|1", LIVE},
|
||||
{"GAMEPLAY_MAP_ZOOM_SENSITIVITY", "1", "0.25..4", LIVE}, {"GAMEPLAY_ROTATION_SENSITIVITY", "1", "0.25..4", LIVE},
|
||||
{"GAMEPLAY_DISTANCE_SENSITIVITY", "1", "0.25..4", LIVE}, {"GAMEPLAY_ITEM_SENSITIVITY", "1", "0.25..4", LIVE},
|
||||
{"GAMEPLAY_WEAPON_WHEEL", "1", "0|1", LIVE}, {"GAMEPLAY_WEAPON_SENSITIVITY", "1", "0.25..4", LIVE},
|
||||
{"MENU_LANG", "", "en|ru|pt-BR|zh-Hans", LIVE},
|
||||
// plat_font_path on Linux: 1 asks fontconfig which file draws the language, 0 keeps the fixed distribution
|
||||
// paths. A rebuild of the atlas reads it, so a change shows on the next window size or language switch.
|
||||
{"MENU_FONT_FONTCONFIG", "1", "0|1", LIVE},
|
||||
{"AMIIBO_DIR", "", NULL, LIVE},
|
||||
// Discord Rich Presence (discord_rpc.c): off by default, the Menu tab of the settings menu switches it.
|
||||
{"DISCORD_RPC", "0", "0|1", LIVE},
|
||||
{"DISCORD_APP_ID", "1567232599846293504", NULL, LIVE},
|
||||
{"DISCORD_IMAGE", "totk_512x512", NULL, LIVE},
|
||||
// Advanced: scheduling
|
||||
{"ASYNC_PREEMPT", "1", "0|1|2", RESTART}, {"REPLAY_ASYNC", "0", "0|1", RESTART},
|
||||
{"REPLAY_WORKERS", "0", "0..16", RESTART}, {"REPLAY_CHUNKS", "0", "0..64", RESTART},
|
||||
{"REPLAY_CHUNK_DRAWS", "128", "1..100000", RESTART}, {"REPLAY_STATE_CHECK", "0", "0|1", RESTART},
|
||||
{"REPLAY_SKEW_US", "0", "0..100000", RESTART},
|
||||
{"SYNC_AHEAD", "0", "0|1|check", RESTART}, {"SHADOW_DEFER", "1", "0|1", RESTART},
|
||||
{"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},
|
||||
{"PIPE_PREBUILD", "1", "0|1", RESTART}, {"PREWARM_XLATE", "", "1..64", RESTART}, {"GPL", "", "0|1", 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},
|
||||
{"TEX_ALIAS", "1", "0|1", RESTART}, {"TEX_VRAM_PRESSURE", "90", "0..100", RESTART}, {"ASTC_BC", "0", "0|1", RESTART}, {"ZSTD_NATIVE", "1", "0|1", RESTART}, {"ZSTD_CHECK", "0", "0|1", RESTART},
|
||||
{"TEX_ALIAS", "1", "0|1", RESTART}, {"TEX_VRAM_PRESSURE", "90", "0..100", RESTART},
|
||||
{"TEX_RELEASED_MIB", "256", "0..65536", RESTART}, {"TEX_BLOCK_MIB", "64", "0..1024", RESTART}, {"VMA_BLOCK_MIB", "64", "0..1024", RESTART}, {"ASTC_BC", "", "0|1", RESTART}, {"ZSTD_NATIVE", "1", "0|1", RESTART}, {"ZSTD_CHECK", "0", "0|1", RESTART},
|
||||
// crash guards: code patch sets (recomp/patches-v*.txt) over game reads that crash on stale data
|
||||
{"OPTREF_GUARD", "1", "0|1", RESTART}, {"ABILITY_GUARD", "1", "0|1", RESTART}, {"REPORT_GUARD", "1", "0|1", RESTART},
|
||||
// render fixes
|
||||
{"LOD_GUARD", "1", "0|1", RESTART}, {"FIX_C0", "1", "0|1", RESTART}, {"FIX_ZERO", "1", "0|1", RESTART},
|
||||
{"BIND_SKIP", "1", "0|1", RESTART}, {"SHADER_MEMO", "1", "0|1", RESTART}, {"PIPE_MEMO", "1", "0|1", RESTART}, {"TEX_MEMO", "1", "0|1", RESTART},
|
||||
{"BIND_SKIP", "1", "0|1", RESTART}, {"SHADER_MEMO", "1", "0|1", RESTART}, {"PIPE_MEMO", "1", "0|1", RESTART}, {"MEMX", "1", "0|1|check", RESTART}, {"BIND_INC", "0", "0|1|check", RESTART}, {"TEX_MEMO", "1", "0|1", RESTART},
|
||||
{"VB_USED", "1", "0|1", RESTART},
|
||||
{"DESC_TEMPLATE", "1", "0|1", RESTART},
|
||||
{"PUSH_SKIP", "1", "0|1", RESTART}, {"SPLIT_DRAWS", "64", "0..1000", RESTART},
|
||||
{"SPLIT_US", "1000", "0..20000", RESTART},
|
||||
// Vulkan
|
||||
{"VK_VALIDATION", "0", "0|1", RESTART}, {"VK_DYN_VERTEX", "", "0|1", RESTART},
|
||||
{"VK_SUBGROUP_PIN", "1", "0|1", RESTART},
|
||||
{"VK_DYN_A2C", "", "0|1", RESTART}, {"VK_SUBGROUP_PIN", "1", "0|1", RESTART},
|
||||
// diagnostics
|
||||
{"TRACE", "", NULL, RESTART}, {"FLIGHT", "0", "0|1", RESTART}, {"FLIGHT_SPIKE_MS", "100", "0..60000", RESTART},
|
||||
{"WB_FENCE_LIMIT", "65536", "0..1073741824", 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},
|
||||
};
|
||||
|
||||
static int is_known(const char *key) {
|
||||
for (size_t i = 0; i < sizeof known / sizeof *known; i++)
|
||||
if (!strcmp(known[i], key)) return 1;
|
||||
return 0;
|
||||
return !strncmp(key, "CHEAT_", 6); // cheats.c and the cheat patch sets (tools/cheats.py)
|
||||
}
|
||||
|
||||
static void clear(void) {
|
||||
@@ -166,11 +283,29 @@ static void add(char *key, char *value, int line) {
|
||||
for (int i = 0; i < n_entries; i++)
|
||||
if (!strcmp(entries[i].key, key)) { // a repeated key: the later line wins
|
||||
free(entries[i].value);
|
||||
entries[i].value = _strdup(value);
|
||||
entries[i].value = strdup(value);
|
||||
return;
|
||||
}
|
||||
if (n_entries == CFG_MAX_KEYS) return;
|
||||
entries[n_entries++] = (CfgEntry){_strdup(key), _strdup(value), 0, 0};
|
||||
entries[n_entries++] = (CfgEntry){strdup(key), strdup(value), 0, 0};
|
||||
}
|
||||
|
||||
// 0.1.9 had the Xbox prompts as a pad layout: pad_layout = xbox_prompts is pad_layout = nintendo with prompts = xbox.
|
||||
// Read as those two, which the menu shows and the next cfg_save writes; a prompts line of the file's own wins. The
|
||||
// value still works from the environment (input_pad_layout_pick, input_prompts_pick).
|
||||
static void migrate(void) {
|
||||
CfgEntry *layout = NULL, *prompts = NULL;
|
||||
for (int i = 0; i < n_entries; i++) {
|
||||
if (!strcmp(entries[i].key, "PAD_LAYOUT")) layout = &entries[i];
|
||||
if (!strcmp(entries[i].key, "PROMPTS")) prompts = &entries[i];
|
||||
}
|
||||
if (!layout || strcasecmp(layout->value, "xbox_prompts")) return;
|
||||
free(layout->value);
|
||||
layout->value = strdup("nintendo");
|
||||
layout->dirty = 1;
|
||||
if (!prompts && n_entries < CFG_MAX_KEYS) entries[n_entries++] = (CfgEntry){strdup("PROMPTS"), strdup("xbox"), 1, 0};
|
||||
rt_log("cfg: totk.ini pad_layout = xbox_prompts is read as pad_layout = nintendo and prompts = %s",
|
||||
prompts ? prompts->value : "xbox");
|
||||
}
|
||||
|
||||
int cfg_load(const char *path) {
|
||||
@@ -196,18 +331,164 @@ int cfg_load(const char *path) {
|
||||
p = eol + 1;
|
||||
}
|
||||
free(data);
|
||||
migrate();
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char *cfg_get(const char *name) {
|
||||
// ---- device profiles: defaults for a known machine, below the environment and totk.ini and above the table, so any
|
||||
// key the player sets wins and resetting a key in the menu returns to the profile's value. TOTK_DEVICE_PROFILE = auto
|
||||
// (default: the Steam Deck when the firmware says so), desktop (none) or deck.
|
||||
//
|
||||
// The Steam Deck (LCD Jupiter, OLED Galileo; 1280x800, 16:10, 4 Zen 2 cores, RDNA 2 with 8 CUs sharing 16 GB): the game
|
||||
// at the screen's 1280x800 with its own 5/6 scene (the aspect patch gives the camera its 16:10, resolution.c, and the
|
||||
// romfs-patches-1280x800 overlay the HUD's);
|
||||
// fullscreen and vsync, as gamescope composes Game Mode; 40 fps, which divides 40 Hz (and 120 Hz on the OLED).
|
||||
// Starting points to replace with measured ones (docs/tester-guide.md, Steam Deck).
|
||||
static const struct { const char *key, *value; } DECK[] = {
|
||||
{"FULLSCREEN", "1"}, {"WINDOW_SIZE", "1280x800"}, {"OUTPUT_RES", "1280x800"}, {"RENDER_SCALE", "game"},
|
||||
{"VK_PRESENT", "fifo"}, {"FPS_LIMIT", "40"},
|
||||
};
|
||||
static int profile = -1; // 0 none, 1 Steam Deck
|
||||
|
||||
static int read_line(const char *path, char *out, size_t n) {
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) return 0;
|
||||
int ok = fgets(out, (int)n, f) != NULL;
|
||||
fclose(f);
|
||||
out[ok ? strcspn(out, "\r\n") : 0] = 0;
|
||||
return ok;
|
||||
}
|
||||
|
||||
// The Steam Deck: Valve's board, product Jupiter or Galileo (/sys/class/dmi/id); SteamDeck=1, which Steam sets on it.
|
||||
static int on_steam_deck(void) {
|
||||
const char *env = getenv("SteamDeck");
|
||||
if (env && !strcmp(env, "1")) return 1;
|
||||
char vendor[64], product[64];
|
||||
return read_line("/sys/class/dmi/id/board_vendor", vendor, sizeof vendor) && !strcmp(vendor, "Valve") &&
|
||||
read_line("/sys/class/dmi/id/product_name", product, sizeof product) &&
|
||||
(!strcmp(product, "Jupiter") || !strcmp(product, "Galileo"));
|
||||
}
|
||||
|
||||
static const char *raw_get(const char *name);
|
||||
|
||||
static int profile_of(void) {
|
||||
int p = __atomic_load_n(&profile, __ATOMIC_ACQUIRE);
|
||||
if (p >= 0) return p;
|
||||
const char *set = raw_get(PREFIX "DEVICE_PROFILE");
|
||||
if (set && !strcmp(set, "deck")) p = 1;
|
||||
else if (set && *set && strcmp(set, "auto")) p = 0;
|
||||
else p = on_steam_deck();
|
||||
__atomic_store_n(&profile, p, __ATOMIC_RELEASE);
|
||||
return p;
|
||||
}
|
||||
|
||||
const char *cfg_device_profile(void) { return profile_of() ? "deck" : "desktop"; }
|
||||
|
||||
static const char *raw_get(const char *name) {
|
||||
const char *e = getenv(name);
|
||||
if (e || strncmp(name, PREFIX, PREFIX_LEN)) return e;
|
||||
int n = __atomic_load_n(&n_entries, __ATOMIC_ACQUIRE);
|
||||
for (int i = 0; i < n; i++)
|
||||
if (!_stricmp(entries[i].key, name + PREFIX_LEN)) return __atomic_load_n(&entries[i].value, __ATOMIC_ACQUIRE);
|
||||
if (!strcasecmp(entries[i].key, name + PREFIX_LEN)) return __atomic_load_n(&entries[i].value, __ATOMIC_ACQUIRE);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// ---- the screen's shape (desktop): a primary display of another shape than 16:9 gives output_res a default of that
|
||||
// shape while neither the environment nor totk.ini sets it, so the first start fills the screen instead of a 16:9
|
||||
// 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, 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.
|
||||
static const unsigned SHAPED[][2] = {
|
||||
{2560, 1080}, {3440, 1440}, {3840, 1600}, {5120, 2160}, // 21:9
|
||||
{3840, 1080}, {5120, 1440}, // 32:9
|
||||
{1280, 800}, {1680, 1050}, {1920, 1200}, {2560, 1600}, // 16:10
|
||||
{1920, 1280}, {2160, 1440}, {2256, 1504}, {2880, 1920}, {3000, 2000}, // 3:2
|
||||
};
|
||||
|
||||
// The folder size of w x h's shape: of SHAPED within 1% of its aspect ratio, the closest, the first of equal ones
|
||||
// (5120x2160 takes 2560x1080). The UI layout depends on the aspect ratio alone (tools/ultrawide_layout.py apply), so
|
||||
// the setup writes one romfs-patches-<w>x<h> per shape, named after this size (installer/screens.py shape_size, the
|
||||
// same rule), and romfs.c overlay_init looks for it. 0 for 16:9 and for a shape without a layout.
|
||||
int cfg_shape_size(unsigned w, unsigned h, unsigned out[2]) {
|
||||
if (!w || !h) return 0;
|
||||
double r = (double)w / h, err = 0;
|
||||
if (fabs(r / (16.0 / 9.0) - 1) <= 0.01) return 0;
|
||||
int best = -1;
|
||||
for (int i = 0; i < (int)(sizeof SHAPED / sizeof *SHAPED); i++) {
|
||||
double e = fabs((double)SHAPED[i][0] / SHAPED[i][1] / r - 1);
|
||||
if (e <= 0.01 && (best < 0 || e < err)) best = i, err = e;
|
||||
}
|
||||
if (best < 0) return 0;
|
||||
out[0] = SHAPED[best][0], out[1] = SHAPED[best][1];
|
||||
return 1;
|
||||
}
|
||||
|
||||
static char screen_res[16]; // set once by cfg_init, "" for none
|
||||
// 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 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 *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) {
|
||||
int sw, sh;
|
||||
if (!plat_screen_size(&sw, &sh)) return;
|
||||
double r = (double)sw / sh;
|
||||
if (fabs(r / (16.0 / 9.0) - 1) <= 0.01) return;
|
||||
int best = -1, fit = -1;
|
||||
for (int i = 0; i < (int)(sizeof SHAPED / sizeof *SHAPED); i++) {
|
||||
unsigned w = SHAPED[i][0], h = SHAPED[i][1];
|
||||
if (fabs((double)w / h / r - 1) > 0.01 || w > (unsigned)sw || h > (unsigned)sh) continue;
|
||||
if (fit < 0 || w > SHAPED[fit][0]) fit = i; // the largest that fits
|
||||
if (h >= 1080 && (best < 0 || w < SHAPED[best][0])) best = i;
|
||||
}
|
||||
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 < 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;
|
||||
if (!profile_of())
|
||||
return screen_res[0] && !strcasecmp(name + PREFIX_LEN, "OUTPUT_RES") && shape_keeps_prompts() ? screen_res
|
||||
: NULL;
|
||||
for (size_t i = 0; i < sizeof DECK / sizeof *DECK; i++)
|
||||
if (!strcasecmp(DECK[i].key, name + PREFIX_LEN)) return DECK[i].value;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Whether name's value comes from the player (the environment or totk.ini), not a profile or the table.
|
||||
int cfg_is_set(const char *name) { return raw_get(name) != NULL; }
|
||||
|
||||
unsigned cfg_version(void) { return __atomic_load_n(&version, __ATOMIC_ACQUIRE); }
|
||||
|
||||
int cfg_from_env(const char *name) { return getenv(name) != NULL; }
|
||||
@@ -222,12 +503,12 @@ void cfg_set(const char *name, const char *value) {
|
||||
while (i < n && strcmp(entries[i].key, key)) i++;
|
||||
if (i < n) {
|
||||
if (!entries[i].value || strcmp(entries[i].value, value)) {
|
||||
__atomic_store_n(&entries[i].value, _strdup(value), __ATOMIC_RELEASE); // the old string stays for readers
|
||||
__atomic_store_n(&entries[i].value, strdup(value), __ATOMIC_RELEASE); // the old string stays for readers
|
||||
entries[i].dirty = 1;
|
||||
}
|
||||
entries[i].removed = 0; // a value set after cfg_reset replaces the line instead of deleting it
|
||||
} else if (n < CFG_MAX_KEYS) {
|
||||
entries[n] = (CfgEntry){_strdup(key), _strdup(value), 1, 0};
|
||||
entries[n] = (CfgEntry){strdup(key), strdup(value), 1, 0};
|
||||
__atomic_store_n(&n_entries, n + 1, __ATOMIC_RELEASE);
|
||||
}
|
||||
__atomic_add_fetch(&version, 1, __ATOMIC_RELEASE);
|
||||
@@ -247,7 +528,7 @@ int cfg_reset(const char *const *keys, int n) {
|
||||
while (i < n_entries && strcmp(entries[i].key, name)) i++;
|
||||
if (i == n_entries) { // no value in memory ("key =" in the file): the line still has to go
|
||||
if (i == CFG_MAX_KEYS) continue;
|
||||
entries[i] = (CfgEntry){_strdup(name), NULL, 0, 1};
|
||||
entries[i] = (CfgEntry){strdup(name), NULL, 0, 1};
|
||||
__atomic_store_n(&n_entries, i + 1, __ATOMIC_RELEASE);
|
||||
} else if (entries[i].value) {
|
||||
__atomic_store_n(&entries[i].value, NULL, __ATOMIC_RELEASE); // the old string stays for readers
|
||||
@@ -394,6 +675,7 @@ static void puts_(Out *o, const char *s) { put(o, s, strlen(s)); }
|
||||
static const char *section_of(const char *key) {
|
||||
for (size_t i = 0; i < sizeof sections / sizeof *sections; i++)
|
||||
if (!strcmp(sections[i].key, key)) return sections[i].section;
|
||||
if (!strncmp(key, "CHEAT_", 6)) return "cheats"; // cheats.c: one key per cheat of the cheat file
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -543,7 +825,7 @@ static int find_ini(void) {
|
||||
if (ini_path[0]) return 1;
|
||||
char path[1024];
|
||||
if (!plat_exe_path(path, sizeof path)) return 0;
|
||||
char *cut = strrchr(path, '\\');
|
||||
char *cut = plat_last_sep(path);
|
||||
if (!cut) cut = strrchr(path, '/');
|
||||
if (!cut || cut + 10 >= path + sizeof path) return 0;
|
||||
strcpy(cut + 1, "totk.ini");
|
||||
@@ -557,7 +839,7 @@ int cfg_save(void) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
void cfg_init(void) {
|
||||
static void load_ini(void) {
|
||||
if (!find_ini()) return;
|
||||
if (!cfg_load(ini_path)) {
|
||||
rt_log("cfg: no settings file at %s", ini_path);
|
||||
@@ -570,3 +852,19 @@ void cfg_init(void) {
|
||||
if (getenv(var)) rt_log("cfg: %s is set in the environment and overrides totk.ini", var);
|
||||
}
|
||||
}
|
||||
|
||||
void cfg_init(void) {
|
||||
load_ini();
|
||||
if (!profile_of()) screen_default();
|
||||
if (profile_of())
|
||||
rt_log("cfg: device profile Steam Deck: defaults for the keys totk.ini does not set (TOTK_DEVICE_PROFILE=desktop "
|
||||
"turns it off)");
|
||||
}
|
||||
|
||||
// scene_upscaler, or for a totk.ini that predates it the dlaa switch it replaced: dlaa = 1 is DLSS, anything else off.
|
||||
// FSR 3.1 is never the answer for a player who did not pick it. An unknown value is off.
|
||||
const char *cfg_scene_upscaler(void) {
|
||||
if (!cfg_is_set("TOTK_SCENE_UPSCALER")) return cfg_bool("TOTK_DLAA") ? "dlss" : "off";
|
||||
const char *v = cfg_value("TOTK_SCENE_UPSCALER");
|
||||
return !strcmp(v, "dlss") ? "dlss" : !strcmp(v, "fsr3") ? "fsr3" : "off";
|
||||
}
|
||||
+26
-1
@@ -2,7 +2,7 @@
|
||||
#pragma once
|
||||
|
||||
// getenv for a setting: the environment variable when set, else the totk.ini key (the name without "TOTK_", any
|
||||
// case), else NULL. Same string semantics as getenv; the pointer stays valid for the process (a value cfg_set replaces
|
||||
// case), else the device profile's default (cfg.c: the Steam Deck), else NULL. Same string semantics as getenv; the pointer stays valid for the process (a value cfg_set replaces
|
||||
// is kept). A name without the TOTK_ prefix goes to getenv unchanged. Safe from any thread once cfg_init has returned.
|
||||
const char *cfg_get(const char *name);
|
||||
|
||||
@@ -21,6 +21,19 @@ void cfg_set(const char *name, const char *value);
|
||||
unsigned cfg_version(void);
|
||||
// 1 when the environment sets name: cfg_set cannot change what cfg_get returns (the menu greys the setting out).
|
||||
int cfg_from_env(const char *name);
|
||||
// 1 when the player set name (the environment or totk.ini), 0 when cfg_get gives a device profile's default or NULL.
|
||||
int cfg_is_set(const char *name);
|
||||
// The folder size of w x h's shape (cfg.c SHAPED: the closest aspect ratio within 1%, the first of equal ones), the
|
||||
// one romfs-patches-<w>x<h> the setup writes for it. 0 for 16:9 and for a shape without a UI layout.
|
||||
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).
|
||||
// Only those lines change: the last line of a changed key gets the new value, a missing key goes under its section
|
||||
// (after the commented example line of the key when the section has one; the section is added at the end of the file
|
||||
@@ -56,3 +69,15 @@ const char *cfg_value(const char *name);
|
||||
int cfg_int(const char *name);
|
||||
double cfg_double(const char *name);
|
||||
int cfg_bool(const char *name);
|
||||
// The 3D scene upscaler the settings name now: "off", "dlss" or "fsr3" (scene_upscaler; without it dlaa = 1 is "dlss").
|
||||
// The engine in use is the one named at start (vk_dlaa.c vk_upscaler_engine).
|
||||
const char *cfg_scene_upscaler(void);
|
||||
// vk_dlaa.c, the 3D scene upscaler (scene_upscaler): the engine picked at start (UPSCALER_*),
|
||||
// 1 while the settings still name it (the menu switches it off at once), the engine that is running (it
|
||||
// ran and has not failed; 0 none), and why an engine cannot run here (UPSCALER_MISSING_*, 0 it can).
|
||||
enum { UPSCALER_OFF, UPSCALER_DLSS, UPSCALER_FSR3 };
|
||||
enum { UPSCALER_MISSING_GPU = 1, UPSCALER_MISSING_DLL };
|
||||
int vk_upscaler_engine(void);
|
||||
int vk_upscaler_on(void);
|
||||
int vk_upscaler_running(void);
|
||||
int vk_upscaler_missing(int engine);
|
||||
+228
-28
@@ -1,10 +1,12 @@
|
||||
// --probe-cfg: totk.ini parsing, the environment override and a missing file (cfg.c). Needs no game files.
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "cfg.h"
|
||||
#include "fs.h"
|
||||
#include "host.h"
|
||||
#include "input.h"
|
||||
#include "input_map.h"
|
||||
@@ -17,7 +19,7 @@ static int fails;
|
||||
int probe_cfg(void) {
|
||||
char path[1024];
|
||||
if (!plat_exe_path(path, sizeof path)) return 1;
|
||||
char *cut = strrchr(path, '\\');
|
||||
char *cut = plat_last_sep(path);
|
||||
if (!cut) return 1;
|
||||
strcpy(cut + 1, "cfg-probe.ini");
|
||||
static const char ini[] =
|
||||
@@ -35,8 +37,8 @@ int probe_cfg(void) {
|
||||
"no_such_setting = 1\r\n"
|
||||
"no equals sign\r\n"
|
||||
"last = no newline at the end";
|
||||
_putenv_s("TOTK_LOCALE", ""); // an empty variable is how _putenv_s spells "remove" on Windows
|
||||
_putenv_s("TOTK_FPS60", "");
|
||||
plat_setenv("TOTK_LOCALE", NULL);
|
||||
plat_setenv("TOTK_FPS60", NULL);
|
||||
CHECK(plat_file_write(path, ini, sizeof ini - 1), "write the probe ini");
|
||||
CHECK(cfg_load(path) == 1, "load the probe ini");
|
||||
CHECK(EQ(cfg_get("TOTK_FPS60"), "0"), "value read, whitespace trimmed, lower-case key");
|
||||
@@ -48,9 +50,9 @@ int probe_cfg(void) {
|
||||
CHECK(cfg_get("TOTK_CLOTH_REALTIME") == NULL, "absent key is NULL");
|
||||
CHECK(cfg_get("TOTK_comment") == NULL, "comment is not a key");
|
||||
CHECK(EQ(cfg_get("TOTK_NO_SUCH_SETTING"), "1"), "unknown key is still readable");
|
||||
_putenv_s("TOTK_FPS60", "1");
|
||||
plat_setenv("TOTK_FPS60", "1");
|
||||
CHECK(EQ(cfg_get("TOTK_FPS60"), "1"), "environment overrides the file");
|
||||
_putenv_s("TOTK_FPS60", "");
|
||||
plat_setenv("TOTK_FPS60", NULL);
|
||||
CHECK(EQ(cfg_get("TOTK_FPS60"), "0"), "file value returns when the variable is removed");
|
||||
plat_file_delete(path);
|
||||
CHECK(cfg_load(path) == 0, "missing file is not an error");
|
||||
@@ -90,9 +92,9 @@ int probe_cfg(void) {
|
||||
"\r\n"
|
||||
"[audio]\r\n"
|
||||
"volume = 40\r\n";
|
||||
_putenv_s("TOTK_MOTION", "");
|
||||
_putenv_s("TOTK_VOLUME", "");
|
||||
_putenv_s("TOTK_RUMBLE_STRENGTH", "");
|
||||
plat_setenv("TOTK_MOTION", NULL);
|
||||
plat_setenv("TOTK_VOLUME", NULL);
|
||||
plat_setenv("TOTK_RUMBLE_STRENGTH", NULL);
|
||||
CHECK(plat_file_write(path, before, sizeof before - 1), "write the save ini");
|
||||
CHECK(cfg_load(path) == 1, "load the save ini");
|
||||
unsigned v0 = cfg_version();
|
||||
@@ -117,11 +119,11 @@ int probe_cfg(void) {
|
||||
EQ(cfg_get("TOTK_RUMBLE_STRENGTH"), "80") && EQ(cfg_get("TOTK_VOLUME"), "40") &&
|
||||
EQ(cfg_get("TOTK_ROMFS_MODS"), "C:\\mods"), "the saved file reads back");
|
||||
const char *held = cfg_get("TOTK_VOLUME");
|
||||
_putenv_s("TOTK_VOLUME", "70");
|
||||
plat_setenv("TOTK_VOLUME", "70");
|
||||
cfg_set("TOTK_VOLUME", "90");
|
||||
CHECK(cfg_from_env("TOTK_VOLUME") && EQ(cfg_get("TOTK_VOLUME"), "70"), "environment wins over cfg_set");
|
||||
CHECK(EQ(held, "40"), "a pointer cfg_get handed out stays valid after cfg_set");
|
||||
_putenv_s("TOTK_VOLUME", "");
|
||||
plat_setenv("TOTK_VOLUME", NULL);
|
||||
CHECK(!cfg_from_env("TOTK_VOLUME") && EQ(cfg_get("TOTK_VOLUME"), "90"), "cfg_set value returns without the variable");
|
||||
plat_file_delete(path);
|
||||
CHECK(cfg_save_to(path) == 1, "cfg_save_to creates a missing file");
|
||||
@@ -134,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");
|
||||
@@ -147,7 +152,7 @@ int probe_cfg(void) {
|
||||
// cfg_reset: the key's active lines leave totk.ini, the commented example stays
|
||||
static const char rbase[] = "[audio]\n# volume = 100\n[input]\nmotion = 0\n";
|
||||
static const char *const vol[] = {"VOLUME"};
|
||||
_putenv_s("TOTK_VOLUME", "");
|
||||
plat_setenv("TOTK_VOLUME", NULL);
|
||||
CHECK(plat_file_write(path, rbase, sizeof rbase - 1), "write the reset ini");
|
||||
CHECK(cfg_load(path) == 1, "load the reset ini");
|
||||
cfg_set("TOTK_VOLUME", "40");
|
||||
@@ -186,9 +191,9 @@ int probe_cfg(void) {
|
||||
|
||||
// a key the environment sets is skipped and keeps its file line
|
||||
CHECK(cfg_load(path) == 1 && EQ(cfg_get("TOTK_VOLUME"), "60"), "reset: reload");
|
||||
_putenv_s("TOTK_VOLUME", "70");
|
||||
plat_setenv("TOTK_VOLUME", "70");
|
||||
CHECK(cfg_reset(vol, 1) == 0, "reset: an environment-set key is skipped");
|
||||
_putenv_s("TOTK_VOLUME", "");
|
||||
plat_setenv("TOTK_VOLUME", NULL);
|
||||
CHECK(EQ(cfg_get("TOTK_VOLUME"), "60"), "reset: the skipped key keeps its value");
|
||||
CHECK(cfg_save_to(path) == 1, "reset: save after a skip");
|
||||
got = plat_file_read(path, &got_n);
|
||||
@@ -200,7 +205,7 @@ int probe_cfg(void) {
|
||||
cfg_set("TOTK_VOLUME", "20");
|
||||
char bad[1100];
|
||||
snprintf(bad, sizeof bad, "%s", path);
|
||||
strcpy(strrchr(bad, '\\') + 1, "no-such-dir\\cfg-probe.ini");
|
||||
strcpy(plat_last_sep(bad) + 1, "no-such-dir/cfg-probe.ini");
|
||||
CHECK(cfg_save_to(bad) == 0 && cfg_last_save_ok() == 0 && EQ(cfg_get("TOTK_VOLUME"), "20"),
|
||||
"save status: an unwritable path fails, the value stays");
|
||||
cfg_set("TOTK_VOLUME", "21");
|
||||
@@ -229,10 +234,24 @@ int probe_cfg(void) {
|
||||
dn[KEY_MOUSE_R] = dn[KEY_Z] = 1;
|
||||
CHECK(input_map_buttons(dn) == (1ull << B_Y | 1ull << B_ZL), "keys: right mouse button and Z both press ZL");
|
||||
memset(dn, 0, sizeof dn);
|
||||
dn[KEY_T] = 1;
|
||||
CHECK(input_map_buttons(dn) == 1ull << B_Y, "keys: T is Y too (the left button is A in the menus)");
|
||||
plat_setenv("TOTK_BIND_X", "key:t");
|
||||
input_map_configure();
|
||||
CHECK(input_map_buttons(dn) == 1ull << B_X, "bind: bind_X = key:t takes T from Y's defaults");
|
||||
dn[KEY_T] = 0, dn[KEY_MOUSE_L] = 1;
|
||||
CHECK(input_map_buttons(dn) == 1ull << B_Y, "bind: Y keeps the left mouse button");
|
||||
plat_setenv("TOTK_BIND_X", NULL);
|
||||
input_map_reset();
|
||||
memset(dn, 0, sizeof dn);
|
||||
dn[KEY_X] = dn[KEY_TAB] = dn[KEY_M] = dn[KEY_LCTRL] = dn[KEY_3] = 1;
|
||||
CHECK(input_map_buttons(dn) == (1ull << B_ZR | 1ull << B_PLUS | 1ull << B_MINUS | 1ull << B_STICK_L | 1ull << B_RIGHT),
|
||||
"keys: X ZR, Tab Plus, M Minus, Left Ctrl stick click, 3 D-pad right");
|
||||
memset(dn, 0, sizeof dn);
|
||||
dn[KEY_G] = 1;
|
||||
CHECK(input_map_buttons(dn) == 0 && input_map_held(dn, B_SHAKE) && !input_map_held(dn, B_A),
|
||||
"keys: G shakes and presses no button");
|
||||
memset(dn, 0, sizeof dn);
|
||||
dn[KEY_W] = 1;
|
||||
input_map_stick(dn, 0, st);
|
||||
CHECK(st[0] == 0 && st[1] == 32767, "keys: W is left stick up");
|
||||
@@ -272,6 +291,22 @@ int probe_cfg(void) {
|
||||
"pad stick: a square gate's corner stays on the unit circle");
|
||||
input_pad_stick(0, 32767 / 2 + 1, 0.2f, st);
|
||||
CHECK(abs(st[1] - 32767 * 3 / 8) <= 3, "pad stick: half deflection past a 20% zone is (0.5 - 0.2) / 0.8 of full");
|
||||
plat_setenv("TOTK_STICK_DEADZONE", "12");
|
||||
plat_setenv("TOTK_LSTICK_DEADZONE", NULL);
|
||||
plat_setenv("TOTK_RSTICK_DEADZONE", NULL);
|
||||
CHECK(fabsf(input_pad_deadzone(0) - 0.12f) < 1e-6f && fabsf(input_pad_deadzone(1) - 0.12f) < 1e-6f,
|
||||
"pad dead zone: both sticks follow stick_deadzone while lstick/rstick are unset");
|
||||
plat_setenv("TOTK_RSTICK_DEADZONE", "20");
|
||||
CHECK(fabsf(input_pad_deadzone(0) - 0.12f) < 1e-6f && fabsf(input_pad_deadzone(1) - 0.20f) < 1e-6f,
|
||||
"pad dead zone: rstick_deadzone sets the right stick alone");
|
||||
plat_setenv("TOTK_LSTICK_DEADZONE", "80");
|
||||
CHECK(fabsf(input_pad_deadzone(0) - 0.5f) < 1e-6f, "pad dead zone: clamped to 50%");
|
||||
plat_setenv("TOTK_STICK_DEADZONE", NULL);
|
||||
plat_setenv("TOTK_LSTICK_DEADZONE", NULL);
|
||||
plat_setenv("TOTK_RSTICK_DEADZONE", NULL);
|
||||
CHECK(input_stick_percent(32767, 0) > 99.99 && input_stick_percent(32767, 0) < 100.01 &&
|
||||
input_stick_percent(0, 0) == 0 && fabs(input_stick_percent(3000, -4000) - 5000 * 100.0 / 32767) < 1e-9,
|
||||
"stick percent: an axis's end is 100%, the centre 0%, round in between");
|
||||
// Gamepad layouts (input_map.c)
|
||||
CHECK(input_pad_layout_pick("auto", 1) == PAD_LAYOUT_NINTENDO && input_pad_layout_pick(NULL, 0) == PAD_LAYOUT_XBOX,
|
||||
"pad layout: automatic is Nintendo for an east button labelled A, Xbox otherwise");
|
||||
@@ -279,7 +314,136 @@ int probe_cfg(void) {
|
||||
"pad layout: a set layout wins over the labels");
|
||||
CHECK(input_pad_layout_pick("xbox_prompts", 0) == PAD_LAYOUT_NINTENDO &&
|
||||
input_pad_layout_pick("Xbox_Prompts", 1) == PAD_LAYOUT_NINTENDO,
|
||||
"pad layout: Xbox prompts keep the Nintendo positions (only the prompts change, romfs.c overlay_init)");
|
||||
"pad layout: 0.1.9's xbox_prompts keeps the Nintendo positions (only the prompts change, romfs.c overlay_init)");
|
||||
// Button prompts (input_map.c)
|
||||
CHECK(input_prompts_pick(NULL, "auto") == PROMPTS_NINTENDO && input_prompts_pick("", "xbox") == PROMPTS_NINTENDO &&
|
||||
input_prompts_pick("Xbox", "nintendo") == PROMPTS_XBOX && input_prompts_pick("nintendo", "xbox") == PROMPTS_NINTENDO,
|
||||
"prompts: the game's own unless set to Xbox");
|
||||
CHECK(input_prompts_pick("PC", "nintendo") == PROMPTS_PC && input_prompts_pick("pc", "xbox_prompts") == PROMPTS_PC &&
|
||||
EQ(input_prompts_folder(PROMPTS_PC, "nintendo"), "romfs-patches-pc") &&
|
||||
EQ(input_prompts_folder(PROMPTS_PC, "xbox"), "romfs-patches-pc") &&
|
||||
EQ(input_prompts_folder(PROMPTS_PC, NULL), "romfs-patches-pc"),
|
||||
"prompts: pc shows the keyboard and mouse whatever the pad layout");
|
||||
CHECK(input_prompts_pick(NULL, "xbox_prompts") == PROMPTS_XBOX && input_prompts_pick("nintendo", "xbox_prompts") == PROMPTS_NINTENDO,
|
||||
"prompts: 0.1.9's pad_layout = xbox_prompts means Xbox while prompts is unset");
|
||||
CHECK(!input_prompts_folder(PROMPTS_NINTENDO, "nintendo") && !input_prompts_folder(PROMPTS_NINTENDO, "xbox"),
|
||||
"prompts: the game's own need no folder");
|
||||
CHECK(EQ(input_prompts_folder(PROMPTS_XBOX, "nintendo"), "romfs-patches-xbox") &&
|
||||
EQ(input_prompts_folder(PROMPTS_XBOX, "xbox_prompts"), "romfs-patches-xbox") &&
|
||||
EQ(input_prompts_folder(PROMPTS_XBOX, "xbox"), "romfs-patches-xbox-label") &&
|
||||
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. 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.
|
||||
unsigned sz[2] = {0, 0};
|
||||
CHECK(cfg_shape_size(5120, 2160, sz) && sz[0] == 2560 && sz[1] == 1080, "shape: 5120x2160 takes 2560x1080's folder");
|
||||
CHECK(cfg_shape_size(3440, 1440, sz) && sz[0] == 3440 && sz[1] == 1440, "shape: 3440x1440 keeps its own (0.8% off 2560x1080)");
|
||||
CHECK(cfg_shape_size(1920, 800, sz) && sz[0] == 3840 && sz[1] == 1600, "shape: 1920x800 takes 3840x1600's folder");
|
||||
CHECK(cfg_shape_size(2560, 1600, sz) && sz[0] == 1280 && sz[1] == 800 && cfg_shape_size(3000, 2000, sz) &&
|
||||
sz[0] == 1920 && sz[1] == 1280 && cfg_shape_size(5120, 1440, sz) && sz[0] == 3840 && sz[1] == 1080,
|
||||
"shape: 16:10, 3:2 and 32:9 take their first size");
|
||||
CHECK(!cfg_shape_size(1920, 1080, sz) && !cfg_shape_size(2560, 1440, sz) && !cfg_shape_size(1024, 768, sz),
|
||||
"shape: none for 16:9 and 4:3");
|
||||
// romfs.c shaped_name: the exact size's folder (an older setup wrote every size) wins, else the shape's
|
||||
{
|
||||
char dir[1100], f[1200];
|
||||
snprintf(dir, sizeof dir, "%.*scfg-probe-shapes", (int)(cut + 1 - path), path);
|
||||
static const char *const made[] = {"romfs-patches-2560x1080", "romfs-patches-xbox-5120x2160"};
|
||||
for (int i = 0; i < 2; i++) {
|
||||
snprintf(f, sizeof f, "%s/%s", dir, made[i]);
|
||||
plat_file_mkdir_p(f);
|
||||
snprintf(f, sizeof f, "%s/%s/manifest.tsv", dir, made[i]);
|
||||
plat_file_write(f, "#\n", 2);
|
||||
}
|
||||
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};
|
||||
pd[PAD_SOUTH] = pd[PAD_NORTH] = 1;
|
||||
CHECK(input_map_pad_buttons(pd, PAD_LAYOUT_NINTENDO) == (1ull << B_B | 1ull << B_X) &&
|
||||
@@ -301,6 +465,14 @@ int probe_cfg(void) {
|
||||
input_map_pad_buttons((uint8_t[PAD_COUNT]){[PAD_ZL] = 1}, PAD_LAYOUT_NINTENDO) == 1ull << B_ZL,
|
||||
"bind: pad:rpaddle1 adds a back paddle, pad:default keeps the trigger");
|
||||
input_map_reset();
|
||||
CHECK(input_map_pad_buttons((uint8_t[PAD_COUNT]){[PAD_TOUCHPAD] = 1}, PAD_LAYOUT_NINTENDO) == 0 &&
|
||||
input_map_pad_buttons((uint8_t[PAD_COUNT]){[PAD_TOUCHPAD] = 1}, PAD_LAYOUT_XBOX) == 0,
|
||||
"pad layout: the touchpad click is unbound by default");
|
||||
CHECK(input_map_bind("MINUS", "pad:default, pad:touchpad") &&
|
||||
input_map_pad_buttons((uint8_t[PAD_COUNT]){[PAD_TOUCHPAD] = 1}, PAD_LAYOUT_XBOX) == 1ull << B_MINUS &&
|
||||
input_map_pad_buttons((uint8_t[PAD_COUNT]){[PAD_BACK] = 1}, PAD_LAYOUT_XBOX) == 1ull << B_MINUS,
|
||||
"bind: pad:touchpad adds the touchpad click, pad:default keeps the button");
|
||||
input_map_reset();
|
||||
// Bind lines for stick directions and default parts; the remapping rows' edits (input_map.c)
|
||||
memset(dn, 0, sizeof dn);
|
||||
dn[KEY_I] = 1;
|
||||
@@ -352,24 +524,42 @@ int probe_cfg(void) {
|
||||
CHECK(!strcmp(line, "none"), "edit: a stick direction without keys is none");
|
||||
// defaults live in the CfgMeta table: cfg_value and the typed accessors fall back to it
|
||||
cfg_load("cfg-probe-missing.ini");
|
||||
_putenv_s("TOTK_FPS60", "");
|
||||
_putenv_s("TOTK_MOUSE_SENS", "");
|
||||
_putenv_s("TOTK_FREE_CORES", "");
|
||||
plat_setenv("TOTK_FPS60", NULL);
|
||||
plat_setenv("TOTK_MOUSE_SENS", NULL);
|
||||
plat_setenv("TOTK_FREE_CORES", NULL);
|
||||
CHECK(cfg_bool("TOTK_FPS60") == 1, "default: unset FPS60 is on");
|
||||
CHECK(EQ(cfg_value("TOTK_VK_PRESENT"), "mailbox") && cfg_int("TOTK_SPLIT_DRAWS") == 64, "default: text and integer");
|
||||
_putenv_s("TOTK_MOUSE_SENS", "2.5");
|
||||
plat_setenv("TOTK_MOUSE_SENS", "2.5");
|
||||
CHECK(cfg_double("TOTK_MOUSE_SENS") == 2.5, "double: the environment value");
|
||||
_putenv_s("TOTK_MOUSE_SENS", "fast");
|
||||
plat_setenv("TOTK_MOUSE_SENS", "fast");
|
||||
CHECK(cfg_double("TOTK_MOUSE_SENS") == 1.0, "double: a value that does not parse gives the default");
|
||||
_putenv_s("TOTK_MOUSE_SENS", "");
|
||||
plat_setenv("TOTK_MOUSE_SENS", NULL);
|
||||
cfg_set("TOTK_MOUSE_SENS", "3");
|
||||
CHECK(cfg_double("TOTK_MOUSE_SENS") == 3.0 && cfg_int("TOTK_MOUSE_SENS") == 3, "a cfg_set value beats the default");
|
||||
CHECK(cfg_bool("TOTK_FREE_CORES") == 0, "free_cores unset: off");
|
||||
_putenv_s("TOTK_FREE_CORES", "0");
|
||||
plat_setenv("TOTK_FREE_CORES", "0");
|
||||
CHECK(cfg_bool("TOTK_FREE_CORES") == 0, "free_cores 0 gives the same as unset");
|
||||
_putenv_s("TOTK_FREE_CORES", "1");
|
||||
plat_setenv("TOTK_FREE_CORES", "1");
|
||||
CHECK(cfg_bool("TOTK_FREE_CORES") == 1, "free_cores 1: on");
|
||||
_putenv_s("TOTK_FREE_CORES", "");
|
||||
plat_setenv("TOTK_FREE_CORES", NULL);
|
||||
// 0.1.9's pad_layout = xbox_prompts (cfg.c migrate): read as the Nintendo layout with the Xbox prompts, saved so
|
||||
plat_setenv("TOTK_PAD_LAYOUT", NULL);
|
||||
plat_setenv("TOTK_PROMPTS", NULL);
|
||||
static const char old_layout[] = "[input]\r\npad_layout = xbox_prompts\r\n";
|
||||
CHECK(plat_file_write(path, old_layout, sizeof old_layout - 1) && cfg_load(path) == 1 &&
|
||||
EQ(cfg_get("TOTK_PAD_LAYOUT"), "nintendo") && EQ(cfg_get("TOTK_PROMPTS"), "xbox"),
|
||||
"0.1.9's pad_layout = xbox_prompts reads as nintendo with prompts = xbox");
|
||||
CHECK(cfg_save_to(path) == 1, "the read pad layout and prompts save");
|
||||
uint64_t saved_n = 0;
|
||||
char *saved = (char *)plat_file_read(path, &saved_n);
|
||||
CHECK(saved && strstr(saved, "pad_layout = nintendo") && strstr(saved, "prompts = xbox") && !strstr(saved, "xbox_prompts"),
|
||||
"the next save writes the pad layout and the prompts");
|
||||
free(saved);
|
||||
static const char old_layout_own[] = "[input]\r\npad_layout = xbox_prompts\r\nprompts = nintendo\r\n";
|
||||
CHECK(plat_file_write(path, old_layout_own, sizeof old_layout_own - 1) && cfg_load(path) == 1 &&
|
||||
EQ(cfg_get("TOTK_PAD_LAYOUT"), "nintendo") && EQ(cfg_get("TOTK_PROMPTS"), "nintendo"),
|
||||
"a prompts line of the file's own wins over 0.1.9's pad_layout = xbox_prompts");
|
||||
plat_file_delete(path);
|
||||
cfg_load("cfg-probe-missing.ini");
|
||||
int listed = 0;
|
||||
for (int i = 0; cfg_meta_at(i); i++) {
|
||||
@@ -378,14 +568,19 @@ int probe_cfg(void) {
|
||||
listed++;
|
||||
char name[96];
|
||||
snprintf(name, sizeof name, "TOTK_%s", m->key);
|
||||
_putenv_s(name, "");
|
||||
CHECK(EQ(cfg_value(name), m->def), "cfg_value returns the table default");
|
||||
plat_setenv(name, "");
|
||||
// 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, "..")) {
|
||||
long lo = strtol(m->values, NULL, 10), hi = strtol(strstr(m->values, "..") + 2, NULL, 10);
|
||||
// strtod: ranges such as 0.2..0.9 have fractional ends
|
||||
double lo = strtod(m->values, NULL), hi = strtod(strstr(m->values, "..") + 2, NULL);
|
||||
double d = strtod(m->def, NULL);
|
||||
ok = d >= (double)lo && d <= (double)hi;
|
||||
ok = d >= lo && d <= hi;
|
||||
} else {
|
||||
size_t dl = strlen(m->def);
|
||||
for (const char *v = m->values; *v;) {
|
||||
@@ -397,6 +592,11 @@ int probe_cfg(void) {
|
||||
if (!ok) fprintf(stderr, "FAIL cfg: default '%s' of %s is not one of its values '%s'\n", m->def, m->key, m->values), fails++;
|
||||
}
|
||||
CHECK(listed >= 30, "the defaults table was walked");
|
||||
// cfg_meta answers with the first row of a key: a second row would be dead, and Reset would visit the key twice
|
||||
for (int i = 0; cfg_meta_at(i); i++)
|
||||
for (int j = i + 1; cfg_meta_at(j); j++)
|
||||
if (!strcmp(cfg_meta_at(i)->key, cfg_meta_at(j)->key))
|
||||
fprintf(stderr, "FAIL cfg: %s has two rows in the defaults table\n", cfg_meta_at(i)->key), fails++;
|
||||
printf("probe-cfg: %s\n", fails ? "FAIL" : "ok");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,753 @@
|
||||
// Cheats of the mods' Atmosphere cheat files (cheats.h). Each enabled mod the port can use (mods.h) may hold
|
||||
// <build id>.txt in its cheats folder, the build id the first 8 bytes of main's NSO build id, as Atmosphere and the
|
||||
// emulators name it; the file name's case does not matter. Each cheat's switch is the setting TOTK_CHEAT_<hash>
|
||||
// (cheat_<hash> under [cheats] in totk.ini), the hash FNV-1a 32 of "<mod folder name>/<cheat name>", so two mods'
|
||||
// cheats of one name keep their own switches.
|
||||
//
|
||||
// Code cheats (opcode 0 writes into main's code) cannot be applied here: the game's code is lifted C. tools/cheats.py
|
||||
// turns the code cheats of every mod into patch sets cheat_<hash> when the game is built and writes
|
||||
// build-cache\cheats.status next to totk.exe, one line per cheat: name hash, content hash, kind, buttons, note
|
||||
// (tools/cheats.py has the format). A cheat whose status line is missing or has another content hash was added or
|
||||
// edited after the build: a data cheat runs anyway, a code cheat waits for the setup to run again.
|
||||
//
|
||||
// Data cheats run in a VM after Atmosphere's dmnt cheat VM (opcodes 0-A and C0-C3; C4 and the 0xF.. extensions are not
|
||||
// supported), every presented frame while their switch is on, with registers and saved registers cleared before each
|
||||
// cheat; the static registers (C3) stay, shared by all cheats, as dmnt keeps them. Memory is the
|
||||
// guest's, mapped at its own addresses: main's image is written with its pages made writable for the write (read-only
|
||||
// data included, as dmnt writes through the debugger), everything else after mem_query says the guest may read or write
|
||||
// it. Buttons are input_poll's HidNpadButton bits, the same as the cheat format's key masks; they read 0 while the menu
|
||||
// is open.
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
|
||||
#include "cfg.h"
|
||||
#include "cheats.h"
|
||||
#include "host.h"
|
||||
#include "input.h"
|
||||
#include "mods.h"
|
||||
#include "platform/platform.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#define SEP "\\"
|
||||
#else
|
||||
#define SEP "/"
|
||||
#endif
|
||||
|
||||
enum { STATUS_MAX = 160, OPS_PER_RUN = 1 << 20 };
|
||||
|
||||
typedef struct {
|
||||
CheatInfo info;
|
||||
uint32_t *words;
|
||||
int n;
|
||||
int dup; // 1 for the first cheat of its name in its file, 2 for the next ...
|
||||
uint32_t content; // FNV-1a 32 of its words as tools/cheats.py writes them
|
||||
int set; // patch set, -1 none
|
||||
volatile int32_t on;
|
||||
char note[STATUS_MAX];
|
||||
} Cheat;
|
||||
|
||||
static Cheat *g_cheats;
|
||||
static int g_n, g_cap, g_vm; // g_vm: some cheat needs cheats_frame
|
||||
static char g_file[64]; // "<build id>.txt"
|
||||
static char g_dir[PLAT_PATH_MAX]; // the folder of totk.exe, with a trailing separator
|
||||
static int g_files; // mods whose file was read
|
||||
static uint64_t g_static[256]; // C3's static registers: 0x00-0x7F loaded by cheats, 0x80-0xFF stored by them
|
||||
static uint64_t g_main, g_main_size, g_code_end; // main's image; its code with the padding up to .rodata
|
||||
|
||||
static uint32_t fnv(const char *s, size_t n) {
|
||||
uint32_t h = 0x811C9DC5u;
|
||||
for (size_t i = 0; i < n; i++) h = (h ^ (uint8_t)s[i]) * 0x01000193u;
|
||||
return h;
|
||||
}
|
||||
|
||||
// The folder of the executable, with a trailing separator.
|
||||
static int exe_dir(char *out, size_t n) {
|
||||
if (!plat_exe_path(out, n)) return 0;
|
||||
char *cut = plat_last_sep(out);
|
||||
if (!cut) return 0;
|
||||
cut[1] = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int build_id(char out[17]) {
|
||||
char path[PLAT_PATH_MAX];
|
||||
snprintf(path, sizeof path, "%s/main", rt_config()->exefs);
|
||||
PlatFile *f = plat_file_open(path);
|
||||
if (!f) return 0;
|
||||
uint8_t head[0x48];
|
||||
int ok = plat_file_pread(f, head, sizeof head, 0) == sizeof head && !memcmp(head, "NSO0", 4);
|
||||
plat_file_close(f);
|
||||
for (int i = 0; ok && i < 8; i++) snprintf(out + 2 * i, 3, "%02X", head[0x40 + i]);
|
||||
return ok;
|
||||
}
|
||||
|
||||
// ---- opcodes
|
||||
|
||||
// Words of the opcode at w (left words remain), 0 when it is cut short.
|
||||
static int op_len(const uint32_t *w, int left) {
|
||||
uint32_t f = w[0];
|
||||
int t = f >> 28, width = (f >> 24) & 0xF, n;
|
||||
switch (t) {
|
||||
case 0: case 1: n = width == 8 ? 4 : 3; break;
|
||||
case 2: case 8: n = 1; break;
|
||||
case 3: n = width == 0 ? 2 : 1; break;
|
||||
case 4: case 6: n = 3; break;
|
||||
case 5: case 7: n = 2; break;
|
||||
case 9: n = 1 + (((f >> 8) & 0xF) ? (width == 8 ? 2 : 1) : 0); break;
|
||||
case 0xA: n = ((f >> 8) & 0xF) == 2 || ((f >> 8) & 0xF) == 4 || ((f >> 8) & 0xF) == 5 ? 2 : 1; break;
|
||||
case 0xC: // C0TcSX..: an address word for operand types 0 and 2, the value (two words at width 8) for 4
|
||||
if (((f >> 24) & 0xF) != 0) n = 1;
|
||||
else if (((f >> 8) & 0xF) == 0 || ((f >> 8) & 0xF) == 2) n = 2;
|
||||
else n = ((f >> 8) & 0xF) == 4 ? (((f >> 20) & 0xF) == 8 ? 3 : 2) : 1;
|
||||
break;
|
||||
default: n = 1; break;
|
||||
}
|
||||
return n <= left ? n : 0;
|
||||
}
|
||||
|
||||
// NULL when the VM runs the opcode, else why not (tools/cheats.py vm_ok).
|
||||
static const char *vm_unsupported(const uint32_t *w, char *buf, int n) {
|
||||
uint32_t f = w[0];
|
||||
int t = f >> 28, width = (f >> 24) & 0xF;
|
||||
int ext = f >> 24; // 0xC0-0xC3 run; C0's width is at bits 20-23 and its operand type (at most 5) at bits 8-11
|
||||
if (ext == 0xC0) t = -1, width = (f >> 20) & 0xF;
|
||||
if ((t > 0xA && (ext < 0xC1 || ext > 0xC3)) || (t == -1 && ((f >> 8) & 0xF) > 5) ||
|
||||
(t == 5 && ((f >> 12) & 0xF) > 1) || (t == 0xA && ((f >> 8) & 0xF) > 5)) {
|
||||
snprintf(buf, n, "opcode %08X is not supported", f);
|
||||
return buf;
|
||||
}
|
||||
if ((t <= 1 || t == 5 || t == 6 || t == 7 || t == 9 || t == 0xA) && width != 1 && width != 2 && width != 4 &&
|
||||
width != 8) { // C0 too (t -1)
|
||||
snprintf(buf, n, "opcode %08X has a bad width", f);
|
||||
return buf;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// The kind of a cheat the build did not see: heading, data, rebuild (it writes main's code) or unsupported.
|
||||
static CheatKind classify(Cheat *c) {
|
||||
int ops = 0, ends = 0;
|
||||
for (int i = 0; i < c->n;) {
|
||||
int len = op_len(c->words + i, c->n - i);
|
||||
if (!len) {
|
||||
snprintf(c->note, sizeof c->note, "opcode %08X is cut short", c->words[i]);
|
||||
return CHEAT_UNSUPPORTED;
|
||||
}
|
||||
uint32_t f = c->words[i];
|
||||
ops++;
|
||||
ends += f >> 28 == 2;
|
||||
if (f >> 28 == 0 && ((f >> 20) & 0xF) == 0) {
|
||||
uint64_t off = ((uint64_t)(f & 0xFF) << 32) | c->words[i + 1];
|
||||
if (off < g_code_end - g_main) return CHEAT_REBUILD;
|
||||
}
|
||||
if (vm_unsupported(c->words + i, c->note, sizeof c->note)) return CHEAT_UNSUPPORTED;
|
||||
i += len;
|
||||
}
|
||||
return ops == ends && ops <= 1 ? CHEAT_HEADING : CHEAT_DATA;
|
||||
}
|
||||
|
||||
// ---- guest memory
|
||||
|
||||
static uint64_t region(int m) {
|
||||
const RtGuestLayout *l = mem_layout();
|
||||
switch (m) {
|
||||
case 0: return g_main;
|
||||
case 1: return l->heap.base;
|
||||
case 2: return l->alias.base;
|
||||
case 3: return l->aslr.base;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static int in_main(uint64_t a, unsigned n) { return a >= g_main && a + n <= g_main + g_main_size; }
|
||||
|
||||
static int guest_ok(uint64_t a, unsigned n, uint32_t perm) {
|
||||
if (in_main(a, n)) return 1;
|
||||
RtMemoryInfo mi;
|
||||
if (mem_query(a, &mi) || !mi.state || (mi.perm & perm) != perm) return 0;
|
||||
return a + n <= mi.base + mi.size;
|
||||
}
|
||||
|
||||
static int rd(uint64_t a, int width, uint64_t *v) {
|
||||
if (!a || !guest_ok(a, (unsigned)width, 1)) return 0;
|
||||
uint64_t x = 0;
|
||||
memcpy(&x, (const void *)(uintptr_t)a, (size_t)width);
|
||||
*v = x;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Writes n bytes into main's image a page at a time: a read-only page is writable for its part of the copy only.
|
||||
static void wr_main(uint64_t a, const uint8_t *from, int n) {
|
||||
while (n > 0) {
|
||||
uint64_t page = a & ~0xFFFull, end;
|
||||
int k = (int)(page + 0x1000 - a);
|
||||
if (k > n) k = n;
|
||||
int prot = plat_mem_state(page, page + 0x1000, &end);
|
||||
if (prot != PLAT_PROT_READ && prot != PLAT_PROT_RW) return;
|
||||
if (prot == PLAT_PROT_READ && !plat_mem_protect(page, 0x1000, PLAT_PROT_RW)) return;
|
||||
memcpy((void *)(uintptr_t)a, from, (size_t)k);
|
||||
if (prot == PLAT_PROT_READ) plat_mem_protect(page, 0x1000, PLAT_PROT_READ);
|
||||
a += (uint64_t)k;
|
||||
from += k;
|
||||
n -= k;
|
||||
}
|
||||
}
|
||||
|
||||
static void wr(uint64_t a, int width, uint64_t v) {
|
||||
uint64_t now;
|
||||
if (!rd(a, width, &now) || !memcmp(&now, &v, (size_t)width)) return; // unchanged: no write, no protection change
|
||||
void *p = (void *)(uintptr_t)a;
|
||||
if (in_main(a, (unsigned)width)) {
|
||||
wr_main(a, (const uint8_t *)&v, width);
|
||||
} else if (guest_ok(a, (unsigned)width, 2)) {
|
||||
memcpy(p, &v, (size_t)width); // a frozen region thaws on the write (memory.c)
|
||||
}
|
||||
}
|
||||
|
||||
static uint64_t masked(int width, uint64_t v) { return width >= 8 ? v : v & ((1ull << (8 * width)) - 1); }
|
||||
|
||||
static uint64_t arith(int op, uint64_t a, uint64_t b) {
|
||||
switch (op) {
|
||||
case 0: return a + b;
|
||||
case 1: return a - b;
|
||||
case 2: return a * b;
|
||||
case 3: return b < 64 ? a << b : 0;
|
||||
case 4: return b < 64 ? a >> b : 0;
|
||||
case 5: return a & b;
|
||||
case 6: return a | b;
|
||||
case 7: return ~a;
|
||||
case 8: return a ^ b;
|
||||
default: return a; // 9: move
|
||||
}
|
||||
}
|
||||
|
||||
static int compare(int cond, uint64_t a, uint64_t b) {
|
||||
switch (cond) {
|
||||
case 1: return a > b;
|
||||
case 2: return a >= b;
|
||||
case 3: return a < b;
|
||||
case 4: return a <= b;
|
||||
case 5: return a == b;
|
||||
case 6: return a != b;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// From i (after a failed condition, or an else reached while running), the opcode to continue at: after the
|
||||
// matching else (else_ok) or end. Conditions 1, 8 and C0 open a block, as in Atmosphere's dmnt
|
||||
// (stratosphere/dmnt/source/cheat/impl/dmnt_cheat_vm.cpp, CheatVirtualMachine::SkipConditionalBlock), which steps
|
||||
// over whole opcodes so that an operand word reading 20000000 ends nothing.
|
||||
static int skip(const uint32_t *w, int n, int i, int else_ok) {
|
||||
int depth = 0;
|
||||
while (i < n) {
|
||||
int len = op_len(w + i, n - i);
|
||||
if (!len) return n;
|
||||
uint32_t f = w[i];
|
||||
int t = f >> 28;
|
||||
i += len;
|
||||
if (t == 1 || t == 8 || f >> 24 == 0xC0) depth++;
|
||||
else if (t == 2 && ((f >> 24) & 0xF) == 1) { // else; any other 2x000000 ends, as dmnt decodes is_else
|
||||
if (depth == 0 && else_ok) return i;
|
||||
} else if (t == 2 && depth-- == 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
static uint64_t imm64(const uint32_t *w) { return (uint64_t)w[0] << 32 | w[1]; }
|
||||
|
||||
// C0TcSX..: if register S <cond c> operand X, all cut to width T; the operand as Atmosphere's dmnt reads it
|
||||
// (stratosphere/dmnt/source/cheat/impl/dmnt_cheat_vm.cpp, CheatVirtualMachine::DecodeNextOpcode and Execute,
|
||||
// BeginRegisterConditionalBlock). X: 0 region M + a, 1 region M + register r, 2 register R + a, 3 register R +
|
||||
// register r, 4 the value V, 5 register R. M, R at bits 4-7, r and the top bits of a at bits 0-3. A read the guest
|
||||
// cannot make compares as 0: dmnt ignores the read's result and compares the zero it started with.
|
||||
static int reg_cond(const uint32_t *w, const uint64_t *r) {
|
||||
uint32_t f = w[0];
|
||||
int width = (f >> 20) & 0xF, cond = (f >> 16) & 0xF, a4 = (f >> 4) & 0xF, a0 = f & 0xF;
|
||||
uint64_t src = masked(width, r[(f >> 12) & 0xF]), b = 0, addr;
|
||||
switch ((f >> 8) & 0xF) { // w[1] exists for types 0, 2 and 4 only (op_len)
|
||||
case 0: addr = region(a4) + (((uint64_t)a0 << 32) | w[1]); break;
|
||||
case 1: addr = region(a4) + r[a0]; break;
|
||||
case 2: addr = r[a4] + (((uint64_t)a0 << 32) | w[1]); break;
|
||||
case 3: addr = r[a4] + r[a0]; break;
|
||||
case 4: return compare(cond, src, width == 8 ? imm64(w + 1) : masked(width, w[1]));
|
||||
default: return compare(cond, src, masked(width, r[a4]));
|
||||
}
|
||||
if (!rd(addr, width, &b)) b = 0;
|
||||
return compare(cond, src, b);
|
||||
}
|
||||
|
||||
static void run(const Cheat *c, uint64_t keys) {
|
||||
uint64_t r[16] = {0}, saved[16] = {0};
|
||||
int loop[16] = {0};
|
||||
const uint32_t *w = c->words;
|
||||
int n = c->n, budget = OPS_PER_RUN;
|
||||
for (int i = 0; i < n && budget-- > 0;) {
|
||||
int len = op_len(w + i, n - i);
|
||||
if (!len) return;
|
||||
uint32_t f = w[i];
|
||||
int t = f >> 28, width = (f >> 24) & 0xF, x = (f >> 20) & 0xF, y = (f >> 16) & 0xF, z = (f >> 12) & 0xF;
|
||||
uint64_t rel = ((uint64_t)(f & 0xFF) << 32) | (len > 1 ? w[i + 1] : 0), v;
|
||||
switch (t) {
|
||||
case 0: // 0TMR00AA AAAAAAAA V..: store a value at region M + A + register R
|
||||
wr(region(x) + rel + r[y], width, width == 8 ? imm64(w + i + 2) : w[i + 2]);
|
||||
break;
|
||||
case 1: // 1TMC00AA AAAAAAAA V..: if (region M + A) <cond C> V
|
||||
if (!rd(region(x) + rel, width, &v) || !compare(y, v, width == 8 ? imm64(w + i + 2) : w[i + 2])) {
|
||||
i = skip(w, n, i + len, 1);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
case 2: // 20000000 end, 21000000 else: an else reached while running skips to the end
|
||||
if (width == 1) {
|
||||
i = skip(w, n, i + len, 0);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
case 3: // 300R0000 VVVVVVVV loop start, 310R0000 loop end
|
||||
if (width == 0) {
|
||||
r[y] = w[i + 1];
|
||||
loop[y] = i + len;
|
||||
} else if (r[y] && --r[y]) {
|
||||
i = loop[y];
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
case 4: // 400R0000 V V: register R = V
|
||||
r[y] = imm64(w + i + 1);
|
||||
break;
|
||||
case 5: // 5TMRI0AA AAAAAAAA: R = (I ? R : region M) + A, read
|
||||
if (!rd(z ? r[y] + rel : region(x) + rel, width, &v)) return; // a broken pointer chain: nothing more
|
||||
r[y] = v;
|
||||
break;
|
||||
case 6: { // 6T0RIor0 V V: store V at R (+ register r); I: R += width
|
||||
uint64_t a = r[y] + (((f >> 8) & 0xF) ? r[(f >> 4) & 0xF] : 0);
|
||||
wr(a, width, imm64(w + i + 1));
|
||||
if (z) r[y] += (uint64_t)width;
|
||||
break;
|
||||
}
|
||||
case 7: // 7T0RC000 VVVVVVVV: R = R <op C> V
|
||||
r[y] = masked(width, arith(z, r[y], w[i + 1]));
|
||||
break;
|
||||
case 8: // 8kkkkkkk: if the buttons are held
|
||||
if ((keys & (f & 0x0FFFFFFF)) != (f & 0x0FFFFFFF)) {
|
||||
i = skip(w, n, i + len, 1);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
case 9: { // 9TCRS0s0 / 9TCRS100 V..: R = S <op C> (s or V)
|
||||
uint64_t b = (f >> 8) & 0xF ? (width == 8 ? imm64(w + i + 1) : w[i + 1]) : r[(f >> 4) & 0xF];
|
||||
r[y] = masked(width, arith(x, r[z], b));
|
||||
break;
|
||||
}
|
||||
case 0xA: { // ATSRIOxa (aaaaaaaa): store register S at an address of type O
|
||||
int o = (f >> 8) & 0xF, m = (f >> 4) & 0xF;
|
||||
uint64_t imm = ((uint64_t)(f & 0xF) << 32) | (len > 1 ? w[i + 1] : 0), a;
|
||||
switch (o) {
|
||||
case 0: a = r[y]; break;
|
||||
case 1: a = r[y] + r[m]; break;
|
||||
case 2: a = r[y] + imm; break;
|
||||
case 3: a = region(m) + r[y]; break;
|
||||
case 4: a = region(m) + imm; break;
|
||||
default: a = region(m) + r[y] + imm; break;
|
||||
}
|
||||
wr(a, width, r[x]);
|
||||
if (z) r[y] += (uint64_t)width;
|
||||
break;
|
||||
}
|
||||
case 0xC: // C1-C3 as dmnt's Execute runs SaveRestoreRegister(Mask) and ReadWriteStaticRegister
|
||||
switch (f >> 24) {
|
||||
case 0xC0:
|
||||
if (!reg_cond(w + i, r)) {
|
||||
i = skip(w, n, i + len, 1);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
case 0xC1: { // C10D0Sx0: x 0 register D = saved S, 1 saved D = register S, 2 saved D = 0,
|
||||
// 3 register D = 0
|
||||
int d = (f >> 16) & 0xF, s = (f >> 8) & 0xF, op = (f >> 4) & 0xF;
|
||||
if (op == 1) saved[d] = r[s];
|
||||
else if (op == 2) saved[d] = 0;
|
||||
else if (op == 3) r[d] = 0;
|
||||
else r[d] = saved[s]; // dmnt restores for any other x too
|
||||
break;
|
||||
}
|
||||
case 0xC2: { // C2x0XXXX: for each register in the mask X, x as C1 with D = S = that register
|
||||
int op = (f >> 20) & 0xF;
|
||||
for (int k = 0; k < 16; k++) {
|
||||
if (!(f >> k & 1)) continue;
|
||||
if (op == 1) saved[k] = r[k];
|
||||
else if (op == 2) saved[k] = 0;
|
||||
else if (op == 3) r[k] = 0;
|
||||
else r[k] = saved[k];
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 0xC3: { // C3000XXx: static register XX < 0x80 into register x, else register x into it
|
||||
int s = (f >> 4) & 0xFF;
|
||||
if (s < 0x80) r[f & 0xF] = g_static[s];
|
||||
else g_static[s] = r[f & 0xF];
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
i += len;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the file
|
||||
|
||||
static char *read_text(const char *path) {
|
||||
uint64_t n = 0;
|
||||
char *s = (char *)plat_file_read(path, &n);
|
||||
if (s && n >= 3 && !memcmp(s, "\xEF\xBB\xBF", 3)) memmove(s, s + 3, (size_t)n - 2); // a UTF-8 BOM
|
||||
return s;
|
||||
}
|
||||
|
||||
static void add_word(Cheat *c, uint32_t v, int *cap) {
|
||||
if (c->n == *cap) {
|
||||
*cap = *cap ? *cap * 2 : 16;
|
||||
c->words = (uint32_t *)realloc(c->words, sizeof *c->words * (size_t)*cap);
|
||||
if (!c->words) rt_fatal("cheats: out of memory");
|
||||
}
|
||||
c->words[c->n++] = v;
|
||||
}
|
||||
|
||||
// Appends the cheats of one mod's file; mod: the mod's folder name (kept).
|
||||
static void parse(char *s, const char *mod) {
|
||||
int first = g_n, wcap = 0;
|
||||
for (char *line = s; line && *line;) {
|
||||
char *end = strchr(line, '\n'), *next = end ? end + 1 : NULL;
|
||||
if (end) *end = 0;
|
||||
while (*line == ' ' || *line == '\t') line++;
|
||||
size_t len = strlen(line);
|
||||
while (len && (line[len - 1] == '\r' || line[len - 1] == ' ' || line[len - 1] == '\t')) line[--len] = 0;
|
||||
if (len >= 2 && (line[0] == '[' || line[0] == '{') && (line[len - 1] == ']' || line[len - 1] == '}')) {
|
||||
if (g_n == g_cap) {
|
||||
g_cap = g_cap ? g_cap * 2 : 32;
|
||||
g_cheats = (Cheat *)realloc(g_cheats, sizeof *g_cheats * (size_t)g_cap);
|
||||
if (!g_cheats) rt_fatal("cheats: out of memory");
|
||||
}
|
||||
Cheat *c = &g_cheats[g_n++];
|
||||
memset(c, 0, sizeof *c);
|
||||
line[len - 1] = 0;
|
||||
char *name = line + 1;
|
||||
while (*name == ' ' || *name == '\t') name++;
|
||||
size_t k = strlen(name);
|
||||
while (k && (name[k - 1] == ' ' || name[k - 1] == '\t')) name[--k] = 0;
|
||||
c->info.name = strdup(name);
|
||||
c->info.mod = mod;
|
||||
c->info.kind = line[0] == '{' ? CHEAT_MASTER : CHEAT_HEADING;
|
||||
c->set = -1;
|
||||
c->dup = 1; // a repeated name gets "#2", "#3" ... (tools/cheats.py parse)
|
||||
for (int j = first; j < g_n - 1; j++) c->dup += !strcmp(g_cheats[j].info.name, c->info.name);
|
||||
wcap = 0;
|
||||
} else if (g_n > first) {
|
||||
for (char *tok = strtok(line, " \t"); tok; tok = strtok(NULL, " \t")) {
|
||||
char *e;
|
||||
unsigned long v = strtoul(tok, &e, 16);
|
||||
if (e - tok == 8 && !*e) add_word(&g_cheats[g_n - 1], (uint32_t)v, &wcap);
|
||||
}
|
||||
}
|
||||
line = next;
|
||||
}
|
||||
}
|
||||
|
||||
// The file g_file in folder, its name in any case, into out; 0 when there is none.
|
||||
typedef struct {
|
||||
const char *dir;
|
||||
char *out;
|
||||
size_t cap;
|
||||
int found;
|
||||
} FindFile;
|
||||
static int find_cb(const char *name, int kind, uint64_t size, void *ctx) {
|
||||
(void)size;
|
||||
FindFile *f = (FindFile *)ctx;
|
||||
if (kind == PLAT_FS_FILE && !strcasecmp(name, g_file) &&
|
||||
snprintf(f->out, f->cap, "%s/%s", f->dir, name) < (int)f->cap)
|
||||
f->found = 1;
|
||||
return !f->found;
|
||||
}
|
||||
static int find_file(const char *folder, char *out, size_t cap) {
|
||||
FindFile f = {folder, out, cap, 0};
|
||||
plat_fs_list(folder, find_cb, &f);
|
||||
return f.found;
|
||||
}
|
||||
|
||||
// The status line of key, its fields split in place; 0 when none.
|
||||
static int status_of(char *status, const char *key, char **fields) {
|
||||
for (char *line = status; line && *line;) {
|
||||
char *end = strchr(line, '\n'), *next = end ? end + 1 : NULL;
|
||||
if (!strncmp(line, key, 8) && line[8] == '\t') {
|
||||
static char copy[512];
|
||||
size_t n = end ? (size_t)(end - line) : strlen(line);
|
||||
if (n >= sizeof copy) n = sizeof copy - 1;
|
||||
memcpy(copy, line, n);
|
||||
copy[n] = 0;
|
||||
if (n && copy[n - 1] == '\r') copy[n - 1] = 0;
|
||||
int k = 0;
|
||||
fields[k++] = copy;
|
||||
for (char *p = copy; *p && k < 5; p++)
|
||||
if (*p == '\t') *p = 0, fields[k++] = p + 1;
|
||||
while (k < 5) fields[k++] = (char *)"";
|
||||
return 1;
|
||||
}
|
||||
line = next;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The menu's font has no numero sign (U+2116), which cheat names often start with: they show "No" instead.
|
||||
static void plain_name(char *s) {
|
||||
for (char *p; (p = strstr(s, "\xE2\x84\x96")) != NULL;) {
|
||||
p[0] = 'N', p[1] = 'o';
|
||||
memmove(p + 2, p + 3, strlen(p + 3) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 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. 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.
|
||||
static void rebuild_if_needed(const char *dir) {
|
||||
uint32_t key = 0x811C9DC5u;
|
||||
int need = 0;
|
||||
for (int i = 0; i < g_n; i++) {
|
||||
const Cheat *c = &g_cheats[i];
|
||||
if (c->info.kind != CHEAT_REBUILD) continue;
|
||||
need++;
|
||||
key = (key ^ fnv(c->info.key, strlen(c->info.key))) * 0x01000193u;
|
||||
key = (key ^ c->content) * 0x01000193u;
|
||||
}
|
||||
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);
|
||||
snprintf(skip_path, sizeof skip_path, "%sbuild-cache" SEP "rebuild.skip", dir);
|
||||
snprintf(want, sizeof want, "%08X", key);
|
||||
char *old = read_text(skip_path);
|
||||
if (old) snprintf(skip, sizeof skip, "%.8s", old);
|
||||
free(old);
|
||||
const char *why = !strcmp(cfg_value("TOTK_MODS_REBUILD"), "off") ? "mods_rebuild = off"
|
||||
: rt_config()->seconds || rt_config()->boot ? "a scripted run"
|
||||
: !strcmp(skip, want) ? "the last rebuild for them failed or was cancelled"
|
||||
: NULL;
|
||||
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 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;
|
||||
if (end) *end = 0;
|
||||
size_t n = strlen(line);
|
||||
if (n && line[n - 1] == '\r') line[n - 1] = 0;
|
||||
if (*line) argv[argc++] = line;
|
||||
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 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 or plugins differ from the build; starting the rebuild: %s",
|
||||
need, patches, argv[0]);
|
||||
int ok = plat_spawn(argv, dir);
|
||||
free(cmd);
|
||||
if (!ok) {
|
||||
// The skip key is for a rebuild that ran and failed or was cancelled. One that never started (a command whose
|
||||
// program is gone) leaves no key, so the next start and "Rebuild the game now" try it again.
|
||||
plat_fs_unlink(skip_path);
|
||||
rt_log("cheats: the rebuild did not start (%s); the game starts with the code it has", cmd_path);
|
||||
return;
|
||||
}
|
||||
prof_write(); // plat_exit runs no atexit handlers
|
||||
plat_exit(0);
|
||||
}
|
||||
|
||||
void cheats_init(void) {
|
||||
const RtLoaded *m = ldr_count() ? ldr_module(0) : NULL;
|
||||
char dir[PLAT_PATH_MAX], bid[17], path[2400]; // path: a mod's cheats folder (ModInfo.cheats) + the file
|
||||
if (!m || !exe_dir(dir, sizeof dir) || !build_id(bid)) return;
|
||||
snprintf(g_dir, sizeof g_dir, "%s", dir);
|
||||
g_main = m->base;
|
||||
g_main_size = m->size;
|
||||
g_code_end = m->base + ((m->text_end + 0xFFF) & ~0xFFFull);
|
||||
snprintf(g_file, sizeof g_file, "%s.txt", bid);
|
||||
mods_scan();
|
||||
for (int k = 0; k < mods_count(); k++) { // the Mods tab's order, top first
|
||||
const ModInfo *mod = mods_at(k);
|
||||
if (!mod->enabled || mod->problem != MOD_OK || !mod->cheats[0] || !find_file(mod->cheats, path, sizeof path))
|
||||
continue;
|
||||
char *text = read_text(path);
|
||||
if (!text) {
|
||||
rt_log("cheats: %s: cannot read %s", mod->name, path);
|
||||
continue;
|
||||
}
|
||||
parse(text, strdup(mod->name));
|
||||
free(text);
|
||||
g_files++;
|
||||
}
|
||||
if (!g_files) {
|
||||
rt_log("cheats: no enabled mod holds cheats/%s", g_file);
|
||||
rebuild_if_needed(dir); // an enabled mod's ExeFS patches may still wait for it
|
||||
return;
|
||||
}
|
||||
snprintf(path, sizeof path, "%sbuild-cache" SEP "cheats.status", dir);
|
||||
char *status = read_text(path);
|
||||
int counts[CHEAT_UNSUPPORTED + 1] = {0}, seen_dups = 0;
|
||||
for (int i = 0; i < g_n; i++) {
|
||||
Cheat *c = &g_cheats[i];
|
||||
char named[900];
|
||||
snprintf(named, sizeof named, c->dup > 1 ? "%s/%s#%d" : "%s/%s", c->info.mod, c->info.name, c->dup);
|
||||
seen_dups += c->dup > 1;
|
||||
char key[9], content[9];
|
||||
snprintf(key, sizeof key, "%08X", fnv(named, strlen(named)));
|
||||
size_t tn = (size_t)c->n * 9 + 1, tl = 0;
|
||||
char *t = (char *)malloc(tn);
|
||||
if (!t) rt_fatal("cheats: out of memory");
|
||||
t[0] = 0;
|
||||
for (int k = 0; k < c->n; k++) tl += (size_t)snprintf(t + tl, tn - tl, k ? " %08X" : "%08X", c->words[k]);
|
||||
c->content = fnv(t, tl);
|
||||
snprintf(content, sizeof content, "%08X", c->content);
|
||||
free(t);
|
||||
snprintf(c->info.key, sizeof c->info.key, "TOTK_CHEAT_%s", key);
|
||||
int master = c->info.kind == CHEAT_MASTER;
|
||||
char *f[5];
|
||||
CheatKind kind;
|
||||
if (status && status_of(status, key, f) && !strcmp(f[1], content)) {
|
||||
const char *k = f[2];
|
||||
kind = !strcmp(k, "code") ? CHEAT_CODE : !strcmp(k, "key") ? CHEAT_KEY : !strcmp(k, "master") ? CHEAT_MASTER
|
||||
: !strcmp(k, "restore") ? CHEAT_RESTORE : !strcmp(k, "heading") ? CHEAT_HEADING
|
||||
: !strcmp(k, "data") ? CHEAT_DATA : CHEAT_UNSUPPORTED;
|
||||
c->info.buttons = (uint32_t)strtoul(f[3], NULL, 16);
|
||||
snprintf(c->note, sizeof c->note, "%s", f[4]);
|
||||
if (kind == CHEAT_CODE || kind == CHEAT_KEY || kind == CHEAT_MASTER) {
|
||||
char set[32];
|
||||
snprintf(set, sizeof set, "cheat_%08x", fnv(named, strlen(named)));
|
||||
c->set = rt_patch_set(set);
|
||||
if (c->set < 0 && kind != CHEAT_MASTER) kind = CHEAT_REBUILD;
|
||||
}
|
||||
} else {
|
||||
kind = classify(c);
|
||||
}
|
||||
if (master && kind == CHEAT_DATA) kind = CHEAT_MASTER; // a data master code: the VM, always on
|
||||
c->info.kind = kind;
|
||||
c->info.note = c->note;
|
||||
const char *v = cfg_get(c->info.key);
|
||||
c->on = kind == CHEAT_MASTER || (v && *v && strcmp(v, "0") != 0);
|
||||
if (kind == CHEAT_KEY && c->set >= 0) rt_patch_switch(c->set, 0); // on while the buttons are held
|
||||
if (kind == CHEAT_KEY || kind == CHEAT_DATA || (kind == CHEAT_MASTER && c->set < 0)) g_vm = 1;
|
||||
counts[kind]++;
|
||||
}
|
||||
free(status);
|
||||
rebuild_if_needed(dir);
|
||||
for (int i = 0; i < g_n; i++) plain_name((char *)g_cheats[i].info.name); // the hashes above read the file's bytes
|
||||
int on = 0;
|
||||
for (int i = 0; i < g_n; i++) on += g_cheats[i].on && g_cheats[i].info.kind != CHEAT_HEADING;
|
||||
rt_log("cheats: %s in %d mods: %d cheats, %d on; %d code, %d while buttons are held, %d data, %d master, "
|
||||
"%d restore, %d headings, %d wait for a rebuild, %d not supported%s",
|
||||
g_file, g_files, g_n, on, counts[CHEAT_CODE], counts[CHEAT_KEY], counts[CHEAT_DATA], counts[CHEAT_MASTER],
|
||||
counts[CHEAT_RESTORE], counts[CHEAT_HEADING], counts[CHEAT_REBUILD], counts[CHEAT_UNSUPPORTED],
|
||||
seen_dups ? " (repeated names numbered)" : "");
|
||||
}
|
||||
|
||||
int cheats_rebuild_pending(void) {
|
||||
char path[PLAT_PATH_MAX + 64];
|
||||
snprintf(path, sizeof path, "%sbuild-cache" SEP "rebuild.txt", g_dir);
|
||||
uint32_t key = 0;
|
||||
int need = mods_exefs_pending(&key);
|
||||
for (int i = 0; i < g_n && !need; i++) need = g_cheats[i].info.kind == CHEAT_REBUILD;
|
||||
return need && g_dir[0] && plat_file_exists(path);
|
||||
}
|
||||
|
||||
void cheats_rebuild_allow(void) {
|
||||
char path[PLAT_PATH_MAX + 64];
|
||||
snprintf(path, sizeof path, "%sbuild-cache" SEP "rebuild.skip", g_dir);
|
||||
plat_fs_unlink(path);
|
||||
}
|
||||
|
||||
int cheats_count(void) { return g_n; }
|
||||
|
||||
const CheatInfo *cheats_info(int i) { return i >= 0 && i < g_n ? &g_cheats[i].info : NULL; }
|
||||
|
||||
int cheats_on(int i) { return i >= 0 && i < g_n && g_cheats[i].on; }
|
||||
|
||||
const char *cheats_file(void) { return g_file; }
|
||||
|
||||
void cheats_set(int i, int on) {
|
||||
if (i < 0 || i >= g_n) return;
|
||||
Cheat *c = &g_cheats[i];
|
||||
if (c->info.kind != CHEAT_CODE && c->info.kind != CHEAT_KEY && c->info.kind != CHEAT_DATA) return;
|
||||
plat_xchg32(&c->on, on != 0);
|
||||
if (c->info.kind == CHEAT_CODE) rt_patch_switch(c->set, on); // CHEAT_KEY: cheats_frame follows the buttons
|
||||
cfg_set(c->info.key, on ? "1" : "0");
|
||||
rt_log("cheats: %s/%s %s", c->info.mod, c->info.name, on ? "on" : "off");
|
||||
}
|
||||
|
||||
void cheats_frame(uint64_t frame) {
|
||||
if (!g_vm || frame < 60) return; // the game polls its input (and starts SDL) before this
|
||||
uint64_t keys = 0;
|
||||
int32_t lx, ly, rx, ry;
|
||||
input_poll(&keys, &lx, &ly, &rx, &ry); // 0 while the menu is open
|
||||
for (int i = 0; i < g_n; i++) {
|
||||
Cheat *c = &g_cheats[i];
|
||||
switch (c->info.kind) {
|
||||
case CHEAT_KEY:
|
||||
if (c->set >= 0) {
|
||||
int want = c->on && (keys & c->info.buttons) == c->info.buttons;
|
||||
if (rt_patch_enabled(c->set) != want) rt_patch_switch(c->set, want);
|
||||
}
|
||||
break;
|
||||
case CHEAT_DATA:
|
||||
if (c->on) run(c, keys);
|
||||
break;
|
||||
case CHEAT_MASTER:
|
||||
if (c->set < 0) run(c, keys);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const char *cheats_buttons(uint32_t mask, char *buf, int n) {
|
||||
static const char *const names[] = {"A", "B", "X", "Y", "Left stick press", "Right stick press", "L", "R", "ZL",
|
||||
"ZR", "+", "-", "D-pad left", "D-pad up", "D-pad right", "D-pad down",
|
||||
"Left stick left", "Left stick up", "Left stick right", "Left stick down",
|
||||
"Right stick left", "Right stick up", "Right stick right", "Right stick down"};
|
||||
int k = 0;
|
||||
buf[0] = 0;
|
||||
for (int b = 0; b < 24; b++)
|
||||
if (mask & (1u << b)) k += snprintf(buf + k, (size_t)(n > k ? n - k : 0), "%s%s", k ? " + " : "", names[b]);
|
||||
return buf;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Cheats of the mods' Atmosphere cheat files (cheats.c): mods\<mod>\cheats\<build id>.txt of each enabled mod,
|
||||
// switched from the menu's Cheats tab. A cheat that writes the game's instructions is a code patch set that tools/cheats.py built into the game
|
||||
// (switched with rt_patch_switch); one that writes data runs in the cheat VM every presented frame.
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef enum {
|
||||
CHEAT_HEADING, // no opcodes: a title or a group label
|
||||
CHEAT_CODE, // a patch set
|
||||
CHEAT_KEY, // a patch set on while the buttons are held
|
||||
CHEAT_DATA, // the cheat VM
|
||||
CHEAT_MASTER, // {master}: always on
|
||||
CHEAT_RESTORE, // writes the original instructions back: nothing to do
|
||||
CHEAT_REBUILD, // writes instructions, but the game was built without this version of it
|
||||
CHEAT_UNSUPPORTED, // note says why
|
||||
} CheatKind;
|
||||
|
||||
typedef struct {
|
||||
const char *name; // UTF-8, as in the file
|
||||
const char *mod; // the mod's folder name; cheats come grouped by mod, in the Mods tab's order
|
||||
const char *note; // why it is unsupported ("" otherwise)
|
||||
CheatKind kind;
|
||||
uint32_t buttons; // CHEAT_KEY: HidNpadButton mask
|
||||
char key[24]; // its setting, TOTK_CHEAT_<hash of "<mod>/<name>">
|
||||
} CheatInfo;
|
||||
|
||||
void cheats_init(void); // after rt_patches_init: reads the mods' files and their build status
|
||||
int cheats_count(void);
|
||||
// 1 when a cheat of an enabled mod waits for a rebuild (CHEAT_REBUILD) and the setup left its rebuild command.
|
||||
int cheats_rebuild_pending(void);
|
||||
// The next start rebuilds again for cheats whose last rebuild failed or was cancelled (the menu restarts after it).
|
||||
void cheats_rebuild_allow(void);
|
||||
const CheatInfo *cheats_info(int i);
|
||||
int cheats_on(int i); // the player's switch (1 for a master cheat)
|
||||
void cheats_set(int i, int on); // switches at once and sets the cheat's setting (the menu saves totk.ini)
|
||||
const char *cheats_file(void); // "<build id>.txt", the name the files have for this game version
|
||||
// Every presented frame (the present path): the data cheats' VM and the button state of CHEAT_KEY cheats.
|
||||
void cheats_frame(uint64_t frame);
|
||||
// The button names of a mask ("ZL + Right stick left"), into buf.
|
||||
const char *cheats_buttons(uint32_t mask, char *buf, int n);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,71 @@
|
||||
// Generated by tools/build_shaders.py from runtime/shaders/color_grade.comp; do not edit.
|
||||
// source sha256 c93d6ac75667bdee5442d7e94fbf0bd6e7fe7250caa98974424aead10f554106
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
static const uint32_t color_grade_spv[] = {
|
||||
0x07230203, 0x00010300, 0x000d000b, 0x00000073, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
|
||||
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
|
||||
0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000d, 0x00060010, 0x00000004,
|
||||
0x00000011, 0x00000008, 0x00000008, 0x00000001, 0x00040047, 0x0000000d, 0x0000000b, 0x0000001c,
|
||||
0x00030047, 0x00000015, 0x00000002, 0x00050048, 0x00000015, 0x00000000, 0x00000023, 0x00000000,
|
||||
0x00050048, 0x00000015, 0x00000001, 0x00000023, 0x00000008, 0x00050048, 0x00000015, 0x00000002,
|
||||
0x00000023, 0x00000010, 0x00040047, 0x00000029, 0x00000021, 0x00000000, 0x00040047, 0x00000029,
|
||||
0x00000022, 0x00000000, 0x00030047, 0x0000005d, 0x00000019, 0x00040047, 0x0000005d, 0x00000021,
|
||||
0x00000001, 0x00040047, 0x0000005d, 0x00000022, 0x00000000, 0x00040047, 0x0000006a, 0x0000000b,
|
||||
0x00000019, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006,
|
||||
0x00000020, 0x00000001, 0x00040017, 0x00000007, 0x00000006, 0x00000002, 0x00040015, 0x0000000a,
|
||||
0x00000020, 0x00000000, 0x00040017, 0x0000000b, 0x0000000a, 0x00000003, 0x00040020, 0x0000000c,
|
||||
0x00000001, 0x0000000b, 0x0004003b, 0x0000000c, 0x0000000d, 0x00000001, 0x00040017, 0x0000000e,
|
||||
0x0000000a, 0x00000002, 0x00030016, 0x00000013, 0x00000020, 0x00040017, 0x00000014, 0x00000013,
|
||||
0x00000004, 0x0005001e, 0x00000015, 0x00000007, 0x00000007, 0x00000014, 0x00040020, 0x00000016,
|
||||
0x00000009, 0x00000015, 0x0004003b, 0x00000016, 0x00000017, 0x00000009, 0x0004002b, 0x00000006,
|
||||
0x00000018, 0x00000001, 0x00040020, 0x00000019, 0x00000009, 0x00000007, 0x00020014, 0x0000001c,
|
||||
0x00040017, 0x0000001d, 0x0000001c, 0x00000002, 0x00040017, 0x00000023, 0x00000013, 0x00000003,
|
||||
0x00090019, 0x00000026, 0x00000013, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001,
|
||||
0x00000000, 0x0003001b, 0x00000027, 0x00000026, 0x00040020, 0x00000028, 0x00000000, 0x00000027,
|
||||
0x0004003b, 0x00000028, 0x00000029, 0x00000000, 0x0004002b, 0x00000006, 0x0000002c, 0x00000000,
|
||||
0x0004002b, 0x00000006, 0x00000033, 0x00000002, 0x0004002b, 0x0000000a, 0x00000034, 0x00000000,
|
||||
0x00040020, 0x00000035, 0x00000009, 0x00000013, 0x0004002b, 0x00000013, 0x0000003c, 0x3f000000,
|
||||
0x0004002b, 0x0000000a, 0x0000003f, 0x00000001, 0x0004002b, 0x00000013, 0x00000046, 0x3e59b3d0,
|
||||
0x0004002b, 0x00000013, 0x00000047, 0x3f371759, 0x0004002b, 0x00000013, 0x00000048, 0x3d93dd98,
|
||||
0x0006002c, 0x00000023, 0x00000049, 0x00000046, 0x00000047, 0x00000048, 0x0004002b, 0x0000000a,
|
||||
0x0000004d, 0x00000002, 0x0004002b, 0x00000013, 0x00000053, 0x00000000, 0x0006002c, 0x00000023,
|
||||
0x00000054, 0x00000053, 0x00000053, 0x00000053, 0x0004002b, 0x0000000a, 0x00000056, 0x00000003,
|
||||
0x00090019, 0x0000005b, 0x00000013, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000002,
|
||||
0x00000002, 0x00040020, 0x0000005c, 0x00000000, 0x0000005b, 0x0004003b, 0x0000005c, 0x0000005d,
|
||||
0x00000000, 0x0004002b, 0x00000013, 0x00000061, 0x3f800000, 0x0004002b, 0x0000000a, 0x00000069,
|
||||
0x00000008, 0x0006002c, 0x0000000b, 0x0000006a, 0x00000069, 0x00000069, 0x0000003f, 0x0006002c,
|
||||
0x00000023, 0x00000071, 0x0000003c, 0x0000003c, 0x0000003c, 0x0006002c, 0x00000023, 0x00000072,
|
||||
0x00000061, 0x00000061, 0x00000061, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003,
|
||||
0x000200f8, 0x00000005, 0x000300f7, 0x0000006b, 0x00000000, 0x000300fb, 0x00000034, 0x0000006c,
|
||||
0x000200f8, 0x0000006c, 0x0004003d, 0x0000000b, 0x0000000f, 0x0000000d, 0x0007004f, 0x0000000e,
|
||||
0x00000010, 0x0000000f, 0x0000000f, 0x00000000, 0x00000001, 0x0004007c, 0x00000007, 0x00000011,
|
||||
0x00000010, 0x00050041, 0x00000019, 0x0000001a, 0x00000017, 0x00000018, 0x0004003d, 0x00000007,
|
||||
0x0000001b, 0x0000001a, 0x000500af, 0x0000001d, 0x0000001e, 0x00000011, 0x0000001b, 0x0004009a,
|
||||
0x0000001c, 0x0000001f, 0x0000001e, 0x000300f7, 0x00000021, 0x00000000, 0x000400fa, 0x0000001f,
|
||||
0x00000020, 0x00000021, 0x000200f8, 0x00000020, 0x000200f9, 0x0000006b, 0x000200f8, 0x00000021,
|
||||
0x0004003d, 0x00000027, 0x0000002a, 0x00000029, 0x00050041, 0x00000019, 0x0000002d, 0x00000017,
|
||||
0x0000002c, 0x0004003d, 0x00000007, 0x0000002e, 0x0000002d, 0x00050080, 0x00000007, 0x0000002f,
|
||||
0x00000011, 0x0000002e, 0x00040064, 0x00000026, 0x00000030, 0x0000002a, 0x0007005f, 0x00000014,
|
||||
0x00000031, 0x00000030, 0x0000002f, 0x00000002, 0x0000002c, 0x0008004f, 0x00000023, 0x00000032,
|
||||
0x00000031, 0x00000031, 0x00000000, 0x00000001, 0x00000002, 0x00060041, 0x00000035, 0x00000036,
|
||||
0x00000017, 0x00000033, 0x00000034, 0x0004003d, 0x00000013, 0x00000037, 0x00000036, 0x00060050,
|
||||
0x00000023, 0x00000039, 0x00000037, 0x00000037, 0x00000037, 0x00050081, 0x00000023, 0x0000003a,
|
||||
0x00000032, 0x00000039, 0x00050083, 0x00000023, 0x0000003e, 0x0000003a, 0x00000071, 0x00060041,
|
||||
0x00000035, 0x00000040, 0x00000017, 0x00000033, 0x0000003f, 0x0004003d, 0x00000013, 0x00000041,
|
||||
0x00000040, 0x0005008e, 0x00000023, 0x00000042, 0x0000003e, 0x00000041, 0x00050081, 0x00000023,
|
||||
0x00000044, 0x00000042, 0x00000071, 0x00050094, 0x00000013, 0x0000004a, 0x00000044, 0x00000049,
|
||||
0x00060050, 0x00000023, 0x0000004b, 0x0000004a, 0x0000004a, 0x0000004a, 0x00060041, 0x00000035,
|
||||
0x0000004e, 0x00000017, 0x00000033, 0x0000004d, 0x0004003d, 0x00000013, 0x0000004f, 0x0000004e,
|
||||
0x00060050, 0x00000023, 0x00000050, 0x0000004f, 0x0000004f, 0x0000004f, 0x0008000c, 0x00000023,
|
||||
0x00000051, 0x00000001, 0x0000002e, 0x0000004b, 0x00000044, 0x00000050, 0x0007000c, 0x00000023,
|
||||
0x00000055, 0x00000001, 0x00000028, 0x00000051, 0x00000054, 0x00060041, 0x00000035, 0x00000057,
|
||||
0x00000017, 0x00000033, 0x00000056, 0x0004003d, 0x00000013, 0x00000058, 0x00000057, 0x00060050,
|
||||
0x00000023, 0x00000059, 0x00000058, 0x00000058, 0x00000058, 0x0007000c, 0x00000023, 0x0000005a,
|
||||
0x00000001, 0x0000001a, 0x00000055, 0x00000059, 0x0004003d, 0x0000005b, 0x0000005e, 0x0000005d,
|
||||
0x0008000c, 0x00000023, 0x00000064, 0x00000001, 0x0000002b, 0x0000005a, 0x00000054, 0x00000072,
|
||||
0x00050051, 0x00000013, 0x00000065, 0x00000064, 0x00000000, 0x00050051, 0x00000013, 0x00000066,
|
||||
0x00000064, 0x00000001, 0x00050051, 0x00000013, 0x00000067, 0x00000064, 0x00000002, 0x00070050,
|
||||
0x00000014, 0x00000068, 0x00000065, 0x00000066, 0x00000067, 0x00000061, 0x00040063, 0x0000005e,
|
||||
0x00000011, 0x00000068, 0x000200f9, 0x0000006b, 0x000200f8, 0x0000006b, 0x000100fd, 0x00010038,
|
||||
};
|
||||
@@ -0,0 +1,274 @@
|
||||
// Generated by tools/build_shaders.py from runtime/shaders/contact_shadow.comp; do not edit.
|
||||
// source sha256 e44a73a42aed3d5c2ac3a0a7e8809234f6175f8e331d30f93331ae9ca32fda71
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
static const uint32_t contact_shadow_spv[] = {
|
||||
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,
|
||||
0x00000002, 0x00050048, 0x00000033, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000033,
|
||||
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, 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,
|
||||
0x40000000, 0x0004002b, 0x00000006, 0x00000029, 0x3f800000, 0x00040015, 0x0000002c, 0x00000020,
|
||||
0x00000000, 0x0004002b, 0x0000002c, 0x0000002d, 0x00000000, 0x00040017, 0x00000032, 0x00000006,
|
||||
0x00000004, 0x0006001e, 0x00000033, 0x00000032, 0x00000032, 0x00000032, 0x00000032, 0x00040020,
|
||||
0x00000034, 0x00000009, 0x00000033, 0x0004003b, 0x00000034, 0x00000035, 0x00000009, 0x0004002b,
|
||||
0x00000019, 0x00000036, 0x00000000, 0x00040020, 0x00000037, 0x00000009, 0x00000006, 0x0004002b,
|
||||
0x0000002c, 0x0000003b, 0x00000001, 0x0004002b, 0x0000002c, 0x0000004a, 0x00000002, 0x0004002b,
|
||||
0x00000006, 0x0000004e, 0x3f000000, 0x0004002b, 0x00000006, 0x00000064, 0x4253ee82, 0x0004002b,
|
||||
0x00000006, 0x00000066, 0x3d897143, 0x0004002b, 0x00000006, 0x00000067, 0x3bbf4590, 0x0005002c,
|
||||
0x00000007, 0x00000068, 0x00000066, 0x00000067, 0x0005002c, 0x0000001a, 0x00000070, 0x00000036,
|
||||
0x00000036, 0x0004002b, 0x00000019, 0x00000071, 0x00000002, 0x00040020, 0x00000072, 0x00000009,
|
||||
0x00000032, 0x0004002b, 0x00000019, 0x00000077, 0x00000001, 0x00090019, 0x00000083, 0x00000006,
|
||||
0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x0003001b, 0x00000084,
|
||||
0x00000083, 0x00040020, 0x00000085, 0x00000000, 0x00000084, 0x0004003b, 0x00000085, 0x00000086,
|
||||
0x00000000, 0x0005002c, 0x0000001a, 0x0000009d, 0x00000077, 0x00000036, 0x0005002c, 0x0000001a,
|
||||
0x000000a8, 0x00000036, 0x00000077, 0x00020014, 0x000000b1, 0x0004002b, 0x00000006, 0x00000110,
|
||||
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, 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,
|
||||
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,
|
||||
0x0000002d, 0x0004003d, 0x00000006, 0x00000127, 0x00000126, 0x0004006e, 0x00000019, 0x00000128,
|
||||
0x00000127, 0x000500af, 0x000000b1, 0x00000129, 0x00000125, 0x00000128, 0x000400a8, 0x000000b1,
|
||||
0x0000012a, 0x00000129, 0x000300f7, 0x0000012c, 0x00000000, 0x000400fa, 0x0000012a, 0x0000012b,
|
||||
0x0000012c, 0x000200f8, 0x0000012b, 0x00050051, 0x00000019, 0x0000012e, 0x00000123, 0x00000001,
|
||||
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, 0x00000244, 0x00000132, 0x0000012b, 0x000300f7, 0x00000135,
|
||||
0x00000000, 0x000400fa, 0x00000133, 0x00000134, 0x00000135, 0x000200f8, 0x00000134, 0x000200f9,
|
||||
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,
|
||||
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, 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, 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,
|
||||
};
|
||||
+33
-5
@@ -18,7 +18,11 @@ typedef struct __attribute__((aligned(16))) Cpu {
|
||||
uint64_t fpcr; // 320: guest FPCR/FPSR (portable FP/SIMD lowering only; the asm path uses the host's)
|
||||
uint64_t fpsr; // 328
|
||||
uint64_t excl_val_hi; // 336: upper half of a 128-bit exclusive pair (LDXP/LDAXP of two X registers)
|
||||
uint8_t _pad[512 - 344];
|
||||
uint64_t _pad0; // 344
|
||||
float fp_th_s[4]; // 352: FP result check threshold, every lane (rt_fpcr_threshold, runtime/simd_fp.h FOKT)
|
||||
double fp_th_d[2]; // 368
|
||||
__uint128_t fp_arg[3]; // 384: operands of a vector FP op handed to its slow path (runtime/simd_fp.h FN(vredo))
|
||||
uint8_t _pad[512 - 432];
|
||||
__uint128_t v[32]; // 512
|
||||
} Cpu;
|
||||
|
||||
@@ -27,6 +31,8 @@ _Static_assert(offsetof(Cpu, pc) == 264, "pc");
|
||||
_Static_assert(offsetof(Cpu, nzcv) == 272, "nzcv");
|
||||
_Static_assert(offsetof(Cpu, fpcr) == 320, "fpcr");
|
||||
_Static_assert(offsetof(Cpu, fpsr) == 328, "fpsr");
|
||||
_Static_assert(offsetof(Cpu, fp_th_s) == 352 && offsetof(Cpu, fp_th_d) == 368, "fp_th");
|
||||
_Static_assert(offsetof(Cpu, fp_arg) == 384, "fp_arg");
|
||||
_Static_assert(offsetof(Cpu, v) == 512, "v");
|
||||
|
||||
typedef void (*GuestFn)(Cpu *);
|
||||
@@ -39,12 +45,24 @@ void rt_brk(Cpu *c, uint32_t imm, uint64_t pc) __attribute__((noreturn));
|
||||
void rt_udf(Cpu *c, uint64_t pc) __attribute__((noreturn));
|
||||
uint64_t rt_ticks(void);
|
||||
|
||||
// The FP fast paths of runtime/simd_fp.h test FPCR.RMode and the result in one compare: a result is good when its
|
||||
// magnitude differs from c->fp_th_*. In round-to-nearest the threshold is the smallest normal, so NaN and +-smallest
|
||||
// normal fail as before; under a directed RMode it is NaN, both compares are unordered and every result goes through
|
||||
// the redo path, which rounds in the FPCR mode. It must follow every change of c->fpcr: rt_fpcr_sync sets it, and so
|
||||
// does code that creates a Cpu or copies fpcr into one. A zeroed threshold is wrong, not merely slow: it passes
|
||||
// +-smallest normal.
|
||||
static inline void rt_fpcr_threshold(Cpu *c) {
|
||||
int directed = (c->fpcr & (3u << 22)) != 0;
|
||||
for (int i = 0; i < 4; i++) c->fp_th_s[i] = directed ? __builtin_nanf("") : 0x1p-126f;
|
||||
for (int i = 0; i < 2; i++) c->fp_th_d[i] = directed ? __builtin_nan("") : 0x1p-1022;
|
||||
}
|
||||
|
||||
#if defined(__aarch64__)
|
||||
static inline uint64_t rt_get_fpcr(void) { uint64_t v; __asm__ volatile("mrs %0, fpcr" : "=r"(v)); return v; }
|
||||
static inline uint64_t rt_get_fpsr(void) { uint64_t v; __asm__ volatile("mrs %0, fpsr" : "=r"(v)); return v; }
|
||||
static inline void rt_set_fpcr(uint64_t v) { __asm__ volatile("msr fpcr, %0" :: "r"(v)); }
|
||||
static inline void rt_set_fpsr(uint64_t v) { __asm__ volatile("msr fpsr, %0" :: "r"(v)); }
|
||||
static inline void rt_fpcr_sync(const Cpu *c) { (void)c; }
|
||||
static inline void rt_fpcr_sync(Cpu *c) { rt_fpcr_threshold(c); }
|
||||
#else
|
||||
// Host FP state is not the guest's here: code lifted with --simd=c keeps FPCR/FPSR in Cpu (c->fpcr, zeroed
|
||||
// with the Cpu), so the host-side reset in thread start-up has nothing to do.
|
||||
@@ -56,12 +74,20 @@ static inline void rt_set_fpsr(uint64_t v) { (void)v; }
|
||||
// the slow paths of runtime/simd.h, which switch RC around one operation). The FP helpers rely on it without checking,
|
||||
// so it is set wherever FPCR or the host FP context changes: MSR FPCR (recomp/lifter.py), rt_call (thread and fiber
|
||||
// entry, host code calling guest code), fiber resume (runtime/kernel.c fiber_resumed; fibers keep their own MXCSR).
|
||||
static inline void rt_fpcr_sync(const Cpu *c) {
|
||||
// It also sets the FP result check threshold (rt_fpcr_threshold).
|
||||
static inline void rt_fpcr_sync(Cpu *c) {
|
||||
rt_fpcr_threshold(c);
|
||||
unsigned cur = __builtin_ia32_stmxcsr();
|
||||
unsigned want = (cur & ~0xE040u) | (c->fpcr & (1u << 24) ? 0x8040u : 0); // FTZ 0x8000, DAZ 0x40, RC 0x6000
|
||||
if (cur != want) __builtin_ia32_ldmxcsr(want);
|
||||
}
|
||||
#endif
|
||||
// MSR FPCR (recomp/lifter.py): the first guest write of a directed rounding mode (FPCR.RMode, bits 22-23) is logged
|
||||
// once with the caller (main.c rt_fpcr_rmode), to learn whether the game ever leaves round-to-nearest. A test of the
|
||||
// value just stored, at the MSR sites only.
|
||||
void rt_fpcr_rmode(uint64_t fpcr, uint64_t lr);
|
||||
#define RT_FPCR_NOTE(c, lr) \
|
||||
do { if (__builtin_expect((c)->fpcr & (3ull << 22), 0)) rt_fpcr_rmode((c)->fpcr, lr); } while (0)
|
||||
|
||||
// ---- memory: guest addresses are host addresses
|
||||
typedef uint16_t __attribute__((aligned(1), may_alias)) u16u;
|
||||
@@ -69,7 +95,9 @@ typedef uint32_t __attribute__((aligned(1), may_alias)) u32u;
|
||||
typedef uint64_t __attribute__((aligned(1), may_alias)) u64u;
|
||||
typedef uint8_t __attribute__((may_alias)) u8a;
|
||||
|
||||
// Function-entry profiler (runtime/fnprof.c, LARECOMP_FNPROF): one predictable branch per call when off.
|
||||
// Function-entry hook: one predictable branch per call while g_fnprof is 0. The generator emits it only in the
|
||||
// functions of the patch table's `hook` lines (recomp/patches.py), or in every function for a table without any and
|
||||
// with gen.py --fn-enter-all.
|
||||
extern volatile int g_fnprof;
|
||||
void fnprof_hit(uint64_t addr, uint64_t lr, uint64_t x0);
|
||||
#define FN_ENTER(a) do { if (__builtin_expect(g_fnprof, 0)) fnprof_hit(a, c->x[30], c->x[0]); } while (0)
|
||||
@@ -109,7 +137,7 @@ EXCL(16, uint16_t)
|
||||
EXCL(32, uint32_t)
|
||||
EXCL(64, uint64_t)
|
||||
|
||||
// Exclusive pair of two X registers: one 16-byte-aligned 128-bit access (cmpxchg16b; x86-64-v3 has CX16).
|
||||
// Exclusive pair of two X registers: one 16-byte-aligned 128-bit access (cmpxchg16b; x86-64-v2 has CX16).
|
||||
// A pair of two W registers is a 64-bit exclusive and uses ldx64/stx64.
|
||||
static inline __uint128_t ldxp128(Cpu *c, uint64_t a) {
|
||||
__uint128_t v = __atomic_load_n((__uint128_t *)(uintptr_t)a, __ATOMIC_ACQUIRE);
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// The mouse pointer's image in the game window while the cursor is not captured (the game's menus, the settings menu):
|
||||
// a gold arrowhead with a notched back, a dark outline, a turquoise gem and a soft shadow, drawn here at the size the
|
||||
// window's DPI asks for instead of the Windows arrow. input_win.c and input_sdl.c make the system cursor from it.
|
||||
// Nothing comes from the game's files.
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "input_wsys.h"
|
||||
|
||||
typedef struct { float x, y; } V;
|
||||
|
||||
// In units of a 32-pixel cursor: the tip at the top left (the hotspot), the wings to the right and below, the notch
|
||||
// between them
|
||||
static const V SHAPE[] = {{1.5f, 1.5f}, {25.0f, 10.5f}, {14.5f, 14.5f}, {10.5f, 25.0f}};
|
||||
static const V GEM[] = {{10.4f, 7.6f}, {13.0f, 10.2f}, {10.4f, 12.8f}, {7.8f, 10.2f}};
|
||||
#define OUTLINE 1.7f // the dark edge's width
|
||||
#define SHADOW 1.6f // the shadow's offset to the bottom right
|
||||
|
||||
static float seg_dist(V p, V a, V b) {
|
||||
float dx = b.x - a.x, dy = b.y - a.y, t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy);
|
||||
t = t < 0 ? 0 : t > 1 ? 1 : t;
|
||||
float ex = a.x + t * dx - p.x, ey = a.y + t * dy - p.y;
|
||||
return sqrtf(ex * ex + ey * ey);
|
||||
}
|
||||
|
||||
// Distance to the polygon's edge, negative inside (even-odd: the shapes are simple)
|
||||
static float poly_sdf(V p, const V *v, int n) {
|
||||
float d = 1e9f;
|
||||
int in = 0;
|
||||
for (int i = 0, j = n - 1; i < n; j = i++) {
|
||||
float e = seg_dist(p, v[j], v[i]);
|
||||
if (e < d) d = e;
|
||||
if ((v[i].y > p.y) != (v[j].y > p.y) && p.x < (v[j].x - v[i].x) * (p.y - v[i].y) / (v[j].y - v[i].y) + v[i].x)
|
||||
in = !in;
|
||||
}
|
||||
return in ? -d : d;
|
||||
}
|
||||
|
||||
// One sample's colour (straight r, g, b in 0..1) and coverage
|
||||
static float sample(V p, float *r, float *g, float *b) {
|
||||
float d = poly_sdf(p, SHAPE, 4);
|
||||
if (d < 0) {
|
||||
if (-d < OUTLINE) { *r = 0.17f, *g = 0.11f, *b = 0.04f; return 1; }
|
||||
if (poly_sdf(p, GEM, 4) < 0) { // the gem, lighter towards its top left
|
||||
float t = (p.x + p.y - 20.4f) / 5.2f + 0.5f;
|
||||
t = t < 0 ? 0 : t > 1 ? 1 : t;
|
||||
*r = 0.62f - 0.42f * t, *g = 0.98f - 0.22f * t, *b = 0.92f - 0.12f * t;
|
||||
return 1;
|
||||
}
|
||||
// gold, pale at the tip and deeper at the wings; a thin light line inside the outline
|
||||
float t = (p.x + p.y) / 34.0f;
|
||||
t = t < 0 ? 0 : t > 1 ? 1 : t;
|
||||
float rim = -d < OUTLINE + 1.0f ? 0.12f : 0;
|
||||
*r = fminf(1, 1.00f - 0.12f * t + rim), *g = fminf(1, 0.93f - 0.32f * t + rim),
|
||||
*b = fminf(1, 0.70f - 0.52f * t + rim);
|
||||
return 1;
|
||||
}
|
||||
V s = {p.x - SHADOW, p.y - SHADOW};
|
||||
float ds = poly_sdf(s, SHAPE, 4);
|
||||
if (ds < 0.8f) { // the shadow, soft at its edge
|
||||
*r = *g = *b = 0;
|
||||
float a = ds < -0.8f ? 1 : (0.8f - ds) / 1.6f;
|
||||
return 0.38f * a;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void cursor_art(uint32_t *argb, int size, int *hot) {
|
||||
float k = 32.0f / (float)size;
|
||||
enum { SS = 4 }; // 4 x 4 samples a pixel
|
||||
for (int y = 0; y < size; y++)
|
||||
for (int x = 0; x < size; x++) {
|
||||
float r = 0, g = 0, b = 0, a = 0;
|
||||
for (int sy = 0; sy < SS; sy++)
|
||||
for (int sx = 0; sx < SS; sx++) {
|
||||
V p = {(x + (sx + 0.5f) / SS) * k, (y + (sy + 0.5f) / SS) * k};
|
||||
float sr, sg, sb, c = sample(p, &sr, &sg, &sb);
|
||||
r += sr * c, g += sg * c, b += sb * c, a += c;
|
||||
}
|
||||
uint32_t px = 0;
|
||||
if (a > 0) { // straight alpha, as Windows and SDL take it
|
||||
r /= a, g /= a, b /= a, a /= SS * SS;
|
||||
px = (uint32_t)lrintf(a * 255) << 24 | (uint32_t)lrintf(r * 255) << 16 |
|
||||
(uint32_t)lrintf(g * 255) << 8 | (uint32_t)lrintf(b * 255);
|
||||
}
|
||||
argb[y * size + x] = px;
|
||||
}
|
||||
*hot = (int)(1.5f / k);
|
||||
}
|
||||
Loaded 100 of 474 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user