diff --git a/README.md b/README.md index 38780dce..104fd074 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,9 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md). - Custom resolutions (1080p, 2k...), supersampling and AMD FSR 1 upscaling - NVIDIA DLSS / DLAA on RTX GPUs: the setup downloads `nvngx_dlss.dll` from NVIDIA's DLSS SDK repository (github.com/NVIDIA/DLSS, NVIDIA RTX SDK license) when it finds an RTX GPU; untick it in the setup to skip it +- AMD FSR 4 on Radeon RX 9000, 7000 and 6000 GPUs (FSR 3.1 on others), in the same modes as DLSS: the setup downloads + AMD's signed FSR SDK libraries (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK, AMD FSR SDK license) when it + finds an AMD GPU; pick *Upscaler: AMD FSR* in the menu (Windows; not yet checked in play) - 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 @@ -53,7 +56,8 @@ Requirements: Windows 10 or later, an x86-64 CPU with SSE4.2 (AVX2/FMA machines 2. Start `TotK-Setup.exe`. If SmartScreen warns about an unsigned app, choose *More info*, then *Run anyway*. 3. Pick your game files, the language and an install folder, and press *Start*. The setup builds the game once. With an NVIDIA RTX GPU it also downloads NVIDIA DLSS, unless you untick *Download NVIDIA DLSS*; turn DLSS on in the - menu (F1). + menu (F1). With an AMD GPU it downloads AMD FSR the same way; in the menu turn on *NVIDIA DLSS / DLAA* and pick + *Upscaler: AMD FSR*. 4. Play `totk.exe` from the install folder. ### Linux diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 289e75a6..c0266a30 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -37,6 +37,8 @@ Code copied or adapted from another project is listed here with its source, the | MacNativeGames host movie decoder (`movie::Decoder` for VP9 over libvpx: entry list, buffer and event semantics, NV12 output format, PTS pacing) | https://github.com/ly05010419/MacNativeGames @ `b75be8cfa704df3701e86130c8ced268e79d6b11` (`games/totk/runtime/movie_host.c`, `movie_host.h`), Copyright (c) 2026 MacNativeGames contributors | MIT | `runtime/ov_movie.c`, `runtime/movie.h` | | libvpx 1.17.0 (MSYS2 `mingw-w64-ucrt-x86_64-libvpx`), static link (`libvpx.a`), no DLL shipped; the release notices must carry its BSD licence text and the WebM Project's `PATENTS` grant | https://chromium.googlesource.com/webm/libvpx, Copyright (c) 2010, The WebM Project authors | BSD-3-Clause | `runtime/ov_movie.c` (VP9 decoding of the `Event/Movie` WebM files) | | MacNativeGames TotK resolution patches: output, swapchain and scene size sites and instruction words for 1.2.1 and 1.4.3, the data-page layout, the HeapDef heap names and sizes | https://github.com/ly05010419/MacNativeGames @ `aaf6ba1f494fabaa209d049e528d6f923dfe822a` (`games/totk/runtime/game_patches.c`, `game_patches_v143.c`, `game_version.h`, `games/totk/scripts/make_output_res_overlay.py`), Copyright (c) 2026 MacNativeGames contributors | MIT | `recomp/patches-v121.txt`, `recomp/patches-v143.txt`, `runtime/resolution.c` | +| AMD FSR SDK ffx-api declarations (`ffx_api.h`, `ffx_api_types.h`, `vk/ffx_api_vk.h`, `upscalers/include/ffx_upscale.h`, trimmed to the declarations used, layouts unchanged) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK @ tag `v2.4.0`, Copyright (C) 2026 Advanced Micro Devices, Inc. | MIT | `runtime/ffx_api_min.h` | +| AMD FSR SDK signed binaries `amd_fidelityfx_loader_vk.dll` and `amd_fidelityfx_upscaler_vk.dll` (not in this repository or the release: the setup's `--fsr` step downloads AMD's copies into the install folder) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK @ tag `v2.4.0` (`Kits/FidelityFX/signedbin/`), Copyright (C) 2026 Advanced Micro Devices, Inc. | AMD FSR SDK license (`docs/license.md` of that tag): redistribution in binary form with its notice, no reverse engineering | loaded at run time by `runtime/vk_ffx.c` | | AMD FidelityFX Super Resolution 1.0 (`ffx_a.h`, `ffx_fsr1.h`, unmodified; licence text in `runtime/shaders/ffx/LICENSE.txt`) | https://github.com/GPUOpen-Effects/FidelityFX-FSR @ `a21ffb8f6c13233ba336352bdff293894c706575`, Copyright (c) 2021 Advanced Micro Devices, Inc. | MIT | `runtime/shaders/ffx/`, `runtime/shaders/fsr_easu.comp`, `runtime/shaders/fsr_rcas.comp` (compiled into `runtime/fsr_easu_spv.h`, `runtime/fsr_rcas_spv.h`) | | AMD Display Library (ADL) declarations: `AdapterInfo`, `ADLSingleSensorData`, `ADLPMLogDataOutput`, the `ADL_PMLOG_*` sensor numbers and the `ADL2_*` function signatures | https://github.com/GPUOpen-LibrariesAndSDKs/display-library @ `84c881cb2136f04287eb3af12de00a9e2867aa9e` (`include/adl_structures.h`, `include/adl_defines.h`, `include/adl_sdk.h`), Copyright (c) 2016 - 2022 Advanced Micro Devices, Inc. | MIT | `runtime/perfmon.c` | | Zstandard 1.5.7 (MSYS2 `mingw-w64-ucrt-x86_64-zstd`), static link | https://github.com/facebook/zstd, Copyright (c) Meta Platforms, Inc. and affiliates | BSD-3-Clause | `runtime/resolution.c` (the HeapDef table), `runtime/ov_zstd.c` (the game's zstd frames decoded on the host) | diff --git a/docs/architecture.md b/docs/architecture.md index 0c123786..1d7dc3ec 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -129,6 +129,14 @@ Every guest thread is a host thread. TotK assumes Horizon's scheduler: three app that computes last frame's position from last frame's blocks (the game writes them into two copies that take turns; the uniform snapshot keeps both) and writes the difference into the motion image. `TOTK_MV_CHECK` measures the vectors against the picture, `TOTK_DLAA_TIMES` times the passes on the GPU. `fxaa` switches the game's own FXAA pass. +- FSR (`vk_ffx.c`, `dlaa_backend = fsr`, Windows). The same frame, jitter, motion vectors and masks go to AMD's FSR + instead of DLSS: `vk_dlaa.c` `evaluate` calls `vk_ffx_dispatch` where it would call NGX, and everything around it is + shared. `amd_fidelityfx_loader_vk.dll` (FSR SDK 2.4) is loaded at run time from the executable's folder and finds + `amd_fidelityfx_upscaler_vk.dll` next to it; only the descriptor layouts of `ffx_api_min.h` are compiled in. At + start the upscaler's versions for the device are listed and the newest FSR 4 is pinned where the DLL offers it (the + DLL decides which GPUs get it), else its default (FSR 3.1). `vk_device.c` enables `VK_KHR_cooperative_matrix` and + `VK_EXT_shader_float8` with their features when the device has them. FSR also asks for the camera's near and far + distances and field of view, which `cam_params` reads from the projection in the scene camera block. - 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`). diff --git a/docs/installer.md b/docs/installer.md index 46d8c5c9..9e74e7c8 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -24,6 +24,7 @@ The install folder (`main.c` `portable_paths()` reads this layout; it stays port / totk.exe, SDL3.dll, libopus-0.dll, totk_xlate.exe nvngx_dlss.dll NVIDIA DLSS, downloaded by the setup's DLSS step when the player keeps it ticked + amd_fidelityfx_*_vk.dll AMD FSR (loader and upscaler), downloaded by the setup's FSR step likewise totk.ini language; the other keys as commented defaults (totk.ini.example) exefs/, romfs/ extracted from the player's files shared-fonts/ the Switch system fonts, with Chinese, Korean or Traditional Chinese text @@ -85,7 +86,13 @@ loads the saves 1.4.3 wrote. the library; NGX loads it from the folder of totk.exe for `dlaa` and the DLSS modes. A DLSS library already in the folder (a newer one the player put there) is kept. Without an RTX GPU the step only logs and does nothing; a failed download warns, the game runs without DLSS, and the next run of the setup tries again. -8. **Clean up** the temp folder, except the generated C and the objects (about 1.3 GB), and write +8. **FSR** (the window's tick box, on by default, or `--fsr`; Windows with an AMD GPU): download + `amd_fidelityfx_loader_vk.dll` and `amd_fidelityfx_upscaler_vk.dll` from AMD's FSR SDK repository + (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK, tag `v2.4.0`, `Kits/FidelityFX/signedbin/`, AMD FSR SDK + license) into the install folder and check their sizes and SHA-256 (`steps.py`, `Fsr`). Both go in only when both + downloaded and matched. `dlaa_backend = fsr` loads them from the folder of totk.exe. Libraries already in the folder + are kept; without an AMD GPU the step only logs; a failed download warns and the next run tries again. +9. **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`). diff --git a/docs/settings.md b/docs/settings.md index eb7cee24..bcb0a367 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -156,6 +156,8 @@ Many rows below are developer tools that only act together with another setting | `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 | +| `fsr_debug` (default `0`) | `1` creates the FSR contexts (`dlaa_backend = fsr`) with AMD's API checks on, whose findings go to the log. | Adds log output and some CPU time per frame; a test setting. | Caution | +| `fsr_jitter_sign` (default `1`) | `-1` hands FSR the camera jitter with the opposite sign (`dlaa_backend = fsr`). | With the wrong sign FSR's picture wobbles and loses detail; a test setting for checking the convention. | 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 | diff --git a/installer/cli.py b/installer/cli.py index 14fa57ed..f3dfb633 100644 --- a/installer/cli.py +++ b/installer/cli.py @@ -1,5 +1,5 @@ """Command line: python -m installer --base FILE --update FILE --keys FILE --lang CODE --dest DIR [--firmware DIR] - [--root DIR] [--temp DIR] [--verify] [--dlss] + [--root DIR] [--temp DIR] [--verify] [--dlss] [--fsr] A first install needs every option. --firmware names the Switch firmware folder (an unpacked firmware or an emulator's Contents/registered); the setup extracts the system shared fonts from it when the language is Chinese, Korean or @@ -9,7 +9,9 @@ extraction has to run again. Prints JSON events on stdout (events.py). Exit code line, 3 cancelled (Ctrl+C or Ctrl+Break). --dlss downloads NVIDIA's DLSS library (nvngx_dlss.dll) from NVIDIA's DLSS SDK repository into the install folder on -Windows with an NVIDIA RTX GPU (steps.py, Dlss). +Windows with an NVIDIA RTX GPU (steps.py, Dlss). --fsr downloads AMD's FSR loader and upscaler +(amd_fidelityfx_loader_vk.dll, amd_fidelityfx_upscaler_vk.dll) from AMD's FSR SDK repository into the install folder on +Windows with an AMD GPU (steps.py, Fsr). """ import argparse import hashlib @@ -63,6 +65,8 @@ def main(argv=None): ap.add_argument('--verify', action='store_true', help='hash every kept file, also those this release made') ap.add_argument('--dlss', action='store_true', help="download NVIDIA's nvngx_dlss.dll (NVIDIA RTX SDK license) next " 'to the game, for dlaa and the DLSS modes') + ap.add_argument('--fsr', action='store_true', help="download AMD's FSR loader and upscaler DLLs (AMD FSR SDK " + 'license) next to the game, for dlaa_backend = fsr') args = ap.parse_args(argv) # The window cancels with Ctrl+Break to the installer's process group (CREATE_NEW_PROCESS_GROUP), which also reaches diff --git a/installer/gui.py b/installer/gui.py index 9c0dc1fd..b19980ac 100644 --- a/installer/gui.py +++ b/installer/gui.py @@ -273,6 +273,11 @@ class App: self.bind_text(dlss, 'text', 'ui.dlss') dlss.pack(anchor='w', pady=(dpi.px(8), 0)) self.label(f, 'ui.dlss_help', wraplength=WRAP, justify='left').pack(anchor='w', padx=(dpi.px(22), 0)) + self.fsr_var = tk.BooleanVar(value=True) + fsr = ttk.Checkbutton(f, variable=self.fsr_var) + self.bind_text(fsr, 'text', 'ui.fsr') + fsr.pack(anchor='w', pady=(dpi.px(8), 0)) + self.label(f, 'ui.fsr_help', wraplength=WRAP, justify='left').pack(anchor='w', padx=(dpi.px(22), 0)) self.update_hint = ttk.Label(f, wraplength=WRAP, justify='left') self.update_hint.pack(anchor='w', pady=(dpi.px(8), 0)) self.form_error = ttk.Label(f, style='Err.TLabel', wraplength=WRAP, justify='left') @@ -344,7 +349,7 @@ class App: def form(self): return Form(base=self.vars['base'].get(), update=self.vars['update'].get(), keys=self.vars['keys'].get(), firmware=self.vars['firmware'].get(), lang=self.selected_lang(), dest=self.vars['dest'].get(), - dlss=self.dlss_var.get()) + dlss=self.dlss_var.get(), fsr=self.fsr_var.get()) def set_prefill(self, name, value): self.programmatic = True @@ -619,7 +624,7 @@ class App: # ---- self test --------------------------------------------------------------------------------------------------- SAMPLE_START = {'type': 'start', 'release': 'selftest', 'mode': 'install', 'dest': 'Z:/selftest/TotK', 'log': 'D:\\log.txt', - 'steps': ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'dlss', 'cleanup']} + 'steps': ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'dlss', 'fsr', 'cleanup']} SAMPLE_RUN = [ SAMPLE_START, {'type': 'plan', 'run': ['check', 'fonts', 'extract'], 'skip': {}}, diff --git a/installer/guilogic.py b/installer/guilogic.py index f17a2dc4..1b369953 100644 --- a/installer/guilogic.py +++ b/installer/guilogic.py @@ -27,7 +27,7 @@ TEXT = Path(__file__).resolve().parent / 'text' UI_LANGUAGES = ('en', 'ru', 'pt-BR', 'zh-Hans') # what the language switch in the window's corner shows for each UI_LANGUAGE_LABELS = {'en': 'English', 'ru': 'Русский', 'pt-BR': 'Português (Brasil)', 'zh-Hans': '简体中文'} -STEP_ORDER = ('check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'dlss', 'cleanup') +STEP_ORDER = ('check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'dlss', 'fsr', 'cleanup') # message parameter -> catalog id prefix of the names that replace its raw values PARAM_NAMES = {'lang': 'lang.', 'known': 'lang.', 'step': 'step.', 'input': 'param.input.'} LANG_RU = 0x19 # primary language id of Russian in a Windows LANGID @@ -138,6 +138,7 @@ class Form: lang: str = '' dest: str = '' dlss: bool = False + fsr: bool = False def installed_state(self): """The recorded state of the install folder (totk-install.json), or None. Never raises.""" @@ -190,6 +191,8 @@ class Form: cmd.append('--verify') if self.dlss: cmd.append('--dlss') + if self.fsr: + cmd.append('--fsr') return cmd diff --git a/installer/steps.py b/installer/steps.py index 4db8a2b5..2efe1032 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -1,4 +1,4 @@ -"""The eight setup steps of docs/installer.md: check, fonts, extract, lift, compile, prepare, dlss, cleanup. +"""The nine setup steps of docs/installer.md: check, fonts, extract, lift, compile, prepare, dlss, fsr, cleanup. Extraction runs in this process through tools/extract.py (the package's sibling tools/, which ships with it); fonts runs the vendored extract_shared_fonts.py on the firmware folder; lift, compile and prepare run the bundled Python on @@ -7,7 +7,8 @@ recomp/gen.py, tools/build_game.py, tools/make_romfs_patches.py and tools/prepar with the bundled clang (hostcheck.c). Install folder: exefs/, romfs/ (romfs.bin, index.json), profile/, shared-fonts/ (Chinese and Korean text), totk.exe -and its DLLs, nvngx_dlss.dll (with --dlss), romfs-index.bin, romfs-patches/, romfs-patches-xbox/, +and its DLLs, nvngx_dlss.dll (with --dlss), amd_fidelityfx_loader_vk.dll and amd_fidelityfx_upscaler_vk.dll (with +--fsr), romfs-index.bin, romfs-patches/, romfs-patches-xbox/, romfs-patches-xbox-label/, romfs-patches-pc/, totk_xlate.exe, the shader state of totk.exe --prepare-shaders, totk.ini, totk-install.json. Temp folder (/-): check/ (ExeFS of both inputs, the host check), unpacked/ (the NSP of an NSZ @@ -1221,7 +1222,96 @@ class Dlss(Step): return {'installed': DLSS_VERSION} -# ---- 8. clean up +# ---- 8. AMD FSR + +# AMD's FSR upscaler for dlaa_backend = fsr (runtime/vk_ffx.c): the ffx-api loader and the upscaler effect, which the +# loader finds next to itself. AMD's FSR SDK license lets them be redistributed in binary form with its notice +# (THIRD_PARTY_NOTICES.md); the setup still does not ship them: with --fsr it downloads AMD's signed copies from the SDK +# repository at a pinned tag and checks their hashes. The game runs without them; dlaa_backend = fsr then does nothing. +FSR_VERSION = '2.4.0' # the FSR SDK release; the upscaler DLL is FSR 4.1.2 with FSR 3.1.6 inside +FSR_BASE = (f'https://raw.githubusercontent.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/v{FSR_VERSION}/' + 'Kits/FidelityFX/signedbin/') +FSR_FILES = ( # name, size, SHA-256 + ('amd_fidelityfx_loader_vk.dll', 39184, '38a56a01fb3565c0757d9f5c1e4e69de4b65e5f2e5769b323b200dc1f142bab9'), + ('amd_fidelityfx_upscaler_vk.dll', 36135696, '4a7e895af6e0b615d40a84d59eb8c2b1054ad91cdd0c739567940270d51bdab7'), +) +FSR_LICENSE = f'https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/blob/v{FSR_VERSION}/docs/license.md' + + +def amd_radeon(host): + """An AMD GPU among the host check's Vulkan devices: FSR 4 runs on Radeon RX 6000 and later, FSR 3.1 on older + ones.""" + return any('AMD' in d['name'].upper() or 'RADEON' in d['name'].upper() for d in (host or {}).get('devices', [])) + + +class Fsr(Step): + """With --fsr on Windows and an AMD GPU: AMD's FSR loader and upscaler next to totk.exe. Libraries the player put + there (other versions) are kept. A failed download warns and is tried again on the next run; the game runs + without them.""" + + id = 'fsr' + + def key(self, ctx): + if not getattr(ctx.options, 'fsr', False): + return fingerprint('fsr-1', 'off') + return fingerprint('fsr-1', FSR_VERSION, *(sha for _, _, sha in FSR_FILES)) + + def current(self, ctx, record): + if record.get('failed'): + return False + return not record.get('installed') or all((ctx.dest / name).is_file() for name, _, _ in FSR_FILES) + + def run(self, ctx): + if not getattr(ctx.options, 'fsr', False): + return {} + if os.name != 'nt': + return {'skipped': 'not_windows'} + if not amd_radeon(getattr(ctx, 'host', None)): + # The box is ticked by default, so most players without an AMD GPU never chose it: a log line, no warning + ctx.reporter.log('fsr: no AMD GPU among the Vulkan devices, nothing downloaded') + return {'skipped': 'no_amd'} + rep = ctx.reporter + present = [ctx.dest / name for name, _, _ in FSR_FILES if (ctx.dest / name).is_file()] + if present: + if all((ctx.dest / name).is_file() and file_sha256(ctx.dest / name) == sha for name, _, sha in FSR_FILES): + return {'installed': FSR_VERSION} + # A set the player put there (or half of one): kept as it is, the loader and its effect belong together + rep.warning('warn.fsr_kept', path=str(present[0])) + return {'kept': True} + total, done = sum(size for _, size, _ in FSR_FILES), 0 + rep.progress('fsr', 'download', 0, total, 'bytes', force=True) + rep.log(f'fsr: {FSR_BASE} (license {FSR_LICENSE})') + parts = [] + try: + for name, size, sha in FSR_FILES: + url, part = FSR_BASE + name, ctx.temp / (name + '.part') + parts.append(part) + part.parent.mkdir(parents=True, exist_ok=True) + h, got = hashlib.sha256(), 0 + with urllib.request.urlopen(url, timeout=60) as r, open(part, 'wb') as f: + while block := r.read(1 << 20): + f.write(block) + h.update(block) + got += len(block) + rep.progress('fsr', 'download', min(done + got, total), total, 'bytes') + if got != size or h.hexdigest() != sha: + raise OSError(f'{name}: {got} bytes, SHA-256 {h.hexdigest()[:16]}, not the expected file') + done += size + # both downloaded and checked: only then into the install folder, so it never holds half a set + for (name, _, _), part in zip(FSR_FILES, parts): + replace_file(part, ctx.dest / name) + remove(part) + # urllib's errors, timeouts and a bad file; a connection cut mid-file raises http.client.IncompleteRead, + # which is not an OSError + except (OSError, http.client.HTTPException) as e: + for part in parts: + remove(part) + rep.warning('warn.fsr_download_failed', url=FSR_BASE, detail=str(e)[:300]) + return {'failed': True} + return {'installed': FSR_VERSION} + + +# ---- 9. clean up class Cleanup(Step): id = 'cleanup' @@ -1289,4 +1379,4 @@ def romfs_problem(romfs, expected): def all_steps(): - return [Check(), Fonts(), Extract(), Lift(), Compile(), Prepare(), Dlss(), Cleanup()] + return [Check(), Fonts(), Extract(), Lift(), Compile(), Prepare(), Dlss(), Fsr(), Cleanup()] diff --git a/installer/text/en.json b/installer/text/en.json index 45618690..28c19e30 100644 --- a/installer/text/en.json +++ b/installer/text/en.json @@ -6,6 +6,7 @@ "step.compile": "Compiling {game_exe}", "step.prepare": "Preparing the shaders", "step.dlss": "Downloading NVIDIA DLSS", + "step.fsr": "Downloading AMD FSR", "step.cleanup": "Cleaning up", "phase.check.host": "Checking the processor and the graphics card", @@ -34,6 +35,7 @@ "phase.prepare.libraries": "Building the shaders for the graphics driver", "phase.prepare.pack": "Packing the shader cache into one file", "phase.dlss.download": "Downloading nvngx_dlss.dll from NVIDIA's DLSS SDK", + "phase.fsr.download": "Downloading the FSR upscaler from AMD's FSR SDK", "phase.cleanup.ini": "Writing totk.ini", "phase.cleanup.temp": "Removing temporary files", @@ -108,6 +110,8 @@ "warn.kernel_old": "Linux {version} lacks the write tracking the game relies on (6.7 or later); the game may run very slowly. Updating the system fixes this.", "warn.dlss_kept": "A DLSS library is already in the install folder ({path}); the setup keeps it.", "warn.dlss_download_failed": "NVIDIA DLSS could not be downloaded from {url}: {detail}. The game runs without it; the next setup run tries again.", + "warn.fsr_kept": "An FSR library is already in the install folder ({path}); the setup keeps the libraries there.", + "warn.fsr_download_failed": "AMD FSR 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", @@ -131,6 +135,8 @@ "ui.firmware_help": "For Chinese, Korean and Traditional Chinese text: the firmware's Contents/registered folder, for example from Ryujinx or Yuzu. The setup copies the Switch system fonts from it into the install folder.", "ui.dlss": "Download NVIDIA DLSS (nvngx_dlss.dll) for NVIDIA RTX graphics cards", "ui.dlss_help": "From NVIDIA's DLSS SDK on GitHub, under NVIDIA's RTX SDK license (github.com/NVIDIA/DLSS). It makes the dlaa and DLSS settings work; without it they do nothing.", + "ui.fsr": "Download AMD FSR 4 (amd_fidelityfx_upscaler_vk.dll) for AMD Radeon graphics cards", + "ui.fsr_help": "From AMD's FSR SDK on GitHub, under AMD's FSR SDK license (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). It lets the dlaa setting run FSR (Upscaler: AMD FSR in the menu); without it that choice does 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.type_game": "Game files (NSP, XCI, NSZ, XCZ)", "ui.type_keys": "Key files (*.keys)", diff --git a/installer/text/pt-BR.json b/installer/text/pt-BR.json index ace24acb..6587c253 100644 --- a/installer/text/pt-BR.json +++ b/installer/text/pt-BR.json @@ -6,6 +6,7 @@ "step.compile": "Compilando o {game_exe}", "step.prepare": "Preparando os shaders", "step.dlss": "Baixando o NVIDIA DLSS", + "step.fsr": "Baixando o AMD FSR", "step.cleanup": "Finalizando", "phase.check.host": "Verificando o processador e a placa de vídeo", @@ -34,6 +35,7 @@ "phase.prepare.libraries": "Montando os shaders para o driver de vídeo", "phase.prepare.pack": "Juntando o cache de shaders num único arquivo", "phase.dlss.download": "Baixando o nvngx_dlss.dll do DLSS SDK da NVIDIA", + "phase.fsr.download": "Baixando o upscaler FSR do FSR SDK da AMD", "phase.cleanup.ini": "Gravando o totk.ini", "phase.cleanup.temp": "Removendo os arquivos temporários", @@ -108,6 +110,8 @@ "warn.kernel_old": "O Linux {version} não tem o rastreamento de escrita de que o jogo depende (6.7 ou mais novo); o jogo pode rodar muito devagar. Atualizar o sistema resolve.", "warn.dlss_kept": "Já existe uma biblioteca DLSS na pasta de instalação ({path}); a instalação a mantém.", "warn.dlss_download_failed": "Não foi possível baixar o NVIDIA DLSS de {url}: {detail}. O jogo funciona sem ele; a próxima execução da instalação tenta de novo.", + "warn.fsr_kept": "Já existe uma biblioteca FSR na pasta de instalação ({path}); a instalação mantém as bibliotecas que estão lá.", + "warn.fsr_download_failed": "Não foi possível baixar o AMD FSR 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", @@ -131,6 +135,8 @@ "ui.firmware_help": "Para textos em chinês, coreano e chinês tradicional: a pasta Contents/registered do firmware, por exemplo do Ryujinx ou do Yuzu. A instalação copia dela as fontes do sistema do Switch para a pasta de instalação.", "ui.dlss": "Baixar o NVIDIA DLSS (nvngx_dlss.dll) para placas de vídeo NVIDIA RTX", "ui.dlss_help": "Do DLSS SDK da NVIDIA no GitHub, sob a licença NVIDIA RTX SDK (github.com/NVIDIA/DLSS). Sem ele as opções dlaa e DLSS não fazem nada.", + "ui.fsr": "Baixar o AMD FSR 4 (amd_fidelityfx_upscaler_vk.dll) para placas de vídeo AMD Radeon", + "ui.fsr_help": "Do FSR SDK da AMD no GitHub, sob a licença do AMD FSR SDK (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). Permite que a opção dlaa use o FSR (Upscaler: AMD FSR no menu); sem ele essa escolha não faz 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.type_game": "Arquivos de jogo (NSP, XCI, NSZ, XCZ)", "ui.type_keys": "Arquivos de chaves (*.keys)", diff --git a/installer/text/ru.json b/installer/text/ru.json index 667b92e8..4fc2a125 100644 --- a/installer/text/ru.json +++ b/installer/text/ru.json @@ -6,6 +6,7 @@ "step.compile": "Сборка {game_exe}", "step.prepare": "Подготовка шейдеров", "step.dlss": "Загрузка NVIDIA DLSS", + "step.fsr": "Загрузка AMD FSR", "step.cleanup": "Уборка", "phase.check.host": "Проверка процессора и видеокарты", @@ -34,6 +35,7 @@ "phase.prepare.libraries": "Сборка шейдеров для драйвера видеокарты", "phase.prepare.pack": "Упаковка кэша шейдеров в один файл", "phase.dlss.download": "Загрузка nvngx_dlss.dll из DLSS SDK от NVIDIA", + "phase.fsr.download": "Загрузка апскейлера FSR из FSR SDK от AMD", "phase.cleanup.ini": "Запись totk.ini", "phase.cleanup.temp": "Удаление временных файлов", @@ -108,6 +110,8 @@ "warn.kernel_old": "В Linux {version} нет отслеживания записи, на которое опирается игра (нужна версия 6.7 или новее); игра может работать очень медленно. Обновление системы это исправит.", "warn.dlss_kept": "В папке установки уже есть библиотека DLSS ({path}); установка её оставляет.", "warn.dlss_download_failed": "Не удалось загрузить NVIDIA DLSS с {url}: {detail}. Игра работает и без него; при следующем запуске установка попробует снова.", + "warn.fsr_kept": "В папке установки уже есть библиотека FSR ({path}); установка оставляет имеющиеся библиотеки.", + "warn.fsr_download_failed": "Не удалось загрузить AMD FSR с {url}: {detail}. Игра работает и без него; при следующем запуске установка попробует снова.", "ui.title": "Установка TotK", "ui.rebuild_title": "Пересборка игры под ваши моды", @@ -131,6 +135,8 @@ "ui.firmware_help": "Для текста на китайском и корейском: папка Contents/registered прошивки, например из Ryujinx или Yuzu. Установка скопирует из неё системные шрифты Switch в папку установки.", "ui.dlss": "Загрузить NVIDIA DLSS (nvngx_dlss.dll) для видеокарт NVIDIA RTX", "ui.dlss_help": "Из DLSS SDK от NVIDIA на GitHub, по лицензии NVIDIA RTX SDK (github.com/NVIDIA/DLSS). Без него настройки dlaa и DLSS ничего не делают.", + "ui.fsr": "Загрузить AMD FSR 4 (amd_fidelityfx_upscaler_vk.dll) для видеокарт AMD Radeon", + "ui.fsr_help": "Из FSR SDK от AMD на GitHub, по лицензии AMD FSR SDK (github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK). С ним настройка dlaa может работать через FSR («Апскейлер: AMD FSR» в меню); без него этот выбор ничего не делает.", "ui.compressed_help": "Сжатые файлы NSZ и XCZ подходят как есть: установка сама их распакует (для этого, пока извлекаются данные игры, нужно столько свободного места, сколько занимают распакованные файлы).", "ui.type_game": "Файлы игры (NSP, XCI, NSZ, XCZ)", "ui.type_keys": "Файлы ключей (*.keys)", diff --git a/installer/text/zh-Hans.json b/installer/text/zh-Hans.json index aa490a93..25a92b06 100644 --- a/installer/text/zh-Hans.json +++ b/installer/text/zh-Hans.json @@ -6,6 +6,7 @@ "step.compile": "编译 {game_exe}", "step.prepare": "准备着色器", "step.dlss": "下载 NVIDIA DLSS", + "step.fsr": "下载 AMD FSR", "step.cleanup": "清理", "phase.check.host": "检查处理器和显卡", @@ -34,6 +35,7 @@ "phase.prepare.libraries": "为显卡驱动构建着色器", "phase.prepare.pack": "将着色器缓存打包成一个文件", "phase.dlss.download": "从 NVIDIA 的 DLSS SDK 下载 nvngx_dlss.dll", + "phase.fsr.download": "从 AMD 的 FSR SDK 下载 FSR 超分辨率组件", "phase.cleanup.ini": "写入 totk.ini", "phase.cleanup.temp": "删除临时文件", @@ -108,6 +110,8 @@ "warn.kernel_old": "Linux {version} 缺少游戏依赖的写入跟踪功能(需要 6.7 或更新版本);游戏可能运行得很慢。更新系统即可解决。", "warn.dlss_kept": "安装文件夹中已有 DLSS 库({path});安装程序将保留它。", "warn.dlss_download_failed": "无法从 {url} 下载 NVIDIA DLSS:{detail}。游戏无需它也能运行;下次运行安装程序时会重试。", + "warn.fsr_kept": "安装文件夹中已有 FSR 库({path});安装程序将保留其中的库。", + "warn.fsr_download_failed": "无法从 {url} 下载 AMD FSR:{detail}。游戏无需它也能运行;下次运行安装程序时会重试。", "ui.title": "TotK 安装程序", "ui.rebuild_title": "正在为你的模组重新构建游戏", @@ -131,6 +135,8 @@ "ui.firmware_help": "用于中文、韩文和繁体中文文本:固件的 Contents/registered 文件夹,例如来自 Ryujinx 或 Yuzu。安装程序会从中把 Switch 系统字体复制到安装文件夹。", "ui.dlss": "为 NVIDIA RTX 显卡下载 NVIDIA DLSS(nvngx_dlss.dll)", "ui.dlss_help": "来自 GitHub 上 NVIDIA 的 DLSS SDK,遵循 NVIDIA RTX SDK 许可(github.com/NVIDIA/DLSS)。没有它,dlaa 和 DLSS 设置不起作用。", + "ui.fsr": "为 AMD Radeon 显卡下载 AMD FSR 4(amd_fidelityfx_upscaler_vk.dll)", + "ui.fsr_help": "来自 GitHub 上 AMD 的 FSR SDK,遵循 AMD FSR SDK 许可(github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK)。有了它,dlaa 设置可以使用 FSR(菜单中的“超分辨率技术:AMD FSR”);没有它,该选项不起作用。", "ui.compressed_help": "压缩的 NSZ 和 XCZ 文件可以直接使用:安装程序会自行解压(在游戏数据提取完成之前,需要与解压后文件大小相同的可用空间)。", "ui.type_game": "游戏文件(NSP、XCI、NSZ、XCZ)", "ui.type_keys": "密钥文件(*.keys)", diff --git a/runtime/cfg.c b/runtime/cfg.c index e2a06afd..63cf2dbc 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -40,10 +40,10 @@ static const char *const known[] = { "BIND_SKIP", "BIND_STATS", "BIND_UP", "BIND_X", "BIND_Y", "BIND_ZL", "BIND_ZR", "BLOCK_VIEWS_3D", "CLOTH_REALTIME", "COLOR_BRIGHTNESS", "COLOR_CONTRAST", "COLOR_GAMMA", "COLOR_PRESET", "COLOR_SATURATION", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT", - "DESC_TEMPLATE", "DEVICE_PROFILE", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR", + "DESC_TEMPLATE", "DEVICE_PROFILE", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_BACKEND", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR", "DUMP_LOG", "EXEFS", "FEEDBACK", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES", "FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FLUSH_SPAN", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FRAME_QUEUE", - "FREEZE_IDLE", "FREE_CORES", + "FREEZE_IDLE", "FREE_CORES", "FSR_DEBUG", "FSR_JITTER_SIGN", "FULLSCREEN", "FXAA", "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "HDR", "HDR_GAME_NITS", "HDR_HUE", "HDR_PEAK_NITS", "HDR_UI_NITS", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "LSTICK_DEADZONE", "MEMORY", "MENU_LANG", "MENU_TEST", @@ -76,7 +76,7 @@ static const struct { const char *key, *section; } sections[] = { {"COLOR_BRIGHTNESS", "display"}, {"COLOR_CONTRAST", "display"}, {"COLOR_SATURATION", "display"}, {"COLOR_GAMMA", "display"}, {"HDR", "display"}, {"HDR_PEAK_NITS", "display"}, {"HDR_GAME_NITS", "display"}, {"HDR_UI_NITS", "display"}, {"HDR_HUE", "display"}, {"SHADOW_RES", "display"}, - {"DLAA", "display"}, {"DLSS", "display"}, {"DLSS_PRESET", "display"}, {"DLSS_CHAR_MASK", "display"}, {"FXAA", "display"}, + {"DLAA", "display"}, {"DLAA_BACKEND", "display"}, {"DLSS", "display"}, {"DLSS_PRESET", "display"}, {"DLSS_CHAR_MASK", "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"}, {"CONTACT_SHADOWS", "display"}, @@ -120,7 +120,7 @@ static const CfgMeta metas[] = { {"PERF_OVERLAY", "off", "off|fps|full", LIVE}, {"OUTPUT_RES", "1920x1080", NULL, RESTART}, {"RENDER_SCALE", "game", "game|50|67|75|100|125|150|200", RESTART}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, - {"DLAA", "0", "0|1", RESTART}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance|ultra_performance", LIVE}, + {"DLAA", "0", "0|1", RESTART}, {"DLAA_BACKEND", "dlss", "dlss|fsr", RESTART}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance|ultra_performance", LIVE}, {"DLSS_PRESET", "default", "default|k|j", LIVE}, {"DLSS_CHAR_MASK", "65", "0|35|65|100", LIVE}, {"FXAA", "1", "0|1", LIVE}, {"ASPECT", "fit", "fit|stretch", LIVE}, {"MOVIE_ASPECT", "keep", "keep|stretch", LIVE}, {"FOV", "100", "70..140", LIVE}, diff --git a/runtime/ffx_api_min.h b/runtime/ffx_api_min.h new file mode 100644 index 00000000..c29c23f1 --- /dev/null +++ b/runtime/ffx_api_min.h @@ -0,0 +1,245 @@ +// The part of AMD's FSR API (ffx-api) that vk_ffx.c uses: the entry points of amd_fidelityfx_loader_vk.dll, the +// Vulkan backend descriptor and the upscaler's create and dispatch descriptors. Copied from the FidelityFX SDK v2.4.0 +// (GPUOpen-LibrariesAndSDKs/FidelityFX-SDK, Kits/FidelityFX/api/include/ffx_api.h, ffx_api_types.h, vk/ffx_api_vk.h +// and Kits/FidelityFX/upscalers/include/ffx_upscale.h), trimmed to those declarations; the layouts and values are +// unchanged. The SDK's headers use a C++ attribute for deprecations, so they are not included as they are. +// +// This file is part of the FidelityFX SDK. +// +// Copyright (C) 2026 Advanced Micro Devices, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files(the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and /or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions : +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +#pragma once +#include +#include +#include + +#include + +// ---- ffx_api.h +enum FfxApiReturnCodes { + FFX_API_RETURN_OK = 0, + FFX_API_RETURN_ERROR = 1, + FFX_API_RETURN_ERROR_UNKNOWN_DESCTYPE = 2, + FFX_API_RETURN_ERROR_RUNTIME_ERROR = 3, + FFX_API_RETURN_NO_PROVIDER = 4, + FFX_API_RETURN_ERROR_MEMORY = 5, + FFX_API_RETURN_ERROR_PARAMETER = 6, + FFX_API_RETURN_PROVIDER_NO_SUPPORT_NEW_DESCTYPE = 7, +}; + +typedef void *ffxContext; +typedef uint32_t ffxReturnCode_t; + +#define FFX_API_EFFECT_MASK 0x00ff0000u +#define FFX_API_BACKEND_MASK 0xff000000u + +typedef uint64_t ffxStructType_t; +typedef struct ffxApiHeader { + ffxStructType_t type; + struct ffxApiHeader *pNext; +} ffxApiHeader; + +typedef ffxApiHeader ffxCreateContextDescHeader; +typedef ffxApiHeader ffxConfigureDescHeader; +typedef ffxApiHeader ffxQueryDescHeader; +typedef ffxApiHeader ffxDispatchDescHeader; + +enum FfxApiMsgType { FFX_API_MESSAGE_TYPE_ERROR = 0, FFX_API_MESSAGE_TYPE_WARNING = 1 }; +typedef void (*ffxApiMessage)(uint32_t type, const wchar_t *message); + +#define FFX_API_QUERY_DESC_TYPE_GET_VERSIONS 4u +struct ffxQueryDescGetVersions { + ffxQueryDescHeader header; + uint64_t createDescType; + void *device; // Vulkan: a VkDeviceContext * + uint64_t *outputCount; + uint64_t *versionIds; + const char **versionNames; +}; + +#define FFX_API_DESC_TYPE_OVERRIDE_VERSION 5u +struct ffxOverrideVersion { + ffxApiHeader header; + uint64_t versionId; +}; + +#define FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION 6u +struct ffxQueryGetProviderVersion { + ffxQueryDescHeader header; + uint64_t versionId; + const char *versionName; +}; + +typedef struct ffxAllocationCallbacks ffxAllocationCallbacks; +typedef ffxReturnCode_t (*PfnFfxCreateContext)(ffxContext *context, ffxCreateContextDescHeader *desc, + const ffxAllocationCallbacks *memCb); +typedef ffxReturnCode_t (*PfnFfxDestroyContext)(ffxContext *context, const ffxAllocationCallbacks *memCb); +typedef ffxReturnCode_t (*PfnFfxQuery)(ffxContext *context, ffxQueryDescHeader *desc); +typedef ffxReturnCode_t (*PfnFfxDispatch)(ffxContext *context, const ffxDispatchDescHeader *desc); + +#define FFX_API_EFFECT_ID_UPSCALE 0x00010000u +#define FFX_API_MAKE_EFFECT_SUB_ID(effectId, subversion) ((effectId & FFX_API_EFFECT_MASK) | (subversion & ~FFX_API_EFFECT_MASK)) +#define FFX_API_BACKEND_ID_VK 0x01000000u +#define FFX_API_MAKE_BACKEND_SUB_ID(backendId, subversion) ((backendId & FFX_API_BACKEND_MASK) | (subversion & ~FFX_API_BACKEND_MASK)) + +// ---- ffx_api_types.h +enum FfxApiSurfaceFormat { + FFX_API_SURFACE_FORMAT_UNKNOWN, + FFX_API_SURFACE_FORMAT_R32G32B32A32_TYPELESS, + FFX_API_SURFACE_FORMAT_R32G32B32A32_UINT, + FFX_API_SURFACE_FORMAT_R32G32B32A32_FLOAT, + FFX_API_SURFACE_FORMAT_R16G16B16A16_FLOAT, + FFX_API_SURFACE_FORMAT_R32G32B32_FLOAT, + FFX_API_SURFACE_FORMAT_R32G32_FLOAT, + FFX_API_SURFACE_FORMAT_R8_UINT, + FFX_API_SURFACE_FORMAT_R32_UINT, + FFX_API_SURFACE_FORMAT_R8G8B8A8_TYPELESS, + FFX_API_SURFACE_FORMAT_R8G8B8A8_UNORM, + FFX_API_SURFACE_FORMAT_R8G8B8A8_SNORM, + FFX_API_SURFACE_FORMAT_R8G8B8A8_SRGB, + FFX_API_SURFACE_FORMAT_B8G8R8A8_TYPELESS, + FFX_API_SURFACE_FORMAT_B8G8R8A8_UNORM, + FFX_API_SURFACE_FORMAT_B8G8R8A8_SRGB, + FFX_API_SURFACE_FORMAT_R11G11B10_FLOAT, + FFX_API_SURFACE_FORMAT_R10G10B10A2_UNORM, + FFX_API_SURFACE_FORMAT_R16G16_FLOAT, + FFX_API_SURFACE_FORMAT_R16G16_UINT, + FFX_API_SURFACE_FORMAT_R16G16_SINT, + FFX_API_SURFACE_FORMAT_R16_FLOAT, + FFX_API_SURFACE_FORMAT_R16_UINT, + FFX_API_SURFACE_FORMAT_R16_UNORM, + FFX_API_SURFACE_FORMAT_R16_SNORM, + FFX_API_SURFACE_FORMAT_R8_UNORM, + FFX_API_SURFACE_FORMAT_R8G8_UNORM, + FFX_API_SURFACE_FORMAT_R8G8_UINT, + FFX_API_SURFACE_FORMAT_R32_FLOAT, +}; + +enum FfxApiResourceUsage { + FFX_API_RESOURCE_USAGE_READ_ONLY = 0, + FFX_API_RESOURCE_USAGE_RENDERTARGET = (1 << 0), + FFX_API_RESOURCE_USAGE_UAV = (1 << 1), + FFX_API_RESOURCE_USAGE_DEPTHTARGET = (1 << 2), +}; + +enum FfxApiResourceState { + FFX_API_RESOURCE_STATE_COMMON = (1 << 0), + FFX_API_RESOURCE_STATE_UNORDERED_ACCESS = (1 << 1), + FFX_API_RESOURCE_STATE_COMPUTE_READ = (1 << 2), + FFX_API_RESOURCE_STATE_PIXEL_READ = (1 << 3), + FFX_API_RESOURCE_STATE_COPY_SRC = (1 << 4), + FFX_API_RESOURCE_STATE_GENERIC_READ = (FFX_API_RESOURCE_STATE_COPY_SRC | FFX_API_RESOURCE_STATE_COMPUTE_READ), +}; + +enum FfxApiResourceType { FFX_API_RESOURCE_TYPE_BUFFER, FFX_API_RESOURCE_TYPE_TEXTURE1D, FFX_API_RESOURCE_TYPE_TEXTURE2D }; + +struct FfxApiDimensions2D { + uint32_t width, height; +}; +struct FfxApiFloatCoords2D { + float x, y; +}; + +struct FfxApiResourceDescription { + uint32_t type; + uint32_t format; + uint32_t width; // union with size (buffers) + uint32_t height; // union with stride + uint32_t depth; // union with alignment + uint32_t mipCount; + uint32_t flags; + uint32_t usage; +}; + +struct FfxApiResource { + void *resource; // Vulkan: the VkImage + struct FfxApiResourceDescription description; + uint32_t state; +}; + +// ---- vk/ffx_api_vk.h +typedef struct VkDeviceContext { + VkDevice vkDevice; + VkPhysicalDevice vkPhysicalDevice; + PFN_vkGetDeviceProcAddr vkDeviceProcAddr; +} VkDeviceContext; + +#define FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK FFX_API_MAKE_BACKEND_SUB_ID(FFX_API_BACKEND_ID_VK, 0x03) +struct ffxCreateBackendVKDesc { + ffxCreateContextDescHeader header; + VkDeviceContext deviceContext; +}; + +// ---- upscalers/include/ffx_upscale.h +#define FFX_UPSCALER_MAKE_VERSION(major, minor, patch) (((major) << 22) | ((minor) << 12) | (patch)) +#define FFX_UPSCALER_VERSION FFX_UPSCALER_MAKE_VERSION(4, 1, 2) + +enum FfxApiCreateContextUpscaleFlags { + FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE = (1 << 0), + FFX_UPSCALE_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS = (1 << 1), + FFX_UPSCALE_ENABLE_MOTION_VECTORS_JITTER_CANCELLATION = (1 << 2), + FFX_UPSCALE_ENABLE_DEPTH_INVERTED = (1 << 3), + FFX_UPSCALE_ENABLE_DEPTH_INFINITE = (1 << 4), + FFX_UPSCALE_ENABLE_AUTO_EXPOSURE = (1 << 5), + FFX_UPSCALE_ENABLE_DYNAMIC_RESOLUTION = (1 << 6), + FFX_UPSCALE_ENABLE_DEBUG_CHECKING = (1 << 7), +}; + +#define FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x00) +struct ffxCreateContextDescUpscale { + ffxCreateContextDescHeader header; + uint32_t flags; + struct FfxApiDimensions2D maxRenderSize; + struct FfxApiDimensions2D maxUpscaleSize; + ffxApiMessage fpMessage; +}; + +#define FFX_API_DISPATCH_DESC_TYPE_UPSCALE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x01) +struct ffxDispatchDescUpscale { + ffxDispatchDescHeader header; + void *commandList; // Vulkan: the VkCommandBuffer + struct FfxApiResource color; + struct FfxApiResource depth; + struct FfxApiResource motionVectors; + struct FfxApiResource exposure; + struct FfxApiResource reactive; + struct FfxApiResource transparencyAndComposition; + struct FfxApiResource output; + struct FfxApiFloatCoords2D jitterOffset; + struct FfxApiFloatCoords2D motionVectorScale; + struct FfxApiDimensions2D renderSize; + struct FfxApiDimensions2D upscaleSize; + bool enableSharpening; + float sharpness; + float frameTimeDelta; // milliseconds + float preExposure; + bool reset; + float cameraNear; + float cameraFar; + float cameraFovAngleVertical; // radians + float viewSpaceToMetersFactor; + uint32_t flags; +}; + +#define FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE_VERSION FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x0b) +struct ffxCreateContextDescUpscaleVersion { + ffxCreateContextDescHeader header; + uint32_t version; // FFX_UPSCALER_VERSION +}; diff --git a/runtime/resolution.c b/runtime/resolution.c index 6c36e8ce..2b645e62 100644 --- a/runtime/resolution.c +++ b/runtime/resolution.c @@ -67,15 +67,25 @@ static struct { // The scene size is decided before the device exists, so NGX cannot be asked yet. NGX loads DLSS from nvngx_dlss.dll // next to totk.exe on Windows, libnvidia-ngx-dlss.so. next to totk on Linux (vk_dlaa.c vk_dlaa_init): // without that file DLSS never runs, and a DLSS mode would leave the game's plain scaling at 50..67 % of the output. +// With dlaa_backend = fsr the modes scale through AMD's FSR instead (vk_ffx.c), which needs its loader and upscaler +// DLLs next to totk.exe; on Linux FSR does not run. static int dlss_dll(void) { + int fsr = !strcmp(cfg_value("TOTK_DLAA_BACKEND"), "fsr"); #ifdef _WIN32 - char exe[1024], path[1024 + 32]; + char exe[1024], path[1024 + 48]; if (!plat_exe_path(exe, sizeof exe)) return 1; char *last = plat_last_sep(exe); if (!last) return 1; + if (fsr) { + snprintf(path, sizeof path, "%.*s/amd_fidelityfx_loader_vk.dll", (int)(last - exe), exe); + if (!plat_file_exists(path)) return 0; + snprintf(path, sizeof path, "%.*s/amd_fidelityfx_upscaler_vk.dll", (int)(last - exe), exe); + return plat_file_exists(path); + } snprintf(path, sizeof path, "%.*s/nvngx_dlss.dll", (int)(last - exe), exe); return plat_file_exists(path); #else + if (fsr) return 0; char exe[1024]; if (!plat_exe_path(exe, sizeof exe)) return 1; char *last = plat_last_sep(exe); @@ -110,8 +120,12 @@ static double dlss_share(const char *m) { if (!strcmp(m, dlss[i].name)) { if (dll < 0 && !(dll = dlss_dll())) { #ifdef _WIN32 - rt_log("resolution: DLSS %s needs nvngx_dlss.dll next to totk.exe, which is missing: the scene follows " - "render_scale", m); + if (!strcmp(cfg_value("TOTK_DLAA_BACKEND"), "fsr")) + rt_log("resolution: FSR %s needs amd_fidelityfx_loader_vk.dll and amd_fidelityfx_upscaler_vk.dll " + "next to totk.exe, which are missing: the scene follows render_scale", m); + else + rt_log("resolution: DLSS %s needs nvngx_dlss.dll next to totk.exe, which is missing: the scene " + "follows render_scale", m); #else rt_log("resolution: DLSS %s needs libnvidia-ngx-dlss.so. next to totk, which is missing: the " "scene follows render_scale", m); diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index aa845156..fe2bcd2e 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -680,6 +680,8 @@ static void tab_screen(float scale) { opt_slider("TOTK_PCSS", UI_MENU_PCSS, 0, 200, UI_MENU_PCSS_DESC, 10, "%.0f %%"); opt_slider("TOTK_CONTACT_SHADOWS", UI_MENU_CONTACT_SHADOWS, 0, 100, UI_MENU_CONTACT_SHADOWS_DESC, 10, "%.0f %%"); opt_toggle("TOTK_DLAA", UI_MENU_DLAA, UI_MENU_DLAA_DESC); + static const UiTextId backend[] = {UI_MENU_DLAA_BACKEND_DLSS, UI_MENU_DLAA_BACKEND_FSR}; + opt_choice("TOTK_DLAA_BACKEND", UI_MENU_DLAA_BACKEND, backend, 2, UI_MENU_DLAA_BACKEND_DESC); static const UiTextId dlss[] = {UI_MENU_DLSS_DLAA, UI_MENU_DLSS_QUALITY, UI_MENU_DLSS_BALANCED, UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA}; opt_choice("TOTK_DLSS", UI_MENU_DLSS, dlss, 5, UI_MENU_DLSS_DESC); diff --git a/runtime/ui_text.c b/runtime/ui_text.c index f4e033c5..8ef51cba 100644 --- a/runtime/ui_text.c +++ b/runtime/ui_text.c @@ -143,6 +143,12 @@ static const char *const text_en[UI_TEXT_COUNT] = { [UI_MENU_DLAA_DESC] = "NVIDIA DLSS for the 3D scene (NVIDIA RTX GPUs; " DLSS_FILE " next to " EXE_FILE "): smoother " "edges and less shimmer. The HUD is not touched. The mode below sets the resolution it works " "from. Takes effect after a restart.", + [UI_MENU_DLAA_BACKEND] = "Upscaler", + [UI_MENU_DLAA_BACKEND_DESC] = "What runs for the option above. NVIDIA DLSS on NVIDIA RTX GPUs; AMD FSR on AMD Radeon " + "GPUs: FSR 4 on the RX 9000, 7000 and 6000 series, FSR 3.1 elsewhere (Windows; " + "amd_fidelityfx_loader_vk.dll and amd_fidelityfx_upscaler_vk.dll next to " EXE_FILE + "). The mode below applies to both. Takes effect after a restart.", + [UI_MENU_DLAA_BACKEND_DLSS] = "NVIDIA DLSS", [UI_MENU_DLAA_BACKEND_FSR] = "AMD FSR", [UI_MENU_DLSS_PRESET] = "DLSS model", [UI_MENU_DLSS_PRESET_DESC] = "Which DLSS model runs. Automatic follows NVIDIA's advice per mode: K for DLAA, Quality " "and Balanced, M for Performance, L for Ultra Performance. J: slightly less ghosting " @@ -618,6 +624,12 @@ static const char *const text_ru[UI_TEXT_COUNT] = { [UI_MENU_DLAA_DESC] = "NVIDIA DLSS для 3D-сцены (видеокарты NVIDIA RTX; " DLSS_FILE " рядом с " EXE_FILE "): ровнее " "края и меньше мерцания. Интерфейс не затрагивается. Режим ниже задаёт разрешение, с которым он " "работает. Действует после перезапуска.", + [UI_MENU_DLAA_BACKEND] = "Апскейлер", + [UI_MENU_DLAA_BACKEND_DESC] = "Что работает для настройки выше. NVIDIA DLSS на видеокартах NVIDIA RTX; AMD FSR на " + "видеокартах AMD Radeon: FSR 4 на сериях RX 9000, 7000 и 6000, FSR 3.1 на остальных " + "(Windows; amd_fidelityfx_loader_vk.dll и amd_fidelityfx_upscaler_vk.dll рядом с " + EXE_FILE "). Режим ниже действует для обоих. Действует после перезапуска.", + [UI_MENU_DLAA_BACKEND_DLSS] = "NVIDIA DLSS", [UI_MENU_DLAA_BACKEND_FSR] = "AMD FSR", [UI_MENU_DLSS_PRESET] = "Модель DLSS", [UI_MENU_DLSS_PRESET_DESC] = "Какая модель DLSS работает. «Автоматически» следует совету NVIDIA для каждого режима: K " "для DLAA, «Качества» и «Баланса», M для «Производительности», L для «Макс. " @@ -1433,6 +1445,12 @@ static const char *const text_pt_br[UI_TEXT_COUNT] = { [UI_MENU_DLAA_DESC] = "NVIDIA DLSS para a cena 3D (placas NVIDIA RTX; nvngx_dlss.dll ao lado do totk.exe): bordas " "mais suaves e menos cintilação. O HUD não é afetado. O modo abaixo define a resolução de " "onde ele parte. Vale após reiniciar.", + [UI_MENU_DLAA_BACKEND] = "Upscaler", + [UI_MENU_DLAA_BACKEND_DESC] = "O que roda na opção acima. NVIDIA DLSS em placas NVIDIA RTX; AMD FSR em placas AMD " + "Radeon: FSR 4 nas séries RX 9000, 7000 e 6000, FSR 3.1 nas demais (Windows; " + "amd_fidelityfx_loader_vk.dll e amd_fidelityfx_upscaler_vk.dll ao lado do totk.exe). " + "O modo abaixo vale para os dois. Vale após reiniciar.", + [UI_MENU_DLAA_BACKEND_DLSS] = "NVIDIA DLSS", [UI_MENU_DLAA_BACKEND_FSR] = "AMD FSR", [UI_MENU_DLSS] = "Modo do DLSS", [UI_MENU_DLSS_DESC] = "DLAA desenha a cena 3D na resolução cheia. Qualidade, Equilibrado, Desempenho e Ultra " "Desempenho a desenham em 67, 58, 50 e 33 % e deixam o DLSS ampliá-la, o que poupa tempo da " @@ -2036,6 +2054,11 @@ static const char *const text_zh_hans[UI_TEXT_COUNT] = { [UI_MENU_DLAA] = "NVIDIA DLSS / DLAA", [UI_MENU_DLAA_DESC] = "用于 3D 场景的 NVIDIA DLSS(NVIDIA RTX 显卡;nvngx_dlss.dll 放在 totk.exe 旁):边缘更平滑,闪烁更少。HUD " "不受影响。下方的模式决定它的工作分辨率。重启后生效。", + [UI_MENU_DLAA_BACKEND] = "超分辨率技术", + [UI_MENU_DLAA_BACKEND_DESC] = "上方选项使用的技术。NVIDIA RTX 显卡用 NVIDIA DLSS;AMD Radeon 显卡用 AMD FSR:RX 9000、7000 " + "和 6000 系列为 FSR 4,其他为 FSR 3.1(Windows;amd_fidelityfx_loader_vk.dll 和 " + "amd_fidelityfx_upscaler_vk.dll 放在 totk.exe 旁)。下方的模式对两者都适用。重启后生效。", + [UI_MENU_DLAA_BACKEND_DLSS] = "NVIDIA DLSS", [UI_MENU_DLAA_BACKEND_FSR] = "AMD FSR", [UI_MENU_DLSS] = "DLSS 模式", [UI_MENU_DLSS_DESC] = "DLAA 以全分辨率绘制 3D 场景。质量、平衡、性能和超级性能分别以 67%、58%、50% 和 33% 绘制,再由 DLSS 放大,以节省 GPU 时间;它们会取代 3D 渲染比例。立即生效。", [UI_MENU_DLSS_DLAA] = "DLAA(原生)", diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 59e277b4..dd4fe343 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -54,7 +54,8 @@ typedef enum { UI_MENU_SHADOW_RANGE, UI_MENU_SHADOW_RANGE_DESC, UI_MENU_CONTACT_SHADOWS, UI_MENU_CONTACT_SHADOWS_DESC, UI_MENU_PCSS, UI_MENU_PCSS_DESC, - UI_MENU_DLAA, UI_MENU_DLAA_DESC, UI_MENU_DLSS, UI_MENU_DLSS_DESC, UI_MENU_DLSS_DLAA, UI_MENU_DLSS_QUALITY, + UI_MENU_DLAA, UI_MENU_DLAA_DESC, UI_MENU_DLAA_BACKEND, UI_MENU_DLAA_BACKEND_DESC, UI_MENU_DLAA_BACKEND_DLSS, + UI_MENU_DLAA_BACKEND_FSR, UI_MENU_DLSS, UI_MENU_DLSS_DESC, UI_MENU_DLSS_DLAA, UI_MENU_DLSS_QUALITY, UI_MENU_DLSS_BALANCED, UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA, UI_MENU_DLSS_PRESET, UI_MENU_DLSS_PRESET_DESC, UI_MENU_DLSS_PRESET_DEFAULT, UI_MENU_DLSS_PRESET_K, UI_MENU_DLSS_PRESET_J, UI_MENU_DLSS_CHARS, UI_MENU_DLSS_CHARS_DESC, UI_MENU_DLSS_CHARS_OFF, UI_MENU_DLSS_CHARS_LIGHT, UI_MENU_DLSS_CHARS_MEDIUM, UI_MENU_DLSS_CHARS_FULL, UI_MENU_FXAA, UI_MENU_FXAA_DESC, diff --git a/runtime/vk_device.c b/runtime/vk_device.c index a063955e..795d9891 100644 --- a/runtime/vk_device.c +++ b/runtime/vk_device.c @@ -217,6 +217,10 @@ typedef struct { VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT gpl; VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT fbl; VkPhysicalDeviceDynamicRenderingLocalReadFeaturesKHR lr; + VkPhysicalDeviceCooperativeMatrixFeaturesKHR coop; // FSR 4 (vk_ffx.c) +#ifdef VK_EXT_SHADER_FLOAT8_EXTENSION_NAME + VkPhysicalDeviceShaderFloat8FeaturesEXT f8; // FSR 4 (vk_ffx.c) +#endif } FeatureChain; static int create_device(void) { @@ -261,7 +265,16 @@ static int create_device(void) { CHAIN(fbl, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_LAYOUT_FEATURES_EXT); CHAIN(lr, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_LOCAL_READ_FEATURES_KHR); } - vk_dlaa_device_exts(ep, ne, ext, &n_ext, 40); // NGX's; the eight slots after it stay for the seven below + vk_dlaa_device_exts(ep, ne, ext, &n_ext, 40); // NGX's or FSR's; the eight slots after it stay for the seven below + // FSR's shader extensions (vk_ffx_device_exts) are enabled with their features, as far as the driver reports them + for (uint32_t i = 0; i < n_ext; i++) { + if (!strcmp(ext[i], VK_KHR_COOPERATIVE_MATRIX_EXTENSION_NAME)) + CHAIN(coop, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR); +#ifdef VK_EXT_SHADER_FLOAT8_EXTENSION_NAME + else if (!strcmp(ext[i], VK_EXT_SHADER_FLOAT8_EXTENSION_NAME)) + CHAIN(f8, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT8_FEATURES_EXT); +#endif + } if (has_ext(ep, ne, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME)) { g_vk.has_memory_budget = 1; ext[n_ext++] = VK_EXT_MEMORY_BUDGET_EXTENSION_NAME; } // GPU timestamps on the CPU clock (vk_sync.c): the perf line splits GPU idle time into waiting for a submission or not. if (has_ext(ep, ne, VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME)) { g_vk.has_calibrated = 2; ext[n_ext++] = VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME; } diff --git a/runtime/vk_dlaa.c b/runtime/vk_dlaa.c index 7ffff8c8..35005c5b 100644 --- a/runtime/vk_dlaa.c +++ b/runtime/vk_dlaa.c @@ -11,6 +11,10 @@ // layout with a set-then-get round trip before anything relies on it. // // Where DLAA runs in the frame, the jitter and the motion vectors: see the sections below. +// +// dlaa_backend = fsr (TOTK_DLAA_BACKEND, read at start) hands the same frame to AMD's FSR instead (vk_ffx.c): the +// arming, the jitter, the motion vectors, the masks and the copy of the result below are shared, and only the call that +// upscales differs (evaluate). NGX is then never loaded. #ifdef _WIN32 #include #endif @@ -26,6 +30,7 @@ #include "vk.h" #include "vk_dlaa.h" #include "vk_exec.h" +#include "vk_ffx.h" #include "vk_rec.h" #include "dlaa_mv_spv.h" @@ -112,6 +117,16 @@ int vk_dlaa_wanted(void) { return wanted; } +// FSR instead of DLSS (TOTK_DLAA_BACKEND=fsr), fixed for the run like dlaa: the backend's extensions are chosen at +// device creation. On Linux FSR is not available, and this choice leaves DLAA off rather than falling back to DLSS. +static int fsr_backend(void) { + static int fsr = -1; + if (fsr < 0) fsr = !strcmp(cfg_value("TOTK_DLAA_BACKEND"), "fsr"); + return fsr; +} + +static int ngx_wanted(void) { return vk_dlaa_wanted() && !fsr_backend(); } + static int core_load(void) { if (N.tried) return N.loaded; N.tried = 1; @@ -167,7 +182,7 @@ static int listed(const char *const *list, uint32_t n, const char *s) { void vk_dlaa_instance_exts(const char **ext, uint32_t *n, uint32_t max) { unsigned ni = 0, nd = 0; const char **ie = NULL, **de = NULL; - if (!vk_dlaa_wanted() || !core_load() || !NGX_OK(N.req_ext(&ni, &ie, &nd, &de))) return; + if (!ngx_wanted() || !core_load() || !NGX_OK(N.req_ext(&ni, &ie, &nd, &de))) return; for (unsigned i = 0; i < ni; i++) if (!listed(ext, *n, ie[i]) && *n < max) ext[(*n)++] = ie[i]; } @@ -176,7 +191,11 @@ void vk_dlaa_device_exts(const VkExtensionProperties *have, uint32_t nhave, cons uint32_t max) { unsigned ni = 0, nd = 0; const char **ie = NULL, **de = NULL; - if (!vk_dlaa_wanted() || !core_load() || !NGX_OK(N.req_ext(&ni, &ie, &nd, &de))) return; + if (fsr_backend()) { + vk_ffx_device_exts(have, nhave, ext, n, max); + return; + } + if (!ngx_wanted() || !core_load() || !NGX_OK(N.req_ext(&ni, &ie, &nd, &de))) return; for (unsigned i = 0; i < nd; i++) { int ok = 0; for (uint32_t k = 0; k < nhave && !ok; k++) ok = !strcmp(have[k].extensionName, de[i]); @@ -226,7 +245,11 @@ static int utf8_to_wide(const char *in, wchar_t *out, size_t cap) { #endif void vk_dlaa_init(void) { - if (!vk_dlaa_wanted() || !core_load()) return; + if (vk_dlaa_wanted() && fsr_backend()) { + vk_ffx_init(); + return; + } + if (!ngx_wanted() || !core_load()) return; #ifdef _WIN32 wchar_t wdir[MAX_PATH]; DWORD len = GetModuleFileNameW(NULL, wdir, MAX_PATH); @@ -263,7 +286,10 @@ void vk_dlaa_init(void) { driver ? "; the driver needs an update" : ""); } -int vk_dlaa_available(void) { return vk_dlaa_wanted() && N.available; } +// The backend of this run came up: DLSS through NGX, or FSR (vk_ffx.c). +static int be_available(void) { return fsr_backend() ? vk_ffx_available() : N.available; } + +int vk_dlaa_available(void) { return vk_dlaa_wanted() && be_available(); } // ---------------------------------------------------------------- where DLAA runs in TotK's frame // Measured (TOTK_DUMP, frame 2100 at Lookout Landing, 2560x1440 scene): the G-buffer passes draw into five targets with @@ -300,6 +326,7 @@ static struct { VkImageView mask_view, chars_view[2]; int chars_cur, chars_ok; // chars[chars_cur] is written next; chars_ok: the other holds last frame's NgxHandle *feat; + void *ffx; // the FSR context instead (fsr_backend) uint64_t used; // evals count when it last ran } sizes[5], *last; // last: the one the previous DLAA frame ran with VkImage last_color; // the target DLAA ran on last frame: another one means a new history @@ -341,7 +368,7 @@ static struct { const VkTexImage *vk_dlaa_swap_img; VkImageView vk_dlaa_swap_view; -static int dl_active(void) { return N.available && !D.failed && D.on; } +static int dl_active(void) { return be_available() && !D.failed && D.on; } static void dl_fail(const char *what, NgxResult r) { rt_log("dlaa: %s failed (%08x): DLAA off for this run", what, (unsigned)r); @@ -377,6 +404,7 @@ static void free_size(struct Size *e) { if (e->chars[i]) vmaDestroyImage(c->vma, e->chars[i], e->chars_mem[i]); } if (e->feat) N.release(e->feat); + if (e->ffx) vk_ffx_release(e->ffx); memset(e, 0, sizeof *e); } @@ -966,6 +994,57 @@ static int perf_quality(uint32_t w, uint32_t ow) { return k >= 0.66 ? 2 : k >= 0.57 ? 1 : k >= 0.49 ? 0 : 3; } +// The camera FSR asks for (its depth handling and its disocclusion use them; DLSS does not): the near and far distances, +// the vertical field of view, and whether depth 1 is near and the far plane infinite. From the projection in rows 7-10 +// of this frame's scene camera block (CAM_BYTES), rows of a row-major 4x4 with OpenGL clip depth as dlaa_mv.comp reads +// the view-projection: clip z = A z + B, clip w = s z with s = +-1 (row 10 is (0, 0, s, 0)), so the depth range's ends +// (ndc z = -1 and +1, depth 0 and 1) sit at z = B / (s ndc - A), and the field of view comes from row 8's +// 1 / tan(fov / 2). A frame whose block does not have that shape (or has no camera block) reuses the last camera that +// did: FSR's contexts are created with the depth flags, and the first run (1.4.3 at the title screen, RX 9070 XT) read +// 0.1 m to 1001 m, 45 degrees, depth not inverted, while later contexts of the dynamic resolution's other sizes got the +// defaults and inverted, infinite depth. Before any camera was read the defaults are 0.1 m to 1000 m, 50 degrees, depth +// not inverted. The first read and the first miss are logged, each once. +static void cam_params(float *cn, float *cf, float *fov, int *inv, int *inf) { + static struct { int ok; float cn, cf, fov; int inv, inf; } last = {0, 0.1f, 1000.0f, 0.8727f, 0, 0}; + *cn = last.cn, *cf = last.cf, *fov = last.fov, *inv = last.inv, *inf = last.inf; + static int logged_ok, logged_miss; + const float *p = D.cam_addr ? (const float *)vk_usnap_bytes(D.cam_addr + 7 * 16, 64) : NULL; + const char *why = "no camera block"; + if (p) { + const float *r8 = p + 4, *r9 = p + 8, *r10 = p + 12; + double s = r10[2], A = r9[2], B = r9[3], f = fabs((double)r8[1]); + double z0 = 0, z1 = 0; + why = "not a perspective projection"; + if (fabs(fabs(s) - 1.0) < 1e-3 && fabs(r10[0]) < 1e-4 && fabs(r10[1]) < 1e-4 && fabs(r10[3]) < 1e-4 && + f > 0.05 && f < 20.0 && fabs(B) > 1e-9) { + double d0 = -s - A, d1 = s - A; // denominators at depth 0 (ndc -1) and depth 1 (ndc +1) + z0 = fabs(d0) > 1e-9 ? fabs(B / d0) : INFINITY; + z1 = fabs(d1) > 1e-9 ? fabs(B / d1) : INFINITY; + double nz = fmin(z0, z1), fz = fmax(z0, z1); + if (nz > 1e-4 && nz < 100.0 && fz > nz) { + *inv = z1 < z0; + *inf = !isfinite(fz) || fz > 1e7; + *cn = (float)nz, *cf = *inf ? 1e30f : (float)fz, *fov = (float)(2.0 * atan(1.0 / f)); + last.ok = 1, last.cn = *cn, last.cf = *cf, last.fov = *fov, last.inv = *inv, last.inf = *inf; + why = NULL; + } else { + why = "depth range out of bounds"; + } + } + } + if (!why && !logged_ok) { + logged_ok = 1; + char fartxt[32]; // not "far": windows.h defines that as a macro + if (*inf) snprintf(fartxt, sizeof fartxt, "infinite"); + else snprintf(fartxt, sizeof fartxt, "%.0f m", *cf); + rt_log("fsr: camera from c4: near %.3f m, far %s, vertical fov %.1f degrees, depth %s", *cn, fartxt, + *fov * 57.29578, *inv ? "inverted" : "not inverted"); + } else if (why && !logged_miss) { + logged_miss = 1; + rt_log("fsr: camera block not read (%s): %s", why, last.ok ? "the last camera read is kept" : "defaults"); + } +} + // dst: the target DLSS's picture goes to, NULL for the light target itself (DLAA in place). static void evaluate(VkExec *ex, const VkExecTarget *dst) { const VkExecTarget *t = &D.color, *z = &D.depth; @@ -981,7 +1060,11 @@ static void evaluate(VkExec *ex, const VkExecTarget *dst) { struct Size *e = size_for(cb, w, h, ow, oh); if (!e) return dl_fail("work image creation", 0); if (e != D.last) D.reset = 1, D.why[0]++, e->chars_ok = 0; // another size's history is from another moment - if (!D.params && !NGX_OK(N.alloc_params(&D.params))) return dl_fail("parameter allocation", 0); + int fsr = fsr_backend(); + // FSR is handed whole images, not views: the light target and the depth must be their image's first level and layer + if (fsr && (t->level || t->base_layer || z->level || z->base_layer)) + return dl_fail("FSR input (the scene targets are not level 0, layer 0 of their images)", 0); + if (!fsr && !D.params && !NGX_OK(N.alloc_params(&D.params))) return dl_fail("parameter allocation", 0); NgxParam *p = D.params; VkImageView zv = vk_exec_target_view(z->img, z->format, VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_ASPECT_DEPTH_BIT, z->level, z->base_layer, 1, 0); @@ -1002,8 +1085,38 @@ static void evaluate(VkExec *ex, const VkExecTarget *dst) { int timed = T.on > 0 && T.used[T.slot]; // mv_pass began this frame's slot if (timed) times_mark(cb, T_DL0); uint64_t c0 = timed ? kern_now_ns() : 0; - rec_drain(); // NGX records into the command buffer itself: the recorder thread must have made every call so far + rec_drain(); // NGX and FSR record into the command buffer themselves: the recorder thread must have made every call so far if (timed) T.cpu_drain += kern_now_ns() - c0; + // The time since the previous evaluation, which DLSS and FSR weigh their history by; 60 fps before the first and + // after a gap (a pause, a load), where no history carries over anyway. + uint64_t now = plat_now_ns(); + double dt = D.last_eval_ns ? (now - D.last_eval_ns) / 1e6 : 0; + D.last_eval_ns = now; + float dt_ms = dt > 0 && dt < 100 ? (float)dt : 16.67f; + if (fsr) { + float cn, cf, fov; + int inv, inf; + cam_params(&cn, &cf, &fov, &inv, &inf); + if (!e->ffx) { + e->ffx = vk_ffx_create(w, h, ow, oh, inv, inf); + if (!e->ffx) return dl_fail("FSR context creation", 0); + D.reset = 1; + } + if (D.last_color != t->image) D.reset = 1, D.why[2]++, D.last_color = t->image; + // The same bias mask DLSS would get, as FSR's reactive mask: how much to favour this frame's colour + VkFfxDispatch fd = {.color = {t->image, t->format, w, h}, .depth = {z->image, z->format, w, h}, + .mv = {e->mv, VK_FORMAT_R16G16_SFLOAT, w, h}, + .out = {e->out, VK_FORMAT_R16G16B16A16_SFLOAT, ow, oh}, + .jx = jx, .jy = jy, .dt_ms = dt_ms, .cam_near = cn, .cam_far = cf, .fov_y = fov, + .reset = D.reset}; + if (mk) fd.reactive = (VkFfxImage){mk->mask, VK_FORMAT_R8_UNORM, w, h}; + else if (masked) fd.reactive = (VkFfxImage){e->mask, VK_FORMAT_R8_UNORM, w, h}; + c0 = timed ? kern_now_ns() : 0; + int ok = vk_ffx_dispatch(e->ffx, cb, &fd); + if (timed) T.cpu_ngx += kern_now_ns() - c0; + if (!ok) return dl_fail("FSR dispatch", 0); + goto upscaled; // the copy of the result and what follows are the same as DLSS's + } if (!e->feat) { p_setu(p, "CreationNodeMask", 1); p_setu(p, "VisibilityNodeMask", 1); @@ -1059,17 +1172,13 @@ static void evaluate(VkExec *ex, const VkExecTarget *dst) { p_setu(p, "DLSS.Render.Subrect.Dimensions.Height", h); p_setf(p, "DLSS.Pre.Exposure", 1.0f); p_setf(p, "DLSS.Exposure.Scale", 1.0f); - // The time since the previous evaluation, which DLSS weighs its history by; 60 fps before the first and after a - // gap (a pause, a load), where no history carries over anyway. - uint64_t now = plat_now_ns(); - double dt = D.last_eval_ns ? (now - D.last_eval_ns) / 1e6 : 0; - D.last_eval_ns = now; - p_setf(p, "FrameTimeDeltaInMsec", dt > 0 && dt < 100 ? (float)dt : 16.67f); + p_setf(p, "FrameTimeDeltaInMsec", dt_ms); c0 = timed ? kern_now_ns() : 0; NgxResult r = N.evaluate(cb, e->feat, p, NULL); if (timed) T.cpu_ngx += kern_now_ns() - c0; if (!NGX_OK(r)) return dl_fail("DLSS evaluation", r); - if (timed) times_mark(cb, T_DL1); // through the recorder, after NGX's own commands +upscaled: + if (timed) times_mark(cb, T_DL1); // through the recorder, after NGX's or FSR's own commands D.reset = 0; D.last = e, e->used = D.evals + 1; full_barrier(cb); @@ -1109,13 +1218,23 @@ static int scene_color(VkFormat f) { return f == VK_FORMAT_B10G11R11_UFLOAT_PACK32 || f == VK_FORMAT_R16G16B16A16_SFLOAT; } +// A scene DLAA may run on: DLAA_SCENE_MIN_W wide at least, and at least a quarter of the output's width, below which +// no mode scales (Ultra Performance renders a third, the game's dynamic resolution a little less). At a 3440x1440 +// output a 387x288 G-buffer and light target (seen while loading, 1.4.3) armed the frame and FSR scaled it ninefold +// into the output. +static int scene_wide(uint32_t w) { + unsigned o[2], s[2]; + res_sizes(o, s); + return w >= DLAA_SCENE_MIN_W && (uint64_t)w * 4 >= o[0]; +} + void vk_dlaa_pass(VkExec *ex) { const VkExecTarget *c = &ex->color[0], *z = &ex->depth; if (!dl_active() || D.done) return; // The G-buffer: several colour targets with a D32F depth of at least DLAA_SCENE_MIN_W wide. Only the light target drawn after it // arms the frame; at night the game draws into the light target alone with the scene depth before the G-buffer too, // and DLAA then ran at a small pass ahead of the whole scene, which reached the screen jittered. - if (ex->pass_ncolor >= 3 && z->image && z->format == VK_FORMAT_D32_SFLOAT && z->width >= DLAA_SCENE_MIN_W) { + if (ex->pass_ncolor >= 3 && z->image && z->format == VK_FORMAT_D32_SFLOAT && scene_wide(z->width)) { D.gbuf = 1, D.armed = 0; // target 0 is the object-class buffer (RGBA8, the scene size): the characters' bias mask reads its green. A // smaller pass of the same shape (640x360, seen while loading) does not replace the scene's in the same frame. @@ -1129,7 +1248,7 @@ void vk_dlaa_pass(VkExec *ex) { // D32F depth after the lighting (852x480 under a 1704x960 scene), and DLSS ran on that and wrote its picture into // the scene's own light target, which left every object black. if (D.gbuf && ex->pass_ncolor == 1 && c->image && scene_color(c->format) && z->image && z->format == VK_FORMAT_D32_SFLOAT && - c->width == z->width && c->height == z->height && c->width >= DLAA_SCENE_MIN_W && + c->width == z->width && c->height == z->height && scene_wide(c->width) && (!D.armed || (c->width >= D.color.width && c->height >= D.color.height)) && c->samples <= 1 && !c->is3d) { int first = !D.armed; @@ -1174,6 +1293,7 @@ static void dlss_mode(void) { // The preset, read again when a setting changed (the menu); a different one recreates the features at the next DLAA run. static void preset_check(void) { + if (fsr_backend()) return; // DLSS models only: FSR's version is fixed at start (vk_ffx_init) unsigned v = cfg_version(); if (v == D.cfg_seen) return; D.cfg_seen = v; @@ -1190,9 +1310,9 @@ void vk_dlaa_frame(void) { vk_dlaa_swap_img = NULL, vk_dlaa_swap_view = VK_NULL_HANDLE; dlss_mode(); preset_check(); - int on = N.available && cfg_bool("TOTK_DLAA"); + int on = be_available() && cfg_bool("TOTK_DLAA"); if (on != D.on) { - rt_log("dlaa: %s", on ? "on" : "off"); + rt_log("dlaa: %s%s%s", on ? "on" : "off", on && fsr_backend() ? ", with " : "", on && fsr_backend() ? vk_ffx_version() : ""); D.on = on; // either way the next DLAA frame starts a new history from an unjittered frame D.reset = 1, D.cam_prev_ok = 0, D.jit_ok = D.jit_used = D.armed = D.done = D.gbuf = D.ended = D.up = 0; diff --git a/runtime/vk_ffx.c b/runtime/vk_ffx.c new file mode 100644 index 00000000..9300276f --- /dev/null +++ b/runtime/vk_ffx.c @@ -0,0 +1,256 @@ +// AMD FSR upscaling for the DLAA path (vk_ffx.h). The FSR SDK 2.4 ships its Vulkan effects as signed DLLs behind a +// loader: amd_fidelityfx_loader_vk.dll exports the five ffx-api entry points and finds the effect DLL +// (amd_fidelityfx_upscaler_vk.dll) next to itself. Both are loaded from the executable's folder at run time; no SDK +// code is compiled in, only the descriptor layouts of ffx_api_min.h. +// +// The upscaler DLL offers several versions (FSR 4.x, FSR 3.1.x) and decides by itself which ones a device can run: +// vk_ffx_init lists them and pins the newest 4.x when there is one, else leaves the DLL's default (3.1 on GPUs without +// FSR 4). Every context is created with that version (ffxOverrideVersion). +// +// What FSR gets is what DLSS gets (vk_dlaa.c evaluate): the R11G11B10F light target as linear HDR colour with automatic +// exposure, the D32F scene depth, motion vectors at the render size in render pixels pointing from this frame's +// position to last frame's without the jitter (motionVectorScale 1), and the jitter the scene was drawn with. That is +// FSR's own convention as well: its guide derives the projection offset as (2 jx / w, -2 jy / h), which moves the +// picture by (jx, jy) window pixels with y down, the way vk_dlaa_viewport moves the viewport. TOTK_FSR_JITTER_SIGN=-1 +// flips it to test the other convention. +#include "vk_ffx.h" + +#include "cfg.h" +#include "host.h" + +#ifndef _WIN32 +int vk_ffx_wanted(void) { return 0; } +void vk_ffx_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max) { + (void)have, (void)nhave, (void)ext, (void)n, (void)max; +} +void vk_ffx_init(void) {} +int vk_ffx_available(void) { return 0; } +void *vk_ffx_create(uint32_t w, uint32_t h, uint32_t ow, uint32_t oh, int depth_inverted, int depth_infinite) { + (void)w, (void)h, (void)ow, (void)oh, (void)depth_inverted, (void)depth_infinite; + return NULL; +} +int vk_ffx_dispatch(void *ctx, VkCommandBuffer cb, const VkFfxDispatch *d) { return (void)ctx, (void)cb, (void)d, 0; } +void vk_ffx_release(void *ctx) { (void)ctx; } +const char *vk_ffx_version(void) { return ""; } +#else +#include +#include +#include +#include + +#include "ffx_api_min.h" + +#define FFX_LOADER L"amd_fidelityfx_loader_vk.dll" +#define FFX_MAX_VERSIONS 16 + +static struct { + HMODULE dll; + PfnFfxCreateContext create; + PfnFfxDestroyContext destroy; + PfnFfxQuery query; + PfnFfxDispatch dispatch; + int tried, loaded, available; + VkDeviceContext dev; + uint64_t version_id; // 0: the DLL's default + char version[48]; + float jitter_sign; +} F = {.jitter_sign = 1.0f}; + +int vk_ffx_wanted(void) { + static int wanted = -1; + if (wanted < 0) wanted = cfg_bool("TOTK_DLAA") && !strcmp(cfg_value("TOTK_DLAA_BACKEND"), "fsr"); + return wanted; +} + +static int loader_load(void) { + if (F.tried) return F.loaded; + F.tried = 1; + wchar_t path[MAX_PATH + 64]; + DWORD len = GetModuleFileNameW(NULL, path, MAX_PATH); + while (len && path[len - 1] != L'\\') len--; + path[len] = 0; + wcscat(path, FFX_LOADER); + // LOAD_WITH_ALTERED_SEARCH_PATH: the loader's own imports and the effect DLL resolve from the executable's folder + F.dll = LoadLibraryExW(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); + if (!F.dll) { + rt_log("fsr: cannot load amd_fidelityfx_loader_vk.dll next to totk.exe (error %lu): FSR off", GetLastError()); + return 0; + } + F.create = (PfnFfxCreateContext)(void *)GetProcAddress(F.dll, "ffxCreateContext"); + F.destroy = (PfnFfxDestroyContext)(void *)GetProcAddress(F.dll, "ffxDestroyContext"); + F.query = (PfnFfxQuery)(void *)GetProcAddress(F.dll, "ffxQuery"); + F.dispatch = (PfnFfxDispatch)(void *)GetProcAddress(F.dll, "ffxDispatch"); + if (!F.create || !F.destroy || !F.query || !F.dispatch) { + rt_log("fsr: amd_fidelityfx_loader_vk.dll lacks the ffx-api entry points: FSR off"); + return 0; + } + return F.loaded = 1; +} + +static int has(const VkExtensionProperties *have, uint32_t nhave, const char *name) { + for (uint32_t i = 0; i < nhave; i++) + if (!strcmp(have[i].extensionName, name)) return 1; + return 0; +} + +static void add(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max, + const char *name) { + for (uint32_t i = 0; i < *n; i++) + if (!strcmp(ext[i], name)) return; + if (has(have, nhave, name) && *n < max) ext[(*n)++] = name; +} + +// The extensions the FSR SDK's own sample enables for its effects (Cauldron2 device_vk.cpp): cooperative matrix and +// 8-bit floats for FSR 4's network where the device has them. The rest it uses (16-bit floats and storage, integer +// dot products, subgroup size control) is core Vulkan 1.3, which vk_device.c enables as far as the driver reports it. +void vk_ffx_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max) { + if (!vk_ffx_wanted()) return; + add(have, nhave, ext, n, max, VK_KHR_COOPERATIVE_MATRIX_EXTENSION_NAME); +#ifdef VK_EXT_SHADER_FLOAT8_EXTENSION_NAME + add(have, nhave, ext, n, max, VK_EXT_SHADER_FLOAT8_EXTENSION_NAME); +#endif +} + +void vk_ffx_init(void) { + if (!vk_ffx_wanted() || !loader_load()) return; + const VkCtx *c = vk_ctx(); + F.dev = (VkDeviceContext){c->device, c->phys, vkGetDeviceProcAddr}; + const char *js = cfg_get("TOTK_FSR_JITTER_SIGN"); + if (js && !strcmp(js, "-1")) F.jitter_sign = -1.0f; + uint64_t count = FFX_MAX_VERSIONS, ids[FFX_MAX_VERSIONS] = {0}; + const char *names[FFX_MAX_VERSIONS] = {0}; + struct ffxQueryDescGetVersions q = {.header = {FFX_API_QUERY_DESC_TYPE_GET_VERSIONS, NULL}, + .createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE, .device = &F.dev, + .outputCount = &count, .versionIds = ids, .versionNames = names}; + ffxReturnCode_t r = F.query(NULL, &q.header); + if (r != FFX_API_RETURN_OK || !count) { + rt_log("fsr: no upscaler for this device (query %u, %llu versions; is amd_fidelityfx_upscaler_vk.dll next to " + "totk.exe?): FSR off", (unsigned)r, (unsigned long long)count); + return; + } + if (count > FFX_MAX_VERSIONS) count = FFX_MAX_VERSIONS; + char list[256] = ""; + int best = -1, best_major = 0, best_minor = 0, best_patch = 0; + for (uint64_t i = 0; i < count; i++) { + const char *nm = names[i] ? names[i] : "?"; + size_t used = strlen(list); + snprintf(list + used, sizeof list - used, "%s%s", i ? ", " : "", nm); + int ma = 0, mi = 0, pa = 0; + if (sscanf(nm, "%d.%d.%d", &ma, &mi, &pa) < 1 || ma < 4) continue; + if (best < 0 || ma > best_major || (ma == best_major && (mi > best_minor || (mi == best_minor && pa > best_patch)))) + best = (int)i, best_major = ma, best_minor = mi, best_patch = pa; + } + if (best >= 0) { + F.version_id = ids[best]; + snprintf(F.version, sizeof F.version, "FSR %s", names[best]); + } else { + snprintf(F.version, sizeof F.version, "FSR %s", names[0] ? names[0] : "?"); // the DLL's default + } + F.available = 1; + rt_log("fsr: upscaler versions for this device: %s; using %s%s", list, F.version, + best >= 0 ? "" : " (FSR 4 is not offered for this GPU)"); +} + +int vk_ffx_available(void) { return vk_ffx_wanted() && F.available; } + +const char *vk_ffx_version(void) { return F.version; } + +// Messages from the upscaler (errors and warnings), in UTF-16; into the log as UTF-8. +static void on_message(uint32_t type, const wchar_t *msg) { + char s[512]; + if (!msg || !WideCharToMultiByte(CP_UTF8, 0, msg, -1, s, (int)sizeof s, NULL, NULL)) return; + rt_log("fsr: %s: %s", type == FFX_API_MESSAGE_TYPE_ERROR ? "error" : "warning", s); +} + +void *vk_ffx_create(uint32_t w, uint32_t h, uint32_t ow, uint32_t oh, int depth_inverted, int depth_infinite) { + if (!F.available) return NULL; + struct ffxOverrideVersion ov = {.header = {FFX_API_DESC_TYPE_OVERRIDE_VERSION, NULL}, .versionId = F.version_id}; + struct ffxCreateContextDescUpscaleVersion ver = { + .header = {FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE_VERSION, F.version_id ? &ov.header : NULL}, + .version = FFX_UPSCALER_VERSION}; + struct ffxCreateBackendVKDesc be = {.header = {FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK, &ver.header}, + .deviceContext = F.dev}; + // Linear HDR scene light with the upscaler's own exposure, as DLSS gets it ("IsHDR | AutoExposure") + uint32_t flags = FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE | FFX_UPSCALE_ENABLE_AUTO_EXPOSURE; + if (depth_inverted) flags |= FFX_UPSCALE_ENABLE_DEPTH_INVERTED; + if (depth_infinite) flags |= FFX_UPSCALE_ENABLE_DEPTH_INFINITE; + if (rt_knob("FSR_DEBUG", "0")) flags |= FFX_UPSCALE_ENABLE_DEBUG_CHECKING; // TOTK_FSR_DEBUG=1: API checks + struct ffxCreateContextDescUpscale cd = {.header = {FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE, &be.header}, + .flags = flags, .maxRenderSize = {w, h}, .maxUpscaleSize = {ow, oh}, + .fpMessage = on_message}; + ffxContext ctx = NULL; + ffxReturnCode_t r = F.create(&ctx, &cd.header, NULL); + if (r != FFX_API_RETURN_OK || !ctx) { + rt_log("fsr: context creation failed (%u) at %ux%u -> %ux%u", (unsigned)r, w, h, ow, oh); + return NULL; + } + struct ffxQueryGetProviderVersion pv = {.header = {FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION, NULL}}; + F.query(&ctx, &pv.header); + rt_log("fsr: context created at %ux%u -> %ux%u with %s (flags %#x)", w, h, ow, oh, + pv.versionName ? pv.versionName : F.version, flags); + return ctx; +} + +void vk_ffx_release(void *ctx) { + if (!ctx) return; + ffxContext c = ctx; + F.destroy(&c, NULL); +} + +static uint32_t surface_format(VkFormat f) { + switch (f) { + case VK_FORMAT_B10G11R11_UFLOAT_PACK32: return FFX_API_SURFACE_FORMAT_R11G11B10_FLOAT; + case VK_FORMAT_R16G16B16A16_SFLOAT: return FFX_API_SURFACE_FORMAT_R16G16B16A16_FLOAT; + case VK_FORMAT_R16G16_SFLOAT: return FFX_API_SURFACE_FORMAT_R16G16_FLOAT; + case VK_FORMAT_D32_SFLOAT: return FFX_API_SURFACE_FORMAT_R32_FLOAT; + case VK_FORMAT_R8_UNORM: return FFX_API_SURFACE_FORMAT_R8_UNORM; + default: return FFX_API_SURFACE_FORMAT_UNKNOWN; + } +} + +// Every image of the DLAA path stays in VK_IMAGE_LAYOUT_GENERAL: GENERIC_READ and UNORDERED_ACCESS are the states the +// Vulkan backend maps to that layout (ffx_vk.cpp getVKImageLayoutFromResourceState), and it puts each resource back +// into the state it was given at the end of the dispatch. +static struct FfxApiResource resource(const VkFfxImage *im, uint32_t usage, uint32_t state) { + struct FfxApiResource r; + memset(&r, 0, sizeof r); + if (!im->image) return r; + r.resource = (void *)im->image; + r.description = (struct FfxApiResourceDescription){.type = FFX_API_RESOURCE_TYPE_TEXTURE2D, + .format = surface_format(im->format), .width = im->width, + .height = im->height, .depth = 1, .mipCount = 1, .usage = usage}; + r.state = state; + return r; +} + +int vk_ffx_dispatch(void *ctx, VkCommandBuffer cb, const VkFfxDispatch *d) { + if (!ctx) return 0; + ffxContext c = ctx; + struct ffxDispatchDescUpscale u; + memset(&u, 0, sizeof u); + u.header.type = FFX_API_DISPATCH_DESC_TYPE_UPSCALE; + u.commandList = (void *)cb; + u.color = resource(&d->color, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_GENERIC_READ); + u.depth = resource(&d->depth, FFX_API_RESOURCE_USAGE_DEPTHTARGET, FFX_API_RESOURCE_STATE_GENERIC_READ); + u.motionVectors = resource(&d->mv, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_GENERIC_READ); + u.reactive = resource(&d->reactive, FFX_API_RESOURCE_USAGE_READ_ONLY, FFX_API_RESOURCE_STATE_GENERIC_READ); + u.output = resource(&d->out, FFX_API_RESOURCE_USAGE_UAV, FFX_API_RESOURCE_STATE_UNORDERED_ACCESS); + u.jitterOffset = (struct FfxApiFloatCoords2D){d->jx * F.jitter_sign, d->jy * F.jitter_sign}; + u.motionVectorScale = (struct FfxApiFloatCoords2D){1.0f, 1.0f}; + u.renderSize = (struct FfxApiDimensions2D){d->color.width, d->color.height}; + u.upscaleSize = (struct FfxApiDimensions2D){d->out.width, d->out.height}; + u.frameTimeDelta = d->dt_ms; + u.preExposure = 1.0f; + u.reset = d->reset != 0; + u.cameraNear = d->cam_near; + u.cameraFar = d->cam_far; + u.cameraFovAngleVertical = d->fov_y; + u.viewSpaceToMetersFactor = 1.0f; // TotK's world units are metres + ffxReturnCode_t r = F.dispatch(&c, &u.header); + if (r != FFX_API_RETURN_OK) { + rt_log("fsr: dispatch failed (%u)", (unsigned)r); + return 0; + } + return 1; +} +#endif diff --git a/runtime/vk_ffx.h b/runtime/vk_ffx.h new file mode 100644 index 00000000..db26e517 --- /dev/null +++ b/runtime/vk_ffx.h @@ -0,0 +1,35 @@ +// AMD FSR upscaling (vk_ffx.c) for the DLAA path (vk_dlaa.c): with totk.ini dlaa = 1 and dlaa_backend = fsr, the +// scene that DLSS would get goes to AMD's FSR (FSR 4 where the GPU has it, FSR 3.1 elsewhere) through +// amd_fidelityfx_loader_vk.dll next to the executable. Windows only; elsewhere every call does nothing. +#pragma once +#include "vk.h" + +int vk_ffx_wanted(void); // dlaa and dlaa_backend = fsr at start (the device may still lack FSR) +// vk_device.c, while it builds the device: the extensions FSR's shaders use (cooperative matrix, 8-bit floats) join +// the list when the device has them; their feature structures are chained there. +void vk_ffx_device_exts(const VkExtensionProperties *have, uint32_t nhave, const char **ext, uint32_t *n, uint32_t max); +void vk_ffx_init(void); // after the device exists: loads the loader and picks the upscaler version +int vk_ffx_available(void); // vk_ffx_init found an upscaler for this device + +typedef struct { // one image FSR reads or writes, in VK_IMAGE_LAYOUT_GENERAL, level 0 and layer 0 + VkImage image; + VkFormat format; + uint32_t width, height; +} VkFfxImage; + +typedef struct { + VkFfxImage color, depth, mv, reactive, out; // reactive.image VK_NULL_HANDLE: none + float jx, jy; // this frame's jitter, render pixels (window x right, y down), as the scene was drawn + float dt_ms; // time since the previous dispatch + float cam_near, cam_far; // view-space distances of the depth range's ends + float fov_y; // vertical field of view, radians + int reset; // a new history +} VkFfxDispatch; + +// A context for one render and output size (vk_dlaa.c keeps one per scene size like DLSS's features). depth_inverted: +// depth 1 is near; depth_infinite: the far plane is at infinity. NULL on failure (logged). +void *vk_ffx_create(uint32_t w, uint32_t h, uint32_t ow, uint32_t oh, int depth_inverted, int depth_infinite); +// Records the upscaling into cb. 0 on failure (logged). FSR binds pipelines and descriptors of its own. +int vk_ffx_dispatch(void *ctx, VkCommandBuffer cb, const VkFfxDispatch *d); +void vk_ffx_release(void *ctx); +const char *vk_ffx_version(void); // the upscaler version in use, for the log ("" before vk_ffx_init) diff --git a/tests/installer_test.py b/tests/installer_test.py index b57ccf41..14270fc1 100644 --- a/tests/installer_test.py +++ b/tests/installer_test.py @@ -552,7 +552,7 @@ class FontsTest(unittest.TestCase): def test_all_steps_order(self): self.assertEqual([s.id for s in steps.all_steps()], - ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'dlss', 'cleanup']) + ['check', 'fonts', 'extract', 'lift', 'compile', 'prepare', 'dlss', 'fsr', 'cleanup']) def test_extracts_into_the_install_folder(self): self.fake_tool() @@ -720,5 +720,77 @@ class DlssTest(unittest.TestCase): self.assertEqual(self.warnings(), []) +@unittest.skipUnless(steps.os.name == 'nt', 'FSR is Windows-only') +class FsrTest(unittest.TestCase): + """The FSR step: off without --fsr, needs an AMD GPU, keeps a player's libraries, installs both files or none.""" + + NAMES = ('amd_fidelityfx_loader_vk.dll', 'amd_fidelityfx_upscaler_vk.dll') + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + base = Path(self.tmp.name) + self.dest, temp, src = base / 'dest', base / 'temp', base / 'src' + for d in (self.dest, temp, src): + d.mkdir() + files = [] + for i, name in enumerate(self.NAMES): + (src / name).write_bytes(bytes([65 + i]) * (1000 + i)) + files.append((name, 1000 + i, steps.file_sha256(src / name))) + self.src = src + self.saved = steps.FSR_BASE, steps.FSR_FILES + steps.FSR_BASE = src.as_uri() + '/' # urllib reads file: URLs as it reads https: ones + steps.FSR_FILES = tuple(files) + amd = {'devices': [{'name': 'AMD Radeon RX 9070 XT', 'api': [1, 4, 0], 'type': 2}]} + self.ctx = SimpleNamespace(dest=self.dest, temp=temp, host=amd, reporter=Reporter(out=io.StringIO()), + options=SimpleNamespace(fsr=True)) + + def tearDown(self): + steps.FSR_BASE, steps.FSR_FILES = self.saved + self.ctx.reporter.close() + self.tmp.cleanup() + + def warnings(self): + return [json.loads(line)['id'] for line in self.ctx.reporter.out.getvalue().splitlines() + if json.loads(line)['type'] == 'warning'] + + def test_off_without_the_option(self): + self.ctx.options.fsr = False + self.assertEqual(steps.Fsr().run(self.ctx), {}) + self.assertFalse(any((self.dest / n).exists() for n in self.NAMES)) + self.assertNotEqual(steps.Fsr().key(self.ctx), steps.Fsr().key(SimpleNamespace(options=SimpleNamespace(fsr=True)))) + + def test_downloads_and_checks_both_libraries(self): + rec = steps.Fsr().run(self.ctx) + self.assertEqual(rec, {'installed': steps.FSR_VERSION}) + for n in self.NAMES: + self.assertEqual((self.dest / n).read_bytes(), (self.src / n).read_bytes()) + self.assertFalse(list(self.ctx.temp.iterdir())) + self.assertTrue(steps.Fsr().current(self.ctx, rec)) + (self.dest / self.NAMES[1]).unlink() + self.assertFalse(steps.Fsr().current(self.ctx, rec)) + + def test_a_wrong_file_installs_neither(self): + name, size, _ = steps.FSR_FILES[1] + steps.FSR_FILES = (steps.FSR_FILES[0], (name, size, '0' * 64)) + rec = steps.Fsr().run(self.ctx) + self.assertEqual(rec, {'failed': True}) + self.assertFalse(any((self.dest / n).exists() for n in self.NAMES)) + self.assertFalse(list(self.ctx.temp.iterdir())) + self.assertEqual(self.warnings(), ['warn.fsr_download_failed']) + self.assertFalse(steps.Fsr().current(self.ctx, rec)) + + def test_keeps_the_players_libraries(self): + (self.dest / self.NAMES[1]).write_bytes(b'newer') + self.assertEqual(steps.Fsr().run(self.ctx), {'kept': True}) + self.assertEqual((self.dest / self.NAMES[1]).read_bytes(), b'newer') + self.assertFalse((self.dest / self.NAMES[0]).exists()) + self.assertEqual(self.warnings(), ['warn.fsr_kept']) + + def test_skipped_without_an_amd_gpu(self): + self.ctx.host = {'devices': [{'name': 'NVIDIA GeForce RTX 4080 SUPER', 'api': [1, 4, 0], 'type': 2}]} + self.assertEqual(steps.Fsr().run(self.ctx), {'skipped': 'no_amd'}) + self.assertEqual(self.warnings(), []) + + if __name__ == '__main__': unittest.main() diff --git a/totk.ini.example b/totk.ini.example index 33e7dc4a..a8bb4a03 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -212,6 +212,10 @@ # NVIDIA driver's libnvidia-ngx.so.1 installed); elsewhere the setting does nothing. The HUD is drawn after it and is not touched. # Read at start. # dlaa = 0 +# What dlaa runs: dlss (NVIDIA DLSS, above) or fsr (AMD FSR: FSR 4 on Radeon RX 9000, 7000 and 6000 GPUs, FSR 3.1 on +# others; Windows, with amd_fidelityfx_loader_vk.dll and amd_fidelityfx_upscaler_vk.dll from AMD's FSR SDK next to +# totk.exe, which the setup downloads). The dlss mode below applies to both; dlss_preset is DLSS's only. Read at start. +# dlaa_backend = dlss # What DLSS works from: dlaa (the 3D scene at full size), quality, balanced, performance or ultra_performance (the # scene at 67, 58, 50 or 33 % of the output, scaled up by DLSS; these replace render_scale and sharpen texture filtering # to match). They apply only with dlaa = 1 and the DLSS model next to the executable; otherwise the scene follows