7 Commits

Author SHA1 Message Date
epicmeme546
4d5454d380 Add AMD FSR 4 upscaling through the libraries of AMD's FSR SDK 2.4, as an Upscaling choice beside FSR 3.1.
runtime/vk_ffx4.cpp loads amd_fidelityfx_loader_vk.dll from beside the executable and asks it which upscaler
versions the device can run. Where a 4.x version is listed (Radeon RX 6000, RX 7000 and RX 9000 cards with AMD's
driver 26.10.1 or newer) the menu's Upscaling row gains AMD FSR 4 Native AA, Quality, Balanced, Performance and
Ultra Performance, and fsr4 = 1 runs it in FSR 3.1's place with the same inputs. Its contexts are made with that
version asked for by its id and the provider is asked afterwards which version it runs, so no other upscaler can
be shown under the name. When a context or a dispatch fails, FSR 3.1 makes the frame, and after three failures
FSR 4 is off for the run. Each upscaler starts its history anew on the frame after a change from one to the other.
The setting is off by default and the Linux build compiles stubs.

On an RX 7900 XT (driver 26.10.1, 3440x1440, HDR) the library runs FSR 4.1.2: a context takes 54 ms to make and
217 MiB of video memory. Standing in Hyrule Field: Quality 47.8 fps where FSR 3.1 gives 51.5, Native AA 41.4.
Screenshots of 601 consecutive frames standing, 801 during a camera sweep, 701 each in Kakariko and the
graveyard, and 1,301 across changes between FSR 3.1 and FSR 4, their modes and off show no flicker that FSR 3.1
does not have, and it runs together with FSR 3.1 frame generation.

The SDK's API headers are in runtime/third_party/ffx_sdk, unmodified, with the licence. tools/make_kit.py and
tools/make_launcher.py take AMD's two signed libraries with --ffx4, and tools/make_game.py copies them beside the
game when the kit has both.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 03:22:08 -05:00
epicmeme546
3fe6965df9 Give the Custom colour scheme a Panel Color for the panels and the title band, and have Button Color change the buttons alone, their orange choices included.
Button Color recoloured the list panel, the description box and the title band, and left the orange choices in the rows as they were, so the buttons themselves seemed not to change. It now takes the rows' label cells, their value cells and the orange choices, which come out a lighter shade of the picked colour; the new Panel Color takes the panels, the dividers and the title band. Text on a light button or panel turns dark, and so does the text in choices that come out bright. The colour is kept as custom_panel in launcher.json.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:11:09 -05:00
epicmeme546
4cc4663008 Show Background Color and Button Color in Customize Launcher as soon as Color Scheme is set to Custom, and hide them again when another scheme is chosen.
Changing the scheme redrew the window but kept the rows the screen was opened with, so the two rows came and went only when the screen was opened again, as after choosing a picture. The rows are now made again each time the scheme changes, with the cursor staying on Color Scheme.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 03:03:11 -05:00
epicmeme546
43760d4129 Add a Custom colour scheme with a colour square and a hex code, start the player's background picture below the title band, and shorten the Add to Steam description.
Custom is the last scheme in Customize Launcher. Its Background Color and Button Color rows open a picker in the description box's place: a square of the hue's colours (saturation across, brightness up and down) with a hue bar under it to click or drag on, Hue, Saturation and Brightness rows for the arrows and the gamepad, and a Hex Code row to type a code into. Each picked colour takes the place of one colour of the first scheme, the backdrop's middle tint or the buttons' wood, and the rest of its group follows it, lighter and darker as in the first scheme; light buttons get dark text. The colours are kept as custom_background and custom_buttons in launcher.json.

The background picture used to fill the whole window, so its top was hidden under the title band. It now fills the window from where the band ends, cut to that shape around its middle and scaled evenly. A copy an older launcher kept for the whole window is cut, never squeezed, and made again from the picture file while it is there.

Add to Steam's description and result are now one plain sentence each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 02:50:15 -05:00
epicmeme546
a7b8810d37 Add the game to Steam from Customize Launcher, with Navi as its icon and the title screen's moonlit field and logo as its pictures, made from the player's own game.
The new row, Add to Steam (Windows), puts a non-Steam shortcut named "The Legend of Zelda Ocarina of Time" into the shortcuts.vdf of every Steam account that signed in on the PC (launcher/steam.py): the binary key-value file is read and written back as it was, with ours added or updated in place, and the file from before the first change kept beside it. Steam reads that file only at its start and writes it back when it closes, so a running Steam is asked to close (-shutdown) and started again after.

The pictures come from the player's game when the row is selected (launcher/gameart.py), as the launcher's fonts and sounds do: Navi from the HUD's icon and its glow, the logo with the Master Sword and the Hylian Shield from the title screen's texture archive (decoded with runtime/tex_astc.c, built into a library with the toolchain's clang), and a frame 12 seconds into the first title movie, the field under the full moon, decoded from its AV1 with the toolchain's dav1d.exe, as the background, the cover and the wide tile. They go into config/grid named by the shortcut's id, CRC-32 of Exe and AppName with the top bit set, which matches the id Steam gave an existing shortcut on the test PC.

Steam starts the launcher's pythonw.exe on data/steam_play.pyw, which runs the launcher of app/current.txt with the new --play: the game starts from its folder with its console hidden, as Play starts it, and the process waits for it and for the copies its own Restart starts, so Steam counts the game as running while it is. ocarina.exe is a console program, so starting it directly would open a console window beside the game, and NX2navi.exe ends six seconds after it started the launcher. Started that way on an RX 7900 XT PC, the game ran, the Python process stayed until the game was closed and ended with code 0. Tested against copies of that PC's Steam files; the real Steam library is not changed until the player selects the row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:49:06 -05:00
epicmeme546
da0d0be700 Read occlusion query results in batches, and wait in the submit call for the game's signal that the frame's data is written.
Both are about the time between two frames. Ocarina waits for the previous frame's fence before it lets the next frame's GPU work start: its main thread signals an event from the CPU, and the main queue's commands begin with a wait for it.

The completion thread ran a submission's callbacks before it let the submission's waiters go, and the occlusion counts were among them: one vkGetQueryPoolResults and one vkResetQueryPool per reported query, about a hundred queries a frame in Hyrule Field. On an RX 7900 XT (26.10.1) each call goes into the kernel, 3.9 ms of every frame, so the fence was reached 4 to 6 ms after the GPU had finished with every game thread waiting. Slots come from the ring in order, so one call now reads up to 256 slots from the one asked for, the available results are kept for the segments that follow, and the slots taken are reset in runs (vk_exec_xfer.c oq_take, NX2NAVI_OQ_BATCH). Standing in Hyrule Field at 3440x1440 with FSR: 52.7 fps against 44.6, the longest frame of the measured minute 46 ms against 55; the completion thread spends 0.3 ms a frame in the callback.

When the CPU's signal came a millisecond or two after the main queue's submit call, the submission took its copies, stopped at the wait and was held; the render thread polled the event, presented, and the present replayed the frame under a value the game's fence does not stand for. The next frame then skipped its wait for the GPU and was replayed inside its submit call, and frames of 23 and 15 ms took turns. A submission that begins with a wait for an event the CPU has signalled before now waits for the signal in the submit call, before its copies are taken, 10 ms at most (vk_exec.c vk_exec_gate_wait, NX2NAVI_GATE_WAIT_MS): 54.5 fps and a longest frame of 33 ms in the same place, 58.6 fps with the recorder thread on. With a camera sweep the pictures went out 21.0 ms apart on average with a 99th percentile of 55 ms, against 25.4 and 64. A village went from 48.6 to 53.7 fps and a graveyard from 56.5 to 64.2. 900 consecutive frames of a still scene show no dark or changed frame, with the recorder thread and without.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 13:37:12 -05:00
epicmeme546
e38f42a959 Test for NaN on the bits of the number on AMD's driver for RX 5000 and 6000 cards, so that no shader compiler can leave a test out.
The reports of black and white blocks on Navi, on Link next to her and on bright surfaces seen from inside a house come from RX 5000 and 6000 cards, whose Windows driver compiles with "AMD proprietary shader compiler" (vk_caps.amd_sc); an RX 7900 XT (LLPC) draws the same scenes clean. The game's shaders test for NaN with OpIsNan in 48,717 of an install's 54,959 translated modules, 26 tests each on average, and the translator's guard that keeps NaN out of every float colour output, so that one bad texel does not spread through blur and bloom into blocks, is such a test too. SignedZeroInfNanPreserve asks the driver to keep those tests; whether that compiler does is not known.

With that driver, vk_pipeline.c spirv_nan_bits now turns every 32-bit isnan, scalar or vector, into (bits & 0x7fffffff) > 0x7f800000 on the number's bits, and a float select with a constant whose bits are a NaN into a select of the bits (issue #156), when the module is created. NX2NAVI_VK_NAN_BITS=1 does it on every driver, 0 on none. Run over every module of an install's shader cache, the rewrite changed 1,281,675 tests and 57 selects with every output well formed (each id defined once, below the bound, the uint types declared once); --selftest checks it on a small module, and Link's house with it forced on (RX 7900 XT) draws as without it. Not yet tried on an RX 5000 or 6000 card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:08:03 -05:00
33 changed files with 3257 additions and 89 deletions

View File

@@ -30,8 +30,8 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
- Game resolutions from 1080p to above the game's 1440p: 1800p, 4K, 5K or the window's own size, sharp on high-DPI - Game resolutions from 1080p to above the game's 1440p: 1800p, 4K, 5K or the window's own size, sharp on high-DPI
displays displays
- Upscaling and anti-aliasing: NVIDIA DLSS (DLAA, Quality, Balanced, Performance, Ultra Performance; RTX GPUs) or - Upscaling and anti-aliasing: NVIDIA DLSS (DLAA, Quality, Balanced, Performance, Ultra Performance; RTX GPUs) or
AMD FSR 3.1 (Native AA and the same modes; any GPU), which render the 3D scene at the mode's share and keep the HUD AMD FSR 3.1 (Native AA and the same modes; any GPU) or AMD FSR 4 (the same modes; Radeon RX 6000, RX 7000 and
sharp; or AMD FSR 1 or bilinear scaling to the window, with a sharpness setting; black bars or stretch RX 9000 GPUs), which render the 3D scene at the mode's share and keep the HUD sharp; or AMD FSR 1 or bilinear scaling to the window, with a sharpness setting; black bars or stretch
- Frame generation: NVIDIA DLSS Frame Generation (RTX 40 and 50 GPUs, paced with Reflex) at 2x, or 3x and 4x on RTX 50 - Frame generation: NVIDIA DLSS Frame Generation (RTX 40 and 50 GPUs, paced with Reflex) at 2x, or 3x and 4x on RTX 50
GPUs (one, two or three generated frames for every frame the game draws), or AMD FSR 3.1 (any GPU), a generated GPUs (one, two or three generated frames for every frame the game draws), or AMD FSR 3.1 (any GPU), a generated
frame between every two the game draws, with the HUD kept out of it, for about twice the frame rate on a fast frame between every two the game draws, with the HUD kept out of it, for about twice the frame rate on a fast

View File

@@ -106,6 +106,7 @@ folder's `licenses/` and in each component's own folder.
| MacNativeGames shader variant list | as in the installer release row above | MIT | `data/shader_list.tsv` | | 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/nx2navi_menu_cursor.cpp`), Copyright (c) 2026 daniel-madrid-07 | MIT | `runtime/menu_cursor.c` | | 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/nx2navi_menu_cursor.cpp`), Copyright (c) 2026 daniel-madrid-07 | MIT | `runtime/menu_cursor.c` |
| AMD FidelityFX API headers (FSR 3.1 upscaling and frame generation) and its signed Vulkan library | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK @ `v1.1.4` (`ffx-api/include/ffx_api/`, `PrebuiltSignedDLL/amd_fidelityfx_vk.dll`), Copyright (C) 2024 Advanced Micro Devices, Inc. | MIT | `runtime/third_party/ffx_api/` (unmodified, with `LICENSE.txt`), used by `runtime/vk_ffx.cpp`; the library ships in the build kit's `bin/` and beside the built game (never in this repository) | | AMD FidelityFX API headers (FSR 3.1 upscaling and frame generation) and its signed Vulkan library | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK @ `v1.1.4` (`ffx-api/include/ffx_api/`, `PrebuiltSignedDLL/amd_fidelityfx_vk.dll`), Copyright (C) 2024 Advanced Micro Devices, Inc. | MIT | `runtime/third_party/ffx_api/` (unmodified, with `LICENSE.txt`), used by `runtime/vk_ffx.cpp`; the library ships in the build kit's `bin/` and beside the built game (never in this repository) |
| AMD FSR SDK API headers (FSR 4 upscaling) and its signed Vulkan libraries | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK @ `v2.4.0` (`Kits/FidelityFX/api/include/`, `Kits/FidelityFX/upscalers/include/ffx_upscale.h`, `Kits/FidelityFX/signedbin/amd_fidelityfx_loader_vk.dll`, `Kits/FidelityFX/signedbin/amd_fidelityfx_upscaler_vk.dll`), Copyright (C) Advanced Micro Devices, Inc. | MIT | `runtime/third_party/ffx_sdk/` (unmodified, with `LICENSE.txt`), used by `runtime/vk_ffx4.cpp`; the libraries ship in the build kit's `bin/` and beside the built game (never in this repository) |
## Distributed in the launcher release ## Distributed in the launcher release

View File

@@ -112,7 +112,8 @@ cannot give back what the game needs after its start: about 10 GB in Kokiri Fore
AMD FSR 3.1 loads AMD's `amd_fidelityfx_vk.dll`, which only the Windows build can use: on Linux the menu offers neither AMD FSR 3.1 loads AMD's `amd_fidelityfx_vk.dll`, which only the Windows build can use: on Linux the menu offers neither
FSR 3.1 upscaling nor FSR 3.1 frame generation, and `taa = fsr3` or `framegen = fsr3` in `nx2navi.ini` leave the FSR 3.1 upscaling nor FSR 3.1 frame generation, and `taa = fsr3` or `framegen = fsr3` in `nx2navi.ini` leave the
game's own scaling and swapchain as they are (the log says so). game's own scaling and swapchain as they are (the log says so). AMD FSR 4 is in the Windows build alone for the same
reason, and `fsr4 = 1` does nothing on Linux.
NVIDIA DLSS (RTX cards) needs the driver's own `libnvidia-ngx.so.1` on the library path (the proprietary driver's NVIDIA DLSS (RTX cards) needs the driver's own `libnvidia-ngx.so.1` on the library path (the proprietary driver's
utilities package, `nvidia-utils` on Arch) and NVIDIA's DLSS library `libnvidia-ngx-dlss.so.<version>` beside utilities package, `nvidia-utils` on Arch) and NVIDIA's DLSS library `libnvidia-ngx-dlss.so.<version>` beside
@@ -151,7 +152,8 @@ beside the game.
- **Screen** in the menu has Texture filtering (anisotropic, up to 16x, at once), Texture detail (Reduced and Low - **Screen** in the menu has Texture filtering (anisotropic, up to 16x, at once), Texture detail (Reduced and Low
leave out the largest versions of the big surface textures so that the game fits the video memory of 6 and 8 GB leave out the largest versions of the big surface textures so that the game fits the video memory of 6 and 8 GB
cards; Automatic picks by the card), Upscaling (DLSS on NVIDIA RTX cards, cards; Automatic picks by the card), Upscaling (DLSS on NVIDIA RTX cards,
FSR 3.1 on any card where `amd_fidelityfx_vk.dll` loads), Frame generation (NVIDIA DLSS on RTX 40 and 50 cards, with FSR 3.1 on any card where `amd_fidelityfx_vk.dll` loads, FSR 4 on the Radeon cards AMD's FSR 4 libraries list it
for), Frame generation (NVIDIA DLSS on RTX 40 and 50 cards, with
a DLSS multiplier of 2x, or 3x and 4x on RTX 50 cards; FSR 3.1 on any card where it loads; it needs DLSS or FSR 3.1 a DLSS multiplier of 2x, or 3x and 4x on RTX 50 cards; FSR 3.1 on any card where it loads; it needs DLSS or FSR 3.1
upscaling on, and the frame limit then counts the frames on screen; with no limit chosen it is the display's refresh upscaling on, and the frame limit then counts the frames on screen; with no limit chosen it is the display's refresh
rate), HDR (the game's picture tone mapped to your display, with its own grading rows, or Native, the game's own HDR; turn HDR on in Windows first) and the rate), HDR (the game's picture tone mapped to your display, with its own grading rows, or Native, the game's own HDR; turn HDR on in Windows first) and the
@@ -162,7 +164,8 @@ beside the game.
the keys `nx2navi.ini` binds when the build runs: after rebinding keys, run the keys `nx2navi.ini` binds when the build runs: after rebinding keys, run
`py -I tools\make_game.py --rebuild --out "C:\Games\Ocarina"` to draw them again (it skips everything else). `py -I tools\make_game.py --rebuild --out "C:\Games\Ocarina"` to draw them again (it skips everything else).
- The build copies NVIDIA's DLSS library `nvngx_dlss.dll` (with `nvngx_dlss-NOTICE.txt`, which names its licence) - The build copies NVIDIA's DLSS library `nvngx_dlss.dll` (with `nvngx_dlss-NOTICE.txt`, which names its licence)
and FSR 3.1's `amd_fidelityfx_vk.dll` beside `ocarina.exe` from the kit's `bin\`. To use another DLSS version, put and FSR 3.1's `amd_fidelityfx_vk.dll` beside `ocarina.exe` from the kit's `bin\`, and FSR 4's
`amd_fidelityfx_loader_vk.dll` and `amd_fidelityfx_upscaler_vk.dll` when the kit has both. To use another DLSS version, put
your own `nvngx_dlss.dll` there: later builds keep it. On Linux the library is `libnvidia-ngx-dlss.so.<version>` your own `nvngx_dlss.dll` there: later builds keep it. On Linux the library is `libnvidia-ngx-dlss.so.<version>`
(see "Linux"). (see "Linux").
- A kit with `bin\dlssg\` (made with `tools/make_kit.py --dlssg`) also brings DLSS Frame Generation on GeForce RTX 40 - A kit with `bin\dlssg\` (made with `tools/make_kit.py --dlssg`) also brings DLSS Frame Generation on GeForce RTX 40

View File

@@ -38,10 +38,19 @@ Customize Launcher (on the home screen) makes the look the player's own:
- Color Scheme: Forest (the colours above), Volcano, Lake, Desert, Temple and Shadow. A scheme is the first one with - Color Scheme: Forest (the colours above), Volcano, Lake, Desert, Temple and Shadow. A scheme is the first one with
its woods, accents, backdrop and glow turned to other hues (`art.THEMES`, `art.recolor`), so each keeps the same its woods, accents, backdrop and glow turned to other hues (`art.THEMES`, `art.recolor`), so each keeps the same
light and dark steps and the same readable text. The window is drawn again in the new colours at once. The names light and dark steps and the same readable text. The window is drawn again in the new colours at once. The names
are plain words, not the game's. are plain words, not the game's. Custom, the last one, takes three colours of the player's: Background Color for
the backdrop, Panel Color for the list panel, the description box and the title band, and Button Color for the
rows' cells and the orange choices in them. Each opens a picker in the description
box's place: a square of the hue's colours (saturation across, brightness up and down) and a hue bar under it, to
click or drag on, Hue, Saturation and Brightness rows for the arrows and the gamepad, and Hex Code, where a code
such as `#3A7BD5` is typed. The picked colour stands in for one colour of the first scheme (`art.CUSTOM_SLOTS`) and
the rest of its part of the window follows it, lighter and darker as in the first scheme (`art.follow`); text on
a light button or panel turns dark. The window takes the new colour as the mouse moves; Reset brings back the first scheme's colour.
- Background: a picture of the player's own behind the panels instead of the scheme's backdrop (`launcher/ui/picture.py`: - Background: a picture of the player's own behind the panels instead of the scheme's backdrop (`launcher/ui/picture.py`:
PNG, JPEG, WebP, BMP, GIF or TIFF, read with Pillow). It is cut to the window's shape around its middle and kept as PNG, JPEG, WebP, BMP, GIF or TIFF, read with Pillow). It fills the window below the title band, so none of it is
`data/background.npy`, so the launcher needs the file no more; Background Dimming darkens it (0 to 80 %) for the hidden under the band: cut to that shape around its middle and scaled evenly, never stretched, and kept as
`data/background.npy`, so the launcher needs the file no more (a copy an older launcher kept for the whole window is
made again from the file while it is there); Background Dimming darkens it (0 to 80 %) for the
text over it, the list panel and the description box turn a little see-through, and Remove Background brings the text over it, the list panel and the description box turn a little see-through, and Remove Background brings the
scheme's backdrop back. scheme's backdrop back.
- Animations (on by default): the cursor glides from row to row, a new screen slides into place, sparks drift up - Animations (on by default): the cursor glides from row to row, a new screen slides into place, sparks drift up
@@ -55,7 +64,20 @@ Customize Launcher (on the home screen) makes the look the player's own:
it is silent until the player's game has been read. Moving the cursor makes no sound. They are played from memory it is silent until the player's game has been read. Moving the cursor makes no sound. They are played from memory
(PlaySound on Windows; `pw-play`, `paplay` or `aplay` elsewhere). (PlaySound on Windows; `pw-play`, `paplay` or `aplay` elsewhere).
The choices are `theme`, `background`, `background_dim`, `animations` and `sounds` in `data/launcher.json`. - Add to Steam (Windows): the game in the player's Steam library as *The Legend of Zelda Ocarina of Time*, started
from there without the launcher's window (`launcher/steam.py`). Its pictures are made from the player's game when
the row is selected (`launcher/gameart.py`): Navi as the game's HUD draws her for the icon, the title screen's logo,
and a frame of the first title movie (the moonlit field) as the background, the cover and the wide tile, the movie
decoded with the toolchain's `dav1d.exe` and the logo with the runtime's own ASTC decoder built with its clang. They
go into each signed-in account's `config/grid`, the shortcut into its `shortcuts.vdf` (other shortcuts kept as they
are, ours updated when it is there; the file before the first change kept as `shortcuts.vdf.nx2navi-backup`).
Steam reads that file only when it starts and writes it back when it closes, so a running Steam is asked to close
first and started again after. The shortcut runs the launcher's `pythonw.exe` on `data/steam_play.pyw`, which
starts the launcher of `app/current.txt` with `--play`: the game starts as Play starts it, and the process waits
for it, so Steam counts the game as running while it is.
The choices are `theme`, `custom_background`, `custom_panel`, `custom_buttons`, `background`, `background_dim`,
`animations` and `sounds` in `data/launcher.json`.
Navi (`art.NAVI`, 22 x 21 pixels, drawn in whole pixels at every size) is also the icon of `NX2navi.exe`, Navi (`art.NAVI`, 22 x 21 pixels, drawn in whole pixels at every size) is also the icon of `NX2navi.exe`,
`NX2navi-Setup.exe`, the window and its taskbar button (`art.navi_ico`, written into the release by `NX2navi-Setup.exe`, the window and its taskbar button (`art.navi_ico`, written into the release by
@@ -65,8 +87,9 @@ identity (`NX2navi.Launcher`), so the taskbar groups and pins it under NX2navi r
Screens (`launcher/ui/app.py`): first run (dump, install folder, Desktop Shortcut, Check for Updates at Start, Screens (`launcher/ui/app.py`): first run (dump, install folder, Desktop Shortcut, Check for Updates at Start,
Update Channel, Begin Installation); the steps of an install, update or rebuild with their progress, the build log's Update Channel, Begin Installation); the steps of an install, update or rebuild with their progress, the build log's
last lines and Cancel, and after a failure Try Again and Copy Report; home (Play, Updates, Game Folder, Saves, last lines and Cancel, and after a failure Try Again and Copy Report; home (Play, Updates, Game Folder, Saves,
Rebuild the Game, Customize Launcher, Settings); customize (Color Scheme, Background, with a picture set Background Rebuild the Game, Customize Launcher, Settings); customize (Color Scheme, with Custom Background Color, Panel Color and
Dimming and Remove Background, Animations, Sounds, Back); saves (Export Save, Add Log and Settings, Export To, Import a Save, Import a Save Folder, Button Color, Background, with a picture set Background Dimming and Remove Background, Animations, Sounds, Add to Steam on
Windows, Back); the colour picker (Hue, Saturation, Brightness, Hex Code, Reset, Done); saves (Export Save, Add Log and Settings, Export To, Import a Save, Import a Save Folder,
Open Saves Folder, Back); settings (update check, Install Updates Automatically, Hide Launcher While Playing, Keep Open Saves Folder, Back); settings (update check, Install Updates Automatically, Hide Launcher While Playing, Keep
Build Cache, Update Channel, the folders, Open Logs Folder, Uninstall, Back); uninstall (keep or remove the built game). Build Cache, Update Channel, the folders, Open Logs Folder, Uninstall, Back); uninstall (keep or remove the built game).
A screen with more rows than the window holds draws them closer together (`fit_rows`). A screen with more rows than the window holds draws them closer together (`fit_rows`).
@@ -93,7 +116,7 @@ toolchain/msys64/ucrt64 MSYS2's clang and libraries, downloaded from the MSYS2
toolchain/pkgs/ the downloaded package files toolchain/pkgs/ the downloaded package files
data/launcher.json settings; data/logs/launcher.log (and crash.log); data/cache/fonts and data/cache/sounds data/launcher.json settings; data/logs/launcher.log (and crash.log); data/cache/fonts and data/cache/sounds
(the game's font and interface sounds, decoded from the player's game); (the game's font and interface sounds, decoded from the player's game);
data/background.npy (the player's background picture, fitted to the window) data/background.npy (the player's background picture, fitted below the title band)
game/ the built game, unless another folder was chosen (its layout: README-BuildKit.md), with game/ the built game, unless another folder was chosen (its layout: README-BuildKit.md), with
saves/ for saves to import and the backups imports make (below) saves/ for saves to import and the backups imports make (below)
``` ```
@@ -334,6 +357,8 @@ game folder is the default `<launcher>\game`. The dump is never touched.
``` ```
`--ffx` puts AMD's signed `amd_fidelityfx_vk.dll` (FidelityFX SDK 1.1.4) in the release for FSR 3.1. `--ffx` puts AMD's signed `amd_fidelityfx_vk.dll` (FidelityFX SDK 1.1.4) in the release for FSR 3.1.
`--ffx4 <folder>` puts AMD's signed `amd_fidelityfx_loader_vk.dll` and `amd_fidelityfx_upscaler_vk.dll` (FSR SDK
2.4.0, the files of its `Kits/FidelityFX/signedbin/`) in the release for FSR 4; without it the menu offers no FSR 4.
NVIDIA's `nvngx_dlss.dll` goes in by itself: the script downloads the version `tools/dlss_pin.py` pins from NVIDIA's `nvngx_dlss.dll` goes in by itself: the script downloads the version `tools/dlss_pin.py` pins from
NVIDIA's DLSS SDK repository (cached in `toolchain/launcher-dl/`), checks its size and sha256, and puts it in NVIDIA's DLSS SDK repository (cached in `toolchain/launcher-dl/`), checks its size and sha256, and puts it in
`bin/` with `nvngx_dlss-NOTICE.txt`; `make_game.py` copies both beside the game. `--dlss FILE` takes a copy on disk `bin/` with `nvngx_dlss-NOTICE.txt`; `make_game.py` copies both beside the game. `--dlss FILE` takes a copy on disk
@@ -378,7 +403,8 @@ pruning, unsafe archives, the background update (a release staged beside the run
`staged.json` marker, a staged release installed after a restart, no install while the game runs, the install once `staged.json` marker, a staged release installed after a restart, no install while the game runs, the install once
it exited, nothing by itself with Install Updates Automatically off, a failed staging tried again after the next it exited, nothing by itself with Install Updates Automatically off, a failed staging tried again after the next
check), the font decoding on a system font wrapped like the game's, the look (every colour scheme complete, the check), the font decoding on a system font wrapped like the game's, the look (every colour scheme complete, the
background picture cut to the window's shape and kept, the sound effects as WAVs and low by default), `make_game.py` Custom scheme's picked colours, colour square and typed hex code, the background picture cut to the shape below the
title band and kept, never stretched, the sound effects as WAVs and low by default), `make_game.py`
on a synthetic on a synthetic
`.nup` (events, skipped steps, `--rebuild` without the dump, step keys, the shaders key following the translator the `.nup` (events, skipped steps, `--rebuild` without the dump, step keys, the shaders key following the translator the
build uses), the RomFS step beside the lift and compile build uses), the RomFS step beside the lift and compile

View File

@@ -75,7 +75,7 @@ Source shorthands:
| 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. Terrain vertex shaders (42 variants) have taken 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. | The translator passes the fields through. Terrain walls and ground went 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 terrain the same before and after. | PTX ISA `bfe`, `bfi` | | 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. Terrain vertex shaders (42 variants) have taken 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. | The translator passes the fields through. Terrain walls and ground went 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 terrain 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`). | The translator's funnel shifts the other word by 32: undefined in SPIR-V; AMD shifts take the low 5 bits and give A \| C. | Gives terrain gaps at a distance. Ours: a select on a zero amount (translator patch 0013). In the shaders checked, every register SHF pairs its word with 0, so the result was right already. | — | | 3.11 | **SHF by 0** gives the unshifted word (C for `SHF.L`, A for `SHF.R`). | The translator's funnel shifts the other word by 32: undefined in SPIR-V; AMD shifts take the low 5 bits and give A \| C. | Gives terrain gaps at a distance. Ours: a select on a zero amount (translator patch 0013). In the shaders checked, 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; the NVIDIA driver has been reported to give 0. | An `OpVariable` without an initializer loads an undefined value; Mesa folds undefined values freely. | Ours: every function-local variable starts at 0 (`OpConstantNull`, job flag `zero_locals`, translator patch 0016) on every driver; `NX2NAVI_ZERO_LOCALS=0` turns it off. On NVIDIA an undefined read takes another warp lane's value: Ocarina's clustered-light loop lit its floors in 4x8-pixel tiles (one warp each) and darkened Link. It was off while DLAA was on, because zeroing moves the SPIR-V hash of the game's FXAA shader that `vk_dlaa.c` `vk_dlaa_skip_draw` matches (`FXAA_FS` holds the zeroed hash too); with it off the tiles showed under DLSS and DLAA, and the shader cache keys, which include the flag, changed with the upscaler, so shaders prepared with one setting missed under the other. Checked on an RTX 5090: zeroed, DLAA keeps its camera motion (`NX2NAVI_MV_CHECK`) and the floor is clean. | — | | 3.12 | **Registers read before any write** on a path (paths the structurizer adds included) have no defined value in the game's code; the NVIDIA driver has been reported to give 0. | An `OpVariable` without an initializer loads an undefined value; Mesa folds undefined values freely. | Ours: every function-local variable starts at 0 (`OpConstantNull`, job flag `zero_locals`, translator patch 0016) on every driver; `NX2NAVI_ZERO_LOCALS=0` turns it off. On NVIDIA an undefined read takes another warp lane's value: Ocarina's clustered-light loop lit its floors in 4x8-pixel tiles (one warp each) and darkened Link. It was off while DLAA was on, because zeroing moves the SPIR-V hash of the game's FXAA shader that `vk_dlaa.c` `vk_dlaa_skip_draw` matches (`FXAA_FS` holds the zeroed hash too); with it off the tiles showed under DLSS and DLAA, and the shader cache keys, which include the flag, changed with the upscaler, so shaders prepared with one setting missed under the other. Checked on an RTX 5090: zeroed, DLAA keeps its camera motion (`NX2NAVI_MV_CHECK`) and the floor is clean. | — |
| 3.13 | **NaN, infinity and signed zero follow IEEE 754**, and the game's code leans on them: its compiler writes an unordered comparison as `x > c \|\| isnan(x)`, a normalisation of a zero-length vector gives an infinity that a later test catches, and integer masks (0xffffffff) pass through float moves and selects. | SPIR-V without the `SignedZeroInfNanPreserve` execution mode lets the driver assume that no float is NaN or infinite. AMD's compilers act on it; NVIDIA's driver keeps the IEEE results. | The isnan tests of the game and of the translator (patches 0027, 0031) are only safe with the mode. On an RX 9070 XT a select between 1 and the bits 0xffffffff, converted as a signed integer, gave 2^32 instead of -1 and blew shadow casters up (issue #156); RX 6000 cards drew black and white blocks on Navi and on Link next to her (#41, #110); AMD GPUs drew Navi's sparkles without her orb. Ours: `vk_pipeline.c` `spirv_nan_preserve` adds the mode for 32-bit floats (16 and 64 where the module declares them and the driver can) when the module is created, on every driver except NVIDIA's (`NX2NAVI_VK_NAN_PRESERVE`). | VKSPEC (SPIR-V environment, precision and operation of SPIR-V instructions) | | 3.13 | **NaN, infinity and signed zero follow IEEE 754**, and the game's code leans on them: its compiler writes an unordered comparison as `x > c \|\| isnan(x)`, a normalisation of a zero-length vector gives an infinity that a later test catches, and integer masks (0xffffffff) pass through float moves and selects. | SPIR-V without the `SignedZeroInfNanPreserve` execution mode lets the driver assume that no float is NaN or infinite. AMD's compilers act on it; NVIDIA's driver keeps the IEEE results. | The isnan tests of the game and of the translator (patches 0027, 0031) are only safe with the mode. On an RX 9070 XT a select between 1 and the bits 0xffffffff, converted as a signed integer, gave 2^32 instead of -1 and blew shadow casters up (issue #156); RX 6000 cards drew black and white blocks on Navi and on Link next to her (#41, #110); AMD GPUs drew Navi's sparkles without her orb. Ours: `vk_pipeline.c` `spirv_nan_preserve` adds the mode for 32-bit floats (16 and 64 where the module declares them and the driver can) when the module is created, on every driver except NVIDIA's (`NX2NAVI_VK_NAN_PRESERVE`). On AMD's Windows driver for RDNA 1 and 2 ("AMD proprietary shader compiler", `vk_caps.amd_sc`), where the black and white blocks were reported, `spirv_nan_bits` also turns every 32-bit `OpIsNan` into an integer test of its bits and a float select with a NaN-bits constant into a select of the bits, which no float assumption can change (`NX2NAVI_VK_NAN_BITS`). | VKSPEC (SPIR-V environment, precision and operation of SPIR-V instructions) |
## 4. Memory model ## 4. Memory model

49
docs/releases/v0.7.2.md Normal file
View File

@@ -0,0 +1,49 @@
Draft notes for the release after 0.7.1. The version number is not decided yet.
## Faster
- **AMD cards: about a fifth more frames in open areas, and more even frame times.** The game asks the video card
which objects are visible, about a hundred questions a frame in Hyrule Field, and waits for a frame to be finished
on the card before it lets the next one start. The answers were fetched one call at a time, on the thread that also
reports "finished", and on AMD's Windows driver each of those calls goes into the kernel: every frame was reported
finished about 4 ms late, with every thread of the game waiting. They are now fetched a few hundred at a time.
Standing in Hyrule Field on an RX 7900 XT (driver 26.10.1, 3440x1440, FSR): 53 fps instead of 45, and the longest
frame of a minute 46 ms instead of 55 (`oq_batch = 0` in `nx2navi.ini` brings the old readback back).
- **No more frames drawn one present late.** The game signals from the CPU when a frame's data is written, and its
render thread submits the frame's commands without waiting for that signal. When the signal came a millisecond or
two after the submit call, in about every other frame in Hyrule Field, the frame was set aside and drawn at its
present, and frames of 23 and 15 ms took turns. The submit call now waits for the signal, 10 ms at most
(`gate_wait_ms`): 54.5 fps instead of 53 in the same place and the longest frame 33 ms instead of 46; with
`vk_recorder = 1`, which AMD cards do not have on by default, 58.6 fps.
## New
- **AMD FSR 4 upscaling** on Radeon RX 6000, RX 7000 and RX 9000 cards (Windows, AMD's driver 26.10.1 or newer):
AMD's machine-learned upscaler, in the menu under Screen, Upscaling, as *AMD FSR 4 Native AA*, *Quality*,
*Balanced*, *Performance* and *Ultra Performance* (`fsr4 = 1` in `nx2navi.ini`). It keeps thin things whole that
FSR 3.1 breaks up or smears when the camera moves: grass and leaves, Navi's wings, the edges of Link's hat. It is
off until you choose it, because it costs more than FSR 3.1: standing in Hyrule Field on an RX 7900 XT at
3440x1440, 47 fps in Quality where FSR 3.1 gives 51, and 41 fps in Native AA; it takes about 220 MB of video
memory. The setup brings AMD's two libraries for it (FSR SDK 2.4, `amd_fidelityfx_loader_vk.dll` and
`amd_fidelityfx_upscaler_vk.dll`), which ask the driver whether the card can run FSR 4: the rows appear only
where it can, and the log names the version (`ffx4:`). It works together with FSR 3.1 frame generation, and you
can switch between FSR 3.1 and FSR 4 while playing.
- **Add to Steam** in Customize Launcher (Windows): adds the game to your Steam library as *The Legend of Zelda
Ocarina of Time*, with Navi as its icon and the title screen's artwork and logo. Starting it from Steam starts the
game. Steam restarts once while it is added.
- **Custom color scheme** in Customize Launcher: pick your own background, panel and button colors on a color
square with a hue bar, or type a hex code.
## Fixed
- Your own background picture in the launcher is no longer partly hidden under the top bar: it now starts right
below it, and keeps its shape.
- Black and white blocks on AMD RX 5000 and RX 6000 cards: on Navi and on Link next to her, on bright floors near her,
and on the bright outdoors seen through a door or window from inside a house. Every float colour a shader writes is
checked for NaN, so that one bad pixel cannot spread through the blur and bloom passes; those checks, and the
game's own NaN tests in nearly nine of ten shaders, are float comparisons that a shader compiler may decide can
never be true. The Windows driver for these cards uses AMD's older shader compiler (the log reads "AMD proprietary
shader compiler"); with it each NaN test is now made on the bits of the number instead, which no compiler can drop.
It is on by default only with that driver (`vk_nan_bits`); the first start after the update compiles the pipelines
again. Untested on those cards before this release: please report whether the blocks are gone.

358
launcher/gameart.py Normal file
View File

@@ -0,0 +1,358 @@
"""The pictures of the game's Steam shortcut (launcher/steam.py), made from the player's own game: nothing ships.
icon Navi as the game's HUD draws her (HUDNaviIcon_Body_00 over the glow HUDNaviIcon_Flare_00), 128 x 128
logo the title screen's logo with the Master Sword and the Hylian Shield (Logo_USEU_00), cut to its outline
hero the title screen's moonlit field, a frame of its first movie (Event/Movie/Dm_Title_0005.webm), 1920 x 620
portrait that frame with the logo over it, 600 x 900 (the library's cover)
wide the same at 920 x 430 (the library's wide tile)
The textures come from the interface archive UI/Layout2Archive/Title...bntx.zs as runtime/menu_assets.c reads them:
a BNTX's BRTI records give format, size, block height and data; the level is block linear in the Switch 2 GOB layout
(runtime/tex_deswizzle.c tex_bl_copy); BC4 masks become white with the mask as alpha; ASTC 4x4 goes through the
runtime's own decoder, runtime/tex_astc.c, built here into a library with the toolchain's clang (the launcher builds
the game with it, so it is on every PC that has a game to add). The movie is WebM with AV1 video: the frames from the
key frame before TITLE_AT up to it go into an IVF file for the toolchain's dav1d.exe, whose last picture (8-bit 4:2:0,
limited range BT.709) becomes the background. Every picture is written as PNG with art.png_bytes; nothing here needs
an imaging package.
"""
import ctypes
import hashlib
import os
import struct
import subprocess
import tempfile
from pathlib import Path
import numpy as np
from . import gamefiles
TITLE_ARCHIVE = 'UI/Layout2Archive/Title.Product.100.Nin_Ounce_NVN2.bntx.zs'
COMMON_ARCHIVE = 'UI/Layout2Archive/Common.Product.100.Nin_Ounce_NVN2.bntx.zs'
LOGO, NAVI, NAVI_GLOW = 'Logo_USEU_00', 'HUDNaviIcon_Body_00', 'HUDNaviIcon_Flare_00'
TITLE_MOVIE = 'Event/Movie/Dm_Title_0005.webm'
TITLE_AT = 12.0 # seconds into it: the field under the full moon, as the title screen shows it first
KIND_BC4, KIND_ASTC4 = 0x1d, 0x2d
NO_WINDOW = 0x08000000 if os.name == 'nt' else 0
class ArtError(Exception):
pass
# ---------------------------------------------------------------- BNTX
def _u16(b, at): return struct.unpack_from('<H', b, at)[0]
def _u32(b, at): return struct.unpack_from('<I', b, at)[0]
def _u64(b, at): return struct.unpack_from('<Q', b, at)[0]
def bntx_textures(b):
"""Each texture of a BNTX file: name, format, size, block height, data offset and size."""
out = []
count, arr = _u32(b, 0x24), _u64(b, 0x28)
for i in range(count):
p = _u64(b, arr + 8 * i)
if b[p:p + 4] != b'BRTI':
continue
no = _u64(b, p + 0x60)
name = b[no + 2:no + 2 + _u16(b, no)].decode('utf-8', 'replace')
out.append({'name': name, 'fmt': _u32(b, p + 0x1c), 'w': _u32(b, p + 0x24), 'h': _u32(b, p + 0x28),
'th': _u32(b, p + 0x34), 'size': _u32(b, p + 0x50), 'data': _u64(b, _u64(b, p + 0x70))})
return out
def deswizzle(t, b, row, rows):
"""The first level as tightly packed rows of `row` bytes (runtime/tex_deswizzle.c tex_bl_copy)."""
th = t['th']
gobs, unit, block = (row + 63) // 64, 8 << th, 512 << th
need = gobs * ((rows + unit - 1) // unit) * block
src = bytearray(max(need, t['size']) + 16)
src[:t['size']] = b[t['data']:t['data'] + t['size']]
bl = np.frombuffer(bytes(src), dtype='V16')
cols = (row + 15) // 16
y = np.arange(rows)[:, None]
x = (np.arange(cols) * 16)[None, :]
at = (y // unit) * gobs * block + (x // 64) * block + ((y % unit) // 8) * 512 + \
(x % 64 // 32) * 256 + (y % 8 // 4) * 128 + (x % 32 // 16) * 64 + (y % 4) * 16
flat = np.frombuffer(bl[at // 16].tobytes(), dtype=np.uint8).reshape(rows, cols * 16)
return flat[:, :row]
def bc4(lin, wb, hb, w, h):
"""White with the mask as alpha (runtime/menu_assets.c bc4_decode)."""
blocks = lin.reshape(hb, wb, 8).astype(np.uint32)
a, b = blocks[..., 0], blocks[..., 1]
pal = np.zeros((hb, wb, 8), dtype=np.uint32)
pal[..., 0], pal[..., 1] = a, b
big = a > b
for i in range(6):
pal[..., 2 + i] = np.where(big, ((6 - i) * a + (i + 1) * b) // 7, 0)
for i in range(4):
pal[..., 2 + i] = np.where(big, pal[..., 2 + i], ((4 - i) * a + (i + 1) * b) // 5)
pal[..., 6] = np.where(big, pal[..., 6], 0)
pal[..., 7] = np.where(big, pal[..., 7], 255)
bits = np.zeros((hb, wb), dtype=np.uint64)
for i in range(6):
bits |= blocks[..., 2 + i].astype(np.uint64) << np.uint64(8 * i)
alpha = np.zeros((hb * 4, wb * 4), dtype=np.uint8)
for i in range(16):
sel = ((bits >> np.uint64(3 * i)) & np.uint64(7)).astype(np.intp)
alpha[i // 4::4, i % 4::4] = np.take_along_axis(pal, sel[..., None], 2)[..., 0]
rgba = np.full((h, w, 4), 255, dtype=np.uint8)
rgba[..., 3] = alpha[:h, :w]
return rgba
def astc_library(layout):
"""runtime/tex_astc.c of this release as a library in data/cache, built once per source with the toolchain."""
src = layout.app / 'runtime' / 'tex_astc.c'
if not src.is_file():
raise ArtError(f'{src} is missing')
tag = hashlib.sha256(src.read_bytes() + (layout.app / 'runtime' / 'tex.h').read_bytes()).hexdigest()[:12]
dll = layout.cache / f'astc-{tag}.dll'
if not dll.is_file():
clang = layout.msys / 'bin' / 'clang.exe'
if not clang.is_file():
raise ArtError('the build tools are not installed (Rebuild the Game installs them)')
env = dict(os.environ, PATH=str(layout.msys / 'bin') + os.pathsep + os.environ.get('PATH', ''))
tmp = dll.with_name(dll.name + '.tmp')
r = subprocess.run([str(clang), '-shared', '-O2', '-static', '-w', '-I', str(layout.app / 'runtime'),
'-I', str(layout.msys / 'include' / 'vma'), str(src), '-o', str(tmp)],
capture_output=True, text=True, env=env, creationflags=NO_WINDOW)
if r.returncode or not tmp.is_file():
raise ArtError(f'the texture decoder did not build: {(r.stderr or r.stdout).strip()[-300:]}')
os.replace(tmp, dll)
lib = ctypes.CDLL(str(dll))
lib.astc_decode_ldr.restype = None
lib.astc_decode_ldr.argtypes = [ctypes.c_char_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32,
ctypes.c_uint32, ctypes.c_bool, ctypes.c_void_p]
return lib
def texture(bntx, name, lib):
"""The named texture as an HxWx4 uint8 array (BC4 or ASTC 4x4), or None when the file has no such texture."""
for t in bntx_textures(bntx):
if t['name'] != name:
continue
kind = t['fmt'] >> 8
w, h = t['w'], t['h']
wb, hb = (w + 3) // 4, (h + 3) // 4
if kind == KIND_BC4:
return bc4(deswizzle(t, bntx, wb * 8, hb), wb, hb, w, h)
if kind == KIND_ASTC4:
lin = deswizzle(t, bntx, wb * 16, hb)
rgba = np.zeros((h, w, 4), dtype=np.uint8)
lib.astc_decode_ldr(lin.tobytes(), w, h, 4, 4, (t['fmt'] & 0xff) == 6, rgba.ctypes.data)
return rgba
raise ArtError(f'{name} has a texture format this launcher does not read ({t["fmt"]:#x})')
return None
# ---------------------------------------------------------------- the title movie
_MASTERS = {0x18538067, 0x1F43B675, 0xA0, 0x1654AE6B, 0xAE, 0xE0} # Segment, Cluster, BlockGroup, Tracks, TrackEntry, Video
def _vint(b, at, keep_marker):
first = b[at]
n = 1
while n <= 8 and not first & (0x80 >> (n - 1)):
n += 1
if n > 8:
raise ArtError('the movie is not WebM')
v = first if keep_marker else first & (0xff >> n)
for i in range(1, n):
v = v << 8 | b[at + i]
return v, n
def webm_frames(b):
"""(time in ms, key frame, data) of every block of a single-track WebM, and the video's width and height."""
out, info = [], {}
def walk(at, end, cluster):
while at < end:
eid, n1 = _vint(b, at, True)
size, n2 = _vint(b, at + n1, False)
body = at + n1 + n2
if size == (1 << (7 * n2)) - 1: # unknown size: to the end of the parent
size = end - body
if eid in _MASTERS:
walk(body, min(body + size, end), cluster)
elif eid == 0xE7:
cluster[0] = int.from_bytes(b[body:body + size], 'big')
elif eid == 0xB0:
info['w'] = int.from_bytes(b[body:body + size], 'big')
elif eid == 0xBA:
info['h'] = int.from_bytes(b[body:body + size], 'big')
elif eid in (0xA3, 0xA1): # SimpleBlock (its flags say key frame), Block
_track, n = _vint(b, body, False)
rel = struct.unpack_from('>h', b, body + n)[0]
key = eid == 0xA3 and bool(b[body + n + 2] & 0x80)
out.append((cluster[0] + rel, key, b[body + n + 3:body + size]))
at = body + size
walk(0, len(b), [0])
if not out or 'w' not in info or 'h' not in info:
raise ArtError('the title movie has no video frames')
return out, info['w'], info['h']
def movie_frame(layout, data, at_s, work):
"""The picture of the movie `data` at at_s seconds as an HxWx3 uint8 array, decoded by the toolchain's dav1d."""
dav1d = layout.msys / 'bin' / 'dav1d.exe'
if not dav1d.is_file():
raise ArtError('the build tools are not installed (Rebuild the Game installs them)')
frames, w, h = webm_frames(data)
upto = [f for f in frames if f[0] <= at_s * 1000] or frames[:1]
k0 = max((i for i, f in enumerate(upto) if f[1]), default=0)
sel = upto[k0:]
ivf, y4m = Path(work) / 'title.ivf', Path(work) / 'title.y4m'
with open(ivf, 'wb') as f:
f.write(b'DKIF' + struct.pack('<HH4sHHIIII', 0, 32, b'AV01', w, h, 1000, 1, len(sel), 0))
for t, _key, d in sel:
f.write(struct.pack('<IQ', len(d), max(t, 0)) + d)
r = subprocess.run([str(dav1d), '-q', '-i', str(ivf), '-o', str(y4m)], capture_output=True, text=True,
cwd=str(dav1d.parent), creationflags=NO_WINDOW)
if r.returncode or not y4m.is_file():
raise ArtError(f'the title movie did not decode: {(r.stderr or r.stdout).strip()[-300:]}')
b = y4m.read_bytes()
at = b.rfind(b'FRAME\n')
if at < 0 or len(b) < at + 6 + w * h * 3 // 2:
raise ArtError('the title movie did not decode to a picture')
at += 6
y = np.frombuffer(b, np.uint8, w * h, at).reshape(h, w).astype(np.float32)
cw, ch = (w + 1) // 2, (h + 1) // 2
u = np.frombuffer(b, np.uint8, cw * ch, at + w * h).reshape(ch, cw).astype(np.float32)
v = np.frombuffer(b, np.uint8, cw * ch, at + w * h + cw * ch).reshape(ch, cw).astype(np.float32)
u = (u.repeat(2, 0).repeat(2, 1)[:h, :w] - 128) * (255 / 224)
v = (v.repeat(2, 0).repeat(2, 1)[:h, :w] - 128) * (255 / 224)
y = (y - 16) * (255 / 219)
rgb = np.stack([y + 1.5748 * v, y - 0.1873 * u - 0.4681 * v, y + 1.8556 * u], -1) # BT.709
return np.clip(rgb + 0.5, 0, 255).astype(np.uint8)
# ---------------------------------------------------------------- pictures
def resize(img, w, h):
"""img (HxWxC uint8 or float) at w x h: whole-pixel box averaging first when it shrinks by 2 or more, then
bilinear. Returns float32."""
a = img.astype(np.float32)
fy, fx = a.shape[0] // h, a.shape[1] // w
if fy >= 2 or fx >= 2:
fy, fx = max(fy, 1), max(fx, 1)
H, W = a.shape[0] // fy * fy, a.shape[1] // fx * fx
a = a[:H, :W].reshape(H // fy, fy, W // fx, fx, -1).mean(axis=(1, 3))
ys = (np.arange(h) + 0.5) * a.shape[0] / h - 0.5
xs = (np.arange(w) + 0.5) * a.shape[1] / w - 0.5
y0 = np.clip(np.floor(ys).astype(int), 0, a.shape[0] - 1)
x0 = np.clip(np.floor(xs).astype(int), 0, a.shape[1] - 1)
y1, x1 = np.minimum(y0 + 1, a.shape[0] - 1), np.minimum(x0 + 1, a.shape[1] - 1)
wy = np.clip(ys - y0, 0, 1)[:, None, None]
wx = np.clip(xs - x0, 0, 1)[None, :, None]
top = a[y0][:, x0] * (1 - wx) + a[y0][:, x1] * wx
bottom = a[y1][:, x0] * (1 - wx) + a[y1][:, x1] * wx
return top * (1 - wy) + bottom * wy
def premultiplied_resize(rgba, w, h):
"""Resize with the colours weighted by alpha, so transparent texels add no dark fringe; uint8 straight alpha out."""
a = rgba.astype(np.float32)
a[..., :3] *= a[..., 3:4] / 255
r = resize(a, w, h)
r[..., :3] /= np.maximum(r[..., 3:4], 1e-3) / 255
return np.clip(r + 0.5, 0, 255).astype(np.uint8)
def trim(rgba, pad=8):
"""rgba cut to the box of its visible texels, pad texels around."""
ys, xs = np.nonzero(rgba[..., 3] > 4)
if not len(ys):
return rgba
y0, y1 = max(ys.min() - pad, 0), min(ys.max() + 1 + pad, rgba.shape[0])
x0, x1 = max(xs.min() - pad, 0), min(xs.max() + 1 + pad, rgba.shape[1])
return rgba[y0:y1, x0:x1]
def place(dst, src, x, y):
"""src (uint8 RGBA, straight alpha) over dst (uint8 RGB) at x, y."""
h, w = src.shape[:2]
s = src.astype(np.float32)
d = dst[y:y + h, x:x + w].astype(np.float32)
al = s[..., 3:4] / 255
dst[y:y + h, x:x + w] = np.clip(d * (1 - al) + s[..., :3] * al + 0.5, 0, 255).astype(np.uint8)
def crop(frame, w, h, cx, cy):
"""The largest w:h part of frame centred near (cx, cy) as fractions, scaled to w x h (uint8 RGB)."""
H, W = frame.shape[:2]
if W * h > H * w:
ch, cw = H, H * w // h
else:
cw, ch = W, W * h // w
x0 = int(np.clip(cx * W - cw / 2, 0, W - cw))
y0 = int(np.clip(cy * H - ch / 2, 0, H - ch))
return np.clip(resize(frame[y0:y0 + ch, x0:x0 + cw], w, h) + 0.5, 0, 255).astype(np.uint8)
def with_logo(bg, logo, width_share, cy):
"""bg (RGB) with the logo scaled to width_share of its width, centred at height cy (a fraction)."""
H, W = bg.shape[:2]
lw = int(W * width_share)
lh = int(lw * logo.shape[0] / logo.shape[1])
if lh > H * 0.8:
lh = int(H * 0.8)
lw = int(lh * logo.shape[1] / logo.shape[0])
small = premultiplied_resize(logo, lw, lh)
out = bg.copy()
place(out, small, (W - lw) // 2, int(np.clip(cy * H - lh / 2, 0, H - lh)))
return out
def navi_icon(body, glow, size=128):
"""Navi's HUD icon on her glow, size x size RGBA: the glow tinted the pale blue of her light."""
out = np.zeros((size, size, 4), dtype=np.float32)
g = resize(glow, size, size)
g[..., :3] = np.array([200, 228, 255], dtype=np.float32)
g[..., 3] *= 0.85
b = resize(body, int(size * 0.8), int(size * 0.8))
for layer, at in ((g, 0), (b, (size - b.shape[0]) // 2)):
h, w = layer.shape[:2]
d = out[at:at + h, at:at + w]
sa, da = layer[..., 3:4] / 255, d[..., 3:4] / 255
oa = sa + da * (1 - sa)
d[..., :3] = (layer[..., :3] * sa + d[..., :3] * da * (1 - sa)) / np.maximum(oa, 1e-6)
d[..., 3:4] = oa * 255
return np.clip(out + 0.5, 0, 255).astype(np.uint8)
def rgba_of(rgb):
return np.concatenate([rgb, np.full(rgb.shape[:2] + (1,), 255, dtype=np.uint8)], -1)
def make(layout, game_dir='', dump=''):
"""{name: HxWx4 uint8} for icon, logo, hero, portrait and wide, from the player's game. ArtError when the game's
files or the tools to read them are not there."""
romfs = gamefiles.open_romfs(layout, game_dir, dump)
if romfs is None:
raise ArtError('the game\'s files were not found (the game folder\'s romfs, or the dump)')
zs = gamefiles.ZsReader(romfs)
title, common = zs.read(TITLE_ARCHIVE), zs.read(COMMON_ARCHIVE)
movie = romfs.read(TITLE_MOVIE)
if not title or not common or not movie:
raise ArtError('the game\'s title screen files were not found')
lib = astc_library(layout)
logo = texture(title, LOGO, lib)
body, glow = texture(common, NAVI, lib), texture(common, NAVI_GLOW, lib)
if logo is None or body is None or glow is None:
raise ArtError('the game\'s logo or Navi\'s icon was not found')
logo = trim(logo)
with tempfile.TemporaryDirectory(dir=str(layout.cache)) as work:
frame = movie_frame(layout, movie, TITLE_AT, work)
# the moon sits right of the middle and high: every cut keeps it, and the hero keeps the horizon too
hero = crop(frame, 1920, 620, 0.5, 0.42)
portrait = with_logo(crop(frame, 600, 900, 0.68, 0.5), logo, 0.88, 0.70)
wide = with_logo(crop(frame, 920, 430, 0.5, 0.45), logo, 0.52, 0.55)
return {'icon': navi_icon(body, glow), 'logo': logo, 'hero': rgba_of(hero), 'portrait': rgba_of(portrait),
'wide': rgba_of(wide)}

View File

@@ -16,6 +16,9 @@ DEFAULTS = {
'save_export_dir': '', # where Saves > Export Save writes its zip; empty: the Downloads folder 'save_export_dir': '', # where Saves > Export Save writes its zip; empty: the Downloads folder
'export_with_log': True, # Export Save adds the game's latest log and nx2navi.ini (for a bug report) 'export_with_log': True, # Export Save adds the game's latest log and nx2navi.ini (for a bug report)
'theme': 'forest', # the colour scheme (launcher/ui/art.py THEMES) 'theme': 'forest', # the colour scheme (launcher/ui/art.py THEMES)
'custom_background': '', # the Custom scheme's backdrop colour, #rrggbb; empty: the first scheme's
'custom_panel': '', # the Custom scheme's colour of the panels and the title band
'custom_buttons': '', # the Custom scheme's colour of the buttons
'background': '', # the picture the player chose as the background; its fitted copy is data/background.npy 'background': '', # the picture the player chose as the background; its fitted copy is data/background.npy
'background_dim': 40, # how much that picture is darkened, in percent 'background_dim': 40, # how much that picture is darkened, in percent
'animations': True, # the cursor glides, screens slide in, sparks drift, Navi bobs 'animations': True, # the cursor glides, screens slide in, sparks drift, Navi bobs

329
launcher/steam.py Normal file
View File

@@ -0,0 +1,329 @@
"""Add to Steam (Customize Launcher): the game as a non-Steam shortcut in the player's Steam library, with Navi as its
icon and the game's title screen and logo as its pictures (launcher/gameart.py). Windows only.
Steam keeps the shortcuts of each account in <Steam>/userdata/<account id>/config/shortcuts.vdf, a binary key-value
file: a map is 0x00 name 0x00 ... 0x08, a string 0x01 name 0x00 value 0x00, a 32-bit integer 0x02 name 0x00 value
(0x07 is a 64-bit one). The file is the map "shortcuts" holding one map per shortcut, named "0", "1", ... Each holds
appid, AppName, Exe, StartDir, icon, LaunchOptions and Steam's own fields; the other shortcuts are read and written
back as they are, and a shortcut of ours already there (by its name or its id) is updated in place. Its pictures go
into config/grid named by the shortcut's id: <id>p.png the cover, <id>.png the wide tile, <id>_hero.png the
background, <id>_logo.png the logo, and the icon file the shortcut names. The id is CRC-32 of Exe and AppName as
Steam writes them, with the top bit set.
Steam reads the file when it starts and writes it back when it closes, so a running Steam would neither see the new
shortcut nor keep it: Steam is asked to close (steam.exe -shutdown), the files are written, and Steam starts again.
The shortcut starts the launcher's pythonw.exe on data/steam_play.pyw, which starts this launcher with --play: the game
runs from its own folder with its console hidden, and the Python process waits for it, so Steam shows the game as
running for as long as it is (the game's own Restart included). Starting ocarina.exe directly would open a console
window beside the game, and NX2navi.exe ends a few seconds after it started the launcher.
"""
import os
import shutil
import struct
import subprocess
import time
import zlib
from pathlib import Path
NAME = 'The Legend of Zelda Ocarina of Time'
PLAY_SCRIPT = 'steam_play.pyw'
NO_WINDOW = 0x08000000 if os.name == 'nt' else 0
STEAM64_BASE = 76561197960265728
PLAY_TEXT = '''"""Written by the NX2navi launcher (Customize Launcher > Add to Steam): Steam starts the game through this file.
It runs the launcher of app/current.txt with --play, which starts the game and waits for it."""
import os
import runpy
import sys
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
with open(os.path.join(root, 'app', 'current.txt'), encoding='utf-8') as f:
version = f.read().strip()
os.environ['NX2NAVI_LAUNCHER_ROOT'] = root
sys.argv = [os.path.join(root, 'app', version, 'launcher', 'start.pyw'), '--play'] + sys.argv[1:]
runpy.run_path(sys.argv[0], run_name='__main__')
'''
class SteamError(Exception):
pass
# ---------------------------------------------------------------- binary VDF
T_MAP, T_STR, T_INT, T_FLOAT, T_PTR, T_WSTR, T_COLOR, T_U64, T_END = 0, 1, 2, 3, 4, 5, 6, 7, 8
def vdf_load(b):
"""A binary VDF as a list of [type, key, value]; a map's value is such a list. Raises SteamError when malformed."""
def cstr(at):
end = b.index(b'\0', at)
return b[at:end].decode('utf-8', 'surrogateescape'), end + 1
def walk(at, top):
items = []
while True:
if at >= len(b):
if top:
return items, at
raise SteamError('shortcuts.vdf ends inside a map')
t = b[at]
at += 1
if t == T_END:
return items, at
key, at = cstr(at)
if t == T_MAP:
v, at = walk(at, False)
elif t == T_STR:
v, at = cstr(at)
elif t in (T_INT, T_FLOAT, T_PTR, T_COLOR):
v, at = b[at:at + 4], at + 4
elif t == T_U64:
v, at = b[at:at + 8], at + 8
else:
raise SteamError(f'shortcuts.vdf holds a value of type {t}')
items.append([t, key, v])
try:
items, at = walk(0, True)
except ValueError:
raise SteamError('shortcuts.vdf is cut short') from None
return items
def vdf_dump(items, top=True):
out = bytearray()
for t, key, v in items:
out += bytes([t]) + key.encode('utf-8', 'surrogateescape') + b'\0'
if t == T_MAP:
out += vdf_dump(v, False)
elif t == T_STR:
out += v.encode('utf-8', 'surrogateescape') + b'\0'
else:
out += v
if not top or items:
out += bytes([T_END])
return bytes(out)
def _get(items, key):
for it in items:
if it[1].lower() == key.lower():
return it
return None
def _set(items, t, key, v):
it = _get(items, key)
if it:
it[0], it[2] = t, v
else:
items.append([t, key, v])
def appid(exe, name):
"""The id Steam gives a shortcut: CRC-32 of its Exe and AppName fields with the top bit set (unsigned)."""
return (zlib.crc32((exe + name).encode('utf-8')) & 0xFFFFFFFF) | 0x80000000
def add_shortcut(vdf_bytes, exe, start_dir, options, icon, name=NAME):
"""shortcuts.vdf (b'' for none) with our shortcut added or updated; returns (new bytes, id)."""
items = vdf_load(vdf_bytes) if vdf_bytes else []
root = _get(items, 'shortcuts')
if root is None or root[0] != T_MAP:
items = [[T_MAP, 'shortcuts', []]]
root = items[0]
sid = appid(exe, name)
entry = None
for it in root[2]:
if it[0] != T_MAP:
continue
n, a = _get(it[2], 'AppName'), _get(it[2], 'appid')
if (n and n[0] == T_STR and n[2] == name) or (a and a[0] == T_INT and struct.unpack('<I', a[2])[0] == sid):
entry = it[2]
break
if entry is None:
used = {it[1] for it in root[2]}
k = 0
while str(k) in used:
k += 1
entry = []
root[2].append([T_MAP, str(k), entry])
for key, t, v in (('IsHidden', T_INT, 0), ('AllowDesktopConfig', T_INT, 1), ('AllowOverlay', T_INT, 1),
('OpenVR', T_INT, 0), ('Devkit', T_INT, 0), ('DevkitGameID', T_STR, ''),
('DevkitOverrideAppID', T_INT, 0), ('LastPlayTime', T_INT, 0), ('FlatpakAppID', T_STR, '')):
entry.append([t, key, struct.pack('<I', v) if t == T_INT else v])
entry.append([T_MAP, 'tags', []])
_set(entry, T_INT, 'appid', struct.pack('<I', sid))
_set(entry, T_STR, 'AppName', name)
_set(entry, T_STR, 'Exe', exe)
_set(entry, T_STR, 'StartDir', start_dir)
_set(entry, T_STR, 'icon', icon)
_set(entry, T_STR, 'LaunchOptions', options)
# Steam's order: appid and the strings first, then the switches and tags
order = ['appid', 'AppName', 'Exe', 'StartDir', 'icon', 'ShortcutPath', 'LaunchOptions']
entry.sort(key=lambda it: order.index(it[1]) if it[1] in order else len(order) + (it[1] == 'tags'))
if _get(entry, 'ShortcutPath') is None:
entry.insert(5, [T_STR, 'ShortcutPath', ''])
return vdf_dump(items), sid
def has_shortcut(vdf_bytes, name=NAME):
try:
root = _get(vdf_load(vdf_bytes), 'shortcuts') if vdf_bytes else None
except SteamError:
return False
return bool(root and root[0] == T_MAP and any(
it[0] == T_MAP and (_get(it[2], 'AppName') or [0, 0, None])[2] == name for it in root[2]))
# ---------------------------------------------------------------- Steam on this PC
def find_steam():
"""(Steam's folder, steam.exe) from the registry, else the usual folder; None when Steam is not installed."""
if os.name != 'nt':
return None
folder = exe = None
try:
import winreg
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Valve\Steam') as k:
for name in ('SteamPath', 'SteamExe'):
try:
v = winreg.QueryValueEx(k, name)[0]
except OSError:
continue
if name == 'SteamPath':
folder = Path(v)
else:
exe = Path(v)
except OSError:
pass
if folder is None:
folder = Path(os.environ.get('ProgramFiles(x86)', r'C:\Program Files (x86)')) / 'Steam'
exe = exe or folder / 'steam.exe'
if not (folder / 'userdata').is_dir() and not exe.is_file():
return None
return folder, exe
def accounts(folder):
"""The config folders of the accounts that signed in to Steam on this PC (config/loginusers.vdf), else of every
account folder under userdata."""
ud = Path(folder) / 'userdata'
if not ud.is_dir():
return []
dirs = {p.name: p / 'config' for p in ud.iterdir() if p.is_dir() and p.name.isdigit() and p.name != '0'}
signed = []
try:
text = (Path(folder) / 'config' / 'loginusers.vdf').read_text(encoding='utf-8', errors='replace')
import re
signed = [str(int(i) - STEAM64_BASE) for i in re.findall(r'"(7656119\d{10})"', text)]
except (OSError, ValueError):
pass
picked = [dirs[a] for a in signed if a in dirs] or list(dirs.values())
return sorted(set(picked))
def added(folder=None):
"""True when an account of this PC has our shortcut."""
found = (folder, None) if folder else find_steam()
if not found:
return False
for cfg in accounts(found[0]):
try:
if has_shortcut((cfg / 'shortcuts.vdf').read_bytes()):
return True
except OSError:
pass
return False
def steam_running():
if os.name != 'nt':
return False
try:
r = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq steam.exe', '/NH', '/FO', 'CSV'], capture_output=True,
text=True, creationflags=NO_WINDOW, timeout=15)
except (OSError, subprocess.TimeoutExpired):
return False
return '"steam.exe"' in r.stdout.lower()
def close_steam(exe, timeout=45.0):
"""Ask Steam to close and wait for it; False when it is still running after timeout seconds."""
subprocess.Popen([str(exe), '-shutdown'], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, creationflags=NO_WINDOW, close_fds=True)
end = time.time() + timeout
while time.time() < end:
time.sleep(1)
if not steam_running():
time.sleep(2) # it writes its files on the way out
return True
return False
def write_atomic(path, data):
tmp = path.with_name(path.name + '.nx2navi-tmp')
tmp.write_bytes(data)
os.replace(tmp, path)
def add(layout, game_dir, dump='', log=print, restart=True):
"""Add the game to Steam (or update the shortcut): the pictures from the player's game, the shortcut in every
account's shortcuts.vdf, Steam closed first and started again. Returns the sentence the launcher shows."""
from . import gameart
from .ui import art
found = find_steam()
if not found:
raise SteamError('Steam is not installed on this PC.')
folder, exe_steam = found
cfgs = accounts(folder)
if not cfgs:
raise SteamError('Steam has no account on this PC yet: sign in to Steam once, then try again.')
game = Path(game_dir) / 'ocarina.exe'
if not game.is_file():
raise SteamError('The game is not built yet.')
try:
pics = gameart.make(layout, game_dir, dump)
except gameart.ArtError as e:
raise SteamError(f'The pictures could not be made: {e}.') from None
script = layout.data / PLAY_SCRIPT
write_atomic(script, PLAY_TEXT.encode('utf-8'))
python = Path(layout.python) / 'pythonw.exe'
if not python.is_file(): # a checkout runs under its own interpreter
import sys
python = Path(sys.executable).with_name('pythonw.exe')
exe, start = f'"{python}"', f'"{layout.root}"'
options = f'"{script}"'
was_running = steam_running()
if was_running:
log('steam: asking Steam to close')
if not close_steam(exe_steam):
raise SteamError('Steam did not close. Close Steam yourself, then select Add to Steam again.')
sid = appid(exe, NAME)
try:
for cfg in cfgs:
grid = cfg / 'grid'
grid.mkdir(parents=True, exist_ok=True)
icon = grid / f'{sid}_icon.png'
for name, file in (('icon', icon.name), ('portrait', f'{sid}p.png'), ('wide', f'{sid}.png'),
('hero', f'{sid}_hero.png'), ('logo', f'{sid}_logo.png')):
write_atomic(grid / file, art.png_bytes(pics[name]))
vdf = cfg / 'shortcuts.vdf'
try:
old = vdf.read_bytes()
except FileNotFoundError:
old = b''
new, got = add_shortcut(old, exe, start, options, str(icon))
if old and not (cfg / 'shortcuts.vdf.nx2navi-backup').exists():
shutil.copyfile(vdf, cfg / 'shortcuts.vdf.nx2navi-backup')
write_atomic(vdf, new)
log(f'steam: shortcut {got} in {vdf}')
finally: # Steam comes back also when a file could not be written
if was_running and restart:
subprocess.Popen([str(exe_steam)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, creationflags=0x00000008, close_fds=True) # detached
if was_running and restart:
return 'Added to Steam.'
return 'Added. It shows up the next time you open Steam.'

View File

@@ -9,7 +9,8 @@ flat cells and the orange choices are canvas items. Screens:
first_run the dump, the install folder, three choices and Begin Installation first_run the dump, the install folder, three choices and Begin Installation
home Play, Updates, the game folder, Saves, Rebuild the Game, Customize Launcher, Settings home Play, Updates, the game folder, Saves, Rebuild the Game, Customize Launcher, Settings
customize the colour scheme, the player's own background picture, animations and sounds customize the colour scheme, the player's own background picture, animations and sounds; Add to Steam
color the Custom scheme's colour picker: a colour square, a hue bar and the hex code
saves Export Save (a zip for a bug report or another player), Import a Save (such a zip), a save folder saves Export Save (a zip for a bug report or another player), Import a Save (such a zip), a save folder
job the steps of an install, update or rebuild, with their progress, and Cancel; after a failure Try Again job the steps of an install, update or rebuild, with their progress, and Cancel; after a failure Try Again
and Copy Report and Copy Report
@@ -24,6 +25,7 @@ rows, a new screen slides in, sparks drift over the backdrop and Navi bobs in th
plays the game's own decide and cancel sounds, read from the player's game, for a choice and for going back. plays the game's own decide and cancel sounds, read from the player's game, for a choice and for going back.
""" """
import argparse import argparse
import colorsys
import math import math
import os import os
import random import random
@@ -35,12 +37,13 @@ import tkinter.font as tkfont
from pathlib import Path from pathlib import Path
from tkinter import filedialog from tkinter import filedialog
from .. import NAME, build, feed, gameini, gamefiles, jobs, saves, versions, winsys from .. import NAME, build, feed, gameini, gamefiles, jobs, saves, steam, versions, winsys
from ..context import Context from ..context import Context
from . import art, picture, sound from . import art, picture, sound
W, H = 1000, 640 W, H = 1000, 640
BAND = (0, 1000, 56) # x0, x1, height: the whole top of the window, which is also its title bar BAND = (0, 1000, 56) # x0, x1, height: the whole top of the window, which is also its title bar
PIC_TOP = 60 # the player's background picture starts under the band and its two lines
TITLE_BUTTONS = (('min', 908, 954), ('close', 954, 1000)) # x ranges on the band TITLE_BUTTONS = (('min', 908, 954), ('close', 954, 1000)) # x ranges on the band
PANEL = (112, 60, 580) # x0, top, x1 PANEL = (112, 60, 580) # x0, top, x1
ROWS = (140, 552, 96) # x0, x1, top ROWS = (140, 552, 96) # x0, x1, top
@@ -50,7 +53,16 @@ DESC = (614, 336) # x, width
P = art.PALETTE # the colour scheme in use: art.set_theme changes it in place P = art.PALETTE # the colour scheme in use: art.set_theme changes it in place
FRAME_MS = 15 # between two steps of the animations; they move by the time that really passed FRAME_MS = 15 # between two steps of the animations; they move by the time that really passed
SPARKS = 22 # the dust drifting over the backdrop SPARKS = 22 # the dust drifting over the backdrop
DEPTH = {'first_run': 0, 'home': 0, 'job': 1, 'saves': 1, 'settings': 1, 'customize': 1, 'uninstall': 2} DEPTH = {'first_run': 0, 'home': 0, 'job': 1, 'saves': 1, 'settings': 1, 'customize': 1, 'uninstall': 2,
'color': 2}
# the Custom scheme's picker (draw_picker), logical pixels: its box (x, top, width, height), the colour square and
# the hue bar (x0, y0, x1, y1)
PICKER_BOX = (614, 100, 336, 452)
SQUARE = (667, 160, 897, 390)
BAR = (667, 408, 897, 430)
CUSTOM_LABELS = {'background': 'Background Color', 'panel': 'Panel Color', 'buttons': 'Button Color'}
CUSTOM_DESC = {'background': 'The color behind the menus.', 'panel': 'The color of the panels and the top bar.',
'buttons': 'The color of the buttons.'}
DIMS = (0, 20, 40, 60, 80) # Background Dimming, in percent DIMS = (0, 20, 40, 60, 80) # Background Dimming, in percent
SOUND_LEVELS = (('off', 'Off'), ('low', 'Low'), ('medium', 'Medium'), ('high', 'High')) SOUND_LEVELS = (('off', 'Off'), ('low', 'Low'), ('medium', 'Medium'), ('high', 'High'))
@@ -170,6 +182,12 @@ class App:
self.look_message = '' # why the last background picture was not taken, in Customize Launcher's descriptions self.look_message = '' # why the last background picture was not taken, in Customize Launcher's descriptions
self.save_message = '' # the last import's result, shown in the import rows' descriptions self.save_message = '' # the last import's result, shown in the import rows' descriptions
self.export_message = '' # the last Export Save result, shown in its description self.export_message = '' # the last Export Save result, shown in its description
self.steam_message = '' # the last Add to Steam result, shown in its description
self.steam_busy = False # Add to Steam is making the pictures or writing Steam's files
self.pick = None # the colour picker: {'slot', 'h', 's', 'v'} (HSV in 0..1) of the colour being picked
self.pick_drag = None # 'square' or 'bar' while the mouse drags on the picker
self.hex_entry = None # the box the hex code is typed into
self.look_after = None # the redraw a picked colour waits for (look_soon)
self.dumps = None self.dumps = None
self.dump_search = None self.dump_search = None
self.uninstall_game = False self.uninstall_game = False
@@ -182,7 +200,7 @@ class App:
self.ico = None self.ico = None
# the look: the colour scheme, the player's background picture at the window's size (None: the scheme's own # the look: the colour scheme, the player's background picture at the window's size (None: the scheme's own
# backdrop), the sounds (none while the selftest draws the screens) # backdrop), the sounds (none while the selftest draws the screens)
art.set_theme(self.settings.get('theme')) art.set_theme(self.settings.get('theme'), self.custom_colors())
self.bg_store = self.layout.data / 'background.npy' self.bg_store = self.layout.data / 'background.npy'
self.picture = None self.picture = None
self.sounds = sound.Sounds(self.layout.cache, 'off' if args.selftest else self.settings.get('sounds'), ctx.log) self.sounds = sound.Sounds(self.layout.cache, 'off' if args.selftest else self.settings.get('sounds'), ctx.log)
@@ -349,10 +367,19 @@ class App:
return bool(self.settings.get('animations')) and not self.args.selftest return bool(self.settings.get('animations')) and not self.args.selftest
def load_picture(self): def load_picture(self):
"""The player's background at the window's size, when one is set and its kept copy is readable.""" """The player's background at the size of the window below the title band, when one is set and its kept copy
is readable. A copy an older launcher kept for the whole window is made again from the picture when the file
is still there, so no more of it is cut off than the new shape needs."""
self.picture = None self.picture = None
if self.settings.get('background'): src = self.settings.get('background')
self.picture = picture.kept(self.bg_store, self.X(W), self.X(H)) if src:
if picture.kept_shape(self.bg_store) not in (None, (picture.KEEP_H, picture.KEEP_W)) \
and Path(src).is_file():
try:
picture.keep(src, self.bg_store, self.root)
except (picture.PictureError, OSError, MemoryError, ValueError) as e:
self.ctx.log(f'background: {src}: {e!r}; the copy kept before stays')
self.picture = picture.kept(self.bg_store, self.X(W), self.X(H) - self.X(PIC_TOP))
if self.picture is None: if self.picture is None:
self.ctx.log(f'background: {self.bg_store} is missing or unreadable; the colour scheme\'s backdrop') self.ctx.log(f'background: {self.bg_store} is missing or unreadable; the colour scheme\'s backdrop')
@@ -365,7 +392,8 @@ class App:
c.delete('static') c.delete('static')
dim = max(0, min(100, self.settings.get('background_dim', 40))) / 100.0 dim = max(0, min(100, self.settings.get('background_dim', 40))) / 100.0
c.create_image(0, 0, anchor='nw', tags='static', c.create_image(0, 0, anchor='nw', tags='static',
image=self.sprite('backdrop', lambda: art.backdrop(self.X(W), self.X(H), s, self.picture, dim))) image=self.sprite('backdrop', lambda: art.backdrop(self.X(W), self.X(H), s, self.picture, dim,
self.X(PIC_TOP))))
self.make_sparks() # over the backdrop, under the panel and the band self.make_sparks() # over the backdrop, under the panel and the band
bx0, bx1, bh = BAND bx0, bx1, bh = BAND
px0, ptop, px1 = PANEL px0, ptop, px1 = PANEL
@@ -416,7 +444,7 @@ class App:
def apply_look(self): def apply_look(self):
"""Draw everything again after the colour scheme, the background or Animations changed.""" """Draw everything again after the colour scheme, the background or Animations changed."""
art.set_theme(self.settings.get('theme')) art.set_theme(self.settings.get('theme'), self.custom_colors())
self.sprites.clear() self.sprites.clear()
self.root.configure(background=P['window']) self.root.configure(background=P['window'])
self.canvas.configure(background=P['window']) self.canvas.configure(background=P['window'])
@@ -458,7 +486,7 @@ class App:
self.canvas.bind('<Motion>', self.on_motion) self.canvas.bind('<Motion>', self.on_motion)
self.canvas.bind('<Button-1>', self.on_click) self.canvas.bind('<Button-1>', self.on_click)
self.canvas.bind('<B1-Motion>', self.on_drag) self.canvas.bind('<B1-Motion>', self.on_drag)
self.canvas.bind('<ButtonRelease-1>', lambda e: setattr(self, 'drag', None)) self.canvas.bind('<ButtonRelease-1>', self.on_release)
self.canvas.bind('<Leave>', lambda e: self.set_tb_hover(None)) self.canvas.bind('<Leave>', lambda e: self.set_tb_hover(None))
r.bind('<Alt-F4>', lambda e: self.on_close()) r.bind('<Alt-F4>', lambda e: self.on_close())
r.protocol('WM_DELETE_WINDOW', self.on_close) r.protocol('WM_DELETE_WINDOW', self.on_close)
@@ -529,9 +557,11 @@ class App:
return next((i for i, r in enumerate(self.rows_home()) if r.label == label), None) return next((i for i, r in enumerate(self.rows_home()) if r.label == label), None)
def back(self): def back(self):
if self.screen in ('settings', 'uninstall', 'saves', 'customize', 'job'): if self.screen in ('settings', 'uninstall', 'saves', 'customize', 'job', 'color'):
self.sounds.play('back') self.sounds.play('back')
if self.screen == 'settings': if self.screen == 'color':
self.pick_done()
elif self.screen == 'settings':
self.show('home', self.home_row('Settings')) self.show('home', self.home_row('Settings'))
elif self.screen == 'uninstall': elif self.screen == 'uninstall':
self.show('settings') self.show('settings')
@@ -558,6 +588,9 @@ class App:
self.draw_title_buttons() self.draw_title_buttons()
def on_drag(self, e): def on_drag(self, e):
if self.pick_drag:
self.picker_at(e.x, e.y, self.pick_drag)
return
if self.drag: # moving the window without the system's help (Linux) if self.drag: # moving the window without the system's help (Linux)
dx, dy = self.drag dx, dy = self.drag
self.root.geometry(f'+{e.x_root - dx}+{e.y_root - dy}') self.root.geometry(f'+{e.x_root - dx}+{e.y_root - dy}')
@@ -595,6 +628,11 @@ class App:
if not winsys.start_drag(self.root): if not winsys.start_drag(self.root):
self.drag = (e.x_root - self.root.winfo_x(), e.y_root - self.root.winfo_y()) self.drag = (e.x_root - self.root.winfo_x(), e.y_root - self.root.winfo_y())
return return
if self.screen == 'color':
part = self.picker_at(e.x, e.y)
if part:
self.pick_drag = part
return
i = self.hit(e.x, e.y) i = self.hit(e.x, e.y)
if i is None: if i is None:
return return
@@ -620,6 +658,12 @@ class App:
else: else:
self.activate() self.activate()
def on_release(self, e):
self.drag = None
if self.pick_drag:
self.pick_drag = None
self.pick_changed(final=True)
def on_close(self): def on_close(self):
if self.job and self.job.result is None: if self.job and self.job.result is None:
self.job.cancel() self.job.cancel()
@@ -669,6 +713,7 @@ class App:
# another screen slides into place: from the right when it lies deeper, from the left on the way back # another screen slides into place: from the right when it lies deeper, from the left on the way back
deeper = DEPTH.get(screen, 1) >= DEPTH.get(self.screen, 0) deeper = DEPTH.get(screen, 1) >= DEPTH.get(self.screen, 0)
self.slide = float(self.X(44) if deeper else -self.X(44)) self.slide = float(self.X(44) if deeper else -self.X(44))
self.close_hex()
self.screen = screen self.screen = screen
self.rows = getattr(self, 'rows_' + screen)() self.rows = getattr(self, 'rows_' + screen)()
idx = self.focusables() idx = self.focusables()
@@ -899,6 +944,10 @@ class App:
def scheme(d): def scheme(d):
self.settings['theme'] = names[(names.index(art.theme) + d) % len(names)] self.settings['theme'] = names[(names.index(art.theme) + d) % len(names)]
self.settings.save() self.settings.save()
# the rows again: Background Color and Button Color are there only while the scheme is Custom; the
# cursor stays on Color Scheme, the first row
art.set_theme(self.settings['theme'], self.custom_colors())
self.rows = self.rows_customize()
self.apply_look() self.apply_look()
def dim(d): def dim(d):
@@ -930,7 +979,13 @@ class App:
rows = [ rows = [
Row('enum', 'Color Scheme', get=lambda: art.THEMES[art.theme]['label'], Row('enum', 'Color Scheme', get=lambda: art.THEMES[art.theme]['label'],
left=lambda: scheme(-1), right=lambda: scheme(1), left=lambda: scheme(-1), right=lambda: scheme(1),
desc=('The launcher\'s colours.',)), desc=('The launcher\'s colours. Custom lets you pick your own.',)),
]
if art.theme == 'custom':
rows += [Row('value', CUSTOM_LABELS[slot], art.CUSTOM[slot], 'swatch',
on=lambda sl=slot: self.open_picker(sl), desc=(CUSTOM_DESC[slot],))
for slot in art.CUSTOM_SLOTS]
rows += [
Row('value', 'Background', Path(self.settings['background']).name if custom else 'Choose a Picture', Row('value', 'Background', Path(self.settings['background']).name if custom else 'Choose a Picture',
'arrow', on=self.choose_background, desc=bg_desc), 'arrow', on=self.choose_background, desc=bg_desc),
] ]
@@ -951,11 +1006,271 @@ class App:
left=lambda: sounds(-1), right=lambda: sounds(1), left=lambda: sounds(-1), right=lambda: sounds(1),
desc=('The game\'s select and back sounds. Low by default.',)), desc=('The game\'s select and back sounds. Low by default.',)),
Row('divider'), Row('divider'),
]
if os.name == 'nt':
rows += [self.steam_row(), Row('divider')]
rows += [
Row('action', 'Back', on=lambda: self.show('home', self.home_row('Customize Launcher')), height=40, Row('action', 'Back', on=lambda: self.show('home', self.home_row('Customize Launcher')), height=40,
desc=('Back to the main menu.',)), desc=('Back to the main menu.',)),
] ]
return rows return rows
# ---- the Custom scheme's colour picker
def custom_colors(self):
return {slot: self.settings.get('custom_' + slot, '') for slot in art.CUSTOM_SLOTS}
def open_picker(self, slot):
h = art.CUSTOM.get(slot) or art.CUSTOM_DEFAULT[slot]
hh, ss, vv = colorsys.rgb_to_hsv(*(int(h[i:i + 2], 16) / 255.0 for i in (1, 3, 5)))
self.pick = {'slot': slot, 'h': hh, 's': ss, 'v': vv}
self.show('color', 0)
def pick_hex(self):
p = self.pick
return art.hexcode(*colorsys.hsv_to_rgb(p['h'], p['s'], p['v']))
def pick_step(self, key, d):
"""Hue by 5 degrees along the hue bar, saturation and brightness by 5 % (the arrows and the gamepad)."""
p = self.pick
if key == 'h':
p['h'] = (round(p['h'] * 72) + d) % 72 / 72.0
else:
p[key] = max(0.0, min(1.0, (round(p[key] * 20) + d) / 20.0))
self.pick_changed(final=True)
def pick_changed(self, final):
"""The picked colour into the settings and onto the screen: the picker at once, the launcher's colours a
moment later (look_soon), so dragging over the square stays smooth. final: saved to launcher.json."""
if not self.pick:
return
self.settings['custom_' + self.pick['slot']] = self.pick_hex()
if final:
self.settings.save()
if self.screen == 'color':
self.rows = self.rows_color()
self.render()
self.look_soon(0 if final else 120)
def look_soon(self, ms):
if self.look_after:
self.root.after_cancel(self.look_after)
self.look_after = self.root.after(ms, self.look_now)
def look_now(self):
self.look_after = None
self.apply_look()
def pick_reset(self):
slot = self.pick['slot']
self.settings['custom_' + slot] = ''
self.settings.save()
art.CUSTOM[slot] = art.CUSTOM_DEFAULT[slot]
self.open_picker(slot)
self.focus = next(i for i, r in enumerate(self.rows) if r.label == 'Reset')
self.apply_look()
def pick_done(self):
slot = self.pick['slot'] if self.pick else 'background'
if self.look_after:
self.root.after_cancel(self.look_after)
self.look_after = None
self.apply_look()
rows = self.rows_customize()
self.show('customize', next((i for i, r in enumerate(rows) if r.label == CUSTOM_LABELS[slot]), 0))
def rows_color(self):
p = self.pick
return [
Row('enum', 'Hue', get=lambda: f'{round(p["h"] * 360) % 360}°',
left=lambda: self.pick_step('h', -1), right=lambda: self.pick_step('h', 1)),
Row('enum', 'Saturation', get=lambda: f'{round(p["s"] * 100)} %',
left=lambda: self.pick_step('s', -1), right=lambda: self.pick_step('s', 1)),
Row('enum', 'Brightness', get=lambda: f'{round(p["v"] * 100)} %',
left=lambda: self.pick_step('v', -1), right=lambda: self.pick_step('v', 1)),
Row('value', 'Hex Code', self.pick_hex().upper(), 'arrow', on=self.type_hex),
Row('divider'),
Row('value', 'Reset', '', 'arrow', on=self.pick_reset),
Row('divider'),
Row('action', 'Done', on=self.pick_done, height=40),
]
def picker_at(self, x, y, part=None):
"""The colour under the mouse at (x, y) on the square or the bar into the picker; which of the two it was
(part: the one being dragged, which takes the mouse also outside it), or None."""
X, p = self.X, self.pick
def inside(box, m=0):
x0, y0, x1, y1 = box
return X(x0) - X(m) <= x <= X(x1) + X(m) and X(y0) - X(m) <= y <= X(y1) + X(m)
def frac(v, a, b):
return max(0.0, min(1.0, (v - X(a)) / max(1, X(b) - X(a))))
sx0, sy0, sx1, sy1 = SQUARE
bx0, _, bx1, _ = BAR
if part == 'square' or (part is None and inside(SQUARE, 4)):
p['s'] = frac(x, sx0, sx1)
p['v'] = 1 - frac(y, sy0, sy1)
part = 'square'
elif part == 'bar' or (part is None and inside(BAR, 8)):
p['h'] = min(frac(x, bx0, bx1), 0.9999)
part = 'bar'
else:
return None
self.pick_changed(final=False)
return part
def type_hex(self):
"""A box over the Hex Code row to type a colour into, like #3A7BD5; Enter takes it, Esc leaves it."""
r = self.focused()
if self.hex_entry or not r or not r.value_rect:
return
x0, y0, x1, y1 = r.value_rect
X = self.X
e = tk.Entry(self.canvas, font=self.f['label'], bg=P['value'], fg=P['value_text'],
insertbackground=P['value_text'], selectbackground=P['orange'], selectforeground=P['on_text'],
relief='flat', justify='center', highlightthickness=1, highlightcolor=P['orange'],
highlightbackground=P['value_border'])
e.insert(0, self.pick_hex().upper())
e.select_range(0, 'end')
self.hex_entry = e
self.canvas.create_window(x0 + X(3), y0 + X(3), anchor='nw', window=e, width=x1 - x0 - X(6),
height=y1 - y0 - X(6), tags='hexentry')
e.focus_set()
def take(ev):
self.hex_typed(e.get())
return 'break'
def leave(ev):
self.close_hex()
return 'break'
for key in ('<Return>', '<KP_Enter>'):
e.bind(key, take)
e.bind('<Escape>', leave)
for key in ('<Up>', '<Down>', '<space>'):
e.bind(key, lambda ev: 'break')
e.bind('<FocusOut>', lambda ev: self.close_hex())
@staticmethod
def parse_hex(text):
"""(r, g, b) in 0..255 of a typed hex code (#3A7BD5, 3A7BD5 or #37D), or None."""
t = text.strip().lstrip('#').lower()
if len(t) == 3:
t = ''.join(ch * 2 for ch in t)
return tuple(int(t[i:i + 2], 16) for i in (0, 2, 4)) if art.HEX.match('#' + t) else None
def hex_typed(self, text):
got = self.parse_hex(text)
if got is None:
self.sounds.play('back')
self.hex_entry.select_range(0, 'end')
return
self.sounds.play('select')
hh, ss, vv = colorsys.rgb_to_hsv(*(v / 255.0 for v in got))
self.pick.update(h=hh, s=ss, v=vv)
self.close_hex()
self.pick_changed(final=True)
def close_hex(self):
if self.hex_entry:
e, self.hex_entry = self.hex_entry, None
self.canvas.delete('hexentry')
e.destroy()
try:
self.root.focus_force()
except tk.TclError:
pass
def draw_picker(self):
"""The colour picker in the description box's place: the slot's name, the colour square of the picked hue
with a ring on the picked colour, the hue bar, and the colour itself with its hex code."""
c, X, s, p = self.canvas, self.X, self.s, self.pick
bx, by, bw, bh = PICKER_BOX
key = ('desc', X(bw), X(bh) // 4)
if key not in self.sprites:
img, pad = art.desc_box(X(bw), X(bh), s, self.see_through())
self.sprites[key] = (art.photo(self.root, img), pad)
pic, pad = self.sprites[key]
c.create_image(X(bx) - pad, X(by) - pad, anchor='nw', image=pic, tags='dyn')
self.text(X(bx + 26), X(by + 34), CUSTOM_LABELS[p['slot']], self.f['heading'], P['text_bright'])
sx0, sy0, sx1, sy1 = SQUARE
sw, sh = X(sx1) - X(sx0), X(sy1) - X(sy0)
hue = round(p['h'], 3)
square = self.sprite(('square', sw, sh, hue), lambda: art.color_square(sw, sh, hue))
c.create_rectangle(X(sx0) - 1, X(sy0) - 1, X(sx0) + sw, X(sy0) + sh, outline=P['value_border'], tags='dyn')
c.create_image(X(sx0), X(sy0), anchor='nw', image=square, tags='dyn')
size = X(18)
mark = self.sprite(('mark', size), lambda: art.picker_mark(size, s))
c.create_image(X(sx0) + round(p['s'] * sw), X(sy0) + round((1 - p['v']) * sh), image=mark, tags='dyn')
bx0, by0, bx1, by1 = BAR
bw_, bh_ = X(bx1) - X(bx0), X(by1) - X(by0)
bar = self.sprite(('hues', bw_, bh_), lambda: art.hue_bar(bw_, bh_))
c.create_rectangle(X(bx0) - 1, X(by0) - 1, X(bx0) + bw_, X(by0) + bh_, outline=P['value_border'], tags='dyn')
c.create_image(X(bx0), X(by0), anchor='nw', image=bar, tags='dyn')
c.create_image(X(bx0) + round(p['h'] * bw_), X(by0) + bh_ // 2, image=mark, tags='dyn')
hexc = self.pick_hex()
c.create_rectangle(X(bx0), X(452), X(bx0 + 64), X(500), fill=hexc, outline=P['value_border'], tags='dyn')
self.text(X(bx0 + 80), X(476), hexc.upper(), self.f['label'], P['text_bright'])
self.text(X(bx + 26), X(526), 'Click or drag the square and the bar.', self.f['small'], P['muted'])
def steam_row(self):
"""Add to Steam: the game in the Steam library, started from there without the launcher (launcher/steam.py)."""
found = steam.find_steam()
desc = ('Adds the game to your Steam library with its own icon and artwork, so you can start it from Steam.',
'Steam restarts while it is added.')
if self.steam_message:
desc = (self.steam_message,) + desc
if self.steam_busy:
value, style = 'Adding…', 'dim'
elif not found:
value, style = 'Steam not found', 'dim'
else:
value, style = ('Added' if steam.added(found[0]) else ''), 'arrow'
return Row('value', 'Add to Steam', value, style, on=self.add_to_steam, desc=desc)
def add_to_steam(self):
import threading
if self.steam_busy:
return
gd = self.settings.get('game_dir')
if not steam.find_steam():
self.steam_message = 'Steam is not installed on this PC.'
self.sounds.play('back')
self.show('customize', self.focus)
return
if not gd or not (Path(gd) / 'ocarina.exe').is_file():
self.steam_message = 'The game is not built yet.'
self.sounds.play('back')
self.show('customize', self.focus)
return
self.steam_busy = True
self.steam_message = 'Adding to Steam…'
self.sounds.play('select')
self.show('customize', self.focus)
dump = self.settings.get('dump')
def work():
try:
text, ok = steam.add(self.layout, gd, dump, self.ctx.log), True
except steam.SteamError as e:
text, ok = str(e), False
except Exception as e: # a Steam folder in a state nobody expected: say so instead of dying
import traceback
self.ctx.log('steam: ' + traceback.format_exc())
text, ok = f'Adding to Steam failed: {e}', False
self.ctx.log(f'steam: {text}')
self.root.after(0, lambda: self.steam_done(text, ok))
threading.Thread(target=work, daemon=True).start()
def steam_done(self, text, ok):
self.steam_busy = False
self.steam_message = text
if not ok:
self.sounds.play('back')
if self.screen == 'customize':
self.show('customize', self.focus)
def choose_background(self): def choose_background(self):
start = self.settings.get('background') start = self.settings.get('background')
start = str(Path(start).parent) if start and Path(start).parent.is_dir() else \ start = str(Path(start).parent) if start and Path(start).parent.is_dir() else \
@@ -1662,6 +1977,9 @@ class App:
y += h + self.row_gap y += h + self.row_gap
self.draw_status() self.draw_status()
self.draw_cursor() self.draw_cursor()
if self.screen == 'color' and self.pick:
self.draw_picker()
else:
self.draw_desc() self.draw_desc()
self.slide_applied = int(self.slide) self.slide_applied = int(self.slide)
if self.slide_applied: # drawn in place, then put where the slide has got to (step_slide) if self.slide_applied: # drawn in place, then put where the slide has got to (step_slide)
@@ -1800,6 +2118,16 @@ class App:
self.canvas.create_text(sx, cy, text=r.value, font=vfont, fill=P['on_text'], anchor='w', tags='dyn') self.canvas.create_text(sx, cy, text=r.value, font=vfont, fill=P['on_text'], anchor='w', tags='dyn')
img = self.sprite(('chev', cw, ch, False, 'on'), lambda: art.chevron(cw, ch, P['on_text'])) img = self.sprite(('chev', cw, ch, False, 'on'), lambda: art.chevron(cw, ch, P['on_text']))
c.create_image(sx + label_w + X(10), cy, anchor='w', image=img, tags='dyn') c.create_image(sx + label_w + X(10), cy, anchor='w', image=img, tags='dyn')
elif r.style == 'swatch': # a colour of the Custom scheme: a patch of it and its hex code
cw, ch = X(9), X(12)
img = self.sprite(('chev', cw, ch, False, 'dim'), lambda: art.chevron(cw, ch, P['chevron_dim']))
c.create_image(x1 - X(16), cy, anchor='e', image=img, tags='dyn')
tw = vfont.measure(r.value.upper())
sw = X(26)
sx = (vx0 + x1 - X(16) - cw - X(10)) // 2 - (sw + X(10) + tw) // 2
c.create_rectangle(sx, cy - X(9), sx + sw, cy + X(9), fill=r.value, outline=P['value_border'], tags='dyn')
c.create_text(sx + sw + X(10), cy, text=r.value.upper(), font=vfont, fill=P['value_text'], anchor='w',
tags='dyn')
elif r.style == 'arrow': elif r.style == 'arrow':
cw, ch = X(9), X(12) cw, ch = X(9), X(12)
img = self.sprite(('chev', cw, ch, False, 'dim'), lambda: art.chevron(cw, ch, P['chevron_dim'])) img = self.sprite(('chev', cw, ch, False, 'dim'), lambda: art.chevron(cw, ch, P['chevron_dim']))
@@ -1982,6 +2310,8 @@ def parse_args(argv):
ap.add_argument('--root', help='the launcher folder (tests)') ap.add_argument('--root', help='the launcher folder (tests)')
ap.add_argument('--selftest', action='store_true', help='draw every screen and close') ap.add_argument('--selftest', action='store_true', help='draw every screen and close')
ap.add_argument('--shots', help='with --selftest: save a PNG of each screen into this folder') ap.add_argument('--shots', help='with --selftest: save a PNG of each screen into this folder')
ap.add_argument('--play', action='store_true',
help='start the game without the window and wait for it (the Steam shortcut, launcher/steam.py)')
a, _unknown = ap.parse_known_args(argv) a, _unknown = ap.parse_known_args(argv)
return a return a
@@ -2011,12 +2341,40 @@ def single_instance(layout, wait):
time.sleep(0.25) time.sleep(0.25)
def play_only(ctx):
"""--play, from the Steam shortcut (launcher/steam.py): the game starts from its folder with its console hidden, as
Play starts it, and this process waits until it and the copies its own Restart starts have ended, so Steam shows
the game as running all that time. None when there is no built game: the launcher's window opens instead."""
gd = ctx.settings.get('game_dir')
exe = Path(gd) / 'ocarina.exe' if gd else None
if not exe or not exe.is_file():
return None
if saves.game_running(gd):
ctx.log('play from Steam: the game is already running')
return 0
try:
proc = winsys.start_game(exe)
except OSError as e:
ctx.log(f'play from Steam: {exe}: {e}')
return None
ctx.log(f'play from Steam: {exe}')
time.sleep(2)
while proc.poll() is None or saves.game_running(gd):
time.sleep(1)
ctx.log(f'play from Steam: the game ended (code {proc.returncode})')
return 0
def main(argv=None): def main(argv=None):
a = parse_args(sys.argv[1:] if argv is None else argv) a = parse_args(sys.argv[1:] if argv is None else argv)
winsys.dpi_aware() winsys.dpi_aware()
winsys.app_id() winsys.app_id()
from ..paths import Layout from ..paths import Layout
ctx = Context(Layout(root=a.root) if a.root else None) ctx = Context(Layout(root=a.root) if a.root else None)
if a.play and not a.selftest:
code = play_only(ctx)
if code is not None:
return code
lock = None lock = None
if not a.selftest: if not a.selftest:
lock = single_instance(ctx.layout, 20 if (a.continue_update or a.rolled_back) else 2) lock = single_instance(ctx.layout, 20 if (a.continue_update or a.rolled_back) else 2)

View File

@@ -7,7 +7,9 @@ shape is a picture; flat rectangles and text stay canvas items.
Colours follow the game's options menu (docs/launcher.md, "Look"). Sizes are in logical pixels times the display Colours follow the game's options menu (docs/launcher.md, "Look"). Sizes are in logical pixels times the display
scale s. PALETTE holds the colours of the colour scheme in use: set_theme fills it from THEMES, each scheme the scale s. PALETTE holds the colours of the colour scheme in use: set_theme fills it from THEMES, each scheme the
first one with its woods, accents, backdrop and glow turned to other hues. first one with its woods, accents, backdrop and glow turned to other hues. The Custom scheme takes three colours the
player picks on a colour square (color_square, hue_bar): one for the backdrop, one for the panels and the title band,
one for the buttons.
""" """
import base64 import base64
import colorsys import colorsys
@@ -75,9 +77,28 @@ THEMES = {
'scene': (222, 0.55, 1.0, 0.05), 'glow': (48, 1.0, 1.0, 0.5), 'text': (48, 0.45, 1.02, 0)}, 'scene': (222, 0.55, 1.0, 0.05), 'glow': (48, 1.0, 1.0, 0.5), 'text': (48, 0.45, 1.02, 0)},
'shadow': {'label': 'Shadow', 'wood': (268, 0.55, 0.78, 0), 'accent': (286, 0.75, 1.0, 0), 'shadow': {'label': 'Shadow', 'wood': (268, 0.55, 0.78, 0), 'accent': (286, 0.75, 1.0, 0),
'scene': (272, 0.9, 0.8, 0.2), 'glow': (280, 1.0, 1.0, 0.2), 'text': (270, 0.5, 1.0, 0)}, 'scene': (272, 0.9, 0.8, 0.2), 'glow': (280, 1.0, 1.0, 0.2), 'text': (270, 0.5, 1.0, 0)},
'custom': {'label': 'Custom'},
} }
DEFAULT_THEME = 'forest' DEFAULT_THEME = 'forest'
# The Custom scheme: each colour the player picks takes the place of one colour of the first scheme (ref), and the
# rest of that colour's part of the window follows it, lighter and darker as in the first scheme (follow). Each part:
# (ref, the colours that follow it, the text on it, which turns dark when the picked colour is light). The buttons are
# the rows' label cells, their value cells and the orange choices in them; the panel is the list panel, the
# description box, the dividers and the title band. The colours start as the first scheme's.
CUSTOM_SLOTS = {
'background': ('tint_mid', GROUPS['scene'], ()),
'panel': ('panel', ('panel', 'desc', 'desc_border', 'line', 'dot', 'filigree', 'button_hover', 'wood_0', 'wood_1',
'wood_2', 'wood_3', 'band_line_dark', 'band_line_light', 'band_shadow', 'frame'),
('desc_text', 'muted', 'band_text', 'status', 'log_text')),
'buttons': ('label_mid', ('label_top', 'label_mid', 'label_bottom', 'label_border', 'ring', 'value', 'value_border',
'text_shadow') + GROUPS['accent'],
('text', 'text_bright', 'value_text', 'on_text', 'icon_frame', 'icon_fill', 'chevron_dim')),
}
CUSTOM_DEFAULT = {slot: BASE[ref] for slot, (ref, _, _) in CUSTOM_SLOTS.items()}
CUSTOM = dict(CUSTOM_DEFAULT)
HEX = re.compile(r'^#[0-9a-f]{6}$')
def recolor(hexcolor, hue, sat=1.0, light=1.0, add=0.0): def recolor(hexcolor, hue, sat=1.0, light=1.0, add=0.0):
"""hexcolor turned to hue (degrees; None keeps its own), its saturation times sat plus add, its lightness times """hexcolor turned to hue (degrees; None keeps its own), its saturation times sat plus add, its lightness times
@@ -91,8 +112,61 @@ def recolor(hexcolor, hue, sat=1.0, light=1.0, add=0.0):
return '#%02x%02x%02x' % tuple(int(round(v * 255)) for v in (r, g, b)) return '#%02x%02x%02x' % tuple(int(round(v * 255)) for v in (r, g, b))
def hls(hexcolor):
h = hexcolor.lstrip('#')
return colorsys.rgb_to_hls(*(int(h[i:i + 2], 16) / 255.0 for i in (0, 2, 4)))
def hexcode(r, g, b):
"""#rrggbb of r, g, b in 0..1."""
return '#%02x%02x%02x' % tuple(int(round(max(0.0, min(1.0, v)) * 255)) for v in (r, g, b))
def follow(hexcolor, ref, chosen):
"""hexcolor moved as ref moves to chosen: chosen's hue, and its lightness and saturation shifted the way ref's
shift, so ref becomes chosen exactly and the colours lighter or darker than ref stay so."""
_, l, s = hls(hexcolor)
_, rl, rs = hls(ref)
ch, cl, cs = hls(chosen)
def move(v, r, c):
if c <= r:
return v * c / r if r > 0 else c
return v + (1 - v) * (c - r) / (1 - r) if r < 1 else c
return hexcode(*colorsys.hls_to_rgb(ch, max(0.0, min(1.0, move(l, rl, cl))), max(0.0, min(1.0, move(s, rs, cs)))))
def luminance(hexcolor):
h = hexcolor.lstrip('#')
r, g, b = (int(h[i:i + 2], 16) / 255.0 for i in (0, 2, 4))
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def custom_palette(colors):
"""The Custom scheme's colours from {slot: '#rrggbb'} (CUSTOM_SLOTS); a slot left out or not a colour keeps the
first scheme's. Text on a light button or panel turns dark, so it stays readable, and its shadow light."""
pal = dict(BASE)
for slot, (ref, keys, text) in CUSTOM_SLOTS.items():
c = str((colors or {}).get(slot) or '').lower()
if not HEX.match(c) or c == BASE[ref]: # the first scheme's own colour: its colours as written
continue
for k in keys:
pal[k] = follow(BASE[k], BASE[ref], c)
if text and luminance(c) > 0.5:
h = hls(c)[0] * 360
for k in text:
pal[k] = recolor(BASE[k], h, 0.5, 0.3 if k == 'chevron_dim' else 0.18)
shadow = 'text_shadow' if slot == 'buttons' else 'band_shadow'
pal[shadow] = follow(BASE['label_top'], BASE[ref], c)
if slot == 'buttons' and luminance(pal['orange']) > 0.65: # the choices come out lighter than the cells
pal['on_text'] = recolor(BASE['on_text'], hls(c)[0] * 360, 0.5, 0.18)
return pal
def theme_palette(name): def theme_palette(name):
"""The colours of scheme name (an unknown name: the first scheme's).""" """The colours of scheme name (an unknown name: the first scheme's)."""
if name == 'custom':
return custom_palette(CUSTOM)
t = THEMES.get(name) or THEMES[DEFAULT_THEME] t = THEMES.get(name) or THEMES[DEFAULT_THEME]
pal = dict(BASE) pal = dict(BASE)
for group, keys in GROUPS.items(): for group, keys in GROUPS.items():
@@ -107,9 +181,14 @@ PALETTE = dict(BASE)
theme = DEFAULT_THEME theme = DEFAULT_THEME
def set_theme(name): def set_theme(name, custom=None):
"""Fills PALETTE (in place: the window holds a reference) with scheme name's colours; the name in effect.""" """Fills PALETTE (in place: the window holds a reference) with scheme name's colours; the name in effect.
custom: the Custom scheme's colours, {slot: '#rrggbb'} (CUSTOM_SLOTS)."""
global theme global theme
if custom is not None:
CUSTOM.clear()
CUSTOM.update(CUSTOM_DEFAULT)
CUSTOM.update({k: v.lower() for k, v in custom.items() if k in CUSTOM_SLOTS and HEX.match(str(v).lower())})
theme = name if name in THEMES else DEFAULT_THEME theme = name if name in THEMES else DEFAULT_THEME
PALETTE.clear() PALETTE.clear()
PALETTE.update(theme_palette(theme)) PALETTE.update(theme_palette(theme))
@@ -462,17 +541,19 @@ FILIGREE_PATHS = (
# ---------------------------------------------------------------- the window's pieces # ---------------------------------------------------------------- the window's pieces
def backdrop(W, H, s, picture=None, dim=0.4): def backdrop(W, H, s, picture=None, dim=0.4, top=0):
"""The whole window behind the panels: a dim misty field under a see-through tint of the colour scheme, darker at """The whole window behind the panels: a dim misty field under a see-through tint of the colour scheme, darker at
the sides. picture: the player's own background instead of the field, an H x W x 3 array in 0..1 (the window's the sides. picture: the player's own background instead of the field, an array of H - top rows and W columns in
size), darkened by dim (0 as it is .. 1 the scheme's darkest colour) so the text over it stays readable.""" 0..1 put below the title band (top: where the band ends), darkened by dim (0 as it is .. 1 the scheme's darkest
colour) so the text over it stays readable."""
P = PALETTE P = PALETTE
img = new(H, W, P['window'], 1.0) img = new(H, W, P['window'], 1.0)
pad = int(45 * s) pad = int(45 * s)
vig = kept(('vignette', W, H, s), lambda: 1 - box_blur(np.pad(rect_mask(H, W, 0, 0, W, H), pad, vig = kept(('vignette', W, H, s), lambda: 1 - box_blur(np.pad(rect_mask(H, W, 0, 0, W, H), pad,
constant_values=0), 45 * s)[pad:-pad, pad:-pad]) constant_values=0), 45 * s)[pad:-pad, pad:-pad])
if picture is not None: if picture is not None:
img[..., :3] = picture[:H, :W] part = picture[:H - top, :W]
img[top:top + part.shape[0], :part.shape[1], :3] = part
paint(img, np.ones((H, W), dtype=np.float32), P['tint_edge'], max(0.0, min(1.0, dim))) paint(img, np.ones((H, W), dtype=np.float32), P['tint_edge'], max(0.0, min(1.0, dim)))
paint(img, np.clip(vig * 1.6, 0, 1), P['vignette'], 0.45) paint(img, np.clip(vig * 1.6, 0, 1), P['vignette'], 0.45)
return img return img
@@ -495,6 +576,54 @@ def backdrop(W, H, s, picture=None, dim=0.4):
return img return img
def hsv_rgb(h, s, v):
"""HSV to RGB on arrays (or numbers) in 0..1; an H... x 3 array."""
h, s, v = (np.asarray(a, dtype=np.float32) for a in (h, s, v))
h6 = (h % 1.0) * 6
c = v * s
x = c * (1 - np.abs(h6 % 2 - 1))
z = np.zeros_like(c)
k = np.floor(h6).astype(int) % 6
r = np.choose(k, [c, x, z, z, x, c])
g = np.choose(k, [x, c, c, x, z, z])
b = np.choose(k, [z, z, x, c, c, x])
m = v - c
return np.stack([r + m, g + m, b + m], axis=-1)
def color_square(w, h, hue):
"""The colour square of the Custom scheme's picker for one hue (0..1): saturation from grey on the left to the
full colour on the right, brightness from black at the bottom to full at the top."""
sat = (np.arange(w, dtype=np.float32) + 0.5) / w
val = 1 - (np.arange(h, dtype=np.float32) + 0.5) / h
img = new(h, w)
img[..., :3] = hsv_rgb(np.full((h, w), hue), np.broadcast_to(sat, (h, w)), np.broadcast_to(val[:, None], (h, w)))
img[..., 3] = 1
return img
def hue_bar(w, h):
"""The picker's hue bar: every hue from red on the left through yellow, green, cyan, blue and magenta to red."""
hue = (np.arange(w, dtype=np.float32) + 0.5) / w
img = new(h, w)
img[..., :3] = hsv_rgb(np.broadcast_to(hue, (h, w)), np.ones((h, w)), np.ones((h, w)))
img[..., 3] = 1
return img
def picker_mark(size, s):
"""The ring that shows the picked colour on the square and the bar: white with a dark edge inside and out."""
t = (np.arange(size, dtype=np.float32) + 0.5) - size / 2
d = np.hypot(t[None, :], t[:, None])
r = size / 2 - 1.5 * s
img = new(size, size, '#000000')
dark = np.clip(1.6 * s - np.abs(d - r) + 0.5, 0, 1) * 0.7
white = np.clip(0.9 * s - np.abs(d - r) + 0.5, 0, 1)
img[..., 3] = np.maximum(dark, white)
img[..., :3] = np.where(white[..., None] > dark[..., None] * 0.5, 1.0, 0.0)
return img
def spark(size, alpha=1.0): def spark(size, alpha=1.0):
"""One spark of the dust drifting over the backdrop: a soft round dot of the scheme's spark colour, size pixels """One spark of the dust drifting over the backdrop: a soft round dot of the scheme's spark colour, size pixels
across, brightest in its middle.""" across, brightest in its middle."""

View File

@@ -1,11 +1,13 @@
"""The player's own background picture (Customize Launcher): read a picture file into a numpy array, fit it to the """The player's own background picture (Customize Launcher): read a picture file into a numpy array, fit it to the
window's shape and keep that copy in data/background.npy, so the launcher shows it without the file it came from. shape of the window below its title band and keep that copy in data/background.npy, so the launcher shows it without
the file it came from. Fitting cuts the picture to that shape around its middle and scales it evenly: it is never
stretched.
Pillow reads the file where the launcher's Python has it (a release's does: tools/requirements-launcher.txt), turned Pillow reads the file where the launcher's Python has it (a release's does: tools/requirements-launcher.txt), turned
the way its EXIF data says. Without Pillow (a checkout's Python may lack it), GDI+ reads it on Windows (PNG, JPEG, the way its EXIF data says. Without Pillow (a checkout's Python may lack it), GDI+ reads it on Windows (PNG, JPEG,
BMP, GIF, TIFF) and Tk elsewhere (PNG, GIF; the pixels come over as a PPM file). The kept copy is 8-bit RGB at BMP, GIF, TIFF) and Tk elsewhere (PNG, GIF; the pixels come over as a PPM file). The kept copy is 8-bit RGB at
KEEP_W x KEEP_H, 1.6 times the window's logical size: enough for a display scaled to 200 %, and five megabytes on KEEP_W x KEEP_H, 1.6 times the logical size of the window below the band: enough for a display scaled to 200 %,
disk. and four and a half megabytes on disk.
""" """
import ctypes import ctypes
import os import os
@@ -14,7 +16,7 @@ from pathlib import Path
import numpy as np import numpy as np
KEEP_W, KEEP_H = 1600, 1024 # the window's 1000 x 640 times 1.6 KEEP_W, KEEP_H = 1600, 928 # the window's 1000 x 580 below the title band, times 1.6
MAX_SIDE, MAX_PIXELS = 16384, 120_000_000 MAX_SIDE, MAX_PIXELS = 16384, 120_000_000
try: try:
from PIL import Image, ImageOps from PIL import Image, ImageOps
@@ -180,9 +182,9 @@ def resize(img, w, h):
return top * (1 - fy) + bot * fy return top * (1 - fy) + bot * fy
def cover(img, w, h): def cover(img, w, h, as_float=False):
"""img cut to the shape w : h around its middle and resized to w x h, so it fills the window with nothing """img cut to the shape w : h around its middle and resized to w x h, so it fills the room with nothing
stretched; uint8.""" stretched; uint8, or float32 in 0..255 with as_float."""
H, W = img.shape[:2] H, W = img.shape[:2]
if W * h > H * w: # wider than the window: cut the sides if W * h > H * w: # wider than the window: cut the sides
cw = max(1, round(H * w / h)) cw = max(1, round(H * w / h))
@@ -193,6 +195,8 @@ def cover(img, w, h):
y = (H - ch) // 2 y = (H - ch) // 2
img = img[y:y + ch] img = img[y:y + ch]
out = resize(img, w, h) out = resize(img, w, h)
if as_float:
return np.clip(out.astype(np.float32), 0, 255)
return np.clip(np.rint(out), 0, 255).astype(np.uint8) return np.clip(np.rint(out), 0, 255).astype(np.uint8)
@@ -207,12 +211,22 @@ def keep(path, store, master=None):
return fitted return fitted
def kept_shape(store):
"""(height, width) of the kept background, or None."""
try:
a = np.load(store, mmap_mode='r', allow_pickle=False)
return a.shape[:2] if a.ndim == 3 else None
except (OSError, ValueError):
return None
def kept(store, w, h): def kept(store, w, h):
"""The kept background at w x h as float32 in 0..1, or None when there is none (or it is not what keep wrote).""" """The kept background at w x h as float32 in 0..1, cut to that shape when it has another (one kept by an older
launcher for the whole window), or None when there is none (or it is not what keep wrote)."""
try: try:
a = np.load(store, allow_pickle=False) a = np.load(store, allow_pickle=False)
except (OSError, ValueError): except (OSError, ValueError):
return None return None
if a.dtype != np.uint8 or a.ndim != 3 or a.shape[2] != 3 or a.shape[0] < 8 or a.shape[1] < 8: if a.dtype != np.uint8 or a.ndim != 3 or a.shape[2] != 3 or a.shape[0] < 8 or a.shape[1] < 8:
return None return None
return np.clip(resize(a, w, h).astype(np.float32) / 255.0, 0, 1) return cover(a, w, h, as_float=True) / 255.0

View File

@@ -203,6 +203,15 @@ def states(app):
app.show('home', 0) app.show('home', 0)
s['theme'] = was s['theme'] = was
def custom_picker(): # the Custom scheme with two picked colours, and its picker on the button colour
from . import art
was = {k: s.get(k) for k in ('theme', 'custom_background', 'custom_panel', 'custom_buttons')}
s.update(theme='custom', custom_background='#3a1d5c', custom_panel='#24324a', custom_buttons='#2f6fb0')
app.apply_look()
app.open_picker('buttons')
s.update(was)
art.set_theme(was['theme'], app.custom_colors()) # the next screen's colours; this one is drawn already
def restore_scheme(): def restore_scheme():
app.apply_look() app.apply_look()
app.show('home', 0) app.show('home', 0)
@@ -211,7 +220,8 @@ def states(app):
('4-update-ready', update_ready), ('5-updating', updating), ('6-settings', settings), ('4-update-ready', update_ready), ('5-updating', updating), ('6-settings', settings),
('7-build-failed', failed), ('8-uninstall', uninstall), ('9-import-saves', import_saves), ('7-build-failed', failed), ('8-uninstall', uninstall), ('9-import-saves', import_saves),
('10-shaders', shaders), ('11-update-staged', update_staged), ('12-export-save', export_save), ('10-shaders', shaders), ('11-update-staged', update_staged), ('12-export-save', export_save),
('13-customize', customize), ('14-color-scheme', color_scheme), ('15-first-scheme', restore_scheme)] ('13-customize', customize), ('14-color-scheme', color_scheme), ('15-custom-picker', custom_picker),
('16-first-scheme', restore_scheme)]
def run(app, shots): def run(app, shots):

View File

@@ -74,6 +74,13 @@
# recorder_core = auto # recorder_core = auto
# Submissions handed to the GPU queue together in one call, 1 to 16 (1 = each one at once). # Submissions handed to the GPU queue together in one call, 1 to 16 (1 = each one at once).
# submit_batch = 4 # submit_batch = 4
# Occlusion query results are read back from the video card in batches, 0 or 1. Default: on. 0 reads each query with a
# call of its own, as before, which on AMD's Windows driver held every frame's "GPU done" back by about 4 ms.
# oq_batch = 1
# How many milliseconds a submit call waits for the game's own signal that the frame's data is written, when the
# frame's commands begin with a wait for that signal (0 to 100; 0: the frame is set aside at once and drawn at its
# present, as before).
# gate_wait_ms = 10
# Dynamic resolution, 0 or 1, applied at once: with a DLSS upscaling mode, the scene resolution follows the GPU time # Dynamic resolution, 0 or 1, applied at once: with a DLSS upscaling mode, the scene resolution follows the GPU time
# per frame toward dyn_res_target milliseconds (1 to 100), one DLSS step at a time, each held for dyn_res_step frames # per frame toward dyn_res_target milliseconds (1 to 100), one DLSS step at a time, each held for dyn_res_step frames
# (8 to 600), from the DLSS mode set down to performance. Default: off. # (8 to 600), from the DLSS mode set down to performance. Default: off.
@@ -276,6 +283,11 @@
# sparkles), black and white blocks on her and on Link, shadows blown up. Default: on, except on NVIDIA's driver, # sparkles), black and white blocks on her and on Link, shadows blown up. Default: on, except on NVIDIA's driver,
# which keeps them anyway; 1 also asks NVIDIA's driver. The first start after a change compiles the pipelines again. # which keeps them anyway; 1 also asks NVIDIA's driver. The first start after a change compiles the pipelines again.
# vk_nan_preserve = 1 # vk_nan_preserve = 1
# Test for NaN in the game's shaders on the bits of the number instead of as a float, 0 or 1, so that no shader
# compiler can leave a test out. Default: on with AMD's driver for RX 5000 and RX 6000 cards (the one whose shader
# compiler reads "AMD proprietary shader compiler" in the log), where the black and white blocks were reported; off
# elsewhere. The first start after a change compiles the pipelines again.
# vk_nan_bits = 1
[display] [display]
# Device profile: auto (the Steam Deck when this is one), desktop or deck. On a Steam Deck the keys this file does not # Device profile: auto (the Steam Deck when this is one), desktop or deck. On a Steam Deck the keys this file does not
@@ -381,6 +393,17 @@
# to match). They apply only with dlaa = 1 and the DLSS model next to the executable; otherwise the scene follows # to match). They apply only with dlaa = 1 and the DLSS model next to the executable; otherwise the scene follows
# render_scale. Changes while the game runs take effect at once. # render_scale. Changes while the game runs take effect at once.
# dlss = dlaa # dlss = dlaa
# AMD FSR in DLSS's place, on any GPU (Windows): with taa = fsr3 and dlaa = 1 the scene is scaled by AMD FSR 3.1 in the
# mode dlss names (dlaa is FSR's Native AA). The menu's Upscaling row sets all of these. Changes while the game runs
# take effect at once.
# taa = dlss
# AMD FSR 4 in FSR 3.1's place (taa = fsr3, dlaa = 1): the machine-learned upscaler, a sharper and steadier picture
# that costs more GPU time (on an RX 7900 XT at 3440x1440, Quality: 47 fps where FSR 3.1 gives 51) and about 220 MB of
# video memory. It runs where AMD's amd_fidelityfx_loader_vk.dll and amd_fidelityfx_upscaler_vk.dll are next to the
# executable (the setup puts them there) and that library lists FSR 4 for the GPU: Radeon RX 6000, RX 7000 and RX 9000
# cards with AMD's driver 26.10.1 or newer. Elsewhere, or when it fails, FSR 3.1 runs and the log says why. Changes
# while the game runs take effect at once.
# fsr4 = 0
# The DLSS model: default (NVIDIA's advice per mode: K for dlaa, quality and balanced, M for performance, L for # The DLSS model: default (NVIDIA's advice per mode: K for dlaa, quality and balanced, M for performance, L for
# ultra_performance), k (K in every mode) or j (the other transformer model: slightly less ghosting behind moving # ultra_performance), k (K in every mode) or j (the other transformer model: slightly less ghosting behind moving
# characters, a little more flicker). Any other model by its letter, a to m: on slower RTX cards the older model e is # characters, a little more flicker). Any other model by its letter, a to m: on slower RTX cards the older model e is

View File

@@ -47,7 +47,7 @@ static const char *const known[] = {
"HDR_EXPOSURE", "HDR_FLARE", "HDR_GAMMA", "HDR_GAME_NITS", "HDR_GRADE", "HDR_HIGHLIGHT_SAT", "HDR_HIGHLIGHTS", "HDR_HUE", "HDR_EXPOSURE", "HDR_FLARE", "HDR_GAMMA", "HDR_GAME_NITS", "HDR_GRADE", "HDR_HIGHLIGHT_SAT", "HDR_HIGHLIGHTS", "HDR_HUE",
"HDR_LIVE", "HDR_LIVE",
"HDR_PEAK_NITS", "HDR_SATURATION", "HDR_SHADOWS", "HDR_TONEMAP", "HDR_UI_NITS", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD", "HDR_PEAK_NITS", "HDR_SATURATION", "HDR_SHADOWS", "HDR_TONEMAP", "HDR_UI_NITS", "HIGHFPS_FIX", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "LANG", "LIB_PREBUILD",
"BIG_BUILD_FREE_MB", "BIG_BUILD_MAX_MB", "LIB_PREBUILD_BIG", "LIB_PREBUILD_BIG_BG", "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LIB_WARM", "PIPE_LINK_MS", "FRAME_HOLD_MS", "PACE_SMOOTH", "LOCALE", "LOD_GUARD", "LSTICK_DEADZONE", "MEMORY", "MEM_CENSUS", "MENU_LANG", "MENU_SOUND_VOLUME", "MENU_TEST", "BIG_BUILD_FREE_MB", "BIG_BUILD_MAX_MB", "LIB_PREBUILD_BIG", "LIB_PREBUILD_BIG_BG", "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LIB_WARM", "PIPE_LINK_MS", "FRAME_HOLD_MS", "PACE_SMOOTH", "OQ_BATCH", "GATE_WAIT_MS", "LOCALE", "LOD_GUARD", "LSTICK_DEADZONE", "MEMORY", "MEM_CENSUS", "MENU_LANG", "MENU_SOUND_VOLUME", "MENU_TEST",
"MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_CLICK", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MICROPHONE", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MODS_REBUILD", "MONITOR", "MOTION", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_HOST", "MOVIE_PACE", "MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_CLICK", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MICROPHONE", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_ORDER", "MODS_REBUILD", "MONITOR", "MOTION", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "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", "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", "MV_SURVEY",
@@ -62,8 +62,8 @@ static const char *const known[] = {
"SVC_SLOW_MS", "SVC_SLOW_MS",
"SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_IDLE", "SPLIT_IN_PASS", "SPLIT_US", "SPV_MARK_TEST", "SPV_OVERRIDE", "STICK_DEADZONE", "STICK_SENS", "SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_IDLE", "SPLIT_IN_PASS", "SPLIT_US", "SPV_MARK_TEST", "SPV_OVERRIDE", "STICK_DEADZONE", "STICK_SENS",
"SWKBD_ANSWER", "SWKBD_ANSWER",
"SET_AT", "SWKBD_TEST", "TAA", "TEST_PAD", "TEST_PAD_AT", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_DISUSE", "TEX_GEN_UNDO", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TEX_RELEASED_MB", "TEX_REUSE", "TEX_COMMIT_FREE_MB", "TEX_PROC_COMMIT_MB", "TEX_EVICT", "TEX_COMMIT_EVICT", "MIRROR_EVICT", "VRAM_BUDGET_MB", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "EVO_TRACE", "EVENT_AT_SYNC", "UPSCALER", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NAN_PRESERVE", "VK_NOOPT", "VK_NO_FLOAT64", "SET_AT", "SWKBD_TEST", "TAA", "FSR4", "TEST_PAD", "TEST_PAD_AT", "TEST_PREPARE_SHADERS", "TEX_ALIAS", "TEX_DISUSE", "TEX_GEN_UNDO", "TEX_MEMO", "TEX_VRAM_PRESSURE", "TEX_RELEASED_MB", "TEX_REUSE", "TEX_COMMIT_FREE_MB", "TEX_PROC_COMMIT_MB", "TEX_EVICT", "TEX_COMMIT_EVICT", "MIRROR_EVICT", "VRAM_BUDGET_MB", "TIMER_1MS", "TRACE", "TXD_TRANSPOSE", "UBO_SNAPSHOT", "EVO_TRACE", "EVENT_AT_SYNC", "UPSCALER", "VK_DYN_A2C", "VK_DYN_VERTEX", "VK_NAN_PRESERVE", "VK_NOOPT", "VK_NO_FLOAT64",
"VK_PRESENT", "VK_RECONVERGE", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VOLUME", "VRAM_HEADROOM", "VS_OUTS", "VK_PRESENT", "VK_RECONVERGE", "VK_NAN_BITS", "VK_RECORDER", "VK_SSBO_ALIGN", "VK_SUBGROUP", "VK_SUBGROUP_PIN", "VK_VALIDATION", "VOLUME", "VRAM_HEADROOM", "VS_OUTS",
"WALK_KEY", "WALK_SCALE", "WB_EXACT", "WB_FENCE_LIMIT", "WB_MERGE", "WB_NO_REUP", "WB_MERGE_MAX", "WB_PROBE", "WB_SPLIT", "WB_LAZY", "WB_LAZY_TOUCH", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_KEEP", "XLATE_PROCS", "WALK_KEY", "WALK_SCALE", "WB_EXACT", "WB_FENCE_LIMIT", "WB_MERGE", "WB_NO_REUP", "WB_MERGE_MAX", "WB_PROBE", "WB_SPLIT", "WB_LAZY", "WB_LAZY_TOUCH", "WINDOW_SIZE", "XLATE", "XLATE_ID", "XLATE_KEEP", "XLATE_PROCS",
"ZSTD_CHECK", "ZSTD_NATIVE", "ZSTD_CHECK", "ZSTD_NATIVE",
"BIND_REUSE", "DYN_DELTA", "STG_ARENA", "SUBMIT_BATCH", "ASTC_GPU_DESWIZZLE", "ASTC_SCRATCH_KEEP", "ASTC_ARENA", "BIND_REUSE", "DYN_DELTA", "STG_ARENA", "SUBMIT_BATCH", "ASTC_GPU_DESWIZZLE", "ASTC_SCRATCH_KEEP", "ASTC_ARENA",
@@ -88,7 +88,7 @@ static const struct { const char *key, *section; } sections[] = {
{"HDR_HIGHLIGHTS", "display"}, {"HDR_SHADOWS", "display"}, {"HDR_CONTRAST", "display"}, {"HDR_SATURATION", "display"}, {"HDR_HIGHLIGHTS", "display"}, {"HDR_SHADOWS", "display"}, {"HDR_CONTRAST", "display"}, {"HDR_SATURATION", "display"},
{"HDR_HIGHLIGHT_SAT", "display"}, {"HDR_BLOWOUT", "display"}, {"HDR_FLARE", "display"}, {"HDR_HUE", "display"}, {"HDR_HIGHLIGHT_SAT", "display"}, {"HDR_BLOWOUT", "display"}, {"HDR_FLARE", "display"}, {"HDR_HUE", "display"},
{"HDR_GRADE", "display"}, {"SHADOW_RES", "display"}, {"HDR_GRADE", "display"}, {"SHADOW_RES", "display"},
{"DLAA", "display"}, {"DLSS", "display"}, {"DLSS_PRESET", "display"}, {"DLSS_IDLE_FREE", "display"}, {"DLSS_CHAR_MASK", "display"}, {"FXAA", "display"}, {"DLAA", "display"}, {"FSR4", "display"}, {"DLSS", "display"}, {"DLSS_PRESET", "display"}, {"DLSS_IDLE_FREE", "display"}, {"DLSS_CHAR_MASK", "display"}, {"FXAA", "display"},
{"FRAMEGEN", "display"}, {"FRAMEGEN_MULTIPLIER", "display"}, {"FG_MULT", "display"}, {"FRAMEGEN", "display"}, {"FRAMEGEN_MULTIPLIER", "display"}, {"FG_MULT", "display"},
{"DEVICE_PROFILE", "display"}, {"ASSUME_FOCUS", "display"}, {"DEVICE_PROFILE", "display"}, {"ASSUME_FOCUS", "display"},
{"DISCORD_RPC", "discord"}, {"DISCORD_APP_ID", "discord"}, {"DISCORD_IMAGE", "discord"}, {"DISCORD_RPC", "discord"}, {"DISCORD_APP_ID", "discord"}, {"DISCORD_IMAGE", "discord"},
@@ -115,14 +115,14 @@ static const struct { const char *key, *section; } sections[] = {
{"POOL_CREATE_MS", "performance"}, {"POOL_LOAD_BACKLOG", "performance"}, {"POOL_LOAD_MS", "performance"}, {"POOL_CREATE_MS", "performance"}, {"POOL_LOAD_BACKLOG", "performance"}, {"POOL_LOAD_MS", "performance"},
{"TIMER_1MS", "performance"}, {"PIPE_WAIT", "performance"}, {"PIPE_SKIP", "performance"}, {"ONESHOT_BUDGET", "performance"}, {"TIMER_1MS", "performance"}, {"PIPE_WAIT", "performance"}, {"PIPE_SKIP", "performance"}, {"ONESHOT_BUDGET", "performance"},
{"CACHE_DIE", "performance"}, {"ONE_PER_CORE", "performance"}, {"CACHE_DIE", "performance"}, {"ONE_PER_CORE", "performance"},
{"LIB_PREBUILD", "performance"}, {"LIB_PREBUILD_THREADS", "performance"}, {"LIB_WARM", "performance"}, {"PIPE_LINK_MS", "performance"}, {"PIPE_LINK_DRAW_MS", "performance"}, {"PIPE_AHEAD", "performance"}, {"PIPE_FAST_WORKERS", "performance"}, {"GPL_FEEDBACK", "performance"}, {"FRAME_HOLD_MS", "performance"}, {"PACE_SMOOTH", "performance"}, {"PIPE_PREBUILD", "performance"}, {"LIB_PREBUILD", "performance"}, {"LIB_PREBUILD_THREADS", "performance"}, {"LIB_WARM", "performance"}, {"PIPE_LINK_MS", "performance"}, {"PIPE_LINK_DRAW_MS", "performance"}, {"PIPE_AHEAD", "performance"}, {"PIPE_FAST_WORKERS", "performance"}, {"GPL_FEEDBACK", "performance"}, {"FRAME_HOLD_MS", "performance"}, {"PACE_SMOOTH", "performance"}, {"OQ_BATCH", "performance"}, {"GATE_WAIT_MS", "performance"}, {"PIPE_PREBUILD", "performance"},
{"COMPUTE_KEEP", "performance"}, {"COMPUTE_KEEP", "performance"},
{"PREWARM_XLATE", "performance"}, {"GPL", "performance"}, {"ASTC", "performance"}, {"MEMORY", "performance"}, {"PREWARM_XLATE", "performance"}, {"GPL", "performance"}, {"ASTC", "performance"}, {"MEMORY", "performance"},
{"TEX_ALIAS", "performance"}, {"TEX_DISUSE", "performance"}, {"TEX_GEN_UNDO", "performance"}, {"TEX_REUSE", "performance"}, {"TEX_VRAM_PRESSURE", "performance"}, {"TEX_PROC_COMMIT_MB", "performance"}, {"ASTC_BC", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"}, {"TEX_ALIAS", "performance"}, {"TEX_DISUSE", "performance"}, {"TEX_GEN_UNDO", "performance"}, {"TEX_REUSE", "performance"}, {"TEX_VRAM_PRESSURE", "performance"}, {"TEX_PROC_COMMIT_MB", "performance"}, {"ASTC_BC", "performance"}, {"LOD_GUARD", "performance"}, {"FIX_C0", "performance"}, {"FIX_ZERO", "performance"},
{"BIND_SKIP", "performance"}, {"SHADER_CACHE_FLUSH", "performance"}, {"SHADER_CARRY", "performance"}, {"SHADER_MEMO", "performance"}, {"PIPE_MEMO", "performance"}, {"TEX_MEMO", "performance"}, {"DESC_TEMPLATE", "performance"}, {"BIND_SKIP", "performance"}, {"SHADER_CACHE_FLUSH", "performance"}, {"SHADER_CARRY", "performance"}, {"SHADER_MEMO", "performance"}, {"PIPE_MEMO", "performance"}, {"TEX_MEMO", "performance"}, {"DESC_TEMPLATE", "performance"},
{"PUSH_SKIP", "performance"}, {"SPLIT_DRAWS", "performance"}, {"SPLIT_IDLE", "performance"}, {"SPLIT_IN_PASS", "performance"}, {"SPLIT_US", "performance"}, {"VK_VALIDATION", "performance"}, {"PUSH_SKIP", "performance"}, {"SPLIT_DRAWS", "performance"}, {"SPLIT_IDLE", "performance"}, {"SPLIT_IN_PASS", "performance"}, {"SPLIT_US", "performance"}, {"VK_VALIDATION", "performance"},
{"VK_DYN_VERTEX", "performance"}, {"VK_DYN_A2C", "performance"}, {"VK_SUBGROUP_PIN", "performance"}, {"VK_RECONVERGE", "performance"}, {"VK_DYN_VERTEX", "performance"}, {"VK_DYN_A2C", "performance"}, {"VK_SUBGROUP_PIN", "performance"}, {"VK_RECONVERGE", "performance"},
{"VK_NAN_PRESERVE", "performance"}, {"VK_NAN_PRESERVE", "performance"}, {"VK_NAN_BITS", "performance"},
{"TRACE", "diagnostics"}, {"FLIGHT", "diagnostics"}, {"PASS_CRUMBS", "diagnostics"}, {"FLIGHT_SPIKE_MS", "diagnostics"}, {"TRACE", "diagnostics"}, {"FLIGHT", "diagnostics"}, {"PASS_CRUMBS", "diagnostics"}, {"FLIGHT_SPIKE_MS", "diagnostics"},
{"WB_FENCE_LIMIT", "diagnostics"}, {"WB_MERGE", "diagnostics"}, {"WB_EXACT", "diagnostics"}, {"MEM_CENSUS", "diagnostics"}, {"WB_NO_REUP", "diagnostics"}, {"WB_PROBE", "diagnostics"}, {"WB_SPLIT", "performance"}, {"SHADOW_BULK_WRITE", "performance"}, {"WB_LAZY", "performance"}, {"WB_LAZY_TOUCH", "diagnostics"}, {"FLUSH_UPLOAD", "diagnostics"}, {"GPA_TWIN_MAX_KB", "diagnostics"}, {"WB_FENCE_LIMIT", "diagnostics"}, {"WB_MERGE", "diagnostics"}, {"WB_EXACT", "diagnostics"}, {"MEM_CENSUS", "diagnostics"}, {"WB_NO_REUP", "diagnostics"}, {"WB_PROBE", "diagnostics"}, {"WB_SPLIT", "performance"}, {"SHADOW_BULK_WRITE", "performance"}, {"WB_LAZY", "performance"}, {"WB_LAZY_TOUCH", "diagnostics"}, {"FLUSH_UPLOAD", "diagnostics"}, {"GPA_TWIN_MAX_KB", "diagnostics"},
{"WB_MERGE_MAX", "diagnostics"}, {"MV_SURVEY", "diagnostics"}, {"TEXUP_LOG_MS", "diagnostics"}, {"WB_MERGE_MAX", "diagnostics"}, {"MV_SURVEY", "diagnostics"}, {"TEXUP_LOG_MS", "diagnostics"},
@@ -152,6 +152,7 @@ static const CfgMeta metas[] = {
{"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE}, {"UPSCALER", "fsr", "fsr|bilinear", LIVE}, {"SHARPNESS", "80", "0..100", LIVE},
{"DLAA", "0", "0|1", LIVE}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance|ultra_performance", LIVE}, {"DLAA", "0", "0|1", LIVE}, {"DLSS", "dlaa", "dlaa|quality|balanced|performance|ultra_performance", LIVE},
{"DLSS_PRESET", "default", "default|k|j", LIVE}, {"DLSS_IDLE_FREE", "1", "0|1|2", RESTART}, {"TAA", "dlss", "dlss|fsr3", LIVE}, // vk_dlaa.c fsr3 {"DLSS_PRESET", "default", "default|k|j", LIVE}, {"DLSS_IDLE_FREE", "1", "0|1|2", RESTART}, {"TAA", "dlss", "dlss|fsr3", LIVE}, // vk_dlaa.c fsr3
{"FSR4", "0", "0|1", LIVE}, // vk_ffx.cpp vk_ffx_fsr4
{"FRAMEGEN", "off", "off|fsr3|dlss", LIVE}, // vk_fg.cpp, vk_dlssg.c {"FRAMEGEN", "off", "off|fsr3|dlss", LIVE}, // vk_fg.cpp, vk_dlssg.c
{"FRAMEGEN_MULTIPLIER", "2", "2|3|4", LIVE}, // vk_dlssg.c: frames on screen per rendered frame with DLSS {"FRAMEGEN_MULTIPLIER", "2", "2|3|4", LIVE}, // vk_dlssg.c: frames on screen per rendered frame with DLSS
// the same where DLSS's frame generation runs through NGX itself (gfx_present.c ng_multiplier): 2x to 6x or dynamic // the same where DLSS's frame generation runs through NGX itself (gfx_present.c ng_multiplier): 2x to 6x or dynamic
@@ -234,6 +235,8 @@ static const CfgMeta metas[] = {
{"PIPE_FAST_WORKERS", "1", "0|1", RESTART}, // vk_pipeline.c lib_worker, fast_take {"PIPE_FAST_WORKERS", "1", "0|1", RESTART}, // vk_pipeline.c lib_worker, fast_take
{"FRAME_HOLD_MS", "120", "0..500", RESTART}, // vk_backend.c frame_hold {"FRAME_HOLD_MS", "120", "0..500", RESTART}, // vk_backend.c frame_hold
{"PACE_SMOOTH", "1", "0|1", RESTART}, // vk_backend.c pace_smooth {"PACE_SMOOTH", "1", "0|1", RESTART}, // vk_backend.c pace_smooth
{"OQ_BATCH", "1", "0|1", RESTART}, // vk_exec_xfer.c oq_take
{"GATE_WAIT_MS", "10", "0..100", RESTART}, // vk_exec.c vk_exec_gate_wait
{"LIB_PREBUILD", "1", "0|1", RESTART}, {"LIB_PREBUILD_THREADS", "", "1..64", RESTART}, {"LIB_PREBUILD", "1", "0|1", RESTART}, {"LIB_PREBUILD_THREADS", "", "1..64", RESTART},
{"LIB_WARM", "1", "0|1|force", RESTART}, // vk_pipeline.c lw_start: the driver's cache of stage libraries, warmed when cold {"LIB_WARM", "1", "0|1|force", RESTART}, // vk_pipeline.c lw_start: the driver's cache of stage libraries, warmed when cold
{"PIPE_PREBUILD", "1", "0|1", RESTART}, {"PREWARM_XLATE", "", "1..64", RESTART}, {"GPL", "1", "0|1", RESTART}, {"PIPE_PREBUILD", "1", "0|1", RESTART}, {"PREWARM_XLATE", "", "1..64", RESTART}, {"GPL", "1", "0|1", RESTART},
@@ -260,6 +263,7 @@ static const CfgMeta metas[] = {
{"VK_DYN_A2C", "", "0|1", RESTART}, {"VK_SUBGROUP_PIN", "1", "0|1", RESTART}, {"VK_DYN_A2C", "", "0|1", RESTART}, {"VK_SUBGROUP_PIN", "1", "0|1", RESTART},
{"VK_RECONVERGE", "1", "0|1", RESTART}, // vk_pipeline.c spirv_reconverge {"VK_RECONVERGE", "1", "0|1", RESTART}, // vk_pipeline.c spirv_reconverge
{"VK_NAN_PRESERVE", "", "0|1", RESTART}, // vk_pipeline.c spirv_nan_preserve; unset: every driver but NVIDIA's {"VK_NAN_PRESERVE", "", "0|1", RESTART}, // vk_pipeline.c spirv_nan_preserve; unset: every driver but NVIDIA's
{"VK_NAN_BITS", "", "0|1", RESTART}, // vk_pipeline.c spirv_nan_bits; unset: AMD's driver for RDNA 1 and 2
{"VK_NOOPT", "0", "0|1", RESTART}, // vk_pipeline.c noopt_flag {"VK_NOOPT", "0", "0|1", RESTART}, // vk_pipeline.c noopt_flag
// diagnostics // diagnostics
{"TRACE", "", NULL, RESTART}, {"FLIGHT", "0", "0|1", RESTART}, {"FLIGHT_SPIKE_MS", "100", "0..60000", RESTART}, {"TRACE", "", NULL, RESTART}, {"FLIGHT", "0", "0|1", RESTART}, {"FLIGHT_SPIKE_MS", "100", "0..60000", RESTART},

11
runtime/third_party/ffx_sdk/LICENSE.txt vendored Normal file
View File

@@ -0,0 +1,11 @@
AMD FSR SDK 2.4.0 (https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK, tag v2.4.0), the files of
Kits/FidelityFX/api/include and Kits/FidelityFX/upscalers/include kept here at the same relative paths, unmodified.
docs/license.md of that tag lists them among the files under this licence:
Copyright (C) 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.

View File

@@ -0,0 +1,213 @@
// 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
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
#define FFX_API_ENTRY __declspec(dllexport)
#include <stdint.h>
enum FfxApiReturnCodes
{
FFX_API_RETURN_OK = 0, ///< The oparation was successful.
FFX_API_RETURN_ERROR = 1, ///< An error occurred that is not further specified.
FFX_API_RETURN_ERROR_UNKNOWN_DESCTYPE = 2, ///< The structure type given was not recognized for the function or context with which it was used. This is likely a programming error.
FFX_API_RETURN_ERROR_RUNTIME_ERROR = 3, ///< The underlying runtime (e.g. D3D12, Vulkan) or effect returned an error code.
FFX_API_RETURN_NO_PROVIDER = 4, ///< No provider was found for the given structure type. This is likely a programming error.
FFX_API_RETURN_ERROR_MEMORY = 5, ///< A memory allocation failed.
FFX_API_RETURN_ERROR_PARAMETER = 6, ///< A parameter was invalid, e.g. a null pointer, empty resource or out-of-bounds enum value.
FFX_API_RETURN_PROVIDER_NO_SUPPORT_NEW_DESCTYPE = 7, ///< The structure type given is new and not supported in the old provider. This is likely fixed with driver upgrade or effect DLL upgrade.
};
typedef void* ffxContext;
typedef uint32_t ffxReturnCode_t;
#define FFX_API_EFFECT_MASK 0x00ff0000u
#define FFX_API_BACKEND_MASK 0xff000000u
#define FFX_API_EFFECT_ID_GENERAL 0x00000000u
// Base Descriptor types
typedef uint64_t ffxStructType_t;
typedef struct ffxApiHeader
{
ffxStructType_t type; ///< The structure type. Must always be set to the corresponding value for any structure (found nearby with a similar name).
struct ffxApiHeader* pNext; ///< Pointer to next structure, used for optional parameters and extensions. Can be null.
} ffxApiHeader;
typedef ffxApiHeader ffxCreateContextDescHeader;
typedef ffxApiHeader ffxConfigureDescHeader;
typedef ffxApiHeader ffxQueryDescHeader;
typedef ffxApiHeader ffxDispatchDescHeader;
// Extensions for global debug
#define FFX_API_CONFIGURE_GLOBALDEBUG_LEVEL_SILENCE 0x0000000u
#define FFX_API_CONFIGURE_GLOBALDEBUG_LEVEL_ERRORS 0x0000001u
#define FFX_API_CONFIGURE_GLOBALDEBUG_LEVEL_WARNINGS 0x0000002u
#define FFX_API_CONFIGURE_GLOBALDEBUG_LEVEL_VERBOSE 0xfffffffu
enum FfxApiMsgType
{
FFX_API_MESSAGE_TYPE_ERROR = 0,
FFX_API_MESSAGE_TYPE_WARNING = 1,
FFX_API_MESSAGE_TYPE_COUNT
};
typedef void (*ffxApiMessage)(uint32_t type, const wchar_t* message);
#define FFX_API_CONFIGURE_DESC_TYPE_GLOBALDEBUG 7u
struct ffxConfigureDescGlobalDebug
{
ffxConfigureDescHeader header;
uint64_t effectId;
ffxApiMessage fpMessage; ///< A pointer to a function that can receive messages from the runtime. May be null.
uint32_t debugLevel;
};
#define FFX_API_QUERY_DESC_TYPE_GET_VERSIONS 4u
struct ffxQueryDescGetVersions
{
ffxQueryDescHeader header;
uint64_t createDescType; ///< Create description for the effect whose versions should be enumerated.
void* device; ///< For DX12: pointer to ID3D12Device. For VK, pointer to VkDeviceContext.
uint64_t *outputCount; ///< Input capacity of id and name arrays. Output number of returned versions. If initially zero, output is number of available versions.
uint64_t *versionIds; ///< Output array of version ids to be used as version overrides. If null, only names and count are returned.
const char** versionNames; ///< Output array of version names for display. If null, only ids and count are returned. If both this and versionIds are null, only count is returned.
};
#define FFX_API_DESC_TYPE_OVERRIDE_VERSION 5u
struct ffxOverrideVersion
{
ffxApiHeader header;
uint64_t versionId; ///< Id of version to use. Must be a value returned from a query in ffxQueryDescGetVersions.versionIds array.
};
#define FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION 6u
struct ffxQueryGetProviderVersion
{
ffxQueryDescHeader header;
uint64_t versionId; ///< Id of provider being used for queried context. 0 if invalid.
const char* versionName; ///< Version name for display. If nullptr, the query was invalid.
};
// Memory allocation function. Must return a valid pointer to at least size bytes of memory aligned to hold any type.
// May return null to indicate failure. Standard library malloc fulfills this requirement.
typedef void* (*ffxAlloc)(void* pUserData, uint64_t size);
// Memory deallocation function. May be called with null pointer as second argument.
typedef void (*ffxDealloc)(void* pUserData, void* pMem);
typedef struct ffxAllocationCallbacks
{
void* pUserData;
ffxAlloc alloc;
ffxDealloc dealloc;
} ffxAllocationCallbacks;
// Creates a FFX object context.
// Depending on the desc structures provided to this function, the context will be created with the desired version and attributes.
// Non-zero return indicates error code.
// Pointers passed in desc must remain live until ffxDestroyContext is called on the context.
// MemCb may be null; the system allocator (malloc/free) will be used in this case.
FFX_API_ENTRY ffxReturnCode_t ffxCreateContext(ffxContext* context, ffxCreateContextDescHeader* desc, const ffxAllocationCallbacks* memCb);
typedef ffxReturnCode_t (*PfnFfxCreateContext)(ffxContext* context, ffxCreateContextDescHeader* desc, const ffxAllocationCallbacks* memCb);
// Destroys an FFX object context.
// Non-zero return indicates error code.
// MemCb must be compatible with the callbacks passed into ffxCreateContext.
FFX_API_ENTRY ffxReturnCode_t ffxDestroyContext(ffxContext* context, const ffxAllocationCallbacks* memCb);
typedef ffxReturnCode_t (*PfnFfxDestroyContext)(ffxContext* context, const ffxAllocationCallbacks* memCb);
// Configures the provided FFX object context.
// If context is null, configure operates on any global state.
// Non-zero return indicates error code.
FFX_API_ENTRY ffxReturnCode_t ffxConfigure(ffxContext* context, const ffxConfigureDescHeader* desc);
typedef ffxReturnCode_t (*PfnFfxConfigure)(ffxContext* context, const ffxConfigureDescHeader* desc);
// Queries the provided FFX object context.
// If context is null, query operates on any global state.
// Non-zero return indicates error code.
FFX_API_ENTRY ffxReturnCode_t ffxQuery(ffxContext* context, ffxQueryDescHeader* desc);
typedef ffxReturnCode_t (*PfnFfxQuery)(ffxContext* context, ffxQueryDescHeader* desc);
// Dispatches work on the given FFX object context defined by the dispatch descriptor.
// Non-zero return indicates error code.
FFX_API_ENTRY ffxReturnCode_t ffxDispatch(ffxContext* context, const ffxDispatchDescHeader* desc);
typedef ffxReturnCode_t (*PfnFfxDispatch)(ffxContext* context, const ffxDispatchDescHeader* desc);
// FFX_API_EFFECT_IDs
#define FFX_API_EFFECT_ID_UPSCALE 0x00010000u
#define FFX_API_EFFECT_ID_FRAMEGENERATION 0x00020000u
#define FFX_API_EFFECT_ID_FRAMEGENERATIONSWAPCHAIN 0x00030000u
// Need to keep this ID around for the deprecated VK frame gen swapchain
#define FFX_API_EFFECT_ID_FRAMEGENERATIONSWAPCHAIN_VK 0x00040000u
#define FFX_API_EFFECT_ID_DENOISER 0x00050000u
#define FFX_API_EFFECT_ID_RADIANCECACHE 0x00060000u
#define FFX_API_EFFECT_COUNT 6u
#define FFX_API_MAKE_EFFECT_SUB_ID(effectId, subversion) ((effectId & FFX_API_EFFECT_MASK) | (subversion & ~FFX_API_EFFECT_MASK))
// FFX_APID_BACKEND_IDs
#define FFX_API_BACKEND_ID_DX12 0x00000000u
#define FFX_API_BACKEND_ID_VK 0x01000000u // For new effects going forward, please use this backend ID for vulkan specifics
#define FFX_API_BACKEND_ID_XBOX 0x02000000u
#define FFX_API_MAKE_BACKEND_SUB_ID(backendId, subversion) ((backendId & FFX_API_BACKEND_MASK) | (subversion & ~FFX_API_BACKEND_MASK))
// Combiner for BACKEND-specific EFFECT sub-Ids
#define FFX_API_MAKE_BACKEND_EFFECT_SUB_ID(backendId, effectId, subversion) ((subversion & ~FFX_API_EFFECT_MASK) | (effectId & FFX_API_EFFECT_MASK) | (backendId & FFX_API_BACKEND_MASK) | (subversion & ~(FFX_API_BACKEND_MASK | FFX_API_EFFECT_MASK)))
// Pragma macros for controlling warnings so that deprecations take affect externally but can be suppressed internally.
// This is so we can maintain the API/ABI until we are ready to make the breaking change.
// These are sadly compiler specific.
#if defined(_MSC_VER) && !defined(__clang__) && !defined(__GNUC__) && !defined(__INTEL_COMPILER)
#define FFX_PRAGMA_WARNING_PUSH warning( push )
#define FFX_PRAGMA_WARNING_POP warning( pop )
#define FFX_PRAGMA_WARNING_DISABLE_DEPRECATIONS warning( disable: 4996 )
#define FFX_PRAGMA_WARNING_WARN_DEPRECATIONS warning( default: 4996 )
#elif defined(__clang__) || defined(__GNUC__)
#define FFX_PRAGMA_WARNING_PUSH GCC diagnostic push
#define FFX_PRAGMA_WARNING_POP GCC diagnostic pop
#define FFX_PRAGMA_WARNING_DISABLE_DEPRECATIONS GCC diagnostic ignored "-Wdeprecated"
#define FFX_PRAGMA_WARNING_WARN_DEPRECATIONS GCC diagnostic warning "-Wdeprecated"
#else
#define FFX_PRAGMA_WARNING_PUSH
#define FFX_PRAGMA_WARNING_POP
#define FFX_PRAGMA_WARNING_DISABLE_DEPRECATIONS
#endif
#define FFX_DEPRECATION(message) [[deprecated(message)]]
#define FFX_API_CONFIGURE_DESC_TYPE_GLOBALDEBUG1 0x0000001u
struct FFX_DEPRECATION("Use ffxConfigureDescGlobalDebug instead of ffxConfigureDescGlobalDebug1.") ffxConfigureDescGlobalDebug1
{
ffxConfigureDescHeader header;
ffxApiMessage fpMessage;
uint32_t debugLevel;
};
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)

View File

@@ -0,0 +1,257 @@
// 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 <stdint.h>
#include <stdbool.h>
/// An enumeration of surface formats. Needs to match enum FfxApiSurfaceFormat
enum FfxApiSurfaceFormat
{
FFX_API_SURFACE_FORMAT_UNKNOWN, ///< Unknown format
FFX_API_SURFACE_FORMAT_R32G32B32A32_TYPELESS, ///< 32 bit per channel, 4 channel typeless format
FFX_API_SURFACE_FORMAT_R32G32B32A32_UINT, ///< 32 bit per channel, 4 channel uint format
FFX_API_SURFACE_FORMAT_R32G32B32A32_FLOAT, ///< 32 bit per channel, 4 channel float format
FFX_API_SURFACE_FORMAT_R16G16B16A16_FLOAT, ///< 16 bit per channel, 4 channel float format
FFX_API_SURFACE_FORMAT_R32G32B32_FLOAT, ///< 32 bit per channel, 3 channel float format
FFX_API_SURFACE_FORMAT_R32G32_FLOAT, ///< 32 bit per channel, 2 channel float format
FFX_API_SURFACE_FORMAT_R8_UINT, ///< 8 bit per channel, 1 channel float format
FFX_API_SURFACE_FORMAT_R32_UINT, ///< 32 bit per channel, 1 channel float format
FFX_API_SURFACE_FORMAT_R8G8B8A8_TYPELESS, ///< 8 bit per channel, 4 channel typeless format
FFX_API_SURFACE_FORMAT_R8G8B8A8_UNORM, ///< 8 bit per channel, 4 channel unsigned normalized format
FFX_API_SURFACE_FORMAT_R8G8B8A8_SNORM, ///< 8 bit per channel, 4 channel signed normalized format
FFX_API_SURFACE_FORMAT_R8G8B8A8_SRGB, ///< 8 bit per channel, 4 channel srgb normalized
FFX_API_SURFACE_FORMAT_B8G8R8A8_TYPELESS, ///< 8 bit per channel, 4 channel typeless format
FFX_API_SURFACE_FORMAT_B8G8R8A8_UNORM, ///< 8 bit per channel, 4 channel unsigned normalized format
FFX_API_SURFACE_FORMAT_B8G8R8A8_SRGB, ///< 8 bit per channel, 4 channel srgb normalized
FFX_API_SURFACE_FORMAT_R11G11B10_FLOAT, ///< 32 bit 3 channel float format
FFX_API_SURFACE_FORMAT_R10G10B10A2_UNORM, ///< 10 bit per 3 channel, 2 bit for 1 channel normalized format
FFX_API_SURFACE_FORMAT_R16G16_FLOAT, ///< 16 bit per channel, 2 channel float format
FFX_API_SURFACE_FORMAT_R16G16_UINT, ///< 16 bit per channel, 2 channel unsigned int format
FFX_API_SURFACE_FORMAT_R16G16_SINT, ///< 16 bit per channel, 2 channel signed int format
FFX_API_SURFACE_FORMAT_R16_FLOAT, ///< 16 bit per channel, 1 channel float format
FFX_API_SURFACE_FORMAT_R16_UINT, ///< 16 bit per channel, 1 channel unsigned int format
FFX_API_SURFACE_FORMAT_R16_UNORM, ///< 16 bit per channel, 1 channel unsigned normalized format
FFX_API_SURFACE_FORMAT_R16_SNORM, ///< 16 bit per channel, 1 channel signed normalized format
FFX_API_SURFACE_FORMAT_R8_UNORM, ///< 8 bit per channel, 1 channel unsigned normalized format
FFX_API_SURFACE_FORMAT_R8G8_UNORM, ///< 8 bit per channel, 2 channel unsigned normalized format
FFX_API_SURFACE_FORMAT_R8G8_UINT, ///< 8 bit per channel, 2 channel unsigned integer format
FFX_API_SURFACE_FORMAT_R32_FLOAT, ///< 32 bit per channel, 1 channel float format
FFX_API_SURFACE_FORMAT_R9G9B9E5_SHAREDEXP, ///< 9 bit per channel, 5 bit exponent format
FFX_API_SURFACE_FORMAT_R16G16B16A16_TYPELESS, ///< 16 bit per channel, 4 channel typeless format
FFX_API_SURFACE_FORMAT_R32G32_TYPELESS, ///< 32 bit per channel, 2 channel typeless format
FFX_API_SURFACE_FORMAT_R10G10B10A2_TYPELESS, ///< 10 bit per 3 channel, 2 bit for 1 channel typeless format
FFX_API_SURFACE_FORMAT_R16G16_TYPELESS, ///< 16 bit per channel, 2 channel typless format
FFX_API_SURFACE_FORMAT_R16_TYPELESS, ///< 16 bit per channel, 1 channel typeless format
FFX_API_SURFACE_FORMAT_R8_TYPELESS, ///< 8 bit per channel, 1 channel typeless format
FFX_API_SURFACE_FORMAT_R8G8_TYPELESS, ///< 8 bit per channel, 2 channel typeless format
FFX_API_SURFACE_FORMAT_R32_TYPELESS, ///< 32 bit per channel, 1 channel typeless format
FFX_API_SURFACE_FORMAT_R32G32_UINT, ///< 32 bit per channel, 2 channel uint format
FFX_API_SURFACE_FORMAT_R8_SNORM, ///< 8 bit per channel, 1 channel signed normalized format
};
/// An enumeration of resource usage.
enum FfxApiResourceUsage
{
FFX_API_RESOURCE_USAGE_READ_ONLY = 0, ///< No usage flags indicate a resource is read only.
FFX_API_RESOURCE_USAGE_RENDERTARGET = (1<<0), ///< Indicates a resource will be used as render target.
FFX_API_RESOURCE_USAGE_UAV = (1<<1), ///< Indicates a resource will be used as UAV.
FFX_API_RESOURCE_USAGE_DEPTHTARGET = (1<<2), ///< Indicates a resource will be used as depth target.
FFX_API_RESOURCE_USAGE_INDIRECT = (1<<3), ///< Indicates a resource will be used as indirect argument buffer
FFX_API_RESOURCE_USAGE_ARRAYVIEW = (1<<4), ///< Indicates a resource that will generate array views. Works on 2D and cubemap textures
FFX_API_RESOURCE_USAGE_STENCILTARGET = (1<<5), ///< Indicates a resource will be used as stencil target.
FFX_API_RESOURCE_USAGE_DCC_RENDERTARGET = (1<<15), ///< Indicates a resource that should specify optimal render target memory access flags (for console use)
};
/// An enumeration of resource states.
enum FfxApiResourceState
{
FFX_API_RESOURCE_STATE_COMMON = (1 << 0),
FFX_API_RESOURCE_STATE_UNORDERED_ACCESS = (1 << 1), ///< Indicates a resource is in the state to be used as UAV.
FFX_API_RESOURCE_STATE_COMPUTE_READ = (1 << 2), ///< Indicates a resource is in the state to be read by compute shaders.
FFX_API_RESOURCE_STATE_PIXEL_READ = (1 << 3), ///< Indicates a resource is in the state to be read by pixel shaders.
FFX_API_RESOURCE_STATE_PIXEL_COMPUTE_READ = (FFX_API_RESOURCE_STATE_PIXEL_READ | FFX_API_RESOURCE_STATE_COMPUTE_READ), ///< Indicates a resource is in the state to be read by pixel or compute shaders.
FFX_API_RESOURCE_STATE_COPY_SRC = (1 << 4), ///< Indicates a resource is in the state to be used as source in a copy command.
FFX_API_RESOURCE_STATE_COPY_DEST = (1 << 5), ///< Indicates a resource is in the state to be used as destination in a copy command.
FFX_API_RESOURCE_STATE_GENERIC_READ = (FFX_API_RESOURCE_STATE_COPY_SRC | FFX_API_RESOURCE_STATE_COMPUTE_READ), ///< Indicates a resource is in generic (slow) read state.
FFX_API_RESOURCE_STATE_INDIRECT_ARGUMENT = (1 << 6), ///< Indicates a resource is in the state to be used as an indirect command argument
FFX_API_RESOURCE_STATE_PRESENT = (1 << 7), ///< Indicates a resource is in the state to be used to present to the swap chain
FFX_API_RESOURCE_STATE_RENDER_TARGET = (1 << 8), ///< Indicates a resource is in the state to be used as render target
FFX_API_RESOURCE_STATE_DEPTH_ATTACHMENT = (1 << 9), ///< Indicates a resource is in the state to be used as depth attachment
};
/// An enumeration of surface dimensions.
enum FfxApiResourceDimension
{
FFX_API_RESOURCE_DIMENSION_TEXTURE_1D, ///< A resource with a single dimension.
FFX_API_RESOURCE_DIMENSION_TEXTURE_2D, ///< A resource with two dimensions.
};
/// An enumeration of resource flags.
enum FfxApiResourceFlags
{
FFX_API_RESOURCE_FLAGS_NONE = 0, ///< No flags.
FFX_API_RESOURCE_FLAGS_ALIASABLE = (1 << 0), ///< A bit indicating a resource does not need to persist across frames.
FFX_API_RESOURCE_FLAGS_UNDEFINED = (1 << 1), ///< Special case flag used internally when importing resources that require additional setup
};
// An enumeration for different resource types
enum FfxApiResourceType
{
FFX_API_RESOURCE_TYPE_BUFFER, ///< The resource is a buffer.
FFX_API_RESOURCE_TYPE_TEXTURE1D, ///< The resource is a 1-dimensional texture.
FFX_API_RESOURCE_TYPE_TEXTURE2D, ///< The resource is a 2-dimensional texture.
FFX_API_RESOURCE_TYPE_TEXTURE_CUBE, ///< The resource is a cube map.
FFX_API_RESOURCE_TYPE_TEXTURE3D, ///< The resource is a 3-dimensional texture.
};
enum FfxApiBackbufferTransferFunction
{
FFX_API_BACKBUFFER_TRANSFER_FUNCTION_SRGB,
FFX_API_BACKBUFFER_TRANSFER_FUNCTION_PQ,
FFX_API_BACKBUFFER_TRANSFER_FUNCTION_SCRGB
};
/// A structure encapsulating a 2-dimensional point, using 32bit unsigned integers.
struct FfxApiDimensions2D
{
uint32_t width; ///< The width of a 2-dimensional range.
uint32_t height; ///< The height of a 2-dimensional range.
};
/// A structure encapsulating a 2-dimensional set of floating point coordinates.
struct FfxApiFloatCoords2D
{
float x; ///< The x coordinate of a 2-dimensional point.
float y; ///< The y coordinate of a 2-dimensional point.
};
/// A structure encapsulating a 3-dimensional set of floating point coordinates.
struct FfxApiFloatCoords3D
{
float x; ///< The x coordinate of a 3-dimensional point.
float y; ///< The y coordinate of a 3-dimensional point.
float z; ///< The z coordinate of a 3-dimensional point.
};
/// A structure encapsulating a 2-dimensional rect.
struct FfxApiRect2D
{
int32_t left;
int32_t top;
int32_t width;
int32_t height;
};
/// A structure describing a resource.
///
/// @ingroup SDKTypes
struct FfxApiResourceDescription
{
uint32_t type; ///< The type of the resource.
uint32_t format; ///< The surface format.
union {
uint32_t width; ///< The width of the texture resource.
uint32_t size; ///< The size of the buffer resource.
};
union {
uint32_t height; ///< The height of the texture resource.
uint32_t stride; ///< The stride of the buffer resource.
};
union {
uint32_t depth; ///< The depth of the texture resource.
uint32_t alignment; ///< The alignment of the buffer resource.
};
uint32_t mipCount; ///< Number of mips (or 0 for full mipchain).
uint32_t flags; ///< A set of resource flags.
uint32_t usage; ///< Resource usage flags.
};
#define FFX_RESOURCE_NAME_SIZE 64
struct FfxApiResource
{
void* resource;
struct FfxApiResourceDescription description;
uint32_t state;
};
//struct definition matches FfxApiEffectMemoryUsage
typedef struct FfxApiEffectMemoryUsage
{
uint64_t totalUsageInBytes;
uint64_t aliasableUsageInBytes;
} FfxApiEffectMemoryUsage;
/// A structure describing a constant buffer allocation.
///
/// @ingroup SDKTypes
typedef struct FfxApiConstantBufferAllocation
{
struct FfxApiResource resource; ///< The resource representing the constant buffer resource.
uint64_t handle; ///< The binding handle for the constant buffer
} FfxApiConstantBufferAllocation;
/// A function definition for a constant buffer allocation callback
/// Used to provide a constant buffer allocator to the calling backend
///
/// @param [in] data The constant buffer data.
/// @param [in] dataSize The size of the constant buffer data.
///
/// @ingroup SDKTypes
typedef FfxApiConstantBufferAllocation(*FfxApiConstantBufferAllocator)(void* data, const uint64_t dataSize);
/// A 4-component floating point vector
typedef struct FfxApiFloat4
{
float x;
float y;
float z;
float w;
} FfxApiFloat4;
/// A 4x4 matrix in row-major layout with row-vector convention.
/// This is the canonical format expected by FFX APIs.
///
/// Memory layout: rows[row_index][column_index]
/// Mathematical convention: v * M (row vector multiplied by matrix)
typedef struct FfxApiMatrix4x4
{
FfxApiFloat4 rows[4]; ///< Four rows of the matrix. Access as rows[row].x, rows[row].y etc.
} FfxApiMatrix4x4;
/// An inclusive floating-point interval [min, max].
/// Valid instances must satisfy min <= max.
typedef struct FfxApiFloatBounds
{
float min; ///< Lower bound of the interval.
float max; ///< Upper bound of the interval.
} FfxApiFloatBounds;

View File

@@ -0,0 +1,308 @@
// 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 "../ffx_api.h"
#include "../ffx_api_types.h"
#include <vulkan/vulkan.h>
/// FFX specific callback type when submitting a command buffer to a queue.
typedef VkResult(*PFN_vkQueueSubmitFFXAPI)(uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence);
/// Helper stucture
struct VkQueueInfoFFXAPI
{
VkQueue queue; ///< the vulkan queue
uint32_t familyIndex; ///< the queue family index, that will be used to perform queue family ownership transfer
PFN_vkQueueSubmitFFXAPI submitFunc; ///< an optional submit function in case there might be some concurrent submissions
};
// We need to keep this one alive because of VK verison of FSR3.1.4
// Deprecated version of the VK backend create context descriptor, please use the non-deprecated version below.
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK_DEPRECATED 0x0000003u
struct ffxCreateBackendVKDesc_DEPRECATED
{
ffxCreateContextDescHeader header;
VkDevice vkDevice; ///< the logical device used by the program.
VkPhysicalDevice vkPhysicalDevice; ///< the physical device used by the program.
PFN_vkGetDeviceProcAddr vkDeviceProcAddr; ///< function pointer to get device procedure addresses
};
/// Convenience structure to hold all VK-related device information.
typedef struct VkDeviceContext {
VkDevice vkDevice; ///< The Vulkan device
VkPhysicalDevice vkPhysicalDevice; ///< The Vulkan physical device
PFN_vkGetDeviceProcAddr vkDeviceProcAddr; ///< The device's function address table
} 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; ///< the VK device information used by the program.
};
/// Resource allocation callback function. (TODO)
typedef ffxReturnCode_t(*PfnFfxResourceAllocatorFunc)(uint32_t effectId/*,
D3D12_RESOURCE_STATES initialState,
const D3D12_HEAP_PROPERTIES* pHeapProps,
const D3D12_RESOURCE_DESC* pD3DDesc,
const FfxApiResourceDescription* pFfxDesc,
const D3D12_CLEAR_VALUE* pOptimizedClear,
ID3D12Resource** ppD3DResource*/);
/// Resource destruction callback function. (TODO)
typedef ffxReturnCode_t(*PfnFfxResourceDeallocatorFunc)(uint32_t effectId/*, ID3D12Resource* pResource*/);
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK_ALLOCATION_CALLBACKS FFX_API_MAKE_BACKEND_SUB_ID(FFX_API_BACKEND_ID_VK, 0x04)
struct ffxCreateBackendVKAllocationCallbacksDesc
{
ffxCreateContextDescHeader header;
PfnFfxResourceAllocatorFunc pfnFfxResourceAllocator; ///< Resource allocation function (can be null) <------- NOT IMPL YET, SEE DX12/XBOX IMPL
PfnFfxResourceDeallocatorFunc pfnFfxResourceDeallocator; ///< Resource deallocation function (can be null) <------- NOT IMPL YET, SEE DX12/XBOX IMPL
FfxApiConstantBufferAllocator pfnFfxConstantBufferAllocator; ///< Constant buffer allocation function (can be null)
};
#if defined(__cplusplus)
static inline uint32_t ffxApiGetSurfaceFormatVK(VkFormat fmt)
{
switch (fmt)
{
case VK_FORMAT_R32G32B32A32_SFLOAT:
return FFX_API_SURFACE_FORMAT_R32G32B32A32_FLOAT;
case VK_FORMAT_R32G32B32_SFLOAT:
return FFX_API_SURFACE_FORMAT_R32G32B32_FLOAT;
case VK_FORMAT_R32G32B32A32_UINT:
return FFX_API_SURFACE_FORMAT_R32G32B32A32_UINT;
case VK_FORMAT_R16G16B16A16_SFLOAT:
return FFX_API_SURFACE_FORMAT_R16G16B16A16_FLOAT;
case VK_FORMAT_R32G32_SFLOAT:
return FFX_API_SURFACE_FORMAT_R32G32_FLOAT;
case VK_FORMAT_R32_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_X8_D24_UNORM_PACK32:
return FFX_API_SURFACE_FORMAT_R32_UINT;
case VK_FORMAT_R8G8B8A8_UNORM:
return FFX_API_SURFACE_FORMAT_R8G8B8A8_UNORM;
case VK_FORMAT_R8G8B8A8_SNORM:
return FFX_API_SURFACE_FORMAT_R8G8B8A8_SNORM;
case VK_FORMAT_R8G8B8A8_SRGB:
return FFX_API_SURFACE_FORMAT_R8G8B8A8_SRGB;
case VK_FORMAT_B8G8R8A8_UNORM:
return FFX_API_SURFACE_FORMAT_B8G8R8A8_UNORM;
case VK_FORMAT_B8G8R8A8_SRGB:
return FFX_API_SURFACE_FORMAT_B8G8R8A8_SRGB;
case VK_FORMAT_B10G11R11_UFLOAT_PACK32:
return FFX_API_SURFACE_FORMAT_R11G11B10_FLOAT;
case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
return FFX_API_SURFACE_FORMAT_R10G10B10A2_UNORM;
case VK_FORMAT_R16G16_SFLOAT:
return FFX_API_SURFACE_FORMAT_R16G16_FLOAT;
case VK_FORMAT_R16G16_UINT:
return FFX_API_SURFACE_FORMAT_R16G16_UINT;
case VK_FORMAT_R16G16_SINT:
return FFX_API_SURFACE_FORMAT_R16G16_SINT;
case VK_FORMAT_R16_SFLOAT:
return FFX_API_SURFACE_FORMAT_R16_FLOAT;
case VK_FORMAT_R16_UINT:
return FFX_API_SURFACE_FORMAT_R16_UINT;
case VK_FORMAT_R16_UNORM:
case VK_FORMAT_D16_UNORM:
case VK_FORMAT_D16_UNORM_S8_UINT:
return FFX_API_SURFACE_FORMAT_R16_UNORM;
case VK_FORMAT_R16_SNORM:
return FFX_API_SURFACE_FORMAT_R16_SNORM;
case VK_FORMAT_R8_UNORM:
return FFX_API_SURFACE_FORMAT_R8_UNORM;
case VK_FORMAT_R8_SNORM:
return FFX_API_SURFACE_FORMAT_R8_SNORM;
case VK_FORMAT_R8_UINT:
case VK_FORMAT_S8_UINT:
return FFX_API_SURFACE_FORMAT_R8_UINT;
case VK_FORMAT_R8G8_UNORM:
return FFX_API_SURFACE_FORMAT_R8G8_UNORM;
case VK_FORMAT_R8G8_UINT:
return FFX_API_SURFACE_FORMAT_R8G8_UINT;
case VK_FORMAT_R32_SFLOAT:
case VK_FORMAT_D32_SFLOAT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
return FFX_API_SURFACE_FORMAT_R32_FLOAT;
case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32:
return FFX_API_SURFACE_FORMAT_R9G9B9E5_SHAREDEXP;
case VK_FORMAT_UNDEFINED:
return FFX_API_SURFACE_FORMAT_UNKNOWN;
default:
// NOTE: we do not support typeless formats here
//FFX_ASSERT_MESSAGE(false, "Format not yet supported");
return FFX_API_SURFACE_FORMAT_UNKNOWN;
}
}
static inline uint32_t ffxApiGetSurfaceFormatToGamma(uint32_t fmt)
{
switch (fmt)
{
case (FFX_API_SURFACE_FORMAT_R8G8B8A8_UNORM):
return FFX_API_SURFACE_FORMAT_R8G8B8A8_SRGB;
case (FFX_API_SURFACE_FORMAT_B8G8R8A8_UNORM):
return FFX_API_SURFACE_FORMAT_B8G8R8A8_SRGB;
default:
return fmt;
}
}
static inline bool ffxApiIsDepthFormat(VkFormat fmt)
{
switch (fmt)
{
case VK_FORMAT_D16_UNORM:
case VK_FORMAT_X8_D24_UNORM_PACK32:
case VK_FORMAT_D32_SFLOAT:
case VK_FORMAT_D16_UNORM_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
return true;
default:
return false;
}
}
static inline bool ffxApiIsStencilFormat(VkFormat fmt)
{
switch (fmt)
{
case VK_FORMAT_S8_UINT:
case VK_FORMAT_D16_UNORM_S8_UINT:
case VK_FORMAT_D24_UNORM_S8_UINT:
case VK_FORMAT_D32_SFLOAT_S8_UINT:
return true;
default:
return false;
}
}
static inline FfxApiResourceDescription ffxApiGetBufferResourceDescriptionVK(const VkBuffer buffer,
const VkBufferCreateInfo createInfo,
uint32_t additionalUsages)
{
FfxApiResourceDescription resourceDescription = {};
// This is valid
if (buffer == VK_NULL_HANDLE)
return resourceDescription;
resourceDescription.flags = FFX_API_RESOURCE_FLAGS_NONE;
resourceDescription.usage = additionalUsages;
resourceDescription.size = (uint32_t)createInfo.size;
resourceDescription.stride = 0;
resourceDescription.format = FFX_API_SURFACE_FORMAT_UNKNOWN;
if ((createInfo.usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) != 0)
resourceDescription.usage |= FFX_API_RESOURCE_USAGE_UAV;
if ((createInfo.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0)
resourceDescription.usage |= FFX_API_RESOURCE_USAGE_INDIRECT;
// What should we initialize this to?? No case for this yet
resourceDescription.depth = 0;
resourceDescription.mipCount = 0;
// Set the type
resourceDescription.type = FFX_API_RESOURCE_TYPE_BUFFER;
return resourceDescription;
}
static inline FfxApiResourceDescription ffxApiGetImageResourceDescriptionVK(const VkImage image, const VkImageCreateInfo createInfo, uint32_t additionalUsages)
{
FfxApiResourceDescription resourceDescription = {};
// This is valid
if (image == VK_NULL_HANDLE)
return resourceDescription;
// Set flags properly for resource registration
resourceDescription.flags = FFX_API_RESOURCE_FLAGS_NONE;
resourceDescription.usage = FFX_API_RESOURCE_USAGE_READ_ONLY;
// Check for depth stencil use
if (ffxApiIsDepthFormat(createInfo.format))
resourceDescription.usage |= FFX_API_RESOURCE_USAGE_DEPTHTARGET;
if (ffxApiIsStencilFormat(createInfo.format))
resourceDescription.usage |= FFX_API_RESOURCE_USAGE_STENCILTARGET;
// Unordered access use
if ((createInfo.usage & VK_IMAGE_USAGE_STORAGE_BIT) != 0)
resourceDescription.usage |= FFX_API_RESOURCE_USAGE_UAV;
// Resource-specific supplemental use flags
resourceDescription.usage |= additionalUsages;
resourceDescription.width = createInfo.extent.width;
resourceDescription.height = createInfo.extent.height;
resourceDescription.mipCount = createInfo.mipLevels;
resourceDescription.format = ffxApiGetSurfaceFormatVK(createInfo.format);
// if the mutable flag is present, assume that the real format is sRGB
if ((createInfo.flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) != 0)
resourceDescription.format = ffxApiGetSurfaceFormatToGamma(resourceDescription.format);
switch (createInfo.imageType)
{
case VK_IMAGE_TYPE_1D:
resourceDescription.type = FFX_API_RESOURCE_TYPE_TEXTURE1D;
break;
case VK_IMAGE_TYPE_2D:
resourceDescription.depth = createInfo.arrayLayers;
if ((additionalUsages & FFX_API_RESOURCE_USAGE_ARRAYVIEW) != 0)
resourceDescription.type = FFX_API_RESOURCE_TYPE_TEXTURE2D;
else if ((createInfo.flags & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) != 0)
resourceDescription.type = FFX_API_RESOURCE_TYPE_TEXTURE_CUBE;
else
resourceDescription.type = FFX_API_RESOURCE_TYPE_TEXTURE2D;
break;
case VK_IMAGE_TYPE_3D:
resourceDescription.depth = createInfo.extent.depth;
resourceDescription.type = FFX_API_RESOURCE_TYPE_TEXTURE3D;
break;
default:
//FFX_ASSERT_MESSAGE(false, "FFXInterface: VK: Unsupported texture dimension requested. Please implement.");
break;
}
return resourceDescription;
}
static inline FfxApiResource ffxApiGetResourceVK(void* vkResource, FfxApiResourceDescription ffxResDescription, uint32_t state)
{
FfxApiResource resource = {};
resource.resource = vkResource;
resource.state = state;
resource.description = ffxResDescription;
return resource;
}
#endif

View File

@@ -0,0 +1,230 @@
// 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 "../../api/include/ffx_api.h"
#include "../../api/include/ffx_api_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define FFX_UPSCALER_VERSION_MAJOR 4
#define FFX_UPSCALER_VERSION_MINOR 1
#define FFX_UPSCALER_VERSION_PATCH 2
#define FFX_UPSCALER_MAKE_VERSION(major, minor, patch) (((major) << 22) | ((minor) << 12) | (patch))
#define FFX_UPSCALER_VERSION FFX_UPSCALER_MAKE_VERSION(FFX_UPSCALER_VERSION_MAJOR, FFX_UPSCALER_VERSION_MINOR, FFX_UPSCALER_VERSION_PATCH)
enum FfxApiUpscaleQualityMode
{
FFX_UPSCALE_QUALITY_MODE_NATIVEAA = 0, ///< Perform upscaling with a per-dimension upscaling ratio of 1.0x.
FFX_UPSCALE_QUALITY_MODE_QUALITY = 1, ///< Perform upscaling with a per-dimension upscaling ratio of 1.5x.
FFX_UPSCALE_QUALITY_MODE_BALANCED = 2, ///< Perform upscaling with a per-dimension upscaling ratio of 1.7x.
FFX_UPSCALE_QUALITY_MODE_PERFORMANCE = 3, ///< Perform upscaling with a per-dimension upscaling ratio of 2.0x.
FFX_UPSCALE_QUALITY_MODE_ULTRA_PERFORMANCE = 4 ///< Perform upscaling with a per-dimension upscaling ratio of 3.0x.
};
enum FfxApiCreateContextUpscaleFlags
{
FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE = (1 << 0), ///< A bit indicating if the input color data provided is using a high-dynamic range.
FFX_UPSCALE_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS = (1 << 1), ///< A bit indicating if the motion vectors are rendered at display resolution.
FFX_UPSCALE_ENABLE_MOTION_VECTORS_JITTER_CANCELLATION = (1 << 2), ///< A bit indicating that the motion vectors have the jittering pattern applied to them.
FFX_UPSCALE_ENABLE_DEPTH_INVERTED = (1 << 3), ///< A bit indicating that the input depth buffer data provided is inverted [1..0].
FFX_UPSCALE_ENABLE_DEPTH_INFINITE = (1 << 4), ///< A bit indicating that the input depth buffer data provided is using an infinite far plane.
FFX_UPSCALE_ENABLE_AUTO_EXPOSURE = (1 << 5), ///< A bit indicating if automatic exposure should be applied to input color data.
FFX_UPSCALE_ENABLE_DYNAMIC_RESOLUTION = (1 << 6), ///< A bit indicating that the application uses dynamic resolution scaling.
FFX_UPSCALE_ENABLE_DEBUG_CHECKING = (1 << 7), ///< A bit indicating that the runtime should check some API values and report issues.
FFX_UPSCALE_ENABLE_NON_LINEAR_COLORSPACE = (1 << 8), ///< A bit indicating that the color resource contains perceptual (gamma corrected) colors
FFX_UPSCALE_ENABLE_DEBUG_VISUALIZATION = (1 << 9), ///< A bit indicating if debug visualization is allowed. (memory consumption could increase)
};
enum FfxApiDispatchFsrUpscaleFlags
{
FFX_UPSCALE_FLAG_DRAW_DEBUG_VIEW = (1 << 0), ///< A bit indicating that the output resource will contain debug views with relevant information.
FFX_UPSCALE_FLAG_NON_LINEAR_COLOR_SRGB = (1 << 1), ///< A bit indicating that the input color resource contains perceptual sRGB colors
FFX_UPSCALE_FLAG_NON_LINEAR_COLOR_PQ = (1 << 2), ///< A bit indicating that the input color resource contains perceptual PQ colors
};
enum FfxApiDispatchUpscaleAutoreactiveFlags
{
FFX_UPSCALE_AUTOREACTIVEFLAGS_APPLY_TONEMAP = (1 << 0), ///< Apply tonemapping function prior to calculating reactivity.
FFX_UPSCALE_AUTOREACTIVEFLAGS_APPLY_INVERSETONEMAP = (1 << 1), ///< Apply inverse tonemapping function prior to calculating reactivity.
FFX_UPSCALE_AUTOREACTIVEFLAGS_APPLY_THRESHOLD = (1 << 2), ///< Compare to a threshold value and only record reactivity above the threshold.
FFX_UPSCALE_AUTOREACTIVEFLAGS_USE_COMPONENTS_MAX = (1 << 3), ///< When enabled use the max. component value, otherwise use the length to calculate reactivity.
};
#define FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x00)
struct ffxCreateContextDescUpscale
{
ffxCreateContextDescHeader header; ///< Header descriptor, use type FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE.
uint32_t flags; ///< Zero or a combination of values from FfxApiCreateContextUpscaleFlags.
struct FfxApiDimensions2D maxRenderSize; ///< The maximum size that rendering will be performed at.
struct FfxApiDimensions2D maxUpscaleSize; ///< The size of the presentation resolution targeted by the upscaling process.
ffxApiMessage fpMessage; ///< A pointer to a function that can receive messages from the runtime. May be null.
};
#define FFX_API_DISPATCH_DESC_TYPE_UPSCALE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x01)
struct ffxDispatchDescUpscale
{
ffxDispatchDescHeader header; ///< Header descriptor, use type FFX_API_DISPATCH_DESC_TYPE_UPSCALE.
void* commandList; ///< Command list to record upscaling rendering commands into.
struct FfxApiResource color; ///< Color buffer for the current frame (at render resolution).
struct FfxApiResource depth; ///< 32bit depth values for the current frame (at render resolution).
struct FfxApiResource motionVectors; ///< 2-dimensional motion vectors (at render resolution if <c><i>FFX_FSR_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS</i></c> is not set).
struct FfxApiResource exposure; ///< Optional resource containing a 1x1 exposure value.
struct FfxApiResource reactive; ///< Optional resource containing alpha value of reactive objects in the scene.
struct FfxApiResource transparencyAndComposition; ///< Optional resource containing alpha value of special objects in the scene.
struct FfxApiResource output; ///< Output color buffer for the current frame (at presentation resolution).
struct FfxApiFloatCoords2D jitterOffset; ///< The subpixel jitter offset applied to the camera.
struct FfxApiFloatCoords2D motionVectorScale; ///< The scale factor to convert motion vectors to pixel space. Internally: pixelSpaceMV = motionVector * motionVectorScale. Set to renderSize if motion vectors are in UV space [0,1], or to (1.0, 1.0) if motion vectors are already in pixel space. When using display-resolution motion vectors, set to displaySize.
struct FfxApiDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
struct FfxApiDimensions2D upscaleSize; ///< The resolution that the upscaler will upscale to (optional, assumed maxUpscaleSize otherwise).
bool enableSharpening; ///< Enable an additional sharpening pass.
float sharpness; ///< The sharpness value between 0 and 1, where 0 is no additional sharpness and 1 is maximum additional sharpness.
float frameTimeDelta; ///< The time elapsed since the last frame (expressed in milliseconds).
float preExposure; ///< The pre exposure value (must be > 0.0f)
bool reset; ///< A boolean value which when set to true, indicates the camera has moved discontinuously.
float cameraNear; ///< The distance to the near plane of the camera.
float cameraFar; ///< The distance to the far plane of the camera.
float cameraFovAngleVertical; ///< The camera angle field of view in the vertical direction (expressed in radians).
float viewSpaceToMetersFactor; ///< The scale factor to convert view space units to meters
uint32_t flags; ///< Zero or a combination of values from FfxApiDispatchFsrUpscaleFlags.
};
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETUPSCALERATIOFROMQUALITYMODE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x02)
struct ffxQueryDescUpscaleGetUpscaleRatioFromQualityMode
{
ffxQueryDescHeader header; ///< Header descriptor, use type FFX_API_QUERY_DESC_TYPE_UPSCALE_GETUPSCALERATIOFROMQUALITYMODE.
uint32_t qualityMode; ///< The desired quality mode for FSR upscaling.
float* pOutUpscaleRatio; ///< A pointer to a <c>float</c> which will hold the upscaling the per-dimension upscaling ratio.
};
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETRENDERRESOLUTIONFROMQUALITYMODE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x03)
struct ffxQueryDescUpscaleGetRenderResolutionFromQualityMode
{
ffxQueryDescHeader header; ///< Header descriptor, use type FFX_API_QUERY_DESC_TYPE_UPSCALE_GETRENDERRESOLUTIONFROMQUALITYMODE.
uint32_t displayWidth; ///< The target display resolution width.
uint32_t displayHeight; ///< The target display resolution height.
uint32_t qualityMode; ///< The desired quality mode for FSR upscaling.
uint32_t* pOutRenderWidth; ///< A pointer to a <c>uint32_t</c> which will hold the calculated render resolution width.
uint32_t* pOutRenderHeight; ///< A pointer to a <c>uint32_t</c> which will hold the calculated render resolution height.
};
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTERPHASECOUNT FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x04)
struct ffxQueryDescUpscaleGetJitterPhaseCount
{
ffxQueryDescHeader header; ///< Header descriptor, use type FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTERPHASECOUNT.
uint32_t renderWidth; ///< The render resolution width.
uint32_t displayWidth; ///< The output resolution width.
int32_t* pOutPhaseCount; ///< A pointer to a <c>int32_t</c> which will hold the jitter phase count for the scaling factor between <c><i>renderWidth</i></c> and <c><i>displayWidth</i></c>.
};
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTEROFFSET FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x05)
struct ffxQueryDescUpscaleGetJitterOffset
{
ffxQueryDescHeader header; ///< Header descriptor, use type FFX_API_QUERY_DESC_TYPE_UPSCALE_GETJITTEROFFSET.
int32_t index; ///< The index within the jitter sequence.
int32_t phaseCount; ///< The length of jitter phase. See <c><i>ffxQueryDescFsrGetJitterPhaseCount</i></c>.
float* pOutX; ///< A pointer to a <c>float</c> which will contain the subpixel jitter offset for the x dimension.
float* pOutY; ///< A pointer to a <c>float</c> which will contain the subpixel jitter offset for the y dimension.
};
#define FFX_API_DISPATCH_DESC_TYPE_UPSCALE_GENERATEREACTIVEMASK FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x06)
struct ffxDispatchDescUpscaleGenerateReactiveMask
{
ffxDispatchDescHeader header; ///< Header descriptor, use type FFX_API_DISPATCH_DESC_TYPE_UPSCALE_GENERATEREACTIVEMASK.
void* commandList; ///< The <c><i>FfxCommandList</i></c> to record FSRUPSCALE rendering commands into.
struct FfxApiResource colorOpaqueOnly; ///< A <c><i>FfxApiResource</i></c> containing the opaque only color buffer for the current frame (at render resolution).
struct FfxApiResource colorPreUpscale; ///< A <c><i>FfxApiResource</i></c> containing the opaque+translucent color buffer for the current frame (at render resolution).
struct FfxApiResource outReactive; ///< A <c><i>FfxApiResource</i></c> containing the surface to generate the reactive mask into.
struct FfxApiDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
float scale; ///< A value to scale the output
float cutoffThreshold; ///< A threshold value to generate a binary reactive mask
float binaryValue; ///< A value to set for the binary reactive mask
uint32_t flags; ///< Flags to determine how to generate the reactive mask
};
#define FFX_API_CONFIGURE_DESC_TYPE_UPSCALE_KEYVALUE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x07)
struct ffxConfigureDescUpscaleKeyValue
{
ffxConfigureDescHeader header; ///< Header descriptor, use type FFX_API_CONFIGURE_DESC_TYPE_UPSCALE_KEYVALUE.
uint64_t key; ///< Configuration key, member of the FfxApiConfigureUpscaleKey enumeration.
uint64_t u64; ///< Integer value or enum value to set.
void* ptr; ///< Pointer to set or pointer to value to set.
};
enum FfxApiConfigureUpscaleKey
{
FFX_API_CONFIGURE_UPSCALE_KEY_FVELOCITYFACTOR = 0, ///< Override constant buffer fVelocityFactor. The float value is casted from void * ptr. Value of 0.0f can improve temporal stability of bright pixels. Default value is 1.0f. Value is clamped to [0.0f, 1.0f].
FFX_API_CONFIGURE_UPSCALE_KEY_FREACTIVENESSSCALE = 1, ///< Override constant buffer fReactivenessScale. The float value is casted from void * ptr. Meant for development purpose to test if writing a larger value to reactive mask, reduces ghosting. Default value is 1.0f. Value is clamped to [0.0f, +infinity].
FFX_API_CONFIGURE_UPSCALE_KEY_FSHADINGCHANGESCALE = 2, ///< Override fShadingChangeScale. Increasing this scales fsr3.1 computed shading change value at read to have higher reactiveness. Default value is 1.0f. Value is clamped to [0.0f, +infinity].
FFX_API_CONFIGURE_UPSCALE_KEY_FACCUMULATIONADDEDPERFRAME = 3, ///< Override constant buffer fAccumulationAddedPerFrame. Corresponds to amount of accumulation added per frame at pixel coordinate where disocclusion occured or when reactive mask value is > 0.0f. Decreasing this and drawing the ghosting object (IE no mv) to reactive mask with value close to 1.0f can decrease temporal ghosting. Decreasing this value could result in more thin feature pixels flickering. Default value is 0.333. Value is clamped to [0.0f, 1.0f].
FFX_API_CONFIGURE_UPSCALE_KEY_FMINDISOCCLUSIONACCUMULATION = 4, ///< Override constant buffer fMinDisocclusionAccumulation. Increasing this value may reduce white pixel temporal flickering around swaying thin objects that are disoccluding one another often. Too high value may increase ghosting. A sufficiently negative value means for pixel coordinate at frame N that is disoccluded, add fAccumulationAddedPerFrame starting at frame N+2. Default value is -0.333. Value is clamped to [-1.0f, 1.0f].
};
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x08)
struct ffxQueryDescUpscaleGetGPUMemoryUsage
{
ffxQueryDescHeader header; ///< Header descriptor, use type FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE.
struct FfxApiEffectMemoryUsage* gpuMemoryUsageUpscaler; ///< Output values by Query() call.
};
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE_V2 FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x09)
struct ffxQueryDescUpscaleGetGPUMemoryUsageV2
{
ffxQueryDescHeader header; ///< Header descriptor, use type FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE_V2.
void* device; ///< For DX12: pointer to ID3D12Device. For VK, pointer to VkDeviceContext. App needs to fill out before Query() call.
struct FfxApiDimensions2D maxRenderSize; ///< App needs to fill out before Query() call.
struct FfxApiDimensions2D maxUpscaleSize; ///< App needs to fill out before Query() call.
uint32_t flags; ///< Zero or a combination of values from FfxApiCreateContextUpscaleFlags. App needs to fill out before Query() call.
struct FfxApiEffectMemoryUsage* gpuMemoryUsageUpscaler; ///< Output values by Query() call.
};
enum FfxApiQueryResourceIdentifiers
{
FFX_API_QUERY_RESOURCE_INPUT_COLOR = (1 << 0), ///< Color buffer for the current frame (at render resolution).
FFX_API_QUERY_RESOURCE_INPUT_DEPTH = (1 << 1), ///< 32bit depth values for the current frame (at render resolution).
FFX_API_QUERY_RESOURCE_INPUT_MV = (1 << 2), ///< 2-dimensional motion vectors (at render resolution if FFX_FSR_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS is not set).
FFX_API_QUERY_RESOURCE_INPUT_EXPOSURE = (1 << 3), ///< A 1x1 texture containing exposure value or the FFX_UPSCALE_ENABLE_AUTO_EXPOSURE set at context creation.
FFX_API_QUERY_RESOURCE_INPUT_REACTIVEMASK = (1 << 4), ///< An R8 UNORM texture at render resolution that controls the influence of pixel history on upscaling result.
FFX_API_QUERY_RESOURCE_INPUT_TRANSPARENCYCOMPOSITION = (1 << 5), ///< An R8 UNORM texture at render resolution that controls the blending of color in the upscaling result.
};
#define FFX_API_QUERY_DESC_TYPE_UPSCALE_GET_RESOURCE_REQUIREMENTS FFX_API_MAKE_EFFECT_SUB_ID(FFX_API_EFFECT_ID_UPSCALE, 0x0a)
struct ffxQueryDescUpscaleGetResourceRequirements
{
ffxQueryDescHeader header; ///< Header descriptor, use type FFX_API_QUERY_DESC_TYPE_UPSCALE_GET_RESOURCE_REQUIREMENTS.
uint64_t required_resources; ///< resources 64b bitfield, that given current context state, are required for effect correctness.
uint64_t optional_resources; ///< resources 64b bitfield, that given current context state, will be consumed if provided, but are optional.
};
#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; ///< Header descriptor, use type FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE_VERSION.
uint32_t version; ///< The version of the API the application was built against. This must be set to FFX_UPSCALER_VERSION.
};
#ifdef __cplusplus
}
#endif

View File

@@ -71,6 +71,8 @@ int vk_ngxfg_wanted(void); // vk_dlaa.c: DLSS's frame generation th
int vk_ngxfg_max(void); // ... and how many frames it may generate per rendered one (0: it cannot) int vk_ngxfg_max(void); // ... and how many frames it may generate per rendered one (0: it cannot)
int vk_ffx_available(void); // vk_ffx.cpp: FSR 3.1 upscaling can run (asked without loading the library) int vk_ffx_available(void); // vk_ffx.cpp: FSR 3.1 upscaling can run (asked without loading the library)
int vk_ffx_framegen_available(void); // ... and FSR 3.1 frame generation int vk_ffx_framegen_available(void); // ... and FSR 3.1 frame generation
int vk_ffx4_available(void); // vk_ffx4.cpp: AMD's FSR 4 runs on this device (its libraries, card and driver)
int vk_ffx_fsr4(void); // vk_ffx.cpp: ... and the setting asks for it (NX2NAVI_FSR4)
int vk_texture_detail_auto(void); // vk_texture.c: the texture detail auto picks on this card, 0 full to 2 low int vk_texture_detail_auto(void); // vk_texture.c: the texture detail auto picks on this card, 0 full to 2 low
double frame_step_limit_hz(void); double frame_step_limit_hz(void);
int frame_limit_follows_display(void); int frame_limit_follows_display(void);
@@ -832,7 +834,8 @@ static void upscaling_name(char *out, size_t size) {
int mode = 0; int mode = 0;
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++)
if (!strcmp(cfg_value("NX2NAVI_DLSS"), modes[i])) mode = i; if (!strcmp(cfg_value("NX2NAVI_DLSS"), modes[i])) mode = i;
if (!strcmp(cfg_value("NX2NAVI_TAA"), "fsr3")) snprintf(out, size, "AMD FSR 3.1 %s", menu_text(fsr3[mode])); if (!strcmp(cfg_value("NX2NAVI_TAA"), "fsr3"))
snprintf(out, size, vk_ffx_fsr4() ? "AMD FSR 4 %s" : "AMD FSR 3.1 %s", menu_text(fsr3[mode]));
else snprintf(out, size, mode ? "DLSS %s" : "NVIDIA %s", menu_text(dlss[mode])); else snprintf(out, size, mode ? "DLSS %s" : "NVIDIA %s", menu_text(dlss[mode]));
} }
@@ -847,20 +850,22 @@ static void row_upscaling(void) {
// FSR 3.1's modes take the same render scales as DLSS's (Native AA is FSR's name for DLAA's full size) // FSR 3.1's modes take the same render scales as DLSS's (Native AA is FSR's name for DLAA's full size)
static const UiTextId fsr_names[] = {UI_MENU_FSR3_NATIVE, UI_MENU_DLSS_QUALITY, UI_MENU_DLSS_BALANCED, static const UiTextId fsr_names[] = {UI_MENU_FSR3_NATIVE, UI_MENU_DLSS_QUALITY, UI_MENU_DLSS_BALANCED,
UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA}; UI_MENU_DLSS_PERFORMANCE, UI_MENU_DLSS_ULTRA};
enum { BILINEAR, FSR1, DLSS, FSR3 }; // FSR 4 (vk_ffx4.cpp) is the same setting as FSR 3.1 with NX2NAVI_FSR4 on, and takes the same modes: listed where
// it runs on this device, after FSR 3.1's
enum { BILINEAR, FSR1, DLSS, FSR3, FSR4 };
struct Entry { int kind, mode; }; struct Entry { int kind, mode; };
static char text[10][96]; static char text[15][96];
Entry list[12]; Entry list[18];
const char *names[12]; const char *names[18];
int n = 0; int n = 0;
auto add = [&](int kind, int mode) { auto add = [&](int kind, int mode) {
list[n] = {kind, mode}; list[n] = {kind, mode};
if (kind == BILINEAR) names[n] = menu_text(UI_MENU_UPSCALER_BILINEAR); if (kind == BILINEAR) names[n] = menu_text(UI_MENU_UPSCALER_BILINEAR);
else if (kind == FSR1) names[n] = menu_text(UI_MENU_UPSCALER_FSR); else if (kind == FSR1) names[n] = menu_text(UI_MENU_UPSCALER_FSR);
else { else {
char *t = text[(kind == FSR3 ? 5 : 0) + mode]; char *t = text[(kind == FSR4 ? 10 : kind == FSR3 ? 5 : 0) + mode];
if (kind == DLSS) snprintf(t, sizeof text[0], mode ? "DLSS %s" : "NVIDIA %s", menu_text(mode_names[mode])); if (kind == DLSS) snprintf(t, sizeof text[0], mode ? "DLSS %s" : "NVIDIA %s", menu_text(mode_names[mode]));
else snprintf(t, sizeof text[0], "AMD FSR 3.1 %s", menu_text(fsr_names[mode])); else snprintf(t, sizeof text[0], kind == FSR4 ? "AMD FSR 4 %s" : "AMD FSR 3.1 %s", menu_text(fsr_names[mode]));
names[n] = t; names[n] = t;
} }
n++; n++;
@@ -868,15 +873,16 @@ static void row_upscaling(void) {
// what is set now // what is set now
Entry now = {strcmp(cfg_value("NX2NAVI_UPSCALER"), "fsr") ? BILINEAR : FSR1, 0}; Entry now = {strcmp(cfg_value("NX2NAVI_UPSCALER"), "fsr") ? BILINEAR : FSR1, 0};
if (cfg_bool("NX2NAVI_DLAA")) { if (cfg_bool("NX2NAVI_DLAA")) {
now = {strcmp(cfg_value("NX2NAVI_TAA"), "fsr3") ? DLSS : FSR3, 0}; now = {strcmp(cfg_value("NX2NAVI_TAA"), "fsr3") ? DLSS : vk_ffx_fsr4() ? FSR4 : FSR3, 0}; // set where it does
for (int i = 0; i < 5; i++) for (int i = 0; i < 5; i++) // not run: FSR 3.1 does
if (!strcmp(cfg_value("NX2NAVI_DLSS"), modes[i])) now.mode = i; if (!strcmp(cfg_value("NX2NAVI_DLSS"), modes[i])) now.mode = i;
} }
const bool dlss = dlss_offered(), fsr = vk_ffx_available(); const bool dlss = dlss_offered(), fsr = vk_ffx_available(), fsr4 = fsr && vk_ffx4_available();
add(BILINEAR, 0); add(BILINEAR, 0);
add(FSR1, 0); add(FSR1, 0);
for (int i = 0; dlss && i < 5; i++) add(DLSS, i); for (int i = 0; dlss && i < 5; i++) add(DLSS, i);
for (int i = 0; fsr && i < 5; i++) add(FSR3, i); for (int i = 0; fsr && i < 5; i++) add(FSR3, i);
for (int i = 0; fsr4 && i < 5; i++) add(FSR4, i);
if (!dlss && now.kind == DLSS) add(DLSS, now.mode); if (!dlss && now.kind == DLSS) add(DLSS, now.mode);
if (!fsr && now.kind == FSR3) add(FSR3, now.mode); if (!fsr && now.kind == FSR3) add(FSR3, now.mode);
int cur = 0; int cur = 0;
@@ -895,7 +901,8 @@ static void row_upscaling(void) {
opt_apply("NX2NAVI_DLAA", e.kind >= DLSS ? "1" : "0"); opt_apply("NX2NAVI_DLAA", e.kind >= DLSS ? "1" : "0");
if (e.kind < DLSS) opt_apply("NX2NAVI_FRAMEGEN", "off"); // it needs DLSS's or FSR 3.1's motion vectors (row_framegen) if (e.kind < DLSS) opt_apply("NX2NAVI_FRAMEGEN", "off"); // it needs DLSS's or FSR 3.1's motion vectors (row_framegen)
if (e.kind >= DLSS) opt_apply("NX2NAVI_DLSS", modes[e.mode]); if (e.kind >= DLSS) opt_apply("NX2NAVI_DLSS", modes[e.mode]);
if (e.kind >= DLSS) opt_apply("NX2NAVI_TAA", e.kind == FSR3 ? "fsr3" : "dlss"); if (e.kind >= DLSS) opt_apply("NX2NAVI_TAA", e.kind >= FSR3 ? "fsr3" : "dlss");
if (e.kind >= FSR3) opt_apply("NX2NAVI_FSR4", e.kind == FSR4 ? "1" : "0");
} }
// Under the HDR value: "after restart" when what is set waits for one (the game's own HDR, to or from it: // Under the HDR value: "after restart" when what is set waits for one (the game's own HDR, to or from it:

View File

@@ -386,6 +386,7 @@ static uint64_t submit_sync(const uint64_t *handles, int n) {
if (!vk_exec_held()) ph_flush(&PH.after); if (!vk_exec_held()) ph_flush(&PH.after);
} }
vk_present_drain(); vk_present_drain();
vk_exec_gate_wait(handles, n); // a submission that begins with a wait for the CPU's signal: before its copies
vk_texture_new_submit(); vk_texture_new_submit();
uint64_t f = vk_sync_submit(handles, n); uint64_t f = vk_sync_submit(handles, n);
// The submission stopped at a wait whose signal the CPU gave while it was being replayed (vk_exec_xfer.c "events // The submission stopped at a wait whose signal the CPU gave while it was being replayed (vk_exec_xfer.c "events

View File

@@ -1124,6 +1124,72 @@ static int cont_ready(const Cont *c) {
return !c->at || vk_exec_event_met(nvn_op_payload(c->at)) || vk_exec_submit_seq - c->since > CONT_MAX; return !c->at || vk_exec_event_met(nvn_op_payload(c->at)) || vk_exec_submit_seq - c->since > CONT_MAX;
} }
// ---- the gate: a submission that begins with a wait for the CPU's signal (NX2NAVI_GATE_WAIT_MS, default 10; 0 off)
// Ocarina's main queue begins with a wait for an event the game signals from the CPU once it has written what the
// frame reads (vk_exec_xfer.c "events the CPU signals"). The render thread submits that queue without waiting for the
// signal, and polls the event afterwards, a millisecond at a time, before it presents. In Hyrule Field the signal
// came 1 to 2 ms after the submit call in about every other frame: the main thread first waits for the previous
// frame's fence and reads back what it needs. The submission then took its copies (the mirror sync and the uniform
// snapshot, 1.1 to 1.7 ms), met the wait unmet and was held; the render thread polled, presented, and the present
// replayed the frame (vk_backend.c held_resume) under a value the game's fence does not stand for, so the game's next
// wait for that fence returned with the GPU still at work and the frame after was replayed inside its submit call
// again: frames of 23 and 15 ms in turn where each takes 17.
// So when a submission would stop at such a wait before it has recorded anything, the submit call waits for the
// signal here, before the copies are taken, as the console's GPU waits at the wait itself: the copies are then
// taken after the game has finished writing, and the frame is replayed in the call the game's fence stands for.
// Only state may precede the wait in the command buffer, and the event must be one the CPU has signalled before;
// the wait ends after NX2NAVI_GATE_WAIT_MS at the latest, and the submission is then held as before.
static struct { uint64_t n, ns, late; } GW; // since the last perf line: waits, their time, waits that ran out
static const void *gate_first_wait(const op_hdr *h) {
for (int k = 0; k < 256; k++) {
if (h->size < sizeof *h || (h->size & 7) || h->op >= OP_COUNT_) return NULL;
const void *a = nvn_op_payload(h);
switch (h->op) {
case OP_WAIT_EVENT: return a;
case OP_JUMP: h = (const op_hdr *)(uintptr_t)((const p_jump *)a)->target; continue;
// state the walk only stores: nothing is recorded and nothing reaches the CPU before the wait
case OP_BEGIN: case OP_SET_RT: case OP_VIEWPORTS: case OP_SCISSOR: case OP_DEPTH_RANGE: case OP_BIND_PROGRAM:
case OP_BIND_STATE: case OP_BIND_VATTR: case OP_BIND_VSTREAM: case OP_BIND_VBUF: case OP_BIND_UBO:
case OP_BIND_SSBO: case OP_BIND_TEX: case OP_BIND_SAMP: case OP_BIND_IMG: case OP_STENCIL: case OP_POLY_OFFSET:
case OP_SET_TEX_POOL: case OP_SET_SAMP_POOL: case OP_COPY_STRIDE: case OP_BLEND_COLOR: case OP_DEPTH_CLAMP:
case OP_RASTER_DISCARD: case OP_PRIM_RESTART: case OP_PUSH_CC:
break;
default: return NULL; // a draw, a copy, a signal, a call: the walk decides, as before
}
h = nvn_op_next(h);
}
return NULL;
}
void vk_exec_gate_wait(const uint64_t *handles, int n) {
static int64_t cap_ns = -1;
if (cap_ns < 0) {
int ms = cfg_int("NX2NAVI_GATE_WAIT_MS");
cap_ns = ms > 0 ? (int64_t)ms * 1000000 : 0;
}
if (!cap_ns || n < 1 || !handles[0] || !gfx_submit_queue || !evo_enabled()) return;
const void *w = gate_first_wait(nvn_op_first(handles[0]));
if (!w || vk_exec_event_holds_now(w) || !vk_exec_event_cpu_known((const void *)((const p_wait_event *)w)->val)) return;
uint64_t t0 = kern_now_ns(), now = t0;
for (unsigned i = 0; !vk_exec_event_holds_now(w); i++) {
if ((i & 15) == 15 && (now = kern_now_ns()) - t0 >= (uint64_t)cap_ns) {
GW.late++;
break;
}
if (i < 20000) plat_pause();
else plat_yield();
}
GW.n++, GW.ns += kern_now_ns() - t0;
if (GW.n >= 600) {
if (rt_trace & RT_TRACE_PERF)
rt_log("perf: gate: %llu submissions waited for the CPU's signal before their copies, %.2f ms on average; "
"%llu waited %lld ms without it and were held", (unsigned long long)GW.n, (double)GW.ns / (double)GW.n / 1e6,
(unsigned long long)GW.late, (long long)(cap_ns / 1000000));
GW.n = GW.ns = GW.late = 0;
}
}
int vk_exec_held_ready(void) { int vk_exec_held_ready(void) {
for (int s = 0; evo_pending && s < EVO_QUEUES; s++) for (int s = 0; evo_pending && s < EVO_QUEUES; s++)
if (evq[s].head && cont_ready(evq[s].head)) return 1; if (evq[s].head && cont_ready(evq[s].head)) return 1;

View File

@@ -242,6 +242,11 @@ extern int vk_exec_signalled; // set by every replayed SignalEve
// Events the CPU signals (vk_exec_xfer.c "events the CPU signals"). // Events the CPU signals (vk_exec_xfer.c "events the CPU signals").
void vk_exec_event_cpu(const void *event); // any thread: nvnEventSignal is about to write the event's value void vk_exec_event_cpu(const void *event); // any thread: nvnEventSignal is about to write the event's value
void vk_exec_event_sync(int begin); // vk_exec_record: its mirror sync and uniform copy are taken now / it ends void vk_exec_event_sync(int begin); // vk_exec_record: its mirror sync and uniform copy are taken now / it ends
int vk_exec_event_cpu_known(const void *event); // the CPU has signalled this event before
int vk_exec_event_holds_now(const void *payload); // an OP_WAIT_EVENT's condition on the value in memory now
// vk_backend.c submit_sync, before a submission is recorded: waits for the CPU's signal when the submission begins
// with a wait for it (vk_exec.c "the gate").
void vk_exec_gate_wait(const uint64_t *handles, int n);
int vk_exec_event_at_sync(void); // NX2NAVI_EVENT_AT_SYNC int vk_exec_event_at_sync(void); // NX2NAVI_EVENT_AT_SYNC
uint64_t vk_exec_event_late_take(void); // waits only a CPU signal after the copies would have passed, since the last call uint64_t vk_exec_event_late_take(void); // waits only a CPU signal after the copies would have passed, since the last call
// Since the last call, which resets them: waits, waits reached before their signal, those of them a later replayed // Since the last call, which resets them: waits, waits reached before their signal, those of them a later replayed

View File

@@ -265,38 +265,103 @@ void vk_exec_oq_draw(VkExec *ex) {
void vk_exec_oq_pass_end(VkExec *ex) { oq_close(ex); } void vk_exec_oq_pass_end(VkExec *ex) { oq_close(ex); }
static void oq_batch_drop(void); // the results kept by the completion thread (oq_take)
void vk_exec_xfer_shutdown(void) { void vk_exec_xfer_shutdown(void) {
if (oq_state > 0) vkDestroyQueryPool(vk_ctx()->device, oq_pool, NULL); if (oq_state > 0) vkDestroyQueryPool(vk_ctx()->device, oq_pool, NULL);
oq_pool = VK_NULL_HANDLE, oq_state = 0, oq_next = 0, oq_counting = oq_reported = oq_keep = 0, oq_open = -1; oq_pool = VK_NULL_HANDLE, oq_state = 0, oq_next = 0, oq_counting = oq_reported = oq_keep = 0, oq_open = -1;
oq_nseg = 0, oq_lost = 0, oq_count = 0; oq_nseg = 0, oq_lost = 0, oq_count = 0;
memset((void *)oq_busy, 0, sizeof oq_busy); memset((void *)oq_busy, 0, sizeof oq_busy);
oq_batch_drop();
} }
static void oq_cb(void *arg) { // The completion thread reads the results in batches (NX2NAVI_OQ_BATCH, default 1; 0: every segment by itself, as
OqSegment *s = arg; // before). The game tests one proxy per report, so a segment holds one query, and a frame of Hyrule Field has about a
VkDevice dev = vk_ctx()->device; // hundred of them: one vkGetQueryPoolResults and one vkResetQueryPool each. On an RX 7900 XT (26.10.1) each of those
uint64_t sum = 0, v[64 * 2]; // calls goes into the kernel, and the two hundred took 3.9 ms of every frame on the completion thread, which runs a
for (uint32_t i = 0; i < s->n;) { // submission's callbacks before it lets the submission's waiters go: the game's main thread waits for the previous
uint32_t j = i + 1; // frame's fence before it lets the next frame's GPU work start, so the frame after one replayed inside its submit
while (j < s->n && j - i < 64 && s->q[j] == s->q[j - 1] + 1) j++; // call began 4 to 6 ms late with every thread idle. Slots come from the ring in order, so the slots of the segments
// The fence has passed, so a query that is still unavailable will not become available: waiting would block the // that follow lie behind the one asked for: one call reads OQ_BATCH slots from there on with their availability, the
// completion thread, and with it every later callback, for good. It counts as visible (one sample). // available ones are kept (the results stay in the pool until the reset), and the segments after it take theirs from
VkResult r = vkGetQueryPoolResults(dev, oq_pool, s->q[i], j - i, sizeof v, v, 2 * sizeof v[0], // what is kept. A slot not available in the batch (its part had not run yet) is read again when its segment comes.
// The slots taken are reset in runs, one vkResetQueryPool for each: a run ends when a slot that does not continue it
// is taken or a new batch is read. Until then its slots stay busy for the replay, at most OQ_BATCH of the ring's
// OQ_N, also while the game reports nothing.
#define OQ_BATCH 256
static struct {
uint32_t first, n; // the slots kept: [first, first + n)
uint64_t v[OQ_BATCH * 2]; // per slot: samples, available
uint8_t taken[OQ_BATCH];
uint32_t r0, rn; // the run of taken slots still to be reset
uint64_t calls, slots, segs; // since the last perf line: result calls, slots they read, segments served
} OQB;
static int oq_batch_mode = -1;
static void oq_batch_drop(void) { OQB.n = OQB.rn = 0; }
static void oq_reset_flush(VkDevice dev) {
if (!OQB.rn) return;
vkResetQueryPool(dev, oq_pool, OQB.r0, OQB.rn);
for (uint32_t k = 0; k < OQB.rn; k++) __atomic_store_n(&oq_busy[OQB.r0 + k], 0, __ATOMIC_RELEASE);
OQB.rn = 0;
}
static void oq_read(VkDevice dev, uint32_t first, uint32_t n) {
VkResult r = vkGetQueryPoolResults(dev, oq_pool, first, n, sizeof OQB.v[0] * 2 * n, OQB.v, 2 * sizeof OQB.v[0],
VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WITH_AVAILABILITY_BIT); VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WITH_AVAILABILITY_BIT);
if (r != VK_SUCCESS && r != VK_NOT_READY) { if (r != VK_SUCCESS && r != VK_NOT_READY) {
vk_device_fault_report(r); vk_device_fault_report(r);
rt_fatal("vk: occlusion query results failed (%d)", (int)r); rt_fatal("vk: occlusion query results failed (%d)", (int)r);
} }
vkResetQueryPool(dev, oq_pool, s->q[i], j - i); OQB.first = first, OQB.n = n;
for (uint32_t k = i; k < j; k++) { memset(OQB.taken, 0, n);
if (v[2 * (k - i) + 1]) sum += v[2 * (k - i)]; OQB.calls++, OQB.slots += n;
}
// The samples of slot q, whose submission has completed; *avail 0 when the query has no result.
static uint64_t oq_take(VkDevice dev, uint32_t q, int *avail) {
uint32_t k = q - OQB.first;
if (!(q >= OQB.first && k < OQB.n && !OQB.taken[k] && OQB.v[2 * k + 1])) {
// not kept, or kept as unavailable (read before its part ran): from this slot on, up to the replay's next slot
oq_reset_flush(dev); // before the kept results go: the run's slots are among them
uint32_t next = __atomic_load_n(&oq_next, __ATOMIC_RELAXED) % OQ_N, n = OQ_N - q;
if (next > q && next - q < n) n = next - q;
if (n > OQ_BATCH) n = OQ_BATCH;
if (oq_batch_mode == 0) n = 1;
oq_read(dev, q, n);
k = 0;
}
OQB.taken[k] = 1;
if (OQB.rn && q != OQB.r0 + OQB.rn) oq_reset_flush(dev);
if (!OQB.rn) OQB.r0 = q;
OQB.rn++;
*avail = OQB.v[2 * k + 1] != 0;
return OQB.v[2 * k];
}
static void oq_cb(void *arg) {
OqSegment *s = arg;
VkDevice dev = vk_ctx()->device;
if (oq_batch_mode < 0) oq_batch_mode = cfg_bool("NX2NAVI_OQ_BATCH");
uint64_t sum = 0;
for (uint32_t i = 0; i < s->n; i++) {
// The fence has passed, so a query that is still unavailable will not become available: waiting would block the
// completion thread, and with it every later callback, for good. It counts as visible (one sample).
int avail;
uint64_t v = oq_take(dev, s->q[i], &avail);
if (avail) sum += v;
else { else {
sum += 1; sum += 1;
LOG_ONCE("vk: occlusion query slot %u not available after its fence, counted as visible", s->q[k]); LOG_ONCE("vk: occlusion query slot %u not available after its fence, counted as visible", s->q[i]);
} }
__atomic_store_n(&oq_busy[s->q[k]], 0, __ATOMIC_RELEASE);
} }
i = j; if (s->n && ++OQB.segs >= 12000) {
if (rt_trace & RT_TRACE_PERF)
rt_log("perf: occlusion queries: %llu segments read with %llu result calls of %.1f slots on average",
(unsigned long long)OQB.segs, (unsigned long long)OQB.calls,
OQB.calls ? (double)OQB.slots / (double)OQB.calls : 0.0);
OQB.calls = OQB.slots = OQB.segs = 0;
} }
if (s->reset) oq_count = 0; if (s->reset) oq_count = 0;
else { else {
@@ -412,6 +477,22 @@ void vk_exec_event_cpu(const void *event) {
plat_mutex_unlock(&cpu_ev_lock); plat_mutex_unlock(&cpu_ev_lock);
} }
// 1 when the CPU has signalled this event before (nvnEventSignal): its waits are gates the game opens from the CPU.
int vk_exec_event_cpu_known(const void *event) {
plat_mutex_lock(&cpu_ev_lock);
int i = 0;
while (i < cpu_ev_n && cpu_ev[i].val != event) i++;
int known = i < cpu_ev_n;
plat_mutex_unlock(&cpu_ev_lock);
return known;
}
// The wait's condition on the value in memory now, whatever the replay has seen. Any thread.
int vk_exec_event_holds_now(const void *payload) {
const p_wait_event *p = payload;
return ev_holds(__atomic_load_n(p->val, __ATOMIC_ACQUIRE), p->mode, p->value);
}
void vk_exec_event_sync(int begin) { void vk_exec_event_sync(int begin) {
plat_mutex_lock(&cpu_ev_lock); plat_mutex_lock(&cpu_ev_lock);
ev_sync_seq = begin ? cpu_ev_seq : UINT64_MAX; ev_sync_seq = begin ? cpu_ev_seq : UINT64_MAX;

View File

@@ -191,9 +191,27 @@ extern "C" int vk_ffx_available(void) {
extern "C" int vk_ffx_framegen_available(void) { return vk_ffx_available(); } // the same library, its API calls extern "C" int vk_ffx_framegen_available(void) { return vk_ffx_available(); } // the same library, its API calls
// NX2NAVI_FSR4 (default 0, live): FSR 4 where it runs (vk_ffx4.cpp), else FSR 3.1.
extern "C" int vk_ffx_fsr4(void) { return cfg_bool("NX2NAVI_FSR4") && vk_ffx4_available(); }
extern "C" int vk_ffx_upscale(VkCommandBuffer cb, const VkFfxImage *color, const VkFfxImage *depth, const VkFfxImage *mv, extern "C" int vk_ffx_upscale(VkCommandBuffer cb, const VkFfxImage *color, const VkFfxImage *depth, const VkFfxImage *mv,
const VkFfxImage *out, float jx, float jy, int reset, float dt_ms, float fov_y) { const VkFfxImage *out, float jx, float jy, int reset, float dt_ms, float fov_y) {
if (!vk_ffx_load()) return 0; if (!vk_ffx_load()) return 0;
// Each upscaler keeps a history of its own: the frame after a change from one to the other starts it anew, or it
// would blend this picture with whatever that upscaler last saw.
static int last; // 3 or 4: which one made the frame before
if (vk_ffx_fsr4()) {
if (vk_ffx4_upscale(cb, color, depth, mv, out, jx, jy, reset || last != 4, dt_ms, fov_y)) {
if (last != 4) rt_log("ffx: the upscaler is %s", vk_ffx4_name());
last = 4;
return 1;
}
// it failed and said so: FSR 3.1 makes this frame
}
if (last != 3) {
if (last) rt_log("ffx: the upscaler is AMD FSR 3.1");
reset = 1, last = 3;
}
Up *u = context_for(color->width, color->height, out->width, out->height); Up *u = context_for(color->width, color->height, out->width, out->height);
if (!u) return 0; if (!u) return 0;
ffxDispatchDescUpscale d = {}; ffxDispatchDescUpscale d = {};
@@ -243,6 +261,7 @@ extern "C" ffxReturnCode_t vk_ffx_dispatch(ffxContext *ctx, const ffxDispatchDes
} }
extern "C" void vk_ffx_release(void) { extern "C" void vk_ffx_release(void) {
vk_ffx4_release();
if (!A.ok) return; if (!A.ok) return;
for (Up &u : U) for (Up &u : U)
if (u.ctx) A.destroy(&u.ctx, nullptr), u.ctx = nullptr; if (u.ctx) A.destroy(&u.ctx, nullptr), u.ctx = nullptr;

View File

@@ -23,7 +23,18 @@ int vk_ffx_upscale(VkCommandBuffer cb, const VkFfxImage *color, const VkFfxImage
const VkFfxImage *out, float jx, float jy, int reset, float dt_ms, float fov_y); const VkFfxImage *out, float jx, float jy, int reset, float dt_ms, float fov_y);
void vk_ffx_release(void); // before the device goes away void vk_ffx_release(void); // before the device goes away
#ifdef __cplusplus // AMD FSR 4 (vk_ffx4.cpp): the ML upscaler of AMD's FSR SDK 2.4, through amd_fidelityfx_loader_vk.dll and
// amd_fidelityfx_upscaler_vk.dll beside the executable. vk_ffx_upscale runs it in FSR 3.1's place when the setting
// asks (NX2NAVI_FSR4) and it runs here, and falls back to FSR 3.1 when it fails.
int vk_ffx4_available(void); // the libraries are there and list a 4.x version for the device; asked once, with the
// device, from any thread (0 before the device exists)
const char *vk_ffx4_name(void); // "AMD FSR 4.1.2" once vk_ffx4_available found it
int vk_ffx4_upscale(VkCommandBuffer cb, const VkFfxImage *color, const VkFfxImage *depth, const VkFfxImage *mv,
const VkFfxImage *out, float jx, float jy, int reset, float dt_ms, float fov_y); // as vk_ffx_upscale
void vk_ffx4_release(void);
int vk_ffx_fsr4(void); // the setting asks for FSR 4 and it runs here: what vk_ffx_upscale uses, for the menu
#if defined(__cplusplus) && !defined(VK_FFX_NO_API)
// The API's calls themselves, for vk_fg.cpp (0 = FFX_API_RETURN_OK): the library loaded first (vk_ffx_load). // The API's calls themselves, for vk_fg.cpp (0 = FFX_API_RETURN_OK): the library loaded first (vk_ffx_load).
#include "third_party/ffx_api/ffx_api.h" #include "third_party/ffx_api/ffx_api.h"
extern "C" { extern "C" {

318
runtime/vk_ffx4.cpp Normal file
View File

@@ -0,0 +1,318 @@
// AMD FSR 4 (FSR Upscaling 4.x, the machine-learned upscaler) through the libraries of AMD's FSR SDK 2.4:
// amd_fidelityfx_loader_vk.dll and amd_fidelityfx_upscaler_vk.dll next to the executable, loaded at run time. The SDK's
// headers are in third_party/ffx_sdk (MIT), at the paths they have in the SDK. FSR 3.1 and frame generation stay with
// vk_ffx.cpp and the library of SDK 1.1.4: the two sets of headers name the same types with other layouts, so nothing
// of the API crosses between the two files, and vk_ffx.cpp's vk_ffx_upscale calls in here first.
//
// The loader answers which upscaler versions it can run on a device (ffxQueryDescGetVersions with the device given):
// 4.1.2, 3.1.6 and 2.3.4 on a Radeon the ML upscaler supports (RX 6000, 7000 and 9000 cards and some Ryzen APUs, with
// AMD's driver 26.10.1 or newer on Windows), 3.1.6 and 2.3.4 on any other. FSR 4 runs only where a 4.x version is
// listed, and its contexts are made with that version asked for by its id, so the loader cannot hand out another.
// Where it is not listed, or a context or a dispatch fails, vk_ffx.cpp's FSR 3.1 serves the frame as before.
//
// The inputs are the ones FSR 3.1 takes (vk_ffx.cpp): the scene's light target in linear HDR, its D32F depth (not
// inverted, the far plane at infinity) and the camera motion vectors in render pixels from this frame to the previous
// one. FSR 4 needs no reactive or transparency mask.
#define VK_FFX_NO_API // vk_ffx.h: without the API declarations of the other set of headers
#ifndef _WIN32
// AMD publishes the SDK's libraries for Windows only: in any other build FSR 4 is never listed, vk_ffx.cpp's FSR 3.1
// path is all there is, and the SDK's headers are not read.
extern "C" {
#include "vk.h"
#include "vk_ffx.h"
}
extern "C" int vk_ffx4_available(void) { return 0; }
extern "C" const char *vk_ffx4_name(void) { return "AMD FSR 4"; }
extern "C" int vk_ffx4_upscale(VkCommandBuffer, const VkFfxImage *, const VkFfxImage *, const VkFfxImage *, const VkFfxImage *,
float, float, int, float, float) {
return 0;
}
extern "C" void vk_ffx4_release(void) {}
#else
#include <windows.h>
#include <atomic>
#include <mutex>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include "third_party/ffx_sdk/api/include/ffx_api.h"
#include "third_party/ffx_sdk/api/include/vk/ffx_api_vk.h"
#include "third_party/ffx_sdk/upscalers/include/ffx_upscale.h"
extern "C" {
#include "cfg.h"
#include "host.h"
#include "platform/platform.h"
#include "vk.h"
#include "vk_ffx.h"
}
namespace {
struct Api {
PfnFfxCreateContext create = nullptr;
PfnFfxDestroyContext destroy = nullptr;
PfnFfxConfigure configure = nullptr;
PfnFfxQuery query = nullptr;
PfnFfxDispatch dispatch = nullptr;
} A;
std::mutex g_lock; // the probe: the menu asks from its thread, the replay from its own
std::atomic<int> g_state{-1}; // -1 not probed; 0 FSR 4 does not run here; 1 it does
uint64_t g_version; // the id of the 4.x version the loader listed for the device
char g_name[48] = "AMD FSR 4"; // "AMD FSR 4.1.2", for the menu and the log
int g_failures; // contexts or dispatches that failed; past FAIL_MAX FSR 4 is off for the run
const int FAIL_MAX = 3;
void message(uint32_t type, const wchar_t *msg) {
char s[512];
size_t n = 0;
for (; msg && msg[n] && n < sizeof s - 1; n++) s[n] = msg[n] < 128 ? (char)msg[n] : '?';
s[n] = 0;
static int told;
if (told++ < 40) rt_log("ffx4: %s %s", type == FFX_API_MESSAGE_TYPE_ERROR ? "error:" : "warning:", s);
}
// a library of the SDK next to the executable; 0 when the path does not fit
int beside_exe(const char *name, char *path, size_t size) {
DWORD n = GetModuleFileNameA(NULL, path, (DWORD)size);
while (n && path[n - 1] != '\\') n--;
return snprintf(path + n, size - n, "%s", name) < (int)(size - n);
}
int file_there(const char *path) {
DWORD attr = GetFileAttributesA(path);
return attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY);
}
// Loads the loader and asks it for the device's upscaler versions. Under g_lock, once the device exists.
int probe(void) {
const VkCtx *c = vk_ctx();
if (!c || !c->device) return -1; // asked before the device: again later
char loader[MAX_PATH], upscaler[MAX_PATH];
if (!beside_exe("amd_fidelityfx_loader_vk.dll", loader, sizeof loader) ||
!beside_exe("amd_fidelityfx_upscaler_vk.dll", upscaler, sizeof upscaler) || !file_there(loader) ||
!file_there(upscaler))
return 0; // not shipped beside this build: nothing is said, FSR 3.1 is what the menu offers
HMODULE m = LoadLibraryA(loader);
if (!m) {
rt_log("ffx4: %s does not load (error %lu): FSR 4 off", loader, (unsigned long)GetLastError());
return 0;
}
A.create = (PfnFfxCreateContext)(void *)GetProcAddress(m, "ffxCreateContext");
A.destroy = (PfnFfxDestroyContext)(void *)GetProcAddress(m, "ffxDestroyContext");
A.configure = (PfnFfxConfigure)(void *)GetProcAddress(m, "ffxConfigure");
A.query = (PfnFfxQuery)(void *)GetProcAddress(m, "ffxQuery");
A.dispatch = (PfnFfxDispatch)(void *)GetProcAddress(m, "ffxDispatch");
if (!A.create || !A.destroy || !A.configure || !A.query || !A.dispatch) {
rt_log("ffx4: amd_fidelityfx_loader_vk.dll lacks the API entry points: FSR 4 off");
return 0;
}
VkDeviceContext dc = {c->device, c->phys, vkGetDeviceProcAddr};
uint64_t ids[16] = {}, n = 0;
const char *names[16] = {};
ffxQueryDescGetVersions q = {};
q.header.type = FFX_API_QUERY_DESC_TYPE_GET_VERSIONS;
q.createDescType = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE;
q.device = &dc;
q.outputCount = &n;
ffxReturnCode_t r = A.query(nullptr, &q.header); // the count
if (r == FFX_API_RETURN_OK && n) {
if (n > 16) n = 16;
q.versionIds = ids;
q.versionNames = names;
r = A.query(nullptr, &q.header);
}
if (r != FFX_API_RETURN_OK || !n) {
rt_log("ffx4: the FSR SDK's loader lists no upscaler for this device (%u): FSR 4 off", (unsigned)r);
return 0;
}
char list[200] = "";
size_t len = 0;
int best = -1, best_major = 0;
for (uint64_t i = 0; i < n; i++) {
const char *nm = names[i] ? names[i] : "?";
len += (size_t)snprintf(list + len, sizeof list - len, "%s%s", i ? ", " : "", nm);
if (len >= sizeof list) len = sizeof list - 1;
int major = atoi(nm); // "4.1.2", and "4.1.2 *" for a version the driver brings
if (major >= 4 && major > best_major) best = (int)i, best_major = major;
}
if (best < 0) {
rt_log("ffx4: upscaler versions for this device: %s; none is FSR 4 (it needs a Radeon RX 6000, 7000 or 9000 card "
"or a supported Ryzen APU, and AMD's driver 26.10.1 or newer): FSR 3.1 stays", list);
return 0;
}
g_version = ids[best];
snprintf(g_name, sizeof g_name, "AMD FSR %.24s", names[best]); // the name is the library's memory: copied
for (char *p = g_name; *p; p++)
if (*p == '*') *p = 0; // the driver's mark
for (size_t k = strlen(g_name); k && g_name[k - 1] == ' '; k--) g_name[k - 1] = 0;
rt_log("ffx4: upscaler versions for this device: %s; FSR 4 is %s (id %#llx)", list, g_name, (unsigned long long)g_version);
return 1;
}
// One context per render and output size, as vk_ffx.cpp keeps them for FSR 3.1; the descriptors a context was made
// from stay with it, as the API asks ("must remain live until ffxDestroyContext").
struct Up {
ffxContext ctx = nullptr;
uint32_t w = 0, h = 0, ow = 0, oh = 0;
uint64_t used = 0;
ffxCreateContextDescUpscale desc = {};
ffxCreateBackendVKDesc backend = {};
ffxOverrideVersion version = {};
ffxCreateContextDescUpscaleVersion built = {};
} U[6];
uint64_t up_tick;
const uint64_t UP_RECENT = 8; // contexts used this recently may sit in a command buffer not submitted yet
FfxApiResource image(const VkFfxImage *i, uint32_t state, uint32_t usage) {
VkImageCreateInfo ci = {};
ci.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
ci.imageType = VK_IMAGE_TYPE_2D;
ci.format = i->format;
ci.extent = {i->width, i->height, 1};
ci.mipLevels = 1;
ci.arrayLayers = 1;
ci.usage = i->storage ? VK_IMAGE_USAGE_STORAGE_BIT : 0;
return ffxApiGetResourceVK((void *)i->image, ffxApiGetImageResourceDescriptionVK(i->image, ci, usage), state);
}
Up *context_for(uint32_t w, uint32_t h, uint32_t ow, uint32_t oh) {
up_tick++;
for (Up &u : U)
if (u.ctx && u.w == w && u.h == h && u.ow == ow && u.oh == oh) {
u.used = up_tick;
return &u;
}
Up *slot = nullptr, *lru = nullptr;
for (Up &u : U) {
if (!u.ctx) {
slot = &u;
break;
}
if (up_tick - u.used >= UP_RECENT && (!lru || u.used < lru->used)) lru = &u;
}
const VkCtx *c = vk_ctx();
if (!slot && lru) {
vk_queue_lock(), vkDeviceWaitIdle(c->device), vk_queue_unlock(); // its work may still be in flight
A.destroy(&lru->ctx, nullptr);
*lru = Up();
slot = lru;
}
if (!slot) return nullptr;
*slot = Up();
slot->built.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE_VERSION;
slot->built.version = FFX_UPSCALER_VERSION;
slot->version.header.type = FFX_API_DESC_TYPE_OVERRIDE_VERSION;
slot->version.header.pNext = &slot->built.header;
slot->version.versionId = g_version;
slot->backend.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_BACKEND_VK;
slot->backend.header.pNext = &slot->version.header;
slot->backend.deviceContext = {c->device, c->phys, vkGetDeviceProcAddr};
slot->desc.header.type = FFX_API_CREATE_CONTEXT_DESC_TYPE_UPSCALE;
slot->desc.header.pNext = &slot->backend.header;
slot->desc.flags =
FFX_UPSCALE_ENABLE_HIGH_DYNAMIC_RANGE | FFX_UPSCALE_ENABLE_DEPTH_INFINITE | FFX_UPSCALE_ENABLE_AUTO_EXPOSURE;
slot->desc.maxRenderSize = {w, h};
slot->desc.maxUpscaleSize = {ow, oh};
slot->desc.fpMessage = message;
uint64_t t0 = plat_now_ns();
ffxReturnCode_t r = A.create(&slot->ctx, &slot->desc.header, nullptr);
if (r != FFX_API_RETURN_OK || !slot->ctx) {
rt_log("ffx4: %s context creation at %ux%u -> %ux%u failed (%u)", g_name, w, h, ow, oh, (unsigned)r);
*slot = Up();
return nullptr;
}
slot->w = w, slot->h = h, slot->ow = ow, slot->oh = oh, slot->used = up_tick;
ffxQueryGetProviderVersion v = {};
v.header.type = FFX_API_QUERY_DESC_TYPE_GET_PROVIDER_VERSION;
A.query(&slot->ctx, &v.header);
FfxApiEffectMemoryUsage mem = {};
ffxQueryDescUpscaleGetGPUMemoryUsage mq = {};
mq.header.type = FFX_API_QUERY_DESC_TYPE_UPSCALE_GPU_MEMORY_USAGE;
mq.gpuMemoryUsageUpscaler = &mem;
A.query(&slot->ctx, &mq.header);
rt_log("ffx4: FSR %s upscaling at %ux%u -> %ux%u, made in %.0f ms, %.0f MiB of video memory",
v.versionName ? v.versionName : "4", w, h, ow, oh, (double)(plat_now_ns() - t0) / 1e6,
(double)mem.totalUsageInBytes / 1048576.0);
// The provider is asked for the version it runs: anything but a 4.x here means the loader gave another upscaler
if (v.versionName && atoi(v.versionName) < 4) {
rt_log("ffx4: the context runs FSR %s, not FSR 4: FSR 4 off", v.versionName);
A.destroy(&slot->ctx, nullptr);
*slot = Up();
return nullptr;
}
return slot;
}
void failed(const char *what, unsigned code) {
if (++g_failures == FAIL_MAX) {
rt_log("ffx4: %s failed %d times (last %u): FSR 4 is off for this run, FSR 3.1 takes its place", what, FAIL_MAX, code);
g_state.store(0, std::memory_order_release);
}
}
} // namespace
extern "C" int vk_ffx4_available(void) {
int s = g_state.load(std::memory_order_acquire);
if (s >= 0) return s;
std::lock_guard<std::mutex> hold(g_lock);
s = g_state.load(std::memory_order_acquire);
if (s >= 0) return s;
s = probe();
if (s >= 0) g_state.store(s, std::memory_order_release);
return s > 0;
}
extern "C" const char *vk_ffx4_name(void) { return g_name; }
extern "C" int vk_ffx4_upscale(VkCommandBuffer cb, const VkFfxImage *color, const VkFfxImage *depth, const VkFfxImage *mv,
const VkFfxImage *out, float jx, float jy, int reset, float dt_ms, float fov_y) {
if (!vk_ffx4_available()) return 0;
Up *u = context_for(color->width, color->height, out->width, out->height);
if (!u) {
failed("making a context", 0);
return 0;
}
ffxDispatchDescUpscale d = {};
d.header.type = FFX_API_DISPATCH_DESC_TYPE_UPSCALE;
d.commandList = cb;
// Every image is in GENERAL, which the back end reads as its unordered-access state, and is left there
d.color = image(color, FFX_API_RESOURCE_STATE_UNORDERED_ACCESS, 0);
d.depth = image(depth, FFX_API_RESOURCE_STATE_UNORDERED_ACCESS, 0);
d.motionVectors = image(mv, FFX_API_RESOURCE_STATE_UNORDERED_ACCESS, 0);
d.output = image(out, FFX_API_RESOURCE_STATE_UNORDERED_ACCESS, FFX_API_RESOURCE_USAGE_UAV);
d.jitterOffset = {jx, jy};
d.motionVectorScale = {1.0f, 1.0f};
d.renderSize = {color->width, color->height};
d.upscaleSize = {out->width, out->height};
int sharp = cfg_int("NX2NAVI_SHARPNESS"); // the slider drives the upscaler's own sharpening, as for FSR 3.1
d.enableSharpening = sharp > 0;
d.sharpness = sharp > 100 ? 1.0f : sharp / 100.0f;
d.frameTimeDelta = dt_ms;
d.preExposure = 1.0f;
d.reset = reset != 0;
d.cameraNear = 0.1f; // Ocarina's projection (vk_dlaa.c ocam_vp): near 0.1, far at infinity
d.cameraFar = 1e8f;
d.cameraFovAngleVertical = fov_y > 0 ? fov_y : 1.0f;
d.viewSpaceToMetersFactor = 0.01f; // the game's units are centimetres
ffxReturnCode_t r = A.dispatch(&u->ctx, &d.header);
if (r != FFX_API_RETURN_OK) {
static int told;
if (told++ < 8) rt_log("ffx4: %s dispatch failed (%u)", g_name, (unsigned)r);
failed("a dispatch", (unsigned)r);
return 0;
}
return 1;
}
extern "C" void vk_ffx4_release(void) {
if (!A.destroy) return;
for (Up &u : U)
if (u.ctx) A.destroy(&u.ctx, nullptr), u = Up();
}
#endif // _WIN32

View File

@@ -87,6 +87,8 @@ static struct {
VkShaderStageFlags sg32_stages; // stages that accept requiredSubgroupSize = 32 (0: not available) VkShaderStageFlags sg32_stages; // stages that accept requiredSubgroupSize = 32 (0: not available)
int reconverge; // modules with subgroup ops get MaximallyReconvergesKHR (spirv_reconverge) int reconverge; // modules with subgroup ops get MaximallyReconvergesKHR (spirv_reconverge)
uint32_t nan_preserve; // float widths that get SignedZeroInfNanPreserve (spirv_nan_preserve): NP_16|NP_32|NP_64 uint32_t nan_preserve; // float widths that get SignedZeroInfNanPreserve (spirv_nan_preserve): NP_16|NP_32|NP_64
int nan_bits; // NaN tests as integer bit tests (spirv_nan_bits)
volatile uint32_t nan_bits_tests, nan_bits_selects, nan_bits_modules; // rewritten so far (the first log line)
VkDynamicState dyn[32]; VkDynamicState dyn[32];
uint32_t n_dyn; uint32_t n_dyn;
PFN_vkCmdPushDescriptorSetKHR push; PFN_vkCmdPushDescriptorSetKHR push;
@@ -658,6 +660,12 @@ static void nan_preserve_init(VkCtx *c) {
(fc.shaderSignedZeroInfNanPreserveFloat32 ? NP_32 : 0) | (fc.shaderSignedZeroInfNanPreserveFloat32 ? NP_32 : 0) |
(fc.shaderSignedZeroInfNanPreserveFloat64 ? NP_64 : 0); (fc.shaderSignedZeroInfNanPreserveFloat64 ? NP_64 : 0);
P.nan_preserve = want && (can & NP_32) ? can : 0; P.nan_preserve = want && (can & NP_32) ? can : 0;
// NX2NAVI_VK_NAN_BITS: 1 every driver, 0 none; unset: AMD's driver for RDNA 1 and 2 (spirv_nan_bits)
const char *nb = cfg_get("NX2NAVI_VK_NAN_BITS");
P.nan_bits = nb && *nb ? strcmp(nb, "0") != 0 : vk_caps.amd_sc;
if (P.nan_bits)
rt_log("vk_pipeline: game shaders test for NaN on the bits of the number, not as a float (%s)",
nb && *nb ? "NX2NAVI_VK_NAN_BITS=1" : "AMD's driver for RDNA 1 and 2");
if (P.nan_preserve) if (P.nan_preserve)
rt_log("vk_pipeline: game shaders keep NaN, infinity and signed zero (SignedZeroInfNanPreserve for %s32%s-bit " rt_log("vk_pipeline: game shaders keep NaN, infinity and signed zero (SignedZeroInfNanPreserve for %s32%s-bit "
"floats%s)", can & NP_16 ? "16, " : "", can & NP_64 ? ", 64" : "", set ? ", NX2NAVI_VK_NAN_PRESERVE=1" : ""); "floats%s)", can & NP_16 ? "16, " : "", can & NP_64 ? ", 64" : "", set ? ", NX2NAVI_VK_NAN_PRESERVE=1" : "");
@@ -1478,6 +1486,125 @@ static uint32_t *spirv_nan_preserve(const uint32_t *w, uint64_t n, uint32_t widt
return o; return o;
} }
// NaN tests that no compiler can drop (P.nan_bits). The game's shaders and the translator's own guards test for NaN with
// OpIsNan: 48,717 of an install's 54,959 translated modules, 26 tests each on average (the game's unordered
// comparisons, and the guard that keeps NaN out of every float colour output, patch 0027, so that one NaN texel does not
// spread through bloom and blur into blocks of black and white). SignedZeroInfNanPreserve asks the driver to keep NaN,
// but whether a compiler that reasons about floats keeps an isnan through every optimisation is up to it. The reports
// of black and white blocks, on Navi, on Link next to her and on bright surfaces seen from inside a house, come from
// RX 5000 and 6000 cards (#41, #110, #117), whose Windows driver compiles with "AMD proprietary shader compiler"
// (vk_caps.amd_sc); RDNA 3 and 4 (LLPC) draw the same scenes clean. It is not known whether that compiler keeps the
// mode: on it each float32 test becomes integer arithmetic on the bits, which means the same under any float
// assumption:
// isnan(x) -> (bitcast<uint>(x) & 0x7fffffff) > 0x7f800000
// for scalars and vectors of 32-bit floats; tests of 16- and 64-bit floats stay. A float32 select with a constant
// operand whose bits are a NaN (an integer mask such as 0xffffffff that the translator types as float) becomes a
// select of the bits (issue #156: on an RX 9070 XT without the mode such a select between 1 and -1 gave 2^32).
// NULL: nothing to change (or no memory); *tests and *selects count what changed.
static uint32_t *spirv_nan_bits(const uint32_t *w, uint64_t n, uint64_t *out_n, uint32_t *tests, uint32_t *selects) {
enum { OP_UNDEF = 1, OP_TYPE_BOOL = 20, OP_SPEC_CONSTANT = 50, OP_SPEC_CONSTANT_COMPOSITE = 51, OP_STORE = 62,
OP_BITCAST = 124, OP_IS_NAN = 156, OP_SELECT = 169, OP_UGREATER = 172, OP_BITWISE_AND = 199 };
*tests = *selects = 0;
if (n < 5 || w[3] >= (1u << 22)) return NULL;
uint32_t bound = w[3];
uint32_t *rtype = calloc(bound, sizeof *rtype), *vec_comp = calloc(bound, sizeof *vec_comp);
uint8_t *f32 = calloc(bound, 1), *vec_n = calloc(bound, 1), *nan_const = calloc(bound, 1);
uint32_t *o = NULL;
if (!rtype || !vec_comp || !f32 || !vec_n || !nan_const) goto out;
uint32_t tu = 0, uvec[5] = {0}; // uint32 and its vectors by component count
uint64_t fn_at = 0;
int vec_used[5] = {0};
// Ids that are not results of the instruction's second word, inside functions: first assignment wins anyway, as
// a definition comes before its uses (OpPhi operands aside, which this never reads).
for (uint64_t i = 5; i < n;) {
uint32_t op = w[i] & 0xffff, l = w[i] >> 16;
if (!l || i + l > n) goto out;
const uint32_t *a = w + i + 1;
if (!fn_at) {
if (op == SPV_OP_FUNCTION) fn_at = i;
else if (op == SPV_OP_TYPE_FLOAT && l >= 3 && a[0] < bound && a[1] == 32) f32[a[0]] = 1;
else if (op == SPV_OP_TYPE_INT && l >= 4 && a[1] == 32 && a[2] == 0 && !tu) tu = a[0];
else if (op == SPV_OP_TYPE_VECTOR && l >= 4 && a[0] < bound && a[2] >= 2 && a[2] <= 4) {
vec_comp[a[0]] = a[1], vec_n[a[0]] = (uint8_t)a[2];
if (tu && a[1] == tu && !uvec[a[2]]) uvec[a[2]] = a[0];
} else if ((op == SPV_OP_CONSTANT || op == SPV_OP_CONSTANT_COMPOSITE || op == SPV_OP_CONSTANT_NULL ||
op == OP_UNDEF || op == SPV_OP_VARIABLE || op == OP_SPEC_CONSTANT ||
op == OP_SPEC_CONSTANT_COMPOSITE) && l >= 3 && a[1] < bound) {
rtype[a[1]] = a[0];
if (op == SPV_OP_CONSTANT && l == 4 && a[0] < bound && f32[a[0]] && (a[2] & 0x7fffffffu) > 0x7f800000u)
nan_const[a[1]] = 1;
}
}
if (fn_at) {
int no_result = op == OP_STORE || op == 63 || op == 64 || op == 8 || op == 317 || (op >= 246 && op <= 255) ||
op == 99 || op == 224 || op == 225 || op == 228 || op == 56 || op == 218 || op == 219 ||
op == 5294 || op == 5295 || op == 4416 || op == 5380 || op == 5364 || op == 5365;
if (!no_result && op != SPV_OP_FUNCTION && l >= 3 && a[1] < bound && !rtype[a[1]]) rtype[a[1]] = a[0];
if (op == OP_IS_NAN && l == 4 && a[2] < bound) {
uint32_t t = rtype[a[2]];
if (t < bound && f32[t]) ++*tests;
else if (t < bound && vec_n[t] && vec_comp[t] < bound && f32[vec_comp[t]]) ++*tests, vec_used[vec_n[t]] = 1;
} else if (op == OP_SELECT && l == 6 && a[0] < bound && f32[a[0]] && a[3] < bound && a[4] < bound &&
(nan_const[a[3]] || nan_const[a[4]])) {
++*selects;
}
}
i += l;
}
if (!fn_at || (!*tests && !*selects)) goto out;
// the declarations go right before the first function: uint32 and its vectors where missing, then the constants
uint32_t next = bound, decl[64], nd = 0;
if (!tu) tu = next++, decl[nd++] = 4u << 16 | SPV_OP_TYPE_INT, decl[nd++] = tu, decl[nd++] = 32, decl[nd++] = 0;
uint32_t c_mag = next++, c_inf = next++, cv_mag[5] = {0}, cv_inf[5] = {0};
for (int k = 2; k <= 4; k++)
if (vec_used[k] && !uvec[k])
uvec[k] = next++, decl[nd++] = 4u << 16 | SPV_OP_TYPE_VECTOR, decl[nd++] = uvec[k], decl[nd++] = tu, decl[nd++] = (uint32_t)k;
decl[nd++] = 4u << 16 | SPV_OP_CONSTANT, decl[nd++] = tu, decl[nd++] = c_mag, decl[nd++] = 0x7fffffffu;
decl[nd++] = 4u << 16 | SPV_OP_CONSTANT, decl[nd++] = tu, decl[nd++] = c_inf, decl[nd++] = 0x7f800000u;
for (int k = 2; k <= 4; k++) {
if (!vec_used[k]) continue;
cv_mag[k] = next++, cv_inf[k] = next++;
decl[nd++] = (uint32_t)(3 + k) << 16 | SPV_OP_CONSTANT_COMPOSITE, decl[nd++] = uvec[k], decl[nd++] = cv_mag[k];
for (int j = 0; j < k; j++) decl[nd++] = c_mag;
decl[nd++] = (uint32_t)(3 + k) << 16 | SPV_OP_CONSTANT_COMPOSITE, decl[nd++] = uvec[k], decl[nd++] = cv_inf[k];
for (int j = 0; j < k; j++) decl[nd++] = c_inf;
}
uint64_t cap = n + nd + 10ull * *tests + 12ull * *selects;
o = malloc(cap * 4);
if (!o) goto out;
memcpy(o, w, fn_at * 4);
uint64_t p = fn_at;
memcpy(o + p, decl, nd * 4), p += nd;
for (uint64_t i = fn_at; i < n;) {
uint32_t op = w[i] & 0xffff, l = w[i] >> 16;
const uint32_t *a = w + i + 1;
uint32_t t = op == OP_IS_NAN && l == 4 && a[2] < bound ? rtype[a[2]] : 0;
int k = t && t < bound ? (f32[t] ? 1 : vec_n[t] && vec_comp[t] < bound && f32[vec_comp[t]] ? vec_n[t] : 0) : 0;
if (k) {
uint32_t ut = k == 1 ? tu : uvec[k], mag = k == 1 ? c_mag : cv_mag[k], inf = k == 1 ? c_inf : cv_inf[k];
uint32_t bits = next++, low = next++;
o[p++] = 4u << 16 | OP_BITCAST, o[p++] = ut, o[p++] = bits, o[p++] = a[2];
o[p++] = 5u << 16 | OP_BITWISE_AND, o[p++] = ut, o[p++] = low, o[p++] = bits, o[p++] = mag;
o[p++] = 5u << 16 | OP_UGREATER, o[p++] = a[0], o[p++] = a[1], o[p++] = low, o[p++] = inf;
} else if (op == OP_SELECT && l == 6 && a[0] < bound && f32[a[0]] && a[3] < bound && a[4] < bound &&
(nan_const[a[3]] || nan_const[a[4]])) {
uint32_t x = next++, y = next++, s = next++;
o[p++] = 4u << 16 | OP_BITCAST, o[p++] = tu, o[p++] = x, o[p++] = a[3];
o[p++] = 4u << 16 | OP_BITCAST, o[p++] = tu, o[p++] = y, o[p++] = a[4];
o[p++] = 6u << 16 | OP_SELECT, o[p++] = tu, o[p++] = s, o[p++] = a[2], o[p++] = x, o[p++] = y;
o[p++] = 4u << 16 | OP_BITCAST, o[p++] = a[0], o[p++] = a[1], o[p++] = s;
} else {
memcpy(o + p, w + i, l * 4), p += l;
}
i += l;
}
o[3] = next;
*out_n = p;
out:
free(rtype), free(vec_comp), free(f32), free(vec_n), free(nan_const);
return o;
}
static int spirv_mark_list_test(const char *list); // texture pool marks, below static int spirv_mark_list_test(const char *list); // texture pool marks, below
// --selftest (main.c): spirv_nan_preserve on a small fragment module, without a device. Returns the number of failures. // --selftest (main.c): spirv_nan_preserve on a small fragment module, without a device. Returns the number of failures.
@@ -1523,6 +1650,42 @@ int vk_pipeline_spirv_selftest(void) {
failures++; failures++;
} }
printf("spirv: SignedZeroInfNanPreserve rewrite: %s\n", failures ? "FAIL" : "ok"); printf("spirv: SignedZeroInfNanPreserve rewrite: %s\n", failures ? "FAIL" : "ok");
{ // spirv_nan_bits: a scalar and a vec2 isnan, a select on a NaN constant; no uint32 type in the module
static const uint32_t m[] = {
0x07230203, 0x00010300, 0, 20, 0,
2u << 16 | 17, 1, // OpCapability Shader
3u << 16 | 14, 0, 1, // OpMemoryModel Logical GLSL450
5u << 16 | 15, 5, 1, 0x6e69616d, 0, // OpEntryPoint GLCompute %1 "main"
2u << 16 | 19, 2, // %2 void
3u << 16 | 33, 3, 2, // %3 fn
3u << 16 | 22, 4, 32, // %4 float
2u << 16 | 20, 5, // %5 bool
4u << 16 | 23, 6, 4, 2, // %6 vec2
4u << 16 | 23, 7, 5, 2, // %7 bvec2
4u << 16 | 43, 4, 8, 0xffffffffu, // %8 = NaN bits
4u << 16 | 43, 4, 9, 0x3f800000u, // %9 = 1.0
5u << 16 | 44, 6, 10, 8, 9, // %10 = vec2(%8, %9)
3u << 16 | 41, 5, 11, // %11 = OpConstantTrue
5u << 16 | 54, 2, 1, 0, 3, // %1 = OpFunction
2u << 16 | 248, 12, // OpLabel
4u << 16 | 156, 5, 13, 9, // %13 = OpIsNan bool %9
4u << 16 | 156, 7, 14, 10, // %14 = OpIsNan bvec2 %10
6u << 16 | 169, 4, 15, 11, 9, 8, // %15 = OpSelect float %11 %9 %8
1u << 16 | 253, 1u << 16 | 56}; // OpReturn, OpFunctionEnd
uint64_t on = 0;
uint32_t tests = 0, sels = 0, isnan_left = 0, ugt = 0, int32 = 0, bitcasts = 0;
uint32_t *o = spirv_nan_bits(m, sizeof m / 4, &on, &tests, &sels);
for (uint64_t i = 5; o && i < on;) {
uint32_t op = o[i] & 0xffff, l = o[i] >> 16;
if (!l) break;
isnan_left += op == 156, ugt += op == 172, int32 += op == 21 && o[i + 2] == 32, bitcasts += op == 124;
i += l;
}
int bad = !o || tests != 2 || sels != 1 || isnan_left || ugt != 2 || int32 != 1 || bitcasts != 5 || o[3] <= 20;
printf("spirv: integer NaN tests rewrite: %s\n", bad ? "FAIL" : "ok");
failures += bad;
free(o);
}
const char *list = cfg_get("NX2NAVI_SPV_MARK_TEST"); const char *list = cfg_get("NX2NAVI_SPV_MARK_TEST");
if (list && *list) failures += spirv_mark_list_test(list); if (list && *list) failures += spirv_mark_list_test(list);
return failures; return failures;
@@ -1867,6 +2030,18 @@ static VkShaderModule make_module(const uint32_t *w, uint64_t words, int early_o
free(fixed); free(fixed);
w = fixed = np, words = np_n; w = fixed = np, words = np_n;
} }
uint64_t nb_n = 0;
uint32_t nb_tests = 0, nb_sels = 0;
uint32_t *nb = P.nan_bits ? spirv_nan_bits(w, words, &nb_n, &nb_tests, &nb_sels) : NULL;
if (nb) {
free(fixed);
w = fixed = nb, words = nb_n;
__atomic_fetch_add(&P.nan_bits_tests, nb_tests, __ATOMIC_RELAXED);
__atomic_fetch_add(&P.nan_bits_selects, nb_sels, __ATOMIC_RELAXED);
if (__atomic_add_fetch(&P.nan_bits_modules, 1, __ATOMIC_RELAXED) == 1)
rt_log("vk_pipeline: first module with NaN tests made integer: %u tests, %u selects of NaN bits", nb_tests,
nb_sels);
}
if (P.feedback >= 2) mm_hash = fnv(FNV0, w, (size_t)words * 4); if (P.feedback >= 2) mm_hash = fnv(FNV0, w, (size_t)words * 4);
VkShaderModuleCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = (size_t)words * 4, .pCode = w}; VkShaderModuleCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = (size_t)words * 4, .pCode = w};
VkShaderModule m = VK_NULL_HANDLE; VkShaderModule m = VK_NULL_HANDLE;

View File

@@ -18,7 +18,9 @@ Run: python tests/launcher_test.py (Python 3.14 for the zstd tests; the window
a source checkout's build/xlate/), the prompts step with a stand-in prompt tool, the object cache of the compile a source checkout's build/xlate/), the prompts step with a stand-in prompt tool, the object cache of the compile
step with the system's C compiler, and its windres call under folders with spaces (a script in windres's place) step with the system's C compiler, and its windres call under folders with spaces (a script in windres's place)
- jobs: an install driven by a fake make_game.py, with and without the prompts row - jobs: an install driven by a fake make_game.py, with and without the prompts row
- the look: the colour schemes, the background picture's fitting and kept copy, the sound effects (low by default, - Add to Steam: the binary shortcuts file read and written back unchanged, a shortcut added and updated in place
- the look: the colour schemes with the Custom one, its colour square and a typed hex code, the background picture's
fitting below the title band and kept copy, the sound effects (low by default,
only the game's own select and back sounds, decoded from a made-up .bwav) only the game's own select and back sounds, decoded from a made-up .bwav)
- the window: --selftest draws every screen (skipped without a display) - the window: --selftest draws every screen (skipped without a display)
""" """
@@ -2708,6 +2710,92 @@ class LookTest(Tmp):
with self.assertRaises(pic.PictureError): with self.assertRaises(pic.PictureError):
pic.load(self.tmp / 'gone.png') pic.load(self.tmp / 'gone.png')
def test_the_custom_scheme(self):
art = self.art
self.assertEqual(art.custom_palette({}), art.BASE) # nothing picked yet: the first scheme's colours
slots = art.CUSTOM_SLOTS
self.assertEqual(list(slots), ['background', 'panel', 'buttons'])
parts = [k for _, keys, _ in slots.values() for k in keys]
self.assertEqual(len(parts), len(set(parts)), 'a colour in two parts')
self.assertEqual(set(parts), set(art.GROUPS['scene'] + art.GROUPS['wood'] + art.GROUPS['accent']))
pal = art.custom_palette({'background': '#3A7BD5', 'panel': '#203040', 'buttons': '#802020'})
self.assertEqual(pal['tint_mid'], '#3a7bd5') # the picked colours exactly where they stand in
self.assertEqual(pal['panel'], '#203040')
self.assertEqual(pal['label_mid'], '#802020')
only = art.custom_palette({'buttons': '#802020'}) # Button Color: the buttons and nothing else
self.assertLessEqual({k for k in art.BASE if only[k] != art.BASE[k]}, set(slots['buttons'][1]))
for k in ('label_top', 'label_bottom', 'value', 'orange', 'orange_light'): # the orange choices too
self.assertNotEqual(only[k], art.BASE[k], k)
for k in ('panel', 'desc', 'wood_1', 'window', 'tint_mid'): # not the panels, the title band, the backdrop
self.assertEqual(only[k], art.BASE[k], k)
self.assertEqual(round(art.hls(only['orange'])[0] * 360), 0) # the choices in the picked hue, lighter
self.assertGreater(art.hls(only['orange'])[1], art.hls(only['label_mid'])[1])
panel = art.custom_palette({'panel': '#203040'})
self.assertLessEqual({k for k in art.BASE if panel[k] != art.BASE[k]}, set(slots['panel'][1]))
self.assertEqual(panel['label_mid'], art.BASE['label_mid'])
for slot, (ref, keys, _) in slots.items():
for k in keys: # lighter than the picked colour where the first scheme's is lighter
if art.hls(art.BASE[k])[1] > art.hls(art.BASE[ref])[1] + 0.02:
self.assertGreater(art.hls(pal[k])[1], art.hls(pal[ref])[1], k)
self.assertGreater(art.luminance(pal['text']), 0.6) # light text on dark buttons
light = art.custom_palette({'buttons': '#f0e0a0'})
self.assertLess(art.luminance(light['text']), 0.3) # and dark text on light ones
self.assertGreater(art.luminance(light['desc_text']), 0.6) # the description box's text stays as it was
light = art.custom_palette({'panel': '#f0e0a0'})
self.assertLess(art.luminance(light['desc_text']), 0.3) # dark on a light panel
self.assertGreater(art.luminance(light['text']), 0.6)
self.assertEqual(art.custom_palette({'buttons': 'red', 'background': None}), art.BASE)
held = art.PALETTE
try:
self.assertEqual(art.set_theme('custom', {'buttons': '#802020', 'other': '#000000'}), 'custom')
self.assertEqual(held['label_mid'], '#802020')
self.assertEqual(art.CUSTOM, {'background': art.BASE['tint_mid'], 'panel': art.BASE['panel'],
'buttons': '#802020'})
art.set_theme('custom', {})
self.assertEqual(dict(held), art.BASE)
finally:
art.set_theme('forest', {})
def test_the_colour_square(self):
import numpy as np
art = self.art
sq = art.color_square(40, 30, 0.0) # red
self.assertEqual(sq.shape, (30, 40, 4))
self.assertTrue(np.allclose(sq[0, -1, :3], [1, 0, 0], atol=0.05)) # top right: the full colour
self.assertLess(sq[-1, :, :3].max(), 0.05) # the bottom row: black
self.assertLess(np.ptp(sq[0, 0, :3]), 0.05) # left: grey
bar = art.hue_bar(60, 4)
self.assertTrue(np.allclose(bar[0, 20, :3], [0, 1, 0], atol=0.1)) # a third of the way: green
self.assertTrue(np.allclose(bar[0, 40, :3], [0, 0, 1], atol=0.1)) # two thirds: blue
def test_a_typed_hex_code(self):
try:
from launcher.ui.app import App
except ImportError:
self.skipTest('needs tkinter')
parse = App.parse_hex
self.assertEqual(parse('#3A7BD5'), (58, 123, 213))
self.assertEqual(parse(' 3a7bd5 '), (58, 123, 213))
self.assertEqual(parse('#37d'), (0x33, 0x77, 0xdd))
self.assertIsNone(parse('#3A7BD'))
self.assertIsNone(parse('blue'))
def test_the_picture_starts_below_the_band_and_is_never_stretched(self):
import numpy as np
art, pic = self.art, self.picture
store = self.tmp / 'background.npy'
old = np.zeros((1024, 1600, 3), dtype=np.uint8) # a copy an older launcher kept for the window
old[:, :800, 0] = 255 # left half red: a circle stays a circle
np.save(store, old)
self.assertEqual(pic.kept_shape(store), (1024, 1600))
back = pic.kept(store, 1000, 580) # cut to the new shape, not squeezed
self.assertEqual(back.shape, (580, 1000, 3))
self.assertGreater(back[:, 490, 0].min(), 0.95)
self.assertLess(back[:, 510, 0].max(), 0.05)
img = art.backdrop(200, 128, 1.0, np.ones((116, 200, 3), dtype=np.float32), 0.0, top=12)
self.assertLess(img[6, 100, :3].max(), 0.2) # under the band: the scheme's colour
self.assertGreater(img[20, 100, :3].min(), 0.7) # from the band's end on: the picture
def test_ppm(self): def test_ppm(self):
import numpy as np import numpy as np
px = bytes(range(18)) px = bytes(range(18))
@@ -2839,6 +2927,60 @@ def have_display():
@unittest.skipUnless(have_display(), 'needs tkinter, numpy and a display') @unittest.skipUnless(have_display(), 'needs tkinter, numpy and a display')
class SteamTest(Tmp):
"""launcher/steam.py on made-up Steam files: the binary shortcuts file read and written back unchanged, our
shortcut added beside another and updated in place, its id as Steam computes it, the accounts that signed in."""
def other(self):
from launcher import steam
exe = '"C:\\Games\\Other\\other.exe"'
entry = [[steam.T_INT, 'appid', struct.pack('<I', steam.appid(exe, 'Other'))], [steam.T_STR, 'AppName', 'Other'],
[steam.T_STR, 'Exe', exe], [steam.T_STR, 'StartDir', '"C:\\Games\\Other\\"'],
[steam.T_STR, 'icon', ''], [steam.T_INT, 'LastPlayTime', struct.pack('<I', 1234)],
[steam.T_STR, 'sortas', ''], [steam.T_MAP, 'tags', [[steam.T_STR, '0', 'Favorite']]]]
return steam.vdf_dump([[steam.T_MAP, 'shortcuts', [[steam.T_MAP, '0', entry]]]])
def test_round_trip_add_and_update(self):
from launcher import steam
b = self.other()
self.assertEqual(b[-4:], b'\x08\x08\x08\x08') # tags, the shortcut, shortcuts, the file
self.assertEqual(steam.vdf_dump(steam.vdf_load(b)), b)
self.assertFalse(steam.has_shortcut(b))
new, sid = steam.add_shortcut(b, '"C:\\NX2navi\\python\\pythonw.exe"', '"C:\\NX2navi"',
'"C:\\NX2navi\\data\\steam_play.pyw"', 'C:\\grid\\x_icon.png')
self.assertEqual(sid, steam.appid('"C:\\NX2navi\\python\\pythonw.exe"', steam.NAME))
self.assertTrue(sid & 0x80000000)
self.assertTrue(new.startswith(b[:-2])) # the other shortcut stays byte for byte
self.assertTrue(steam.has_shortcut(new))
items = steam.vdf_load(new)[0][2]
self.assertEqual([k for _, k, _ in items], ['0', '1'])
ours = {k: v for _, k, v in items[1][2]}
self.assertEqual(ours['AppName'], 'The Legend of Zelda Ocarina of Time')
self.assertEqual(struct.unpack('<I', ours['appid'])[0], sid)
self.assertEqual(ours['LaunchOptions'], '"C:\\NX2navi\\data\\steam_play.pyw"')
self.assertEqual(ours['AllowOverlay'], struct.pack('<I', 1))
again, _ = steam.add_shortcut(new, '"D:\\NX2navi\\python\\pythonw.exe"', '"D:\\NX2navi"', '', 'x')
items = steam.vdf_load(again)[0][2]
self.assertEqual(len(items), 2) # moved launcher: the same shortcut, updated
self.assertEqual({k: v for _, k, v in items[1][2]}['StartDir'], '"D:\\NX2navi"')
with self.assertRaises(steam.SteamError):
steam.vdf_load(b[:-5])
def test_new_file_and_accounts(self):
from launcher import steam
new, _ = steam.add_shortcut(b'', '"x.exe"', '"."', '', '')
self.assertTrue(steam.has_shortcut(new))
root = self.tmp / 'Steam'
for a in ('0', '1046310423', '22'):
(root / 'userdata' / a / 'config').mkdir(parents=True)
(root / 'config').mkdir()
(root / 'config' / 'loginusers.vdf').write_text('"users"\n{\n\t"76561199006576151"\n\t{\n\t}\n}\n')
self.assertEqual(steam.accounts(root), [root / 'userdata' / '1046310423' / 'config'])
(root / 'config' / 'loginusers.vdf').unlink()
self.assertEqual(steam.accounts(root), sorted([root / 'userdata' / '1046310423' / 'config',
root / 'userdata' / '22' / 'config']))
class WhilePlayingTest(Tmp): class WhilePlayingTest(Tmp):
def test_the_games_restart_does_not_bring_the_launcher_back(self): def test_the_games_restart_does_not_bring_the_launcher_back(self):
try: try:

View File

@@ -126,6 +126,7 @@ XLATE_NAME = 'nx2navi_xlate.exe' if WIN else 'nx2navi_xlate'
# through a runtime header, is compiled on the player's PC; every other runtime source can come prebuilt. # through a runtime header, is compiled on the player's PC; every other runtime source can come prebuilt.
GENERATED_HEADERS = ('layout.h', 'patches.h', 'romfs_config.h') GENERATED_HEADERS = ('layout.h', 'patches.h', 'romfs_config.h')
RUNTIME_LIB = 'libnx2navirt.a' RUNTIME_LIB = 'libnx2navirt.a'
FFX4_DLLS = ('amd_fidelityfx_loader_vk.dll', 'amd_fidelityfx_upscaler_vk.dll') # AMD's FSR SDK 2.4, for FSR 4
RUNTIME_PATTERNS = ('*.c', '*.cpp', 'platform/*.c', 'ui/*.cpp', 'third_party/imgui/*.cpp', RUNTIME_PATTERNS = ('*.c', '*.cpp', 'platform/*.c', 'ui/*.cpp', 'third_party/imgui/*.cpp',
'third_party/imgui/backends/*.cpp') 'third_party/imgui/backends/*.cpp')
INCLUDE = re.compile(r'^[ \t]*#[ \t]*include[ \t]+"([^"]+)"', re.M) INCLUDE = re.compile(r'^[ \t]*#[ \t]*include[ \t]+"([^"]+)"', re.M)
@@ -1358,6 +1359,9 @@ def step_compile(out, cache_dir, msys, jobs, romfs_job=None, update=False):
copy_if_changed(xlate / name, out / name) copy_if_changed(xlate / name, out / name)
if (KIT / 'bin' / 'amd_fidelityfx_vk.dll').is_file(): # FSR 3.1 (runtime/vk_ffx.cpp) if (KIT / 'bin' / 'amd_fidelityfx_vk.dll').is_file(): # FSR 3.1 (runtime/vk_ffx.cpp)
copy_if_changed(KIT / 'bin' / 'amd_fidelityfx_vk.dll', out / 'amd_fidelityfx_vk.dll') copy_if_changed(KIT / 'bin' / 'amd_fidelityfx_vk.dll', out / 'amd_fidelityfx_vk.dll')
for name in FFX4_DLLS: # FSR 4 (runtime/vk_ffx4.cpp): both or neither
if all((KIT / 'bin' / n).is_file() for n in FFX4_DLLS):
copy_if_changed(KIT / 'bin' / name, out / name)
kept = place_dlss(out, linux=not WIN) # NVIDIA DLSS (runtime/vk_dlaa.c): this platform's library from the kit kept = place_dlss(out, linux=not WIN) # NVIDIA DLSS (runtime/vk_dlaa.c): this platform's library from the kit
if kept: if kept:
say(f' {kept}') say(f' {kept}')

View File

@@ -1,6 +1,7 @@
"""Assemble the build kit: what a player needs to build Ocarina of Time on their own PC with tools/make_game.py. """Assemble the build kit: what a player needs to build Ocarina of Time on their own PC with tools/make_game.py.
python tools/make_kit.py --xlate <dir with nx2navi_xlate.exe and .id> [--ffx amd_fidelityfx_vk.dll] python tools/make_kit.py --xlate <dir with nx2navi_xlate.exe and .id> [--ffx amd_fidelityfx_vk.dll]
[--ffx4 FOLDER]
[--dlss nvngx_dlss.dll | --no-dlss] [--dlssg nx2navi_dlssg.dll [--streamline SDK]] [--dlss nvngx_dlss.dll | --no-dlss] [--dlssg nx2navi_dlssg.dll [--streamline SDK]]
[--prompt-art FOLDER [FOLDER ...]] [--out build/kit] [--zip] [--prompt-art FOLDER [FOLDER ...]] [--out build/kit] [--zip]
@@ -10,9 +11,9 @@ translator built from tools/xlate,
NVIDIA's DLSS library with its notice (tools/dlss_pin.py: downloaded from NVIDIA's DLSS SDK repository and checked, NVIDIA's DLSS library with its notice (tools/dlss_pin.py: downloaded from NVIDIA's DLSS SDK repository and checked,
or --dlss; not with --no-dlss), DLSS Frame Generation in bin/dlssg/ with --dlssg (nx2navi_dlssg.dll from or --dlss; not with --no-dlss), DLSS Frame Generation in bin/dlssg/ with --dlssg (nx2navi_dlssg.dll from
tools/build_dlssg.py beside NVIDIA Streamline's runtime, tools/streamline_pin.py: downloaded from NVIDIA's Streamline tools/build_dlssg.py beside NVIDIA Streamline's runtime, tools/streamline_pin.py: downloaded from NVIDIA's Streamline
SDK release and checked, or --streamline), AMD's FSR 3.1 library with --ffx, the button art with --prompt-art, and SDK release and checked, or --streamline), AMD's FSR 3.1 library with --ffx, its two FSR 4 libraries with --ffx4, the
README-BuildKit.md; no game code, data or anything generated from the game. check_content runs over the folder before button art with --prompt-art, and README-BuildKit.md; no game code, data or anything generated from the game.
it is zipped. check_content runs over the folder before it is zipped.
--prompt-art names folders that hold XGamepad, P5Gamepad and Keyboard_Mouse, or those three folders themselves: the --prompt-art names folders that hold XGamepad, P5Gamepad and Keyboard_Mouse, or those three folders themselves: the
pictures tools/pad_prompts.py reads go into the kit's prompt-art folder (tools/prompt_art.py art_files), and pictures tools/pad_prompts.py reads go into the kit's prompt-art folder (tools/prompt_art.py art_files), and
@@ -50,6 +51,8 @@ def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('--xlate', type=Path, required=True, help='folder with nx2navi_xlate.exe and nx2navi_xlate.id') ap.add_argument('--xlate', type=Path, required=True, help='folder with nx2navi_xlate.exe and nx2navi_xlate.id')
ap.add_argument('--ffx', type=Path, help="AMD's signed amd_fidelityfx_vk.dll (FidelityFX SDK 1.1.4, MIT) for FSR 3.1") ap.add_argument('--ffx', type=Path, help="AMD's signed amd_fidelityfx_vk.dll (FidelityFX SDK 1.1.4, MIT) for FSR 3.1")
ap.add_argument('--ffx4', type=Path, help="the folder with AMD's signed amd_fidelityfx_loader_vk.dll and "
'amd_fidelityfx_upscaler_vk.dll (FSR SDK 2.4.0, MIT) for FSR 4')
ap.add_argument('--dlss', type=Path, help="NVIDIA's nvngx_dlss.dll from disk instead of downloading it from " ap.add_argument('--dlss', type=Path, help="NVIDIA's nvngx_dlss.dll from disk instead of downloading it from "
"NVIDIA's DLSS SDK repository") "NVIDIA's DLSS SDK repository")
ap.add_argument('--no-dlss', action='store_true', help='leave NVIDIA DLSS out of the kit') ap.add_argument('--no-dlss', action='store_true', help='leave NVIDIA DLSS out of the kit')
@@ -92,6 +95,9 @@ def main():
shutil.copy2(a.xlate / n, kit / 'bin' / n) shutil.copy2(a.xlate / n, kit / 'bin' / n)
if a.ffx: # FSR 3.1 loads it from beside the game (runtime/vk_ffx.cpp); its licence is runtime/third_party/ffx_api if a.ffx: # FSR 3.1 loads it from beside the game (runtime/vk_ffx.cpp); its licence is runtime/third_party/ffx_api
shutil.copy2(a.ffx, kit / 'bin' / 'amd_fidelityfx_vk.dll') shutil.copy2(a.ffx, kit / 'bin' / 'amd_fidelityfx_vk.dll')
if a.ffx4: # FSR 4 loads them from beside the game (runtime/vk_ffx4.cpp); their licence is runtime/third_party/ffx_sdk
for n in ('amd_fidelityfx_loader_vk.dll', 'amd_fidelityfx_upscaler_vk.dll'):
shutil.copy2(a.ffx4 / n, kit / 'bin' / n)
if dlss: # DLSS: NGX loads it from beside the game (runtime/vk_dlaa.c); make_game.py copies it there if dlss: # DLSS: NGX loads it from beside the game (runtime/vk_dlaa.c); make_game.py copies it there
dlss_pin.place(dlss, kit / 'bin') dlss_pin.place(dlss, kit / 'bin')
if sdk: # DLSS Frame Generation (runtime/vk_dlssg.c): make_game.py place_dlssg copies it beside the game if sdk: # DLSS Frame Generation (runtime/vk_dlssg.c): make_game.py place_dlssg copies it beside the game

View File

@@ -1,6 +1,7 @@
"""Build a release of the NX2navi launcher (docs/launcher.md, "Releases"). """Build a release of the NX2navi launcher (docs/launcher.md, "Releases").
python tools/make_launcher.py --xlate build/xlate [--ffx amd_fidelityfx_vk.dll] [--dlss nvngx_dlss.dll | --no-dlss] python tools/make_launcher.py --xlate build/xlate [--ffx amd_fidelityfx_vk.dll] [--dlss nvngx_dlss.dll | --no-dlss]
[--ffx4 FOLDER]
[--prompt-art FOLDER [FOLDER ...]] [--out build/launcher-release] [--prompt-art FOLDER [FOLDER ...]] [--out build/launcher-release]
[--feed owner/name] [--feed owner/name]
[--notes notes.md] [--publish] [--notes notes.md] [--publish]
@@ -17,7 +18,8 @@ The release folder (--out) holds:
python/ python.org's embeddable Python 3.14.9, tkinter and Tcl/Tk 9.0 from its tcltk.msi, python/ python.org's embeddable Python 3.14.9, tkinter and Tcl/Tk 9.0 from its tcltk.msi,
the packages of tools/requirements-launcher.txt, runtime-id.txt the packages of tools/requirements-launcher.txt, runtime-id.txt
app/current.txt, app/<version>/ launcher/ (without native/), runtime/, recomp/, the tools make_game.py uses, app/current.txt, app/<version>/ launcher/ (without native/), runtime/, recomp/, the tools make_game.py uses,
bin/nx2navi_xlate.exe and .id (and amd_fidelityfx_vk.dll with --ffx), bin/nx2navi_xlate.exe and .id (and amd_fidelityfx_vk.dll with --ffx, AMD's two
FSR 4 libraries with --ffx4),
bin/nvngx_dlss.dll and its notice (NVIDIA DLSS at the version tools/dlss_pin.py bin/nvngx_dlss.dll and its notice (NVIDIA DLSS at the version tools/dlss_pin.py
pins, downloaded from NVIDIA's DLSS SDK repository and checked, or --dlss; not with pins, downloaded from NVIDIA's DLSS SDK repository and checked, or --dlss; not with
--no-dlss), --no-dlss),
@@ -177,7 +179,7 @@ def build_python(py):
# ---------------------------------------------------------------- app/<version>/ # ---------------------------------------------------------------- app/<version>/
def build_app(app, ver, xlate, feed_repo, lock, ffx=None, dlss=None, art=None, dlssg=None): def build_app(app, ver, xlate, feed_repo, lock, ffx=None, dlss=None, art=None, dlssg=None, ffx4=None):
# The runtime's own shaders are source in the repository and SPIR-V headers in a release: a player's PC compiles # The runtime's own shaders are source in the repository and SPIR-V headers in a release: a player's PC compiles
# runtime/ (make_game.py) and has no shader compiler. Build the missing and the stale ones before the copy. # runtime/ (make_game.py) and has no shader compiler. Build the missing and the stale ones before the copy.
build_shaders.build(ROOT / 'runtime') build_shaders.build(ROOT / 'runtime')
@@ -198,6 +200,9 @@ def build_app(app, ver, xlate, feed_repo, lock, ffx=None, dlss=None, art=None, d
shutil.copy2(xlate / n, app / 'bin' / n) shutil.copy2(xlate / n, app / 'bin' / n)
if ffx: # FSR 3.1 loads it from beside the game (runtime/vk_ffx.cpp); make_game.py copies it there if ffx: # FSR 3.1 loads it from beside the game (runtime/vk_ffx.cpp); make_game.py copies it there
shutil.copy2(ffx, app / 'bin' / 'amd_fidelityfx_vk.dll') shutil.copy2(ffx, app / 'bin' / 'amd_fidelityfx_vk.dll')
if ffx4: # FSR 4 loads them from beside the game (runtime/vk_ffx4.cpp); make_game.py copies them there
for n in ('amd_fidelityfx_loader_vk.dll', 'amd_fidelityfx_upscaler_vk.dll'):
shutil.copy2(ffx4 / n, app / 'bin' / n)
if dlss: # DLSS: NGX loads it from beside the game (runtime/vk_dlaa.c); make_game.py copies it there if dlss: # DLSS: NGX loads it from beside the game (runtime/vk_dlaa.c); make_game.py copies it there
dlss_pin.place(dlss, app / 'bin') dlss_pin.place(dlss, app / 'bin')
if dlssg: # DLSS Frame Generation (runtime/vk_dlssg.c): make_game.py place_dlssg copies it beside the game if dlssg: # DLSS Frame Generation (runtime/vk_dlssg.c): make_game.py place_dlssg copies it beside the game
@@ -314,6 +319,8 @@ def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('--xlate', type=Path, required=True, help='folder with nx2navi_xlate.exe and nx2navi_xlate.id') ap.add_argument('--xlate', type=Path, required=True, help='folder with nx2navi_xlate.exe and nx2navi_xlate.id')
ap.add_argument('--ffx', type=Path, help="AMD's signed amd_fidelityfx_vk.dll (FidelityFX SDK 1.1.4, MIT) for FSR 3.1") ap.add_argument('--ffx', type=Path, help="AMD's signed amd_fidelityfx_vk.dll (FidelityFX SDK 1.1.4, MIT) for FSR 3.1")
ap.add_argument('--ffx4', type=Path, help="the folder with AMD's signed amd_fidelityfx_loader_vk.dll and "
'amd_fidelityfx_upscaler_vk.dll (FSR SDK 2.4.0, MIT) for FSR 4')
ap.add_argument('--dlss', type=Path, help=f"NVIDIA's nvngx_dlss.dll (DLSS {dlss_pin.VERSION}) from disk instead of " ap.add_argument('--dlss', type=Path, help=f"NVIDIA's nvngx_dlss.dll (DLSS {dlss_pin.VERSION}) from disk instead of "
"downloading it from NVIDIA's DLSS SDK repository") "downloading it from NVIDIA's DLSS SDK repository")
ap.add_argument('--no-dlss', action='store_true', help='leave NVIDIA DLSS out of the release') ap.add_argument('--no-dlss', action='store_true', help='leave NVIDIA DLSS out of the release')
@@ -356,7 +363,7 @@ def main():
dlssg = (a.dlssg, streamline_pin.resolve(a.streamline, DL)) if a.dlssg else None dlssg = (a.dlssg, streamline_pin.resolve(a.streamline, DL)) if a.dlssg else None
say(f'DLSS Frame Generation: {a.dlssg}, Streamline {streamline_pin.VERSION}: {dlssg[1]}' if dlssg say(f'DLSS Frame Generation: {a.dlssg}, Streamline {streamline_pin.VERSION}: {dlssg[1]}' if dlssg
else 'DLSS Frame Generation left out (no --dlssg)') else 'DLSS Frame Generation left out (no --dlssg)')
build_app(folder / 'app' / ver, ver, a.xlate, a.feed, lock, a.ffx, dlss, a.prompt_art, dlssg) build_app(folder / 'app' / ver, ver, a.xlate, a.feed, lock, a.ffx, dlss, a.prompt_art, dlssg, a.ffx4)
(folder / 'app' / 'current.txt').write_text(ver + '\n', encoding='utf-8') (folder / 'app' / 'current.txt').write_text(ver + '\n', encoding='utf-8')
build_python(folder / 'python') build_python(folder / 'python')
cc, windres = native_compiler(lock) cc, windres = native_compiler(lock)