FidelityFX SDK 1.1.4 frame interpolation and optical flow built into totk.exe behind frame_gen, contexts created and destroyed only, no frame-path change

The SDK subset, its compat header and the SPIR-V shader header come from Savage Wind (MIT); tools/ffx_shaders.py regenerates the header with glslangValidator, build_game.py compiles the SDK sources with ffx_compat.h force-included, and runtime/vk_fg.cpp makes the backend, optical flow and frame interpolation contexts after the device exists when frame_gen = 1 (default 0, read at start).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Revivedx <82332536+Revivedx@users.noreply.github.com>
This commit is contained in:
committed 2026-11-20 09:40:26 +03:00
1 parent 25a53e5ef2
commit 4e48669c86
114 files changed
+46877 -6

No files matched your search

+2
View File
@@ -30,6 +30,8 @@ Code copied or adapted from another project is listed here with its source, the
| SDL 3.4.20, dynamic link, `SDL3.dll` copied next to `totk.exe`. Developer builds use the MSYS2 build (`mingw-w64-ucrt-x86_64-sdl3`, which imports `libiconv-2.dll`, LGPL-2.1, unmodified, copied beside it); the installer release ships the upstream release `SDL3-3.4.20-win32-x64.zip`, which imports no libiconv | https://libsdl.org, Copyright (c) 1997-2026 Sam Lantinga | zlib | `runtime/input_win.c` (gamepad input, rumble, gyro and accelerometer) |
| libopus (MSYS2 `mingw-w64-ucrt-x86_64-opus`), dynamic link, `libopus-0.dll` copied next to `totk.exe` | https://opus-codec.org, Copyright (c) 2001-2023 Xiph.Org, Skype Limited, Octasic, Jean-Marc Valin, Timothy B. Terriberry, CSIRO, Gregory Maxwell, Mark Borgerding, Erik de Castro Lopo, Mozilla, Amazon | BSD-3-Clause | `runtime/ov_media.c` (nn::codec hardware Opus decoder) |
| Dear ImGui 1.91.9 (core and Vulkan back end, unmodified), as vendored by LAS Recomp | https://github.com/ocornut/imgui, via https://github.com/peiikai/LASRecomp @ `da35b83a9611d046a9a681aae668d7085954d37f` (`third_party/imgui/`), Copyright (c) 2014-2025 Omar Cornut | MIT | `runtime/third_party/imgui/` (compiled into `totk.exe` for the in-game menu, `runtime/ui/`) |
| AMD FidelityFX SDK 1.1.4 subset (public host and shader headers, frame interpolation and optical flow components, the Vulkan backend `ffx_vk.cpp` and its GLSL shaders, shared helpers), with three marked Savage Wind patches (64-byte aligned backend scratch arrays, doubled context size where `wchar_t` is 4 bytes, all six descriptor pool sizes) | https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/tree/v1.1.4, Copyright (C) 2024 Advanced Micro Devices, Inc., via https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`third_party/FidelityFX/`) | MIT | `runtime/third_party/FidelityFX/` (compiled into `totk.exe`; licence text in `runtime/third_party/FidelityFX/LICENSE.txt`, shipped as `licenses/FidelityFX-SDK-LICENSE.txt`) |
| SavageWindRecomp FidelityFX build support and frame generation set-up: the SDK-to-clang compat header, the glslang SPIR-V shader generator with its resource reflection, the blob lookup and the backend and context creation of `runtime/nvn/vulkan/framegen.cpp` | https://github.com/Revivedx/SavageWindRecomp @ `bf6146c14c37fee8781a601e5a544b93dff6d75e` (`third_party/FidelityFX/ffx_compat.h`, `tools/ffx_shaders.py`, `runtime/nvn/vulkan/framegen.cpp`) | MIT | `runtime/third_party/FidelityFX/ffx_compat.h`, `runtime/third_party/FidelityFX/spirv/ffx_shaders_vk.h` (output of `tools/ffx_shaders.py`), `tools/ffx_shaders.py`, `runtime/vk_fg.cpp` |
| SavageWindRecomp settings menu: two-pane option rows (row look, left / right stepping, hold speed-up, description pane), the menu style and tab bar | https://github.com/Revivedx/SavageWindRecomp @ `575ad88e02f9a89a9a885d90039d48af33c982f4` (`runtime/ui/option_rows.mm`, `runtime/ui/menu.mm`), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/ui/option_rows.cpp`, `runtime/ui/option_rows.h`, `runtime/ui/menu.cpp` |
| SavageWindRecomp descriptor sets allocated in growing batches per layout | https://github.com/Revivedx/SavageWindRecomp @ `740b18025fe11ba03c117dbb56668db304b5043e` (`runtime/nvn/vulkan/exec.c` vk_alloc_set), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/vk_exec_draw.c` (alloc_set_batched) |
| SavageWindRecomp performance overlay: the frame ring and its one-second summary, the NVML calls, the sampling loop, the full panel's layout | https://github.com/Revivedx/SavageWindRecomp @ `575ad88e02f9a89a9a885d90039d48af33c982f4` (`runtime/perfmon.c`, `runtime/perfmon.h`, `perf_overlay_draw` in `runtime/ui/menu.mm`), Copyright (c) 2026 Revivedx and the Savage Wind Recomp contributors, Copyright (c) 2026 Peiikai | MIT | `runtime/perfmon.c`, `runtime/perfmon.h`, `runtime/ui/menu.cpp` |
+1
View File
@@ -143,6 +143,7 @@ Many rows below are developer tools that only act together with another setting
| `dyn_delta` (default `1`) | Records only the pipeline dynamic states (cull mode, depth and stencil tests, vertex input, blend enables, equations and write masks, ...) whose values changed since the last draw in the command buffer, also across pipeline changes; `0` records the full set at every change of pipeline state, as before; `ab` alternates with the `ab` blocks. | Fewer commands per pipeline change on the render and recorder threads; a driver that loses dynamic state across pipeline binds would draw with stale state. `TOTK_TRACE=perf` prints the calls and commands per submission. | Caution |
| `feedback` | `0` samples a target that an earlier draw of the same pass wrote with no barrier; `restart` ends and restarts the pass behind a full barrier; otherwise the feedback-loop layout is used when the GPU supports it. | `0` brings back the old behaviour that the barrier fixed, so the picture can break in passes that read a target they draw into; `restart` costs extra passes. | Risky |
| `flush_span` (default `0`) | `1` copies one span from the lowest to the highest flushed address of a pool, as an older version did. | Copies far more data to the GPU in crowded towns: an estimated 30-50 ms of GPU time per large copy over PCIe 3.0 x8. | Caution |
| `frame_gen` (default `0`) | `1` creates AMD FSR 3 frame interpolation and optical flow (FidelityFX SDK 1.1.4) at start, on a 1920x1080 placeholder size or `output_res`. Read at start. | Work in progress: the contexts are made and destroyed, nothing generates frames yet. Costs start-up time and GPU memory while set. | Caution |
| `shadow_snap` (default `1`) | Shadow storage (Linux, Wine): `1` syncs the pools from per-submission write-watch snapshots, each 2 MiB region queried at most once per submission and shared with the texture checks; `0` queries each pool at every part of a submission, as before. | `1` cut the replay thread's write tracking from about 4.4 to 1.3 ms a frame on a Steam Deck; `0` is for comparison runs. Under Wine/Proton the default is `0` until it has been measured there; `1` turns it on. No effect where shadow storage is off (Windows by default). | Caution |
| `freeze_idle` (default `60`) | Number of submissions a 2 MiB region stays unwritten before it is made read-only; `0` turns the freeze off. | A larger value keeps more regions writable and costs more write tracking; a write to a frozen region costs about 60 microseconds. | Caution |
| `gpl_draw_build` (default `1`) | `0` leaves the missing shader libraries of a waiting draw to its background job instead of building them in parallel at once. | Draws whose pipeline is not ready are skipped meanwhile, until the job finishes. | Caution |
+3 -2
View File
@@ -43,7 +43,7 @@ static const char *const known[] = {
"COLOR_PRESET", "COLOR_SATURATION", "CONTACT_DEBUG", "CONTACT_SHADOWS", "CORE_DIAG", "CRIT", "CRIT_OUT",
"DESC_TEMPLATE", "DESWIZZLE", "DEVICE_PROFILE", "DIALOGUE_CLICK", "DISCORD_APP_ID", "DISCORD_IMAGE", "DISCORD_RPC", "DLAA", "DLAA_CAM_JITTER", "DLAA_EFFECTS_AFTER", "DLAA_JITTER", "DLAA_MV", "DLAA_MASKDEBUG", "DLAA_MVDEBUG", "DLAA_OBJMV", "DLAA_SURVEY", "DLAA_TIMES", "DLSS", "DLSS_CHAR_MASK", "DLSS_FIXED_EXPOSURE", "DLSS_PRESET", "DLSS_REACTIVE", "DUMP", "DUMP_BUF", "DUMP_DIR",
"DUMP_LOG", "DYNAMIC_RES", "DYN_DELTA", "EXEFS", "FEEDBACK", "FIXED_RES_PATCH", "FIX_C0", "FIX_ZERO", "FLIGHT", "FLIGHT_AT", "FLIGHT_DIR", "FLIGHT_FRAMES",
"FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FLUSH_SPAN", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FRAME_QUEUE", "FREECAM_KEY", "FREECAM_PAD", "FREECAM_PATCH",
"FLIGHT_SPIKE_MS", "FLIGHT_THUMBS", "FLUSH_SPAN", "FOV", "FOV_PATCH", "FPS60", "FPS_LIMIT", "FRAME_GEN", "FRAME_QUEUE", "FREECAM_KEY", "FREECAM_PAD", "FREECAM_PATCH",
"FREEZE_IDLE", "FREE_CORES",
"FULLSCREEN", "FXAA",
"GAMEPLAY_DISTANCE_SENSITIVITY", "GAMEPLAY_ITEM_AD", "GAMEPLAY_ITEM_SENSITIVITY", "GAMEPLAY_ITEM_WHEEL",
@@ -74,7 +74,7 @@ static const char *const known[] = {
// The totk.ini section a key cfg_set may write goes to when the file lacks it (totk.ini.example's sections).
static const struct { const char *key, *section; } sections[] = {
{"FPS_LIMIT", "frame rate"}, {"FPS60", "frame rate"}, {"FRAME_QUEUE", "frame rate"},
{"FPS_LIMIT", "frame rate"}, {"FPS60", "frame rate"}, {"FRAME_QUEUE", "frame rate"}, {"FRAME_GEN", "frame rate"},
{"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"},
{"CLIMB_FIX", "frame rate"}, {"AUDIO_DRAIN_FIX", "frame rate"}, {"SHUTTER_FIX", "frame rate"},
{"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"},
@@ -161,6 +161,7 @@ static const CfgMeta metas[] = {
{"PCSS", "0", "0..200", RESTART},
// Game
{"FPS_LIMIT", "60", "30|40|45|60|90|120|144|display", LIVE}, {"FPS60", "1", "0|1", LIVE}, {"FRAME_QUEUE", "0", "0|1", LIVE},
{"FRAME_GEN", "0", "0|1", RESTART}, // vk_fg.cpp vk_fg_init
{"REALTIME", "1", "0|1", RESTART}, {"CLOTH_REALTIME", "1", "0|1", RESTART},
{"MODS_REBUILD", "auto", "auto|off", RESTART},
{"MODS_WITHOUT_CODE", "0", "0|1", RESTART}, // 1: a mod is used without the code module it cannot run (mods.c)
+21
View File
@@ -0,0 +1,21 @@
This file is part of the FidelityFX SDK.
Copyright (C) 2024 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.
+32
View File
@@ -0,0 +1,32 @@
# AMD FidelityFX SDK 1.1.4 (subset)
From <https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/tree/v1.1.4>, MIT (`LICENSE.txt`), via Savage Wind
(<https://github.com/Revivedx/SavageWindRecomp>, MIT, `third_party/FidelityFX`). `runtime/vk_fg.cpp` drives the frame
interpolation and optical flow of FSR 3 on the SDK's Vulkan backend directly, without the SDK's frame interpolation
swapchain or its ffx-api DLL layer.
What is here:
- `sdk/include/FidelityFX/host`: the SDK's public headers; `gpu`: the shader headers of frame interpolation, optical
flow and SPD (which optical flow includes). Left out against Savage Wind's copy: the FSR 3 upscaler's and FSR 1's
shader headers (`gpu/fsr3upscaler`, `gpu/fsr1`), its component and its GLSL. The host headers of the upscaler and
the other effects stay, unchanged, because the SDK's own headers include each other.
- `sdk/src/components/frameinterpolation`, `opticalflow`: the two effects.
- `sdk/src/backends/vk/ffx_vk.cpp` and its `shaders/frameinterpolation`, `shaders/opticalflow` (GLSL).
- `sdk/src/shared`: the SDK's assert, message and object-management helpers.
- `sdk/src/backends/shared/ffx_shader_blobs.h`: the declaration of the blob lookup, which `runtime/vk_fg.cpp` implements.
- `spirv/ffx_shaders_vk.h`: the shaders compiled to SPIR-V with their bindings, by `tools/ffx_shaders.py`
(glslangValidator from MSYS2 UCRT64 or the Vulkan SDK) in place of the SDK's Windows-only FidelityFX_SC.exe. Only the
permutations used. Committed like `runtime/*_spv.h`: AMD's shaders, no game data. Regenerate after changing the GLSL:
`python tools/ffx_shaders.py`.
- `ffx_compat.h`: force-included into the SDK's sources (`tools/build_game.py`, rule `cc_ffx`) so they build with clang.
Changes to the SDK's files (marked "Savage Wind" in them):
- `sdk/src/backends/vk/ffx_vk.cpp`: the arrays the backend lays out in its scratch memory are aligned to 64 bytes
instead of 4, and start 64-byte aligned after its context. With 4, clang's aligned SSE stores into them (`movdqa`)
faulted; MSVC emits unaligned ones.
- `sdk/include/FidelityFX/host/ffx_types.h`: the contexts' default size is doubled outside Windows, where `wchar_t`
(their resources' debug names) is 4 bytes instead of 2.
- `sdk/src/backends/vk/ffx_vk.cpp`: the global descriptor pool is created with all six of the sizes it lists. It passed
five, leaving out the storage buffers (the validation layer reports it).
+67
View File
@@ -0,0 +1,67 @@
// Savage Wind: force-included (-include) into the FidelityFX SDK's C++ sources, so that they build with clang/gcc
// (MinGW-w64 and Linux) unchanged: what MSVC's headers bring in on their own, and its _s functions where the C library
// has none.
#pragma once
#ifdef __cplusplus
#include <cmath>
#include <codecvt> // (std::wstring_convert, which ffx_vk.cpp uses for the debug names: MSVC's headers bring it)
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <locale>
#include <new>
#include <string>
#endif
#if !defined(_MSC_VER)
#define swprintf_s swprintf // (the SDK passes the size)
#if defined(__cplusplus) && !defined(_countof)
template <typename T, size_t N> constexpr size_t ffx_countof_(T (&)[N]) { return N; }
#define _countof(a) ffx_countof_(a) // (stdlib.h's on Windows; glibc has none)
#endif
#if !defined(_WIN32)
#include <stddef.h>
#include <wchar.h>
static inline int wcscpy_s(wchar_t *d, size_t n, const wchar_t *s) {
size_t l = wcslen(s);
if (l >= n) l = n - 1;
wmemcpy(d, s, l);
d[l] = 0;
return 0;
}
static inline int wcscat_s(wchar_t *d, size_t n, const wchar_t *s) {
size_t l = wcslen(d);
return l < n ? wcscpy_s(d + l, n - l, s) : 0;
}
static inline int strcpy_s(char *d, size_t n, const char *s) {
size_t l = strlen(s);
if (l >= n) l = n - 1;
memcpy(d, s, l);
d[l] = 0;
return 0;
}
#ifdef __cplusplus
template <size_t N> static inline int wcscpy_s(wchar_t (&d)[N], const wchar_t *s) { return wcscpy_s(d, N, s); }
template <size_t N> static inline int strcpy_s(char (&d)[N], const char *s) { return strcpy_s(d, N, s); }
template <size_t N, typename... A> static inline int sprintf_s(char (&d)[N], const char *f, A... a) { return snprintf(d, N, f, a...); }
template <typename... A> static inline int sprintf_s(char *d, size_t n, const char *f, A... a) { return snprintf(d, n, f, a...); }
#endif
#ifndef FFX_UNUSED
#define FFX_UNUSED(x) ((void)(x)) // (ffx_message.cpp: defined by the SDK's Windows headers only)
#endif
#define sprintf_s snprintf // (the SDK passes the size and uses what it returns: the length written)
#ifndef _countof
#define _countof(a) (sizeof(a) / sizeof((a)[0])) // (MSVC's and MinGW's stdlib.h have it)
#endif
#endif
#endif
// The contexts are opaque arrays of FFX_SDK_DEFAULT_CONTEXT_SIZE words, sized for Windows, where wchar_t is 2 bytes:
// with Linux's 4-byte wchar_t the frame interpolation context's own part is 768,072 bytes (401,992 with 2-byte
// wchar_t), past its 524,288 (a static assertion in ffx_frameinterpolation.cpp). Twice the room where wchar_t is wider.
#include <FidelityFX/host/ffx_types.h>
#if __SIZEOF_WCHAR_T__ > 2
#undef FFX_SDK_DEFAULT_CONTEXT_SIZE
#define FFX_SDK_DEFAULT_CONTEXT_SIZE (1024 * 256)
#endif
#define FFX_UNUSED(x) ((void)(x)) // (as ffx_util.h has it: ffx_message.cpp uses it through ffx_assert.h alone)
@@ -0,0 +1,230 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_BRIXELIZER_HOST_GPU_SHARED_H
#define FFX_BRIXELIZER_HOST_GPU_SHARED_H
#include "../ffx_core.h"
#define FFX_BRIXELIZER_MAX_CASCADES 24
#define FFX_BRIXELIZER_MAX_INSTANCES (FfxUInt32(1) << FfxUInt32(16))
#define FFX_BRIXELIZER_CASCADE_RESOLUTION 64
#define FFX_BRIXELIZER_MAX_INSTANCES (FfxUInt32(1) << FfxUInt32(16))
#define FFX_BRIXELIZER_INVALID_ID 0x00ffffffu
#define FFX_BRIXELIZER_UNINITIALIZED_ID 0xffffffffu
#define FFX_BRIXELIZER_INVALID_BOTTOM_AABB_NODE 0x7fff
#define FFX_BRIXELIZER_MAX_BRICKS_X8 (1 << 18)
#define FFX_BRIXELIZER_MAX_BRICKS FFX_BRIXELIZER_MAX_BRICKS_X8
#define FFX_BRIXELIZER_BRICK_AABBS_STRIDE (sizeof(FfxUInt32))
#define FFX_BRIXELIZER_BRICK_AABBS_SIZE (FFX_BRIXELIZER_MAX_BRICKS_X8 * FFX_BRIXELIZER_BRICK_AABBS_STRIDE)
#define FFX_BRIXELIZER_CASCADE_AABB_TREE_SIZE ((16 * 16 * 16) * sizeof(FfxUInt32) + (4 * 4 * 4 + 1) * sizeof(FfxFloat32x3) * 2)
#define FFX_BRIXELIZER_CASCADE_AABB_TREE_STRIDE (sizeof(FfxUInt32))
#define FFX_BRIXELIZER_CASCADE_BRICK_MAP_SIZE (FFX_BRIXELIZER_CASCADE_RESOLUTION * FFX_BRIXELIZER_CASCADE_RESOLUTION * FFX_BRIXELIZER_CASCADE_RESOLUTION * sizeof(FfxUInt32))
#define FFX_BRIXELIZER_CASCADE_BRICK_MAP_STRIDE (sizeof(FfxUInt32))
#define FFX_BRIXELIZER_BRICK_ID_MASK 0xffffff
#define FFX_BRIXELIZER_CASCADE_DEGREE FfxUInt32(6)
#define FFX_BRIXELIZER_CASCADE_WRAP_MASK FfxUInt32(63)
#define FFX_BRIXELIZER_STATIC_CONFIG_SDF_ATLAS_SIZE FfxUInt32(512)
#if defined(FFX_CPU)
#define FFX_BRIXELIZER_CONST static const
#elif defined(FFX_HLSL)
#define FFX_BRIXELIZER_CONST static const
#elif defined(FFX_GLSL)
#define FFX_BRIXELIZER_CONST const
#else
FFX_STATIC_ASSERT(0)
#endif
#ifdef FFX_CPU
#define FFX_BRIXELIZER_BEGIN_STRUCT(name) typedef struct name {
#define FFX_BRIXELIZER_END_STRUCT(name) } name;
#define FFX_BRIXELIZER_BEGIN_ENUM(name) typedef enum name {
#define FFX_BRIXELIZER_END_ENUM(name) } name;
#define FFX_BRIXELIZER_ENUM_VALUE(name, value) name = value,
#else
#define FFX_BRIXELIZER_BEGIN_STRUCT(name) struct name {
#define FFX_BRIXELIZER_END_STRUCT(name) };
#define FFX_BRIXELIZER_BEGIN_ENUM(name)
#define FFX_BRIXELIZER_END_ENUM(name)
#define FFX_BRIXELIZER_ENUM_VALUE(name, value) FFX_BRIXELIZER_CONST FfxUInt32 name = value;
#endif
/// An enumeration of flags which can be specified for different options when doing a cascade update.
///
/// @ingroup Brixelizer
FFX_BRIXELIZER_BEGIN_ENUM(FfxBrixelizerCascadeUpdateFlags)
FFX_BRIXELIZER_ENUM_VALUE(FFX_BRIXELIZER_CASCADE_UPDATE_FLAG_NONE, FfxUInt32(0)) ///< No flags.
FFX_BRIXELIZER_ENUM_VALUE(FFX_BRIXELIZER_CASCADE_UPDATE_FLAG_RESET, FfxUInt32(1) << FfxUInt32(0)) ///< Reset the cascade. This clears and frees all bricks currently in the cascade ready to rebuild the cascade completely.
FFX_BRIXELIZER_END_ENUM(FfxBrixelizerCascadeUpdateFlags)
/// An enumeration of the different possible debug outputs for the Brixelizer debug visualization.
///
/// @ingroup Brixelizer
FFX_BRIXELIZER_BEGIN_ENUM(FfxBrixelizerTraceDebugModes)
FFX_BRIXELIZER_ENUM_VALUE(FFX_BRIXELIZER_TRACE_DEBUG_MODE_DISTANCE, 0) ///< Display a visualisation of the distance to hit, with closer hits in blue and further hits in green.
FFX_BRIXELIZER_ENUM_VALUE(FFX_BRIXELIZER_TRACE_DEBUG_MODE_UVW, 1) ///< Display the UVW coordinates of hits.
FFX_BRIXELIZER_ENUM_VALUE(FFX_BRIXELIZER_TRACE_DEBUG_MODE_ITERATIONS, 2) ///< Display a heatmap visualizing number of iterations in the scene.
FFX_BRIXELIZER_ENUM_VALUE(FFX_BRIXELIZER_TRACE_DEBUG_MODE_GRAD, 3) ///< Display the normals at hits.
FFX_BRIXELIZER_ENUM_VALUE(FFX_BRIXELIZER_TRACE_DEBUG_MODE_BRICK_ID, 4) ///< Display each brick in its own color.
FFX_BRIXELIZER_ENUM_VALUE(FFX_BRIXELIZER_TRACE_DEBUG_MODE_CASCADE_ID, 5) ///< Display each cascade in itw own color.
FFX_BRIXELIZER_END_ENUM(FfxBrixelizerTraceDebugModes)
/// A structure of parameters describing a cascade. This structure is primarily for Brixelizer
/// internal use.
///
/// @ingroup Brixelizer
FFX_BRIXELIZER_BEGIN_STRUCT(FfxBrixelizerCascadeInfo)
FfxFloat32x3 grid_min;
FfxFloat32 voxel_size;
FfxFloat32x3 grid_max;
FfxUInt32 flags; ///< the latest build_flags; see FfxBrixelizerCascadeUpdateFlags
FfxUInt32x3 clipmap_offset;
FfxUInt32 pad00;
FfxInt32x3 clipmap_invalidation_offset;
FfxUInt32 pad33;
FfxInt32x3 ioffset;
FfxUInt32 index;
FfxFloat32x3 grid_mid;
FfxUInt32 is_enabled;
FfxUInt32x2 rel_grid_min_fp16;
FfxUInt32x2 rel_grid_max_fp16;
FfxUInt32 pad11;
FfxUInt32 pad22;
FfxFloat32 ivoxel_size;
FfxUInt32 is_initialized;
FFX_BRIXELIZER_END_STRUCT(FfxBrixelizerCascadeInfo)
/// A structure of parameters describing the Brixelizer context. This structure is primarily
/// for Brixelizer internal use.
///
/// @ingroup Brixelizer
FFX_BRIXELIZER_BEGIN_STRUCT(FfxBrixelizerContextInfo)
FfxUInt32 num_bricks;
FfxUInt32 frame_index;
FfxFloat32 imesh_unit;
FfxFloat32 mesh_unit;
FfxBrixelizerCascadeInfo cascades[FFX_BRIXELIZER_MAX_CASCADES];
FFX_BRIXELIZER_END_STRUCT(FfxBrixelizerContextInfo)
// =============================================================================
// Debug/context counters
// =============================================================================
// Important to match the first a couple of counters with the FfxBrixelizerScratchCounters to share code
#define MEMBER_LIST \
MEMBER(brickCount, BRICK_COUNT, 0) \
MEMBER(dirtyBricks, DIRTY_BRICKS, 1) \
MEMBER(freeBricks, FREE_BRICKS, 2) \
MEMBER(clearBricks, CLEAR_BRICKS, 3) \
MEMBER(mergeBricks, MERGE_BRICKS, 4) \
MEMBER(numDebugAABBs, NUM_DEBUG_AABBS, 5)
/// A structure containing all the counters used by the Brixelizer context. These can
/// be read back from the context after processing each update for analysis.
/// <c><i>brickCount</i></c> gives the total number of bricks allocated.
/// <c><i>dirtyBricks</i></c> gives the total number of bricks requiring an eikonal pass for completion.
/// <c><i>freeBricks</i></c> gives the total number of free bricks. This is the maximum number of bricks which can be allocated within a frame.
/// <c><i>clearBricks</i></c> gives the total number of bricks to be cleared in a frame. Bricks are cleared by having all distance values reset to 1.
/// <c><i>mergeBricks</i></c> gives the total number of bricks to be merged in a frame.
/// <c><i>numDebugAABBs</i></c> gives the total number of debug AABBs requested to be drawn in a debug visualization.
///
/// @ingroup Brixelizer
FFX_BRIXELIZER_BEGIN_STRUCT(FfxBrixelizerDebugCounters)
#define MEMBER(camel_name, _upper_name, _index) FfxUInt32 camel_name;
MEMBER_LIST
#undef MEMBER
FFX_BRIXELIZER_END_STRUCT(FfxBrixelizerDebugCounters)
FFX_BRIXELIZER_BEGIN_ENUM(FfxBrixelizerContextCounterIndex)
#define MEMBER(_camel_name, upper_name, index) FFX_BRIXELIZER_ENUM_VALUE(FFX_BRIXELIZER_CONTEXT_COUNTER_##upper_name, index)
MEMBER_LIST
#undef MEMBER
FFX_BRIXELIZER_END_ENUM(FfxBrixelizerContextCounterIndex)
#define MEMBER(_camel_name, _upper_name, _index) + 1
FFX_BRIXELIZER_CONST FfxUInt32 FFX_BRIXELIZER_NUM_CONTEXT_COUNTERS = 0 MEMBER_LIST;
#undef MEMBER
#undef MEMBER_LIST
// =============================================================================
// Scratch counters
// =============================================================================
#define MEMBER_LIST \
MEMBER(triangles, TRIANGLES, 0) \
MEMBER(maxTriangles, MAX_TRIANGLES, 1) \
MEMBER(references, REFERENCES, 2) \
MEMBER(maxReferences, MAX_REFERENCES, 3) \
MEMBER(groupIndex, GROUP_INDEX, 4) \
MEMBER(compressionBricks, COMPRESSION_BRICKS, 5) \
MEMBER(storageOffset, STORAGE_OFFSET, 6) \
MEMBER(storageSize, STORAGE_SIZE, 7) \
MEMBER(numBricksAllocated, NUM_BRICKS_ALLOCATED, 8) \
MEMBER(clearBricks, CLEAR_BRICKS, 9)
/// A structure containing the counters used by the Brixelizer context for each cascade
/// update. This can be readback and used for analysis after each update. The following
/// members contain useful information for analysing Brixelizer resource usage.
///
/// <c><i>triangles</i></c> is used to store the total amount of storage space requested within the triangle buffer during an update. This is useful for determining a sensible value of <c><i>triangleSwapSize</i></c> in either <c><i>FfxBrixelizerRawCascadeUpdateDescription</i></c> or <c><i>FfxBrixelizerUpdateDescription</i></c>.
/// <c><i>references</i></c> is used to store the total number of reference allocations requested by Brixelizer during an update. This is useful for determining a sensible value of <c><i>maxReferences</i></c> in either <c><i>FfxBrixelizerRawCascadeUpdateDescription</i></c> or <c><i>FfxBrixelizerUpdateDescription</i></c>.
/// <c><i>numBricksAllocated</i></c> is used to store the number of brick allocations requested in an update. This is useful for determining a sensible value of <c><i>maxBricksPerBake</i></c> in either <c><i>FfxBrixelizerRawCascadeUpdateDescription</i></c> or <c><i>FfxBrixelizerUpdateDescription</i></c>.
///
/// The following counters are used internally by Brixelizer.
///
/// <c><i>maxTriangles</i></c> is used to store the storage size of the triangle buffer.
/// <c><i>maxReferences</i></c> is used to store the maxmimum number of references that can be stored.
/// <c><i>groupIndex</i></c> is used as a global atomic for wavefront synchronisation.
/// <c><i>compressionBricks</i></c> the number of bricks to compress (i.e. calculate AABBs for) this udpate.
/// <c><i>storageOffset</i></c> the next free position in the bricks scratch buffer.
/// <c><i>storageSize</i></c> the size of the bricks scratch buffer.
/// <c><i>clearBricks</i></c> the amount of bricks in the scratch buffer to initialize.
///
/// @ingroup Brixelizer
FFX_BRIXELIZER_BEGIN_STRUCT(FfxBrixelizerScratchCounters)
#define MEMBER(camel_name, _upper_name, _index) FfxUInt32 camel_name;
MEMBER_LIST
#undef MEMBER
FFX_BRIXELIZER_END_STRUCT(FfxBrixelizerScratchCounters)
FFX_BRIXELIZER_BEGIN_ENUM(FfxBrixelizerScratchCounterIndex)
#define MEMBER(_camel_name, upper_name, index) FFX_BRIXELIZER_ENUM_VALUE(FFX_BRIXELIZER_SCRATCH_COUNTER_##upper_name, index)
MEMBER_LIST
#undef MEMBER
FFX_BRIXELIZER_END_ENUM(FfxBrixelizerScratchCounterIndex)
#define MEMBER(_camel_name, _upper_name, _index) + 1
FFX_BRIXELIZER_CONST FfxUInt32 FFX_BRIXELIZER_NUM_SCRATCH_COUNTERS = 0 MEMBER_LIST;
#undef MEMBER
#undef MEMBER_LIST
#endif
@@ -0,0 +1,558 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_COMMON_TYPES_H
#define FFX_COMMON_TYPES_H
#if defined(FFX_CPU)
#define FFX_PARAMETER_IN
#define FFX_PARAMETER_OUT
#define FFX_PARAMETER_INOUT
#define FFX_PARAMETER_UNIFORM
#elif defined(FFX_HLSL)
#define FFX_PARAMETER_IN in
#define FFX_PARAMETER_OUT out
#define FFX_PARAMETER_INOUT inout
#define FFX_PARAMETER_UNIFORM uniform
#elif defined(FFX_GLSL)
#define FFX_PARAMETER_IN in
#define FFX_PARAMETER_OUT out
#define FFX_PARAMETER_INOUT inout
#define FFX_PARAMETER_UNIFORM const //[cacao_placeholder] until a better fit is found!
#endif // #if defined(FFX_CPU)
#if defined(FFX_CPU)
/// A typedef for a boolean value.
///
/// @ingroup CPUTypes
typedef bool FfxBoolean;
/// A typedef for a unsigned 8bit integer.
///
/// @ingroup CPUTypes
typedef uint8_t FfxUInt8;
/// A typedef for a unsigned 16bit integer.
///
/// @ingroup CPUTypes
typedef uint16_t FfxUInt16;
/// A typedef for a unsigned 32bit integer.
///
/// @ingroup CPUTypes
typedef uint32_t FfxUInt32;
/// A typedef for a unsigned 64bit integer.
///
/// @ingroup CPUTypes
typedef uint64_t FfxUInt64;
/// A typedef for a signed 8bit integer.
///
/// @ingroup CPUTypes
typedef int8_t FfxInt8;
/// A typedef for a signed 16bit integer.
///
/// @ingroup CPUTypes
typedef int16_t FfxInt16;
/// A typedef for a signed 32bit integer.
///
/// @ingroup CPUTypes
typedef int32_t FfxInt32;
/// A typedef for a signed 64bit integer.
///
/// @ingroup CPUTypes
typedef int64_t FfxInt64;
/// A typedef for a floating point value.
///
/// @ingroup CPUTypes
typedef float FfxFloat32;
/// A typedef for a 2-dimensional floating point value.
///
/// @ingroup CPUTypes
typedef float FfxFloat32x2[2];
/// A typedef for a 3-dimensional floating point value.
///
/// @ingroup CPUTypes
typedef float FfxFloat32x3[3];
/// A typedef for a 4-dimensional floating point value.
///
/// @ingroup CPUTypes
typedef float FfxFloat32x4[4];
/// A typedef for a 2x2 floating point matrix.
///
/// @ingroup CPUTypes
typedef float FfxFloat32x2x2[4];
/// A typedef for a 3x3 floating point matrix.
///
/// @ingroup CPUTypes
typedef float FfxFloat32x3x3[9];
/// A typedef for a 3x4 floating point matrix.
///
/// @ingroup CPUTypes
typedef float FfxFloat32x3x4[12];
/// A typedef for a 4x4 floating point matrix.
///
/// @ingroup CPUTypes
typedef float FfxFloat32x4x4[16];
/// A typedef for a 2-dimensional 32bit signed integer.
///
/// @ingroup CPUTypes
typedef int32_t FfxInt32x2[2];
/// A typedef for a 3-dimensional 32bit signed integer.
///
/// @ingroup CPUTypes
typedef int32_t FfxInt32x3[3];
/// A typedef for a 4-dimensional 32bit signed integer.
///
/// @ingroup CPUTypes
typedef int32_t FfxInt32x4[4];
/// A typedef for a 2-dimensional 32bit usigned integer.
///
/// @ingroup CPUTypes
typedef uint32_t FfxUInt32x2[2];
/// A typedef for a 3-dimensional 32bit unsigned integer.
///
/// @ingroup CPUTypes
typedef uint32_t FfxUInt32x3[3];
/// A typedef for a 4-dimensional 32bit unsigned integer.
///
/// @ingroup CPUTypes
typedef uint32_t FfxUInt32x4[4];
#endif // #if defined(FFX_CPU)
#if defined(FFX_HLSL)
#define FfxFloat32Mat4 matrix <float, 4, 4>
#define FfxFloat32Mat3 matrix <float, 3, 3>
/// A typedef for a boolean value.
///
/// @ingroup HLSLTypes
typedef bool FfxBoolean;
#if FFX_HLSL_SM>=62
/// @defgroup HLSL62Types HLSL 6.2 And Above Types
/// HLSL 6.2 and above type defines for all commonly used variables
///
/// @ingroup HLSLTypes
/// A typedef for a floating point value.
///
/// @ingroup HLSL62Types
typedef float32_t FfxFloat32;
/// A typedef for a 2-dimensional floating point value.
///
/// @ingroup HLSL62Types
typedef float32_t2 FfxFloat32x2;
/// A typedef for a 3-dimensional floating point value.
///
/// @ingroup HLSL62Types
typedef float32_t3 FfxFloat32x3;
/// A typedef for a 4-dimensional floating point value.
///
/// @ingroup HLSL62Types
typedef float32_t4 FfxFloat32x4;
/// A [cacao_placeholder] typedef for matrix type until confirmed.
typedef float4x4 FfxFloat32x4x4;
typedef float3x4 FfxFloat32x3x4;
typedef float3x3 FfxFloat32x3x3;
typedef float2x2 FfxFloat32x2x2;
/// A typedef for a unsigned 32bit integer.
///
/// @ingroup HLSL62Types
typedef uint32_t FfxUInt32;
/// A typedef for a 2-dimensional 32bit unsigned integer.
///
/// @ingroup HLSL62Types
typedef uint32_t2 FfxUInt32x2;
/// A typedef for a 3-dimensional 32bit unsigned integer.
///
/// @ingroup HLSL62Types
typedef uint32_t3 FfxUInt32x3;
/// A typedef for a 4-dimensional 32bit unsigned integer.
///
/// @ingroup HLSL62Types
typedef uint32_t4 FfxUInt32x4;
/// A typedef for a signed 32bit integer.
///
/// @ingroup HLSL62Types
typedef int32_t FfxInt32;
/// A typedef for a 2-dimensional signed 32bit integer.
///
/// @ingroup HLSL62Types
typedef int32_t2 FfxInt32x2;
/// A typedef for a 3-dimensional signed 32bit integer.
///
/// @ingroup HLSL62Types
typedef int32_t3 FfxInt32x3;
/// A typedef for a 4-dimensional signed 32bit integer.
///
/// @ingroup HLSL62Types
typedef int32_t4 FfxInt32x4;
#else // #if FFX_HLSL_SM>=62
/// @defgroup HLSLBaseTypes HLSL 6.1 And Below Types
/// HLSL 6.1 and below type defines for all commonly used variables
///
/// @ingroup HLSLTypes
#define FfxFloat32 float
#define FfxFloat32x2 float2
#define FfxFloat32x3 float3
#define FfxFloat32x4 float4
/// A [cacao_placeholder] typedef for matrix type until confirmed.
#define FfxFloat32x4x4 float4x4
#define FfxFloat32x3x4 float3x4
#define FfxFloat32x3x3 float3x3
#define FfxFloat32x2x2 float2x2
/// A typedef for a unsigned 32bit integer.
///
/// @ingroup GPU
typedef uint FfxUInt32;
typedef uint2 FfxUInt32x2;
typedef uint3 FfxUInt32x3;
typedef uint4 FfxUInt32x4;
typedef int FfxInt32;
typedef int2 FfxInt32x2;
typedef int3 FfxInt32x3;
typedef int4 FfxInt32x4;
#endif // #if FFX_HLSL_SM>=62
#if FFX_HALF
#if FFX_HLSL_SM >= 62
typedef float16_t FfxFloat16;
typedef float16_t2 FfxFloat16x2;
typedef float16_t3 FfxFloat16x3;
typedef float16_t4 FfxFloat16x4;
/// A typedef for an unsigned 16bit integer.
///
/// @ingroup HLSLTypes
typedef uint16_t FfxUInt16;
typedef uint16_t2 FfxUInt16x2;
typedef uint16_t3 FfxUInt16x3;
typedef uint16_t4 FfxUInt16x4;
/// A typedef for a signed 16bit integer.
///
/// @ingroup HLSLTypes
typedef int16_t FfxInt16;
typedef int16_t2 FfxInt16x2;
typedef int16_t3 FfxInt16x3;
typedef int16_t4 FfxInt16x4;
#else // #if FFX_HLSL_SM>=62
typedef min16float FfxFloat16;
typedef min16float2 FfxFloat16x2;
typedef min16float3 FfxFloat16x3;
typedef min16float4 FfxFloat16x4;
/// A typedef for an unsigned 16bit integer.
///
/// @ingroup HLSLTypes
typedef min16uint FfxUInt16;
typedef min16uint2 FfxUInt16x2;
typedef min16uint3 FfxUInt16x3;
typedef min16uint4 FfxUInt16x4;
/// A typedef for a signed 16bit integer.
///
/// @ingroup HLSLTypes
typedef min16int FfxInt16;
typedef min16int2 FfxInt16x2;
typedef min16int3 FfxInt16x3;
typedef min16int4 FfxInt16x4;
#endif // #if FFX_HLSL_SM>=62
#endif // FFX_HALF
#endif // #if defined(FFX_HLSL)
#if defined(FFX_GLSL)
#define FfxFloat32Mat4 mat4
#define FfxFloat32Mat3 mat3
/// A typedef for a boolean value.
///
/// @ingroup GLSLTypes
#define FfxBoolean bool
#define FfxFloat32 float
#define FfxFloat32x2 vec2
#define FfxFloat32x3 vec3
#define FfxFloat32x4 vec4
#define FfxUInt32 uint
#define FfxUInt32x2 uvec2
#define FfxUInt32x3 uvec3
#define FfxUInt32x4 uvec4
#define FfxInt32 int
#define FfxInt32x2 ivec2
#define FfxInt32x3 ivec3
#define FfxInt32x4 ivec4
/// A [cacao_placeholder] typedef for matrix type until confirmed.
#define FfxFloat32x4x4 mat4
#define FfxFloat32x3x4 mat4x3
#define FfxFloat32x3x3 mat3
#define FfxFloat32x2x2 mat2
#if FFX_HALF
#define FfxFloat16 float16_t
#define FfxFloat16x2 f16vec2
#define FfxFloat16x3 f16vec3
#define FfxFloat16x4 f16vec4
#define FfxUInt16 uint16_t
#define FfxUInt16x2 u16vec2
#define FfxUInt16x3 u16vec3
#define FfxUInt16x4 u16vec4
#define FfxInt16 int16_t
#define FfxInt16x2 i16vec2
#define FfxInt16x3 i16vec3
#define FfxInt16x4 i16vec4
#endif // FFX_HALF
#endif // #if defined(FFX_GLSL)
// Global toggles:
// #define FFX_HALF (1)
// #define FFX_HLSL_SM (62)
#if FFX_HALF
#if FFX_HLSL_SM >= 62
#define FFX_MIN16_SCALAR( TypeName, BaseComponentType ) typedef BaseComponentType##16_t TypeName;
#define FFX_MIN16_VECTOR( TypeName, BaseComponentType, COL ) typedef vector<BaseComponentType##16_t, COL> TypeName;
#define FFX_MIN16_MATRIX( TypeName, BaseComponentType, ROW, COL ) typedef matrix<BaseComponentType##16_t, ROW, COL> TypeName;
#define FFX_16BIT_SCALAR( TypeName, BaseComponentType ) typedef BaseComponentType##16_t TypeName;
#define FFX_16BIT_VECTOR( TypeName, BaseComponentType, COL ) typedef vector<BaseComponentType##16_t, COL> TypeName;
#define FFX_16BIT_MATRIX( TypeName, BaseComponentType, ROW, COL ) typedef matrix<BaseComponentType##16_t, ROW, COL> TypeName;
#else //FFX_HLSL_SM>=62
#define FFX_MIN16_SCALAR( TypeName, BaseComponentType ) typedef min16##BaseComponentType TypeName;
#define FFX_MIN16_VECTOR( TypeName, BaseComponentType, COL ) typedef vector<min16##BaseComponentType, COL> TypeName;
#define FFX_MIN16_MATRIX( TypeName, BaseComponentType, ROW, COL ) typedef matrix<min16##BaseComponentType, ROW, COL> TypeName;
#define FFX_16BIT_SCALAR( TypeName, BaseComponentType ) FFX_MIN16_SCALAR( TypeName, BaseComponentType );
#define FFX_16BIT_VECTOR( TypeName, BaseComponentType, COL ) FFX_MIN16_VECTOR( TypeName, BaseComponentType, COL );
#define FFX_16BIT_MATRIX( TypeName, BaseComponentType, ROW, COL ) FFX_MIN16_MATRIX( TypeName, BaseComponentType, ROW, COL );
#endif //FFX_HLSL_SM>=62
#else //FFX_HALF
#define FFX_MIN16_SCALAR( TypeName, BaseComponentType ) typedef BaseComponentType TypeName;
#define FFX_MIN16_VECTOR( TypeName, BaseComponentType, COL ) typedef vector<BaseComponentType, COL> TypeName;
#define FFX_MIN16_MATRIX( TypeName, BaseComponentType, ROW, COL ) typedef matrix<BaseComponentType, ROW, COL> TypeName;
#define FFX_16BIT_SCALAR( TypeName, BaseComponentType ) typedef BaseComponentType TypeName;
#define FFX_16BIT_VECTOR( TypeName, BaseComponentType, COL ) typedef vector<BaseComponentType, COL> TypeName;
#define FFX_16BIT_MATRIX( TypeName, BaseComponentType, ROW, COL ) typedef matrix<BaseComponentType, ROW, COL> TypeName;
#endif //FFX_HALF
#if defined(FFX_GPU)
// Common typedefs:
#if defined(FFX_HLSL)
FFX_MIN16_SCALAR( FFX_MIN16_F , float );
FFX_MIN16_VECTOR( FFX_MIN16_F2, float, 2 );
FFX_MIN16_VECTOR( FFX_MIN16_F3, float, 3 );
FFX_MIN16_VECTOR( FFX_MIN16_F4, float, 4 );
FFX_MIN16_SCALAR( FFX_MIN16_I, int );
FFX_MIN16_VECTOR( FFX_MIN16_I2, int, 2 );
FFX_MIN16_VECTOR( FFX_MIN16_I3, int, 3 );
FFX_MIN16_VECTOR( FFX_MIN16_I4, int, 4 );
FFX_MIN16_SCALAR( FFX_MIN16_U, uint );
FFX_MIN16_VECTOR( FFX_MIN16_U2, uint, 2 );
FFX_MIN16_VECTOR( FFX_MIN16_U3, uint, 3 );
FFX_MIN16_VECTOR( FFX_MIN16_U4, uint, 4 );
FFX_16BIT_SCALAR( FFX_F16_t , float );
FFX_16BIT_VECTOR( FFX_F16_t2, float, 2 );
FFX_16BIT_VECTOR( FFX_F16_t3, float, 3 );
FFX_16BIT_VECTOR( FFX_F16_t4, float, 4 );
FFX_16BIT_SCALAR( FFX_I16_t, int );
FFX_16BIT_VECTOR( FFX_I16_t2, int, 2 );
FFX_16BIT_VECTOR( FFX_I16_t3, int, 3 );
FFX_16BIT_VECTOR( FFX_I16_t4, int, 4 );
FFX_16BIT_SCALAR( FFX_U16_t, uint );
FFX_16BIT_VECTOR( FFX_U16_t2, uint, 2 );
FFX_16BIT_VECTOR( FFX_U16_t3, uint, 3 );
FFX_16BIT_VECTOR( FFX_U16_t4, uint, 4 );
#define TYPEDEF_MIN16_TYPES(Prefix) \
typedef FFX_MIN16_F Prefix##_F; \
typedef FFX_MIN16_F2 Prefix##_F2; \
typedef FFX_MIN16_F3 Prefix##_F3; \
typedef FFX_MIN16_F4 Prefix##_F4; \
typedef FFX_MIN16_I Prefix##_I; \
typedef FFX_MIN16_I2 Prefix##_I2; \
typedef FFX_MIN16_I3 Prefix##_I3; \
typedef FFX_MIN16_I4 Prefix##_I4; \
typedef FFX_MIN16_U Prefix##_U; \
typedef FFX_MIN16_U2 Prefix##_U2; \
typedef FFX_MIN16_U3 Prefix##_U3; \
typedef FFX_MIN16_U4 Prefix##_U4;
#define TYPEDEF_16BIT_TYPES(Prefix) \
typedef FFX_16BIT_F Prefix##_F; \
typedef FFX_16BIT_F2 Prefix##_F2; \
typedef FFX_16BIT_F3 Prefix##_F3; \
typedef FFX_16BIT_F4 Prefix##_F4; \
typedef FFX_16BIT_I Prefix##_I; \
typedef FFX_16BIT_I2 Prefix##_I2; \
typedef FFX_16BIT_I3 Prefix##_I3; \
typedef FFX_16BIT_I4 Prefix##_I4; \
typedef FFX_16BIT_U Prefix##_U; \
typedef FFX_16BIT_U2 Prefix##_U2; \
typedef FFX_16BIT_U3 Prefix##_U3; \
typedef FFX_16BIT_U4 Prefix##_U4;
#define TYPEDEF_FULL_PRECISION_TYPES(Prefix) \
typedef FfxFloat32 Prefix##_F; \
typedef FfxFloat32x2 Prefix##_F2; \
typedef FfxFloat32x3 Prefix##_F3; \
typedef FfxFloat32x4 Prefix##_F4; \
typedef FfxInt32 Prefix##_I; \
typedef FfxInt32x2 Prefix##_I2; \
typedef FfxInt32x3 Prefix##_I3; \
typedef FfxInt32x4 Prefix##_I4; \
typedef FfxUInt32 Prefix##_U; \
typedef FfxUInt32x2 Prefix##_U2; \
typedef FfxUInt32x3 Prefix##_U3; \
typedef FfxUInt32x4 Prefix##_U4;
#endif // #if defined(FFX_HLSL)
#if defined(FFX_GLSL)
#if FFX_HALF
#define FFX_MIN16_F float16_t
#define FFX_MIN16_F2 f16vec2
#define FFX_MIN16_F3 f16vec3
#define FFX_MIN16_F4 f16vec4
#define FFX_MIN16_I int16_t
#define FFX_MIN16_I2 i16vec2
#define FFX_MIN16_I3 i16vec3
#define FFX_MIN16_I4 i16vec4
#define FFX_MIN16_U uint16_t
#define FFX_MIN16_U2 u16vec2
#define FFX_MIN16_U3 u16vec3
#define FFX_MIN16_U4 u16vec4
#define FFX_16BIT_F float16_t
#define FFX_16BIT_F2 f16vec2
#define FFX_16BIT_F3 f16vec3
#define FFX_16BIT_F4 f16vec4
#define FFX_16BIT_I int16_t
#define FFX_16BIT_I2 i16vec2
#define FFX_16BIT_I3 i16vec3
#define FFX_16BIT_I4 i16vec4
#define FFX_16BIT_U uint16_t
#define FFX_16BIT_U2 u16vec2
#define FFX_16BIT_U3 u16vec3
#define FFX_16BIT_U4 u16vec4
#else // FFX_HALF
#define FFX_MIN16_F float
#define FFX_MIN16_F2 vec2
#define FFX_MIN16_F3 vec3
#define FFX_MIN16_F4 vec4
#define FFX_MIN16_I int
#define FFX_MIN16_I2 ivec2
#define FFX_MIN16_I3 ivec3
#define FFX_MIN16_I4 ivec4
#define FFX_MIN16_U uint
#define FFX_MIN16_U2 uvec2
#define FFX_MIN16_U3 uvec3
#define FFX_MIN16_U4 uvec4
#define FFX_16BIT_F float
#define FFX_16BIT_F2 vec2
#define FFX_16BIT_F3 vec3
#define FFX_16BIT_F4 vec4
#define FFX_16BIT_I int
#define FFX_16BIT_I2 ivec2
#define FFX_16BIT_I3 ivec3
#define FFX_16BIT_I4 ivec4
#define FFX_16BIT_U uint
#define FFX_16BIT_U2 uvec2
#define FFX_16BIT_U3 uvec3
#define FFX_16BIT_U4 uvec4
#endif // FFX_HALF
#endif // #if defined(FFX_GLSL)
#endif // #if defined(FFX_GPU)
#endif // #ifndef FFX_COMMON_TYPES_H
@@ -0,0 +1,80 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
/// @defgroup FfxGPU GPU
/// The FidelityFX SDK GPU References
///
/// @ingroup ffxSDK
/// @defgroup FfxHLSL HLSL References
/// FidelityFX SDK HLSL GPU References
///
/// @ingroup FfxGPU
/// @defgroup FfxGLSL GLSL References
/// FidelityFX SDK GLSL GPU References
///
/// @ingroup FfxGPU
/// @defgroup FfxGPUEffects FidelityFX GPU References
/// FidelityFX Effect GPU Reference Documentation
///
/// @ingroup FfxGPU
/// @defgroup GPUCore GPU Core
/// GPU defines and functions
///
/// @ingroup FfxGPU
#if !defined(FFX_CORE_H)
#define FFX_CORE_H
#ifdef __hlsl_dx_compiler
#pragma dxc diagnostic push
#pragma dxc diagnostic ignored "-Wambig-lit-shift"
#endif //__hlsl_dx_compiler
#include "ffx_common_types.h"
#if defined(FFX_CPU)
#include "ffx_core_cpu.h"
#endif // #if defined(FFX_CPU)
#if defined(FFX_GLSL) && defined(FFX_GPU)
#include "ffx_core_glsl.h"
#endif // #if defined(FFX_GLSL) && defined(FFX_GPU)
#if defined(FFX_HLSL) && defined(FFX_GPU)
#include "ffx_core_hlsl.h"
#endif // #if defined(FFX_HLSL) && defined(FFX_GPU)
#if defined(FFX_GPU)
#include "ffx_core_gpu_common.h"
#include "ffx_core_gpu_common_half.h"
#include "ffx_core_portability.h"
#endif // #if defined(FFX_GPU)
#ifdef __hlsl_dx_compiler
#pragma dxc diagnostic pop
#endif //__hlsl_dx_compiler
#endif // #if !defined(FFX_CORE_H)
@@ -0,0 +1,338 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
/// A define for a true value in a boolean expression.
///
/// @ingroup CPUTypes
#define FFX_TRUE (1)
/// A define for a false value in a boolean expression.
///
/// @ingroup CPUTypes
#define FFX_FALSE (0)
#if !defined(FFX_STATIC)
/// A define to abstract declaration of static variables and functions.
///
/// @ingroup CPUTypes
#define FFX_STATIC static
#endif // #if !defined(FFX_STATIC)
/// @defgroup CPUCore CPU Core
/// Core CPU-side defines and functions
///
/// @ingroup ffxHost
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
/// Interpret the bit layout of an IEEE-754 floating point value as an unsigned integer.
///
/// @param [in] x A 32bit floating value.
///
/// @returns
/// An unsigned 32bit integer value containing the bit pattern of <c><i>x</i></c>.
///
/// @ingroup CPUCore
FFX_STATIC FfxUInt32 ffxAsUInt32(FfxFloat32 x)
{
union
{
FfxFloat32 f;
FfxUInt32 u;
} bits;
bits.f = x;
return bits.u;
}
FFX_STATIC FfxFloat32 ffxDot2(FfxFloat32x2 a, FfxFloat32x2 b)
{
return a[0] * b[0] + a[1] * b[1];
}
FFX_STATIC FfxFloat32 ffxDot3(FfxFloat32x3 a, FfxFloat32x3 b)
{
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
FFX_STATIC FfxFloat32 ffxDot4(FfxFloat32x4 a, FfxFloat32x4 b)
{
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
}
/// Compute the linear interopation between two values.
///
/// Implemented by calling the GLSL <c><i>mix</i></c> instrinsic function. Implements the
/// following math:
///
/// (1 - t) * x + t * y
///
/// @param [in] x The first value to lerp between.
/// @param [in] y The second value to lerp between.
/// @param [in] t The value to determine how much of <c><i>x</i></c> and how much of <c><i>y</i></c>.
///
/// @returns
/// A linearly interpolated value between <c><i>x</i></c> and <c><i>y</i></c> according to <c><i>t</i></c>.
///
/// @ingroup CPUCore
FFX_STATIC FfxFloat32 ffxLerp(FfxFloat32 x, FfxFloat32 y, FfxFloat32 t)
{
return y * t + (-x * t + x);
}
/// Compute the reciprocal of a value.
///
/// @param [in] x The value to compute the reciprocal for.
///
/// @returns
/// The reciprocal value of <c><i>x</i></c>.
///
/// @ingroup CPUCore
FFX_STATIC FfxFloat32 ffxReciprocal(FfxFloat32 x)
{
return 1.0f / x;
}
/// Compute the square root of a value.
///
/// @param [in] x The first value to compute the min of.
///
/// @returns
/// The the square root of <c><i>x</i></c>.
///
/// @ingroup CPUCore
FFX_STATIC FfxFloat32 ffxSqrt(FfxFloat32 x)
{
return FfxFloat32(sqrt(x));
}
FFX_STATIC FfxUInt32 ffxAShrSU1(FfxUInt32 a, FfxUInt32 b)
{
return FfxUInt32(FfxInt32(a) >> FfxInt32(b));
}
/// Compute the factional part of a decimal value.
///
/// This function calculates <c><i>x - floor(x)</i></c>.
///
/// @param [in] x The value to compute the fractional part from.
///
/// @returns
/// The fractional part of <c><i>x</i></c>.
///
/// @ingroup CPUCore
FFX_STATIC FfxFloat32 ffxFract(FfxFloat32 x)
{
return x - FfxFloat32(floor(x));
}
/// Compute the reciprocal square root of a value.
///
/// @param [in] x The value to compute the reciprocal for.
///
/// @returns
/// The reciprocal square root value of <c><i>x</i></c>.
///
/// @ingroup CPUCore
FFX_STATIC FfxFloat32 ffxRsqrt(FfxFloat32 x)
{
return ffxReciprocal(ffxSqrt(x));
}
FFX_STATIC FfxFloat32 ffxMin(FfxFloat32 x, FfxFloat32 y)
{
return x < y ? x : y;
}
FFX_STATIC FfxUInt32 ffxMin(FfxUInt32 x, FfxUInt32 y)
{
return x < y ? x : y;
}
FFX_STATIC FfxFloat32 ffxMax(FfxFloat32 x, FfxFloat32 y)
{
return x > y ? x : y;
}
FFX_STATIC FfxUInt32 ffxMax(FfxUInt32 x, FfxUInt32 y)
{
return x > y ? x : y;
}
/// Clamp a value to a [0..1] range.
///
/// @param [in] x The value to clamp to [0..1] range.
///
/// @returns
/// The clamped version of <c><i>x</i></c>.
///
/// @ingroup CPUCore
FFX_STATIC FfxFloat32 ffxSaturate(FfxFloat32 x)
{
return ffxMin(1.0f, ffxMax(0.0f, x));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FFX_STATIC void ffxOpAAddOneF3(FfxFloat32x3 d, FfxFloat32x3 a, FfxFloat32 b)
{
d[0] = a[0] + b;
d[1] = a[1] + b;
d[2] = a[2] + b;
return;
}
FFX_STATIC void ffxOpACpyF3(FfxFloat32x3 d, FfxFloat32x3 a)
{
d[0] = a[0];
d[1] = a[1];
d[2] = a[2];
return;
}
FFX_STATIC void ffxOpAMulF3(FfxFloat32x3 d, FfxFloat32x3 a, FfxFloat32x3 b)
{
d[0] = a[0] * b[0];
d[1] = a[1] * b[1];
d[2] = a[2] * b[2];
return;
}
FFX_STATIC void ffxOpAMulOneF3(FfxFloat32x3 d, FfxFloat32x3 a, FfxFloat32 b)
{
d[0] = a[0] * b;
d[1] = a[1] * b;
d[2] = a[2] * b;
return;
}
FFX_STATIC void ffxOpARcpF3(FfxFloat32x3 d, FfxFloat32x3 a)
{
d[0] = ffxReciprocal(a[0]);
d[1] = ffxReciprocal(a[1]);
d[2] = ffxReciprocal(a[2]);
return;
}
/// Convert FfxFloat32 to half (in lower 16-bits of output).
///
/// This function implements the same fast technique that is documented here: ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf
///
/// The function supports denormals.
///
/// Some conversion rules are to make computations possibly "safer" on the GPU,
/// -INF & -NaN -> -65504
/// +INF & +NaN -> +65504
///
/// @param [in] f The 32bit floating point value to convert.
///
/// @returns
/// The closest 16bit floating point value to <c><i>f</i></c>.
///
/// @ingroup CPUCore
FFX_STATIC FfxUInt32 ffxF32ToF16(FfxFloat32 f)
{
static FfxUInt16 base[512] = {
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400,
0x0800, 0x0c00, 0x1000, 0x1400, 0x1800, 0x1c00, 0x2000, 0x2400, 0x2800, 0x2c00, 0x3000, 0x3400, 0x3800, 0x3c00, 0x4000, 0x4400, 0x4800, 0x4c00, 0x5000,
0x5400, 0x5800, 0x5c00, 0x6000, 0x6400, 0x6800, 0x6c00, 0x7000, 0x7400, 0x7800, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff,
0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff,
0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff,
0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff,
0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff,
0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff,
0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x7bff, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000,
0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000,
0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000,
0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000,
0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000,
0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8001, 0x8002,
0x8004, 0x8008, 0x8010, 0x8020, 0x8040, 0x8080, 0x8100, 0x8200, 0x8400, 0x8800, 0x8c00, 0x9000, 0x9400, 0x9800, 0x9c00, 0xa000, 0xa400, 0xa800, 0xac00,
0xb000, 0xb400, 0xb800, 0xbc00, 0xc000, 0xc400, 0xc800, 0xcc00, 0xd000, 0xd400, 0xd800, 0xdc00, 0xe000, 0xe400, 0xe800, 0xec00, 0xf000, 0xf400, 0xf800,
0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff,
0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff,
0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff,
0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff,
0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff,
0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff, 0xfbff
};
static FfxUInt8 shift[512] = {
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0x0f, 0x0e, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d,
0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0x0f, 0x0e, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d,
0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18
};
union
{
FfxFloat32 f;
FfxUInt32 u;
} bits;
bits.f = f;
FfxUInt32 u = bits.u;
FfxUInt32 i = u >> 23;
return (FfxUInt32)(base[i]) + ((u & 0x7fffff) >> shift[i]);
}
/// Pack 2x32-bit floating point values in a single 32bit value.
///
/// This function first converts each component of <c><i>value</i></c> into their nearest 16-bit floating
/// point representation, and then stores the X and Y components in the lower and upper 16 bits of the
/// 32bit unsigned integer respectively.
///
/// @param [in] x A 2-dimensional floating point value to convert and pack.
///
/// @returns
/// A packed 32bit value containing 2 16bit floating point values.
///
/// @ingroup CPUCore
FFX_STATIC FfxUInt32 ffxPackHalf2x16(FfxFloat32x2 x)
{
return ffxF32ToF16(x[0]) + (ffxF32ToF16(x[1]) << 16);
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,46 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
void ffxOpAAddOneF3(FFX_PARAMETER_OUT FfxFloat32x3 d, FfxFloat32x3 a, FfxFloat32 b)
{
d = a + ffxBroadcast3(b);
}
void ffxOpACpyF3(FFX_PARAMETER_OUT FfxFloat32x3 d, FfxFloat32x3 a)
{
d = a;
}
void ffxOpAMulF3(FFX_PARAMETER_OUT FfxFloat32x3 d, FfxFloat32x3 a, FfxFloat32x3 b)
{
d = a * b;
}
void ffxOpAMulOneF3(FFX_PARAMETER_OUT FfxFloat32x3 d, FfxFloat32x3 a, FfxFloat32 b)
{
d = a * b;
}
void ffxOpARcpF3(FFX_PARAMETER_OUT FfxFloat32x3 d, FfxFloat32x3 a)
{
d = ffxReciprocal(a);
}
@@ -0,0 +1,187 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_H
#define FFX_FRAMEINTERPOLATION_H
struct InterpolationSourceColor
{
FfxFloat32x3 fRaw;
FfxFloat32x3 fLinear;
FfxFloat32 fBilinearWeightSum;
};
InterpolationSourceColor NewInterpolationSourceColor()
{
InterpolationSourceColor c;
c.fRaw = FfxFloat32x3(0.0, 0.0, 0.0);
c.fLinear = FfxFloat32x3(0.0, 0.0, 0.0);
c.fBilinearWeightSum = 0.0;
return c;
}
InterpolationSourceColor SampleTextureBilinear(FfxBoolean isCurrent, FfxFloat32x2 fUv, FfxFloat32x2 fMotionVector, FfxInt32x2 texSize)
{
InterpolationSourceColor result = NewInterpolationSourceColor();
FfxFloat32x2 fReprojectedUv = fUv + fMotionVector;
BilinearSamplingData bilinearInfo = GetBilinearSamplingData(fReprojectedUv, texSize);
FfxFloat32x3 fColor = FfxFloat32x3(0.0, 0.0, 0.0);
FfxFloat32 fWeightSum = 0.0f;
for (FfxInt32 iSampleIndex = 0; iSampleIndex < 4; iSampleIndex++) {
const FfxInt32x2 iOffset = bilinearInfo.iOffsets[iSampleIndex];
const FfxInt32x2 iSamplePos = bilinearInfo.iBasePos + iOffset;
if (IsInRect(iSamplePos, InterpolationRectBase(), InterpolationRectSize()))
{
FfxFloat32 fWeight = bilinearInfo.fWeights[iSampleIndex];
if (isCurrent)
fColor += LoadCurrentBackbuffer(iSamplePos).rgb * fWeight;
else
fColor += LoadPreviousBackbuffer(iSamplePos).rgb * fWeight;
fWeightSum += fWeight;
}
}
//normalize colors
fColor = (fWeightSum != 0.0f) ? fColor / fWeightSum : FfxFloat32x3(0.0f, 0.0f, 0.0f);
result.fRaw = fColor;
result.fLinear = RawRGBToLinear(fColor);
result.fBilinearWeightSum = fWeightSum;
return result;
}
void updateInPaintingWeight(inout FfxFloat32 fInPaintingWeight, FfxFloat32 fFactor)
{
fInPaintingWeight = ffxSaturate(ffxMax(fInPaintingWeight, fFactor));
}
void computeInterpolatedColor(FfxUInt32x2 iPxPos, out FfxFloat32x3 fInterpolatedColor, inout FfxFloat32 fInPaintingWeight)
{
const FfxFloat32x2 fUvInInterpolationRect = (FfxFloat32x2(iPxPos - InterpolationRectBase()) + 0.5f) / InterpolationRectSize();
const FfxFloat32x2 fUvInScreenSpace = (FfxFloat32x2(iPxPos) + 0.5f) / DisplaySize();
const FfxFloat32x2 fLrUvInInterpolationRect = fUvInInterpolationRect * (FfxFloat32x2(RenderSize()) / GetMaxRenderSize());
const FfxFloat32x2 fUvLetterBoxScale = FfxFloat32x2(InterpolationRectSize()) / DisplaySize();
// game MV are top left aligned, the function scales them to render res UV
VectorFieldEntry gameMv;
LoadInpaintedGameFieldMv(fUvInInterpolationRect, gameMv);
// OF is done on the back buffers which already have black bars
VectorFieldEntry ofMv;
SampleOpticalFlowMotionVectorField(fUvInScreenSpace, ofMv);
// Binarize disucclusion factor
FfxFloat32x2 fDisocclusionFactor = FfxFloat32x2(FFX_EQUAL(ffxSaturate(SampleDisocclusionMask(fLrUvInInterpolationRect).xy), FfxFloat32x2(1.0, 1.0)));
InterpolationSourceColor fPrevColorGame = SampleTextureBilinear(false, fUvInScreenSpace, +gameMv.fMotionVector * fUvLetterBoxScale, DisplaySize()); // Get in previous frame buffer, the color of interpolated pixel
InterpolationSourceColor fCurrColorGame = SampleTextureBilinear(true, fUvInScreenSpace, -gameMv.fMotionVector * fUvLetterBoxScale, DisplaySize()); // Get color in current framebuffer, of color of interpolated pixel
InterpolationSourceColor fPrevColorOF = SampleTextureBilinear(false, fUvInScreenSpace, +ofMv.fMotionVector * fUvLetterBoxScale, DisplaySize());
InterpolationSourceColor fCurrColorOF = SampleTextureBilinear(true, fUvInScreenSpace, -ofMv.fMotionVector * fUvLetterBoxScale, DisplaySize());
FfxFloat32 fDisoccludedFactor = 0.0f;
// Disocclusion logic
{
fDisocclusionFactor.x *= FfxFloat32(!gameMv.bPosOutside); // fDisocclusionFactor.x of 1 means the pos of interpolated pixel is within bounds of previous frame.
fDisocclusionFactor.y *= FfxFloat32(!gameMv.bNegOutside); // fDisocclusionFactor.y of 1 means the pos of interpolated pixel is within bounds of current frame
// Inpaint in bi-directional disocclusion areas
updateInPaintingWeight(fInPaintingWeight, FfxFloat32(length(fDisocclusionFactor) <= FFX_FRAMEINTERPOLATION_EPSILON));
FfxFloat32 t = 0.5f;
t += 0.5f * (1 - (fDisocclusionFactor.x));
t -= 0.5f * (1 - (fDisocclusionFactor.y));
// Say if fDisocclusionFactor.x is 1 and fDisocclusionFactor.y = 0, then t will be 0. fInterpolatedColor will be entirely from fPrevColorGame
fInterpolatedColor = ffxLerp(fPrevColorGame.fRaw, fCurrColorGame.fRaw, ffxSaturate(t));
fDisoccludedFactor = ffxSaturate(1 - ffxMin(fDisocclusionFactor.x, fDisocclusionFactor.y));
if (fPrevColorGame.fBilinearWeightSum == 0.0f)
{
fInterpolatedColor = fCurrColorGame.fRaw;
}
else if (fCurrColorGame.fBilinearWeightSum == 0.0f)
{
fInterpolatedColor = fPrevColorGame.fRaw;
}
if (fPrevColorGame.fBilinearWeightSum == 0 && fCurrColorGame.fBilinearWeightSum == 0)
{
fInPaintingWeight = 1.0f;
}
}
{
FfxFloat32 ofT = 0.5f;
if (fPrevColorOF.fBilinearWeightSum > 0 && fCurrColorOF.fBilinearWeightSum > 0)
{
ofT = 0.5f;
}
else if (fPrevColorOF.fBilinearWeightSum > 0)
{
ofT = 0;
} else {
ofT = 1;
}
const FfxFloat32x3 ofColor = ffxLerp(fPrevColorOF.fRaw, fCurrColorOF.fRaw, ofT);
FfxFloat32 fOF_Sim = NormalizedDot3(fPrevColorOF.fRaw, fCurrColorOF.fRaw);
FfxFloat32 fGame_Sim = NormalizedDot3(fPrevColorGame.fRaw, fCurrColorGame.fRaw);
fGame_Sim = ffxLerp(ffxMax(FFX_FRAMEINTERPOLATION_EPSILON, fGame_Sim), 1.0f, ffxSaturate(fDisoccludedFactor));
FfxFloat32 fGameMvBias = ffxPow(ffxSaturate(fGame_Sim / ffxMax(FFX_FRAMEINTERPOLATION_EPSILON, fOF_Sim)), 1.0f);
const FfxFloat32 fFrameIndexFactor = FfxFloat32(FrameIndexSinceLastReset() < 10);
fGameMvBias = ffxLerp(fGameMvBias, 1.0f, fFrameIndexFactor);
fInterpolatedColor = ffxLerp(ofColor, fInterpolatedColor, ffxSaturate(fGameMvBias));
}
}
void computeFrameinterpolation(FfxInt32x2 iPxPos)
{
FfxFloat32x3 fColor = FfxFloat32x3(0, 0, 0);
FfxFloat32 fInPaintingWeight = 0.0f;
if (IsInRect(iPxPos, InterpolationRectBase(), InterpolationRectSize()) == false || FrameIndexSinceLastReset() == 0)
{
// if we just reset or we are out of the interpolation rect, copy the current back buffer and don't interpolate
fColor = LoadCurrentBackbuffer(iPxPos);
}
else
{
computeInterpolatedColor(iPxPos, fColor, fInPaintingWeight);
}
StoreFrameinterpolationOutput(FfxInt32x2(iPxPos), FfxFloat32x4(fColor, fInPaintingWeight));
}
#endif // FFX_FRAMEINTERPOLATION_H
@@ -0,0 +1,758 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#include "ffx_frameinterpolation_resources.h"
#include "ffx_core.h"
#define COUNTER_SPD 0
#define COUNTER_FRAME_INDEX_SINCE_LAST_RESET 1
///////////////////////////////////////////////
// declare CBs and CB accessors
///////////////////////////////////////////////
#if defined(FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION)
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION, std140) uniform cbFI_t
{
FfxInt32x2 renderSize;
FfxInt32x2 displaySize;
FfxFloat32x2 displaySizeRcp;
FfxFloat32 cameraNear;
FfxFloat32 cameraFar;
FfxInt32x2 upscalerTargetSize;
FfxInt32 Mode;
FfxInt32 reset;
FfxFloat32x4 fDeviceToViewDepth;
FfxFloat32 deltaTime;
FfxInt32 HUDLessAttachedFactor;
FfxInt32x2 distortionFieldSize;
FfxFloat32x2 opticalFlowScale;
FfxInt32 opticalFlowBlockSize;
FfxUInt32 dispatchFlags;
FfxInt32x2 maxRenderSize;
FfxInt32 opticalFlowHalfResMode;
FfxInt32 NumInstances;
FfxInt32x2 interpolationRectBase;
FfxInt32x2 interpolationRectSize;
FfxFloat32x3 debugBarColor;
FfxUInt32 backBufferTransferFunction;
FfxFloat32x2 minMaxLuminance;
FfxFloat32 fTanHalfFOV;
FfxInt32 _pad1;
FfxFloat32x2 fJitter;
FfxFloat32x2 fMotionVectorScale;
} cbFI;
FfxFloat32x2 Jitter()
{
return cbFI.fJitter;
}
FfxInt32x2 InterpolationRectBase()
{
return cbFI.interpolationRectBase;
}
FfxInt32x2 InterpolationRectSize()
{
return cbFI.interpolationRectSize;
}
FfxFloat32x2 MotionVectorScale()
{
return cbFI.fMotionVectorScale;
}
FfxInt32x2 RenderSize()
{
return cbFI.renderSize;
}
FfxInt32x2 DisplaySize()
{
return cbFI.displaySize;
}
FfxBoolean Reset()
{
return cbFI.reset == 1;
}
FfxFloat32x4 DeviceToViewSpaceTransformFactors()
{
return cbFI.fDeviceToViewDepth;
}
FfxInt32x2 GetOpticalFlowSize()
{
FfxInt32x2 iOpticalFlowSize = FfxInt32x2((1.0 / cbFI.opticalFlowScale) / FfxFloat32x2(cbFI.opticalFlowBlockSize.xx));
return iOpticalFlowSize;
}
FfxInt32x2 GetOpticalFlowSize2()
{
return GetOpticalFlowSize() * 1;
}
FfxFloat32x2 GetOpticalFlowScale()
{
return cbFI.opticalFlowScale;
}
FfxInt32 GetOpticalFlowBlockSize()
{
return cbFI.opticalFlowBlockSize;
}
FfxInt32 GetHUDLessAttachedFactor()
{
return cbFI.HUDLessAttachedFactor;
}
FfxInt32x2 GetDistortionFieldSize()
{
return cbFI.distortionFieldSize;
}
FfxUInt32 GetDispatchFlags()
{
return cbFI.dispatchFlags;
}
FfxInt32x2 GetMaxRenderSize()
{
return cbFI.maxRenderSize;
}
FfxInt32 GetOpticalFlowHalfResMode()
{
return cbFI.opticalFlowHalfResMode;
}
FfxFloat32x3 GetDebugBarColor()
{
return cbFI.debugBarColor;
}
FfxFloat32 TanHalfFoV()
{
return cbFI.fTanHalfFOV;
}
FfxUInt32 BackBufferTransferFunction()
{
return cbFI.backBufferTransferFunction;
}
FfxFloat32 MinLuminance()
{
return cbFI.minMaxLuminance[0];
}
FfxFloat32 MaxLuminance()
{
return cbFI.minMaxLuminance[1];
}
#endif // defined(FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION)
#if defined(FFX_FRAMEINTERPOLATION_BIND_CB_INPAINTING_PYRAMID)
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_CB_INPAINTING_PYRAMID, std140) uniform cbInpaintingPyramid_t
{
FfxUInt32 mips;
FfxUInt32 numWorkGroups;
FfxUInt32x2 workGroupOffset;
} cbInpaintingPyramid;
FfxUInt32 NumMips()
{
return cbInpaintingPyramid.mips;
}
FfxUInt32 NumWorkGroups()
{
return cbInpaintingPyramid.numWorkGroups;
}
FfxUInt32x2 WorkGroupOffset()
{
return cbInpaintingPyramid.workGroupOffset;
}
#endif // defined(FFX_FRAMEINTERPOLATION_BIND_CB_INPAINTING_PYRAMID)
///////////////////////////////////////////////
// declare samplers
///////////////////////////////////////////////
layout (set = 0, binding = 1000) uniform sampler s_LinearClamp;
///////////////////////////////////////////////
// declare SRVs and SRV accessors
///////////////////////////////////////////////
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_PREVIOUS_INTERPOLATION_SOURCE
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_PREVIOUS_INTERPOLATION_SOURCE) uniform texture2D r_previous_interpolation_source;
FfxFloat32x3 LoadPreviousBackbuffer(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return texelFetch(r_previous_interpolation_source, iPxPos, 0).rgb;
}
FfxFloat32x3 SamplePreviousBackbuffer(FFX_PARAMETER_IN FfxFloat32x2 fUv)
{
return textureLod(sampler2D(r_previous_interpolation_source, s_LinearClamp), fUv, 0.0).xyz;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_CURRENT_INTERPOLATION_SOURCE
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_CURRENT_INTERPOLATION_SOURCE) uniform texture2D r_current_interpolation_source;
FfxFloat32x3 LoadCurrentBackbuffer(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return texelFetch(r_current_interpolation_source, iPxPos, 0).rgb;
}
FfxFloat32x3 SampleCurrentBackbuffer(FFX_PARAMETER_IN FfxFloat32x2 fUv)
{
return textureLod(sampler2D(r_current_interpolation_source, s_LinearClamp), fUv, 0.0).xyz;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_MOTION_VECTORS
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_MOTION_VECTORS) uniform texture2D r_dilated_motion_vectors;
FfxFloat32x2 LoadDilatedMotionVector(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return texelFetch(r_dilated_motion_vectors, iPxPos, 0).xy;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_DEPTH
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_DEPTH) uniform texture2D r_dilated_depth;
FfxFloat32 LoadDilatedDepth(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return texelFetch(r_dilated_depth, iPxPos, 0).x;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_RECONSTRUCTED_DEPTH_PREVIOUS_FRAME
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_RECONSTRUCTED_DEPTH_PREVIOUS_FRAME) uniform utexture2D r_reconstructed_depth_previous_frame;
FfxFloat32 LoadReconstructedDepthPreviousFrame(FFX_PARAMETER_IN FfxInt32x2 iPxInput)
{
return ffxAsFloat(texelFetch(r_reconstructed_depth_previous_frame, iPxInput, 0).x);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_RECONSTRUCTED_DEPTH_INTERPOLATED_FRAME
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_RECONSTRUCTED_DEPTH_INTERPOLATED_FRAME) uniform utexture2D r_reconstructed_depth_interpolated_frame;
FfxFloat32 LoadEstimatedInterpolationFrameDepth(FFX_PARAMETER_IN FfxInt32x2 iPxInput)
{
return ffxAsFloat(texelFetch(r_reconstructed_depth_interpolated_frame, iPxInput, 0).x);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_DISOCCLUSION_MASK
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_DISOCCLUSION_MASK) uniform texture2D r_disocclusion_mask;
FfxFloat32x4 LoadDisocclusionMask(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return texelFetch(r_disocclusion_mask, iPxPos, 0);
}
FfxFloat32x4 SampleDisocclusionMask(FFX_PARAMETER_IN FfxFloat32x2 fUv)
{
return textureLod(sampler2D(r_disocclusion_mask, s_LinearClamp), fUv, 0);
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_X) && \
defined(FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_Y)
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_X) uniform utexture2D r_game_motion_vector_field_x;
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_Y) uniform utexture2D r_game_motion_vector_field_y;
FfxUInt32x2 LoadGameFieldMv(FFX_PARAMETER_IN FfxInt32x2 iPxSample)
{
FfxUInt32 packedX = texelFetch(r_game_motion_vector_field_x, iPxSample, 0).x;
FfxUInt32 packedY = texelFetch(r_game_motion_vector_field_y, iPxSample, 0).x;
return FfxUInt32x2(packedX, packedY);
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X) && \
defined(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y)
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X) uniform utexture2D r_optical_flow_motion_vector_field_x;
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y) uniform utexture2D r_optical_flow_motion_vector_field_y;
FfxUInt32x2 LoadOpticalFlowFieldMv(FFX_PARAMETER_IN FfxInt32x2 iPxSample)
{
FfxUInt32 packedX = texelFetch(r_optical_flow_motion_vector_field_x, iPxSample, 0).x;
FfxUInt32 packedY = texelFetch(r_optical_flow_motion_vector_field_y, iPxSample, 0).x;
return FfxUInt32x2(packedX, packedY);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW) uniform itexture2D r_optical_flow;
#if defined(FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION)
FfxFloat32x2 LoadOpticalFlow(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return texelFetch(r_optical_flow, iPxPos, 0).xy * GetOpticalFlowScale();
}
#endif
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_UPSAMPLED
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_UPSAMPLED) uniform texture2D r_optical_flow_upsampled;
FfxFloat32x2 LoadOpticalFlowUpsampled(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return texelFetch(r_optical_flow_upsampled, iPxPos, 0).xy;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_CONFIDENCE
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_CONFIDENCE) uniform utexture2D r_optical_flow_confidence;
FfxFloat32 LoadOpticalFlowConfidence(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return texelFetch(r_optical_flow_confidence, iPxPos, 0).y;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_GLOBAL_MOTION
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_GLOBAL_MOTION) uniform utexture2D r_optical_flow_global_motion;
FfxUInt32 LoadOpticalFlowGlobalMotion(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return texelFetch(r_optical_flow_global_motion, iPxPos, 0).x;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_SCENE_CHANGE_DETECTION
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_SCENE_CHANGE_DETECTION) uniform utexture2D r_optical_flow_scd;
FfxUInt32 LoadOpticalFlowSceneChangeDetection(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return texelFetch(r_optical_flow_scd, iPxPos, 0).x;
}
FfxBoolean HasSceneChanged()
{
#define SCD_OUTPUT_HISTORY_BITS_SLOT 1
//if (FrameIndex() <= 5) // threshold according to original OpenCL code
//{
// return 1.0;
//}
//else
{
// Report that the scene is changed if the change was detected in any of the
// 4 previous frames (0xfu - covers 4 history bits).
return ((texelFetch(r_optical_flow_scd, FfxInt32x2(SCD_OUTPUT_HISTORY_BITS_SLOT, 0), 0).x) & 0xfu) != 0;
}
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_DEBUG
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_DEBUG) uniform texture2D r_optical_flow_debug;
FfxFloat32x4 LoadOpticalFlowDebug(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return texelFetch(r_optical_flow_debug, iPxPos, 0);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OUTPUT
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_OUTPUT) uniform texture2D r_output;
FfxFloat32x4 LoadFrameInterpolationOutput(FFX_PARAMETER_IN FfxInt32x2 iPxInput)
{
return texelFetch(r_output, iPxInput, 0);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_INPAINTING_PYRAMID
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_INPAINTING_PYRAMID) uniform texture2D r_inpainting_pyramid;
FfxFloat32x4 LoadInpaintingPyramid(FFX_PARAMETER_IN FfxInt32 mipLevel, FFX_PARAMETER_IN FfxUInt32x2 iPxInput)
{
return texelFetch(r_inpainting_pyramid, FfxInt32x2(iPxInput), mipLevel);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_PRESENT_BACKBUFFER
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_PRESENT_BACKBUFFER) uniform texture2D r_present_backbuffer;
FfxFloat32x4 LoadPresentBackbuffer(FFX_PARAMETER_IN FfxInt32x2 iPxInput)
{
return texelFetch(r_present_backbuffer, iPxInput, 0);
}
FfxFloat32x4 SamplePresentBackbuffer(FFX_PARAMETER_IN FfxFloat32x2 fUv)
{
return textureLod(sampler2D(r_present_backbuffer, s_LinearClamp), fUv, 0.0);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_COUNTERS
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_COUNTERS) readonly buffer FrameInterpolationCounters_t
{
FfxUInt32 data[];
} r_counters;
FfxUInt32 LoadCounter(FFX_PARAMETER_IN FfxInt32 iPxPos)
{
return r_counters.data[iPxPos];
}
FfxUInt32 FrameIndexSinceLastReset()
{
return LoadCounter(COUNTER_FRAME_INDEX_SINCE_LAST_RESET);
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_INPUT_DEPTH)
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_INPUT_DEPTH) uniform texture2D r_input_depth;
FfxFloat32 LoadInputDepth(FfxInt32x2 iPxPos)
{
return texelFetch(r_input_depth, iPxPos, 0).x;
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_INPUT_MOTION_VECTORS)
layout (set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_INPUT_MOTION_VECTORS) uniform texture2D r_input_motion_vectors;
FfxFloat32x2 LoadInputMotionVector(FfxInt32x2 iPxDilatedMotionVectorPos)
{
FfxFloat32x2 fSrcMotionVector = texelFetch(r_input_motion_vectors, iPxDilatedMotionVectorPos, 0).xy;
FfxFloat32x2 fUvMotionVector = fSrcMotionVector * MotionVectorScale();
#if FFX_FRAMEINTERPOLATION_OPTION_JITTERED_MOTION_VECTORS
fUvMotionVector -= MotionVectorJitterCancellation();
#endif
return fUvMotionVector;
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_DISTORTION_FIELD)
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_SRV_DISTORTION_FIELD) uniform texture2D r_input_distortion_field;
FfxFloat32x2 SampleDistortionField(FFX_PARAMETER_IN FfxFloat32x2 fUv)
{
return textureLod(sampler2D(r_input_distortion_field, s_LinearClamp), fUv, 0.0).xy;
}
#endif
///////////////////////////////////////////////
// declare UAVs and UAV accessors
///////////////////////////////////////////////
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_OUTPUT
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_OUTPUT /* app controlled format */) uniform image2D rw_output;
FfxFloat32x4 RWLoadFrameinterpolationOutput(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return imageLoad(rw_output, iPxPos);
}
void StoreFrameinterpolationOutput(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32x4 val)
{
imageStore(rw_output, iPxPos, val);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_DILATED_MOTION_VECTORS
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_DILATED_MOTION_VECTORS, rg16f) uniform image2D rw_dilated_motion_vectors;
FfxFloat32x2 RWLoadDilatedMotionVectors(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return imageLoad(rw_dilated_motion_vectors, iPxPos).xy;
}
void StoreDilatedMotionVectors(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32x2 val)
{
imageStore(rw_dilated_motion_vectors, iPxPos, FfxFloat32x4(val, 0.0, 0.0));
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_DILATED_DEPTH
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_DILATED_DEPTH, r32f) uniform image2D rw_dilated_depth;
FfxFloat32 RWLoadDilatedDepth(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return imageLoad(rw_dilated_depth, iPxPos).x;
}
void StoreDilatedDepth(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32 val)
{
imageStore(rw_dilated_depth, iPxPos, FfxFloat32x4(val, 0.0, 0.0, 0.0));
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_RECONSTRUCTED_DEPTH_PREVIOUS_FRAME
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_RECONSTRUCTED_DEPTH_PREVIOUS_FRAME, r32ui) uniform uimage2D rw_reconstructed_depth_previous_frame;
FfxFloat32 RWLoadReconstructedDepthPreviousFrame(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return ffxAsFloat(imageLoad(rw_reconstructed_depth_previous_frame, iPxPos).x);
}
void UpdateReconstructedDepthPreviousFrame(FfxInt32x2 iPxSample, FfxFloat32 fDepth)
{
FfxUInt32 uDepth = ffxAsUInt32(fDepth);
#if FFX_FRAMEINTERPOLATION_OPTION_INVERTED_DEPTH
imageAtomicMax(rw_reconstructed_depth_previous_frame, iPxSample, uDepth);
#else
imageAtomicMin(rw_reconstructed_depth_previous_frame, iPxSample, uDepth); // min for standard, max for inverted depth
#endif
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_RECONSTRUCTED_DEPTH_INTERPOLATED_FRAME
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_RECONSTRUCTED_DEPTH_INTERPOLATED_FRAME, r32ui) uniform uimage2D rw_reconstructed_depth_interpolated_frame;
FfxFloat32 RWLoadReconstructedDepthInterpolatedFrame(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return ffxAsFloat(imageLoad(rw_reconstructed_depth_interpolated_frame, iPxPos).x);
}
void StoreReconstructedDepthInterpolatedFrame(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32 value)
{
FfxUInt32 uDepth = ffxAsUInt32(value);
imageStore(rw_reconstructed_depth_interpolated_frame, iPxPos, FfxUInt32x4(uDepth, 0, 0, 0));
}
void UpdateReconstructedDepthInterpolatedFrame(FfxInt32x2 iPxSample, FfxFloat32 fDepth)
{
FfxUInt32 uDepth = ffxAsUInt32(fDepth);
#if FFX_FRAMEINTERPOLATION_OPTION_INVERTED_DEPTH
imageAtomicMax(rw_reconstructed_depth_interpolated_frame, iPxSample, uDepth);
#else
imageAtomicMin(rw_reconstructed_depth_interpolated_frame, iPxSample, uDepth); // min for standard, max for inverted depth
#endif
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_DISOCCLUSION_MASK
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_DISOCCLUSION_MASK, rg8) uniform image2D rw_disocclusion_mask;
FfxFloat32x2 RWLoadDisocclusionMask(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return imageLoad(rw_disocclusion_mask, iPxPos).xy;
}
void StoreDisocclusionMask(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32x2 val)
{
imageStore(rw_disocclusion_mask, iPxPos, FfxFloat32x4(val, 0.0, 0.0));
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_X) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_Y)
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_X, r32ui) uniform uimage2D rw_game_motion_vector_field_x;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_Y, r32ui) uniform uimage2D rw_game_motion_vector_field_y;
FfxUInt32 RWLoadGameMotionVectorFieldX(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return imageLoad(rw_game_motion_vector_field_x, iPxPos).x;
}
void StoreGameMotionVectorFieldX(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32 val)
{
imageStore(rw_game_motion_vector_field_x, iPxPos, FfxUInt32x4(val, 0, 0, 0));
}
FfxUInt32 RWLoadGameMotionVectorFieldY(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return imageLoad(rw_game_motion_vector_field_y, iPxPos).x;
}
void StoreGameMotionVectorFieldY(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32 val)
{
imageStore(rw_game_motion_vector_field_y, iPxPos, FfxUInt32x4(val, 0, 0, 0));
}
void UpdateGameMotionVectorField(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32x2 packedVector)
{
imageAtomicMax(rw_game_motion_vector_field_x, iPxPos, packedVector.x);
imageAtomicMax(rw_game_motion_vector_field_y, iPxPos, packedVector.y);
}
FfxUInt32 UpdateGameMotionVectorFieldEx(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32x2 packedVector)
{
FfxUInt32 uPreviousValueX = imageAtomicMax(rw_game_motion_vector_field_x, iPxPos, packedVector.x);
FfxUInt32 uPreviousValueY = imageAtomicMax(rw_game_motion_vector_field_y, iPxPos, packedVector.y);
const FfxUInt32 uExistingVectorFieldEntry = ffxMax(uPreviousValueX, uPreviousValueY);
return uExistingVectorFieldEntry;
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y)
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X, r32ui) uniform uimage2D rw_optical_flow_motion_vector_field_x;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y, r32ui) uniform uimage2D rw_optical_flow_motion_vector_field_y;
FfxUInt32 RWLoadOpticalflowMotionVectorFieldX(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return imageLoad(rw_optical_flow_motion_vector_field_x, iPxPos).x;
}
void StoreOpticalflowMotionVectorFieldX(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32 val)
{
imageStore(rw_optical_flow_motion_vector_field_x, iPxPos, FfxUInt32x4(val, 0, 0, 0));
}
FfxUInt32 RWLoadOpticalflowMotionVectorFieldY(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return imageLoad(rw_optical_flow_motion_vector_field_y, iPxPos).x;
}
void StoreOpticalflowMotionVectorFieldY(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32 val)
{
imageStore(rw_optical_flow_motion_vector_field_y, iPxPos, FfxUInt32x4(val, 0, 0, 0));
}
void UpdateOpticalflowMotionVectorField(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32x2 packedVector)
{
imageAtomicMax(rw_optical_flow_motion_vector_field_x, iPxPos, packedVector.x);
imageAtomicMax(rw_optical_flow_motion_vector_field_y, iPxPos, packedVector.y);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_COUNTERS
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_COUNTERS) coherent buffer FrameInterpolationRWCounters_t
{
FfxUInt32 data[];
} rw_counters;
FfxUInt32 RWLoadCounter(FFX_PARAMETER_IN FfxInt32 iPxPos)
{
return rw_counters.data[iPxPos];
}
void StoreCounter(FFX_PARAMETER_IN FfxInt32 iPxPos, FFX_PARAMETER_IN FfxUInt32 counter)
{
rw_counters.data[iPxPos] = counter;
}
void AtomicIncreaseCounter(FFX_PARAMETER_IN FfxInt32 iPxPos, FFX_PARAMETER_OUT FfxUInt32 oldVal)
{
oldVal = atomicAdd(rw_counters.data[iPxPos], 1);
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_0) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_1) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_2) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_3) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_4) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_5) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_6) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_7) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_8) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_9) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_10) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_11) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_12)
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_0, rgba16f) uniform image2D rw_inpainting_pyramid0;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_1, rgba16f) uniform image2D rw_inpainting_pyramid1;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_2, rgba16f) uniform image2D rw_inpainting_pyramid2;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_3, rgba16f) uniform image2D rw_inpainting_pyramid3;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_4, rgba16f) uniform image2D rw_inpainting_pyramid4;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_5, rgba16f) coherent uniform image2D rw_inpainting_pyramid5;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_6, rgba16f) uniform image2D rw_inpainting_pyramid6;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_7, rgba16f) uniform image2D rw_inpainting_pyramid7;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_8, rgba16f) uniform image2D rw_inpainting_pyramid8;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_9, rgba16f) uniform image2D rw_inpainting_pyramid9;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_10, rgba16f) uniform image2D rw_inpainting_pyramid10;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_11, rgba16f) uniform image2D rw_inpainting_pyramid11;
layout(set = 0, binding = FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_12, rgba16f) uniform image2D rw_inpainting_pyramid12;
FfxFloat32x4 RWLoadInpaintingPyramid(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32 index)
{
#define LOAD(idx) \
if (index == idx) \
{ \
return imageLoad(rw_inpainting_pyramid##idx, iPxPos); \
}
LOAD(0);
LOAD(1);
LOAD(2);
LOAD(3);
LOAD(4);
LOAD(5);
LOAD(6);
LOAD(7);
LOAD(8);
LOAD(9);
LOAD(10);
LOAD(11);
LOAD(12);
return FfxFloat32x4(0.0, 0.0, 0.0, 0.0);
#undef LOAD
}
void StoreInpaintingPyramid(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32x4 outValue, FFX_PARAMETER_IN FfxUInt32 index)
{
#define STORE(idx) \
if (index == idx) \
{ \
imageStore(rw_inpainting_pyramid##idx, iPxPos, outValue); \
}
STORE(0);
STORE(1);
STORE(2);
STORE(3);
STORE(4);
STORE(5);
STORE(6);
STORE(7);
STORE(8);
STORE(9);
STORE(10);
STORE(11);
STORE(12);
#undef STORE
}
#endif
@@ -0,0 +1,814 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#include "ffx_frameinterpolation_resources.h"
#if defined(FFX_GPU)
#ifdef __hlsl_dx_compiler
#pragma dxc diagnostic push
#pragma dxc diagnostic ignored "-Wambig-lit-shift"
#endif //__hlsl_dx_compiler
#include "ffx_core.h"
#ifdef __hlsl_dx_compiler
#pragma dxc diagnostic pop
#endif //__hlsl_dx_compiler
#endif // #if defined(FFX_GPU)
#if defined(FFX_GPU)
#define COUNTER_SPD 0
#define COUNTER_FRAME_INDEX_SINCE_LAST_RESET 1
///////////////////////////////////////////////
// declare CBs and CB accessors
///////////////////////////////////////////////
#if defined(FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION)
cbuffer cbFI : FFX_DECLARE_CB(FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION)
{
FfxInt32x2 renderSize;
FfxInt32x2 displaySize;
FfxFloat32x2 displaySizeRcp;
FfxFloat32 cameraNear;
FfxFloat32 cameraFar;
FfxInt32x2 upscalerTargetSize;
FfxInt32 Mode;
FfxInt32 reset;
FfxFloat32x4 fDeviceToViewDepth;
FfxFloat32 deltaTime;
FfxInt32 HUDLessAttachedFactor;
FfxInt32x2 distortionFieldSize;
FfxFloat32x2 opticalFlowScale;
FfxInt32 opticalFlowBlockSize;
FfxUInt32 dispatchFlags;
FfxInt32x2 maxRenderSize;
FfxInt32 opticalFlowHalfResMode;
FfxInt32 NumInstances;
FfxInt32x2 interpolationRectBase;
FfxInt32x2 interpolationRectSize;
FfxFloat32x3 debugBarColor;
FfxUInt32 backBufferTransferFunction;
FfxFloat32x2 minMaxLuminance;
FfxFloat32 fTanHalfFOV;
FfxInt32 _pad1;
FfxFloat32x2 fJitter;
FfxFloat32x2 fMotionVectorScale;
}
const FfxFloat32x2 Jitter()
{
return fJitter;
}
const FfxFloat32x2 MotionVectorScale()
{
return fMotionVectorScale;
}
const FfxInt32x2 InterpolationRectBase()
{
return interpolationRectBase;
}
const FfxInt32x2 InterpolationRectSize()
{
return interpolationRectSize;
}
const FfxInt32x2 RenderSize()
{
return renderSize;
}
const FfxInt32x2 DisplaySize()
{
return displaySize;
}
const FfxBoolean Reset()
{
return reset == 1;
}
FfxFloat32x4 DeviceToViewSpaceTransformFactors()
{
return fDeviceToViewDepth;
}
FfxInt32x2 GetOpticalFlowSize()
{
FfxInt32x2 iOpticalFlowSize = (1.0f / opticalFlowScale) / FfxFloat32x2(opticalFlowBlockSize.xx);
return iOpticalFlowSize;
}
FfxInt32x2 GetOpticalFlowSize2()
{
return GetOpticalFlowSize() * 1;
}
FfxFloat32x2 GetOpticalFlowScale()
{
return opticalFlowScale;
}
FfxInt32 GetOpticalFlowBlockSize()
{
return opticalFlowBlockSize;
}
FfxInt32 GetHUDLessAttachedFactor()
{
return HUDLessAttachedFactor;
}
FfxInt32x2 GetDistortionFieldSize()
{
return distortionFieldSize;
}
FfxUInt32 GetDispatchFlags()
{
return dispatchFlags;
}
FfxInt32x2 GetMaxRenderSize()
{
return maxRenderSize;
}
FfxInt32 GetOpticalFlowHalfResMode()
{
return opticalFlowHalfResMode;
}
FfxFloat32x3 GetDebugBarColor()
{
return debugBarColor;
}
FfxFloat32 TanHalfFoV()
{
return fTanHalfFOV;
}
FfxUInt32 BackBufferTransferFunction()
{
return backBufferTransferFunction;
}
FfxFloat32 MinLuminance()
{
return minMaxLuminance[0];
}
FfxFloat32 MaxLuminance()
{
return minMaxLuminance[1];
}
#endif // #if defined(FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION)
#if defined(FFX_FRAMEINTERPOLATION_BIND_CB_INPAINTING_PYRAMID)
cbuffer cbInpaintingPyramid : FFX_DECLARE_CB(FFX_FRAMEINTERPOLATION_BIND_CB_INPAINTING_PYRAMID)
{
FfxUInt32 mips;
FfxUInt32 numWorkGroups;
FfxUInt32x2 workGroupOffset;
}
FfxUInt32 NumMips()
{
return mips;
}
FfxUInt32 NumWorkGroups()
{
return numWorkGroups;
}
FfxUInt32x2 WorkGroupOffset()
{
return workGroupOffset;
}
#endif // #if defined(FFX_FRAMEINTERPOLATION_BIND_CB_INPAINTING_PYRAMID)
#define FFX_FRAMEINTERPOLATION_ROOTSIG_STRINGIFY(p) FFX_FRAMEINTERPOLATION_ROOTSIG_STR(p)
#define FFX_FRAMEINTERPOLATION_ROOTSIG_STR(p) #p
#define FFX_FRAMEINTERPOLATION_ROOTSIG [RootSignature( "DescriptorTable(UAV(u0, numDescriptors = " FFX_FRAMEINTERPOLATION_ROOTSIG_STRINGIFY(FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_COUNT) ")), " \
"DescriptorTable(SRV(t0, numDescriptors = " FFX_FRAMEINTERPOLATION_ROOTSIG_STRINGIFY(FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_COUNT) ")), " \
"CBV(b0), " \
"StaticSampler(s0, filter = FILTER_MIN_MAG_MIP_LINEAR, " \
"addressU = TEXTURE_ADDRESS_CLAMP, " \
"addressV = TEXTURE_ADDRESS_CLAMP, " \
"addressW = TEXTURE_ADDRESS_CLAMP, " \
"comparisonFunc = COMPARISON_NEVER, " \
"borderColor = STATIC_BORDER_COLOR_TRANSPARENT_BLACK)" )]
#define FFX_FRAMEINTERPOLATION_INPAINTING_ROOTSIG [RootSignature( "DescriptorTable(UAV(u0, numDescriptors = " FFX_FRAMEINTERPOLATION_ROOTSIG_STRINGIFY(FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_COUNT) ")), " \
"DescriptorTable(SRV(t0, numDescriptors = " FFX_FRAMEINTERPOLATION_ROOTSIG_STRINGIFY(FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_COUNT) ")), " \
"CBV(b0), " \
"CBV(b1), " \
"StaticSampler(s0, filter = FILTER_MIN_MAG_MIP_LINEAR, " \
"addressU = TEXTURE_ADDRESS_CLAMP, " \
"addressV = TEXTURE_ADDRESS_CLAMP, " \
"addressW = TEXTURE_ADDRESS_CLAMP, " \
"comparisonFunc = COMPARISON_NEVER, " \
"borderColor = STATIC_BORDER_COLOR_TRANSPARENT_BLACK)" )]
#if defined(FFX_FRAMEINTERPOLATION_EMBED_ROOTSIG)
#define FFX_FRAMEINTERPOLATION_EMBED_ROOTSIG_CONTENT FFX_FRAMEINTERPOLATION_ROOTSIG
#define FFX_FRAMEINTERPOLATION_EMBED_INPAINTING_ROOTSIG_CONTENT FFX_FRAMEINTERPOLATION_INPAINTING_ROOTSIG
#else
#define FFX_FRAMEINTERPOLATION_EMBED_ROOTSIG_CONTENT
#define FFX_FRAMEINTERPOLATION_EMBED_INPAINTING_ROOTSIG_CONTENT
#endif // #if FFX_FRAMEINTERPOLATION_EMBED_ROOTSIG
///////////////////////////////////////////////
// declare samplers
///////////////////////////////////////////////
SamplerState s_LinearClamp : register(s0);
///////////////////////////////////////////////
// declare SRVs and SRV accessors
///////////////////////////////////////////////
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_PREVIOUS_INTERPOLATION_SOURCE
Texture2D<FfxFloat32x4> r_previous_interpolation_source : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_PREVIOUS_INTERPOLATION_SOURCE);
FfxFloat32x3 LoadPreviousBackbuffer(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return r_previous_interpolation_source[iPxPos].rgb;
}
FfxFloat32x3 SamplePreviousBackbuffer(FFX_PARAMETER_IN FfxFloat32x2 fUv)
{
return r_previous_interpolation_source.SampleLevel(s_LinearClamp, fUv, 0).xyz;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_CURRENT_INTERPOLATION_SOURCE
Texture2D<FfxFloat32x4> r_current_interpolation_source : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_CURRENT_INTERPOLATION_SOURCE);
FfxFloat32x3 LoadCurrentBackbuffer(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return r_current_interpolation_source[iPxPos].rgb;
}
FfxFloat32x3 SampleCurrentBackbuffer(FFX_PARAMETER_IN FfxFloat32x2 fUv)
{
return r_current_interpolation_source.SampleLevel(s_LinearClamp, fUv, 0).xyz;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_MOTION_VECTORS
Texture2D<FfxFloat32x2> r_dilated_motion_vectors : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_MOTION_VECTORS);
FfxFloat32x2 LoadDilatedMotionVector(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return r_dilated_motion_vectors[iPxPos].xy;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_DEPTH
Texture2D<FfxFloat32> r_dilated_depth : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_DEPTH);
FfxFloat32 LoadDilatedDepth(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return r_dilated_depth[iPxPos].x;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_RECONSTRUCTED_DEPTH_PREVIOUS_FRAME
Texture2D<FfxUInt32> r_reconstructed_depth_previous_frame : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_RECONSTRUCTED_DEPTH_PREVIOUS_FRAME);
FfxFloat32 LoadReconstructedDepthPreviousFrame(FFX_PARAMETER_IN FfxInt32x2 iPxInput)
{
return asfloat(r_reconstructed_depth_previous_frame[iPxInput]);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_RECONSTRUCTED_DEPTH_INTERPOLATED_FRAME
Texture2D<FfxUInt32> r_reconstructed_depth_interpolated_frame : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_RECONSTRUCTED_DEPTH_INTERPOLATED_FRAME);
FfxFloat32 LoadEstimatedInterpolationFrameDepth(FFX_PARAMETER_IN FfxInt32x2 iPxInput)
{
return asfloat(r_reconstructed_depth_interpolated_frame[iPxInput]);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_DISOCCLUSION_MASK
Texture2D<FfxFloat32x4> r_disocclusion_mask : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_DISOCCLUSION_MASK);
FfxFloat32x4 LoadDisocclusionMask(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return r_disocclusion_mask[iPxPos];
}
FfxFloat32x4 SampleDisocclusionMask(FFX_PARAMETER_IN FfxFloat32x2 fUv)
{
return r_disocclusion_mask.SampleLevel(s_LinearClamp, fUv, 0);
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_X) && \
defined(FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_Y)
Texture2D<FfxUInt32> r_game_motion_vector_field_x : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_X);
Texture2D<FfxUInt32> r_game_motion_vector_field_y : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_Y);
FfxUInt32x2 LoadGameFieldMv(FFX_PARAMETER_IN FfxInt32x2 iPxSample)
{
FfxUInt32 packedX = r_game_motion_vector_field_x[iPxSample];
FfxUInt32 packedY = r_game_motion_vector_field_y[iPxSample];
return FfxUInt32x2(packedX, packedY);
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X) && \
defined(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y)
Texture2D<FfxUInt32> r_optical_flow_motion_vector_field_x : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X);
Texture2D<FfxUInt32> r_optical_flow_motion_vector_field_y : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y);
FfxUInt32x2 LoadOpticalFlowFieldMv(FFX_PARAMETER_IN FfxInt32x2 iPxSample)
{
FfxUInt32 packedX = r_optical_flow_motion_vector_field_x[iPxSample];
FfxUInt32 packedY = r_optical_flow_motion_vector_field_y[iPxSample];
return FfxUInt32x2(packedX, packedY);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW
Texture2D<FfxInt32x2> r_optical_flow : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW);
#if defined(FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION)
FfxFloat32x2 LoadOpticalFlow(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return r_optical_flow[iPxPos] * GetOpticalFlowScale();
}
#endif
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_UPSAMPLED
Texture2D<FfxFloat32x2> r_optical_flow_upsampled : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_UPSAMPLED);
FfxFloat32x2 LoadOpticalFlowUpsampled(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return r_optical_flow_upsampled[iPxPos];
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_CONFIDENCE
Texture2D<FfxUInt32x2> r_optical_flow_confidence : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_CONFIDENCE);
FfxFloat32 LoadOpticalFlowConfidence(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return r_optical_flow_confidence[iPxPos].y;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_GLOBAL_MOTION
Texture2D<FfxUInt32> r_optical_flow_global_motion : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_GLOBAL_MOTION);
FfxUInt32 LoadOpticalFlowGlobalMotion(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return r_optical_flow_global_motion[iPxPos];
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_SCENE_CHANGE_DETECTION
Texture2D<FfxUInt32> r_optical_flow_scd : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_SCENE_CHANGE_DETECTION);
FfxUInt32 LoadOpticalFlowSceneChangeDetection(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return r_optical_flow_scd[iPxPos];
}
FfxBoolean HasSceneChanged()
{
#define SCD_OUTPUT_HISTORY_BITS_SLOT 1
//if (FrameIndex() <= 5) // threshold according to original OpenCL code
//{
// return 1.0;
//}
//else
{
// Report that the scene is changed if the change was detected in any of the
// 4 previous frames (0xfu - covers 4 history bits).
return (r_optical_flow_scd[FfxInt32x2(SCD_OUTPUT_HISTORY_BITS_SLOT, 0)] & 0xfu) != 0;
}
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_DEBUG
Texture2D<FfxFloat32x4> r_optical_flow_debug : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_DEBUG);
FfxFloat32x4 LoadOpticalFlowDebug(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return r_optical_flow_debug[iPxPos];
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_INPAINTING_MASK) && defined(FFX_FRAMEINTERPOLATION_BIND_SRV_OUTPUT)
Texture2D<FfxFloat32x3> r_output : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_OUTPUT);
Texture2D<FfxFloat32> r_inpainting_mask : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_INPAINTING_MASK);
FfxFloat32x4 LoadFrameInterpolationOutput(FFX_PARAMETER_IN FfxInt32x2 iPxInput)
{
return FfxFloat32x4(r_output[iPxInput], r_inpainting_mask[iPxInput]);
}
#elif defined(FFX_FRAMEINTERPOLATION_BIND_SRV_OUTPUT)
Texture2D<FfxFloat32x4> r_output : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_OUTPUT);
FfxFloat32x4 LoadFrameInterpolationOutput(FFX_PARAMETER_IN FfxInt32x2 iPxInput)
{
return r_output[iPxInput];
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_INPAINTING_PYRAMID
Texture2D<FfxFloat32x4> r_inpainting_pyramid : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_INPAINTING_PYRAMID);
FfxFloat32x4 LoadInpaintingPyramid(FFX_PARAMETER_IN FfxInt32 mipLevel, FFX_PARAMETER_IN FfxUInt32x2 iPxInput)
{
return r_inpainting_pyramid.mips[mipLevel][iPxInput];
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_PRESENT_BACKBUFFER
Texture2D<FfxFloat32x4> r_present_backbuffer : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_PRESENT_BACKBUFFER);
FfxFloat32x4 LoadPresentBackbuffer(FFX_PARAMETER_IN FfxInt32x2 iPxInput)
{
return r_present_backbuffer[iPxInput];
}
FfxFloat32x4 SamplePresentBackbuffer(FFX_PARAMETER_IN FfxFloat32x2 fUv)
{
return r_present_backbuffer.SampleLevel(s_LinearClamp, fUv, 0);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_SRV_COUNTERS
StructuredBuffer<FfxUInt32> r_counters : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_COUNTERS);
FfxUInt32 LoadCounter(FFX_PARAMETER_IN FfxInt32 iPxPos)
{
return r_counters[iPxPos];
}
const FfxUInt32 FrameIndexSinceLastReset()
{
return LoadCounter(COUNTER_FRAME_INDEX_SINCE_LAST_RESET);
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_INPUT_DEPTH)
Texture2D<FfxFloat32> r_input_depth : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_INPUT_DEPTH);
FfxFloat32 LoadInputDepth(FfxInt32x2 iPxPos)
{
return r_input_depth[iPxPos];
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_INPUT_MOTION_VECTORS)
Texture2D<FfxFloat32x4> r_input_motion_vectors : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_INPUT_MOTION_VECTORS);
FfxFloat32x2 LoadInputMotionVector(FfxInt32x2 iPxDilatedMotionVectorPos)
{
FfxFloat32x2 fSrcMotionVector = r_input_motion_vectors[iPxDilatedMotionVectorPos].xy;
FfxFloat32x2 fUvMotionVector = fSrcMotionVector * MotionVectorScale();
#if FFX_FRAMEINTERPOLATION_OPTION_JITTERED_MOTION_VECTORS
fUvMotionVector -= MotionVectorJitterCancellation();
#endif
return fUvMotionVector;
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_DISTORTION_FIELD)
Texture2D<FfxFloat32x2> r_input_distortion_field : FFX_DECLARE_SRV(FFX_FRAMEINTERPOLATION_BIND_SRV_DISTORTION_FIELD);
FfxFloat32x2 SampleDistortionField(FFX_PARAMETER_IN FfxFloat32x2 fUv)
{
return r_input_distortion_field.SampleLevel(s_LinearClamp, fUv, 0);
}
#endif
///////////////////////////////////////////////
// declare UAVs and UAV accessors
///////////////////////////////////////////////
#if defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_MASK) && defined(FFX_FRAMEINTERPOLATION_BIND_UAV_OUTPUT)
RWTexture2D<FfxFloat32x3> rw_output : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_OUTPUT);
RWTexture2D<FfxFloat32> rw_inpainting_mask : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_MASK);
FfxFloat32x4 RWLoadFrameinterpolationOutput(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return FfxFloat32x4(rw_output[iPxPos], rw_inpainting_mask[iPxPos]);
}
void StoreFrameinterpolationOutput(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32x4 val)
{
rw_output[iPxPos] = val.rgb;
rw_inpainting_mask[iPxPos] = val.a;
}
#elif defined(FFX_FRAMEINTERPOLATION_BIND_UAV_OUTPUT)
RWTexture2D<FfxFloat32x4> rw_output : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_OUTPUT);
FfxFloat32x4 RWLoadFrameinterpolationOutput(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return rw_output[iPxPos];
}
void StoreFrameinterpolationOutput(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32x4 val)
{
rw_output[iPxPos] = val;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_DILATED_MOTION_VECTORS
RWTexture2D<FfxFloat32x2> rw_dilated_motion_vectors : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_DILATED_MOTION_VECTORS);
FfxFloat32x2 RWLoadDilatedMotionVectors(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return rw_dilated_motion_vectors[iPxPos];
}
void StoreDilatedMotionVectors(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32x2 val)
{
rw_dilated_motion_vectors[iPxPos] = val;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_DILATED_DEPTH
RWTexture2D<FfxFloat32> rw_dilated_depth : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_DILATED_DEPTH);
FfxFloat32 RWLoadDilatedDepth(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return rw_dilated_depth[iPxPos];
}
void StoreDilatedDepth(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32 val)
{
rw_dilated_depth[iPxPos] = val;
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_RECONSTRUCTED_DEPTH_PREVIOUS_FRAME
RWTexture2D<FfxUInt32> rw_reconstructed_depth_previous_frame : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_RECONSTRUCTED_DEPTH_PREVIOUS_FRAME);
FfxFloat32 RWLoadReconstructedDepthPreviousFrame(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return ffxAsFloat(rw_reconstructed_depth_previous_frame[iPxPos]);
}
void UpdateReconstructedDepthPreviousFrame(FfxInt32x2 iPxSample, FfxFloat32 fDepth)
{
FfxUInt32 uDepth = ffxAsUInt32(fDepth);
#if FFX_FRAMEINTERPOLATION_OPTION_INVERTED_DEPTH
InterlockedMax(rw_reconstructed_depth_previous_frame[iPxSample], uDepth);
#else
InterlockedMin(rw_reconstructed_depth_previous_frame[iPxSample], uDepth); // min for standard, max for inverted depth
#endif
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_RECONSTRUCTED_DEPTH_INTERPOLATED_FRAME
RWTexture2D<FfxUInt32> rw_reconstructed_depth_interpolated_frame : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_RECONSTRUCTED_DEPTH_INTERPOLATED_FRAME);
FfxFloat32 RWLoadReconstructedDepthInterpolatedFrame(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return ffxAsFloat(rw_reconstructed_depth_interpolated_frame[iPxPos]);
}
void StoreReconstructedDepthInterpolatedFrame(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32 value)
{
FfxUInt32 uDepth = ffxAsUInt32(value);
rw_reconstructed_depth_interpolated_frame[iPxPos] = uDepth;
}
void UpdateReconstructedDepthInterpolatedFrame(FfxInt32x2 iPxSample, FfxFloat32 fDepth)
{
FfxUInt32 uDepth = ffxAsUInt32(fDepth);
#if FFX_FRAMEINTERPOLATION_OPTION_INVERTED_DEPTH
InterlockedMax(rw_reconstructed_depth_interpolated_frame[iPxSample], uDepth);
#else
InterlockedMin(rw_reconstructed_depth_interpolated_frame[iPxSample], uDepth); // min for standard, max for inverted depth
#endif
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_DISOCCLUSION_MASK
RWTexture2D<FfxFloat32x2> rw_disocclusion_mask : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_DISOCCLUSION_MASK);
FfxFloat32x2 RWLoadDisocclusionMask(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return rw_disocclusion_mask[iPxPos];
}
void StoreDisocclusionMask(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32x2 val)
{
rw_disocclusion_mask[iPxPos] = val;
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_X) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_Y)
RWTexture2D<FfxUInt32> rw_game_motion_vector_field_x : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_X);
RWTexture2D<FfxUInt32> rw_game_motion_vector_field_y : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_Y);
FfxUInt32 RWLoadGameMotionVectorFieldX(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return rw_game_motion_vector_field_x[iPxPos];
}
void StoreGameMotionVectorFieldX(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32 val)
{
rw_game_motion_vector_field_x[iPxPos] = val;
}
FfxUInt32 RWLoadGameMotionVectorFieldY(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return rw_game_motion_vector_field_y[iPxPos];
}
void StoreGameMotionVectorFieldY(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32 val)
{
rw_game_motion_vector_field_y[iPxPos] = val;
}
void UpdateGameMotionVectorField(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32x2 packedVector)
{
InterlockedMax(rw_game_motion_vector_field_x[iPxPos], packedVector.x);
InterlockedMax(rw_game_motion_vector_field_y[iPxPos], packedVector.y);
}
FfxUInt32 UpdateGameMotionVectorFieldEx(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32x2 packedVector)
{
FfxUInt32 uPreviousValueX = 0;
FfxUInt32 uPreviousValueY = 0;
InterlockedMax(rw_game_motion_vector_field_x[iPxPos], packedVector.x, uPreviousValueX);
InterlockedMax(rw_game_motion_vector_field_y[iPxPos], packedVector.y, uPreviousValueY);
const FfxUInt32 uExistingVectorFieldEntry = ffxMax(uPreviousValueX, uPreviousValueY);
return uExistingVectorFieldEntry;
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y)
RWTexture2D<FfxUInt32> rw_optical_flow_motion_vector_field_x : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X);
RWTexture2D<FfxUInt32> rw_optical_flow_motion_vector_field_y : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y);
FfxUInt32 RWLoadOpticalflowMotionVectorFieldX(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return rw_optical_flow_motion_vector_field_x[iPxPos];
}
void StoreOpticalflowMotionVectorFieldX(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32 val)
{
rw_optical_flow_motion_vector_field_x[iPxPos] = val;
}
FfxUInt32 RWLoadOpticalflowMotionVectorFieldY(FFX_PARAMETER_IN FfxInt32x2 iPxPos)
{
return rw_optical_flow_motion_vector_field_y[iPxPos];
}
void StoreOpticalflowMotionVectorFieldY(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32 val)
{
rw_optical_flow_motion_vector_field_y[iPxPos] = val;
}
void UpdateOpticalflowMotionVectorField(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32x2 packedVector)
{
InterlockedMax(rw_optical_flow_motion_vector_field_x[iPxPos], packedVector.x);
InterlockedMax(rw_optical_flow_motion_vector_field_y[iPxPos], packedVector.y);
}
#endif
#ifdef FFX_FRAMEINTERPOLATION_BIND_UAV_COUNTERS
globallycoherent RWStructuredBuffer<FfxUInt32> rw_counters : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_COUNTERS);
FfxUInt32 RWLoadCounter(FFX_PARAMETER_IN FfxInt32 iPxPos)
{
return rw_counters[iPxPos];
}
void StoreCounter(FFX_PARAMETER_IN FfxInt32 iPxPos, FFX_PARAMETER_IN FfxUInt32 counter)
{
rw_counters[iPxPos] = counter;
}
void AtomicIncreaseCounter(FFX_PARAMETER_IN FfxInt32 iPxPos, FFX_PARAMETER_OUT FfxUInt32 oldVal)
{
InterlockedAdd(rw_counters[iPxPos], 1, oldVal);
}
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_0) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_1) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_2) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_3) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_4) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_5) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_6) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_7) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_8) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_9) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_10) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_11) && \
defined(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_12)
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid0 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_0);
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid1 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_1);
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid2 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_2);
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid3 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_3);
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid4 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_4);
globallycoherent RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid5 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_5);
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid6 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_6);
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid7 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_7);
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid8 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_8);
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid9 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_9);
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid10 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_10);
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid11 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_11);
RWTexture2D<FfxFloat32x4> rw_inpainting_pyramid12 : FFX_DECLARE_UAV(FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_12);
FfxFloat32x4 RWLoadInpaintingPyramid(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxUInt32 index)
{
#define LOAD(idx) \
if (index == idx) \
{ \
return rw_inpainting_pyramid##idx[iPxPos]; \
}
LOAD(0);
LOAD(1);
LOAD(2);
LOAD(3);
LOAD(4);
LOAD(5);
LOAD(6);
LOAD(7);
LOAD(8);
LOAD(9);
LOAD(10);
LOAD(11);
LOAD(12);
return 0;
#undef LOAD
}
void StoreInpaintingPyramid(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxFloat32x4 outValue, FFX_PARAMETER_IN FfxUInt32 index)
{
#define STORE(idx) \
if (index == idx) \
{ \
rw_inpainting_pyramid##idx[iPxPos] = outValue; \
}
STORE(0);
STORE(1);
STORE(2);
STORE(3);
STORE(4);
STORE(5);
STORE(6);
STORE(7);
STORE(8);
STORE(9);
STORE(10);
STORE(11);
STORE(12);
#undef STORE
}
#endif
#endif // #if defined(FFX_GPU)
@@ -0,0 +1,445 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#if !defined(FFX_FRAMEINTERPOLATION_COMMON_H)
#define FFX_FRAMEINTERPOLATION_COMMON_H
#define FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_TEAR_LINES (1 << 0)
#define FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_RESET_INDICATORS (1 << 1)
#define FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_VIEW (1 << 2)
FFX_STATIC const FfxFloat32 FFX_FRAMEINTERPOLATION_EPSILON = 1e-03f;
FFX_STATIC const FfxFloat32 FFX_FRAMEINTERPOLATION_FLT_MAX = 3.402823466e+38f;
FFX_STATIC const FfxFloat32 FFX_FRAMEINTERPOLATION_FLT_MIN = 1.175494351e-38f;
FFX_STATIC const FfxFloat32 fReconstructedDepthBilinearWeightThreshold = FFX_FRAMEINTERPOLATION_EPSILON;
FfxFloat32 RGBToLuma(FfxFloat32x3 fLinearRgb)
{
return dot(fLinearRgb, FfxFloat32x3(0.2126f, 0.7152f, 0.0722f));
}
FfxFloat32 LinearRec2020ToLuminance(FfxFloat32x3 linearRec2020RGB)
{
FfxFloat32 fY = 0.2627 * linearRec2020RGB.x + 0.678 * linearRec2020RGB.y + 0.0593 * linearRec2020RGB.z;
return fY;
}
FfxFloat32x3 ffxscRGBToLinear(FfxFloat32x3 value, FfxFloat32 minLuminance, FfxFloat32 maxLuminance)
{
FfxFloat32x3 p = value - ffxBroadcast3(minLuminance / 80.0f);
return p / ffxBroadcast3((maxLuminance - minLuminance) / 80.0f);
}
FfxFloat32x3 RawRGBToLinear(FfxFloat32x3 fRawRgb)
{
FfxFloat32x3 fLinearRgb;
switch (BackBufferTransferFunction())
{
case 0:
fLinearRgb = ffxLinearFromSrgb(fRawRgb);
break;
case 1:
fLinearRgb = ffxLinearFromPQ(fRawRgb) * (10000.0f / MaxLuminance());
break;
case 2:
fLinearRgb = ffxscRGBToLinear(fRawRgb, MinLuminance(), MaxLuminance());
break;
}
return fLinearRgb;
}
FfxFloat32 RawRGBToLuminance(FfxFloat32x3 fRawRgb)
{
FfxFloat32 fLuminance = 0.0f;
switch (BackBufferTransferFunction())
{
case 0:
fLuminance = RGBToLuma(RawRGBToLinear(fRawRgb));
break;
case 1:
fLuminance = LinearRec2020ToLuminance(RawRGBToLinear(fRawRgb));
break;
case 2:
fLuminance = RGBToLuma(RawRGBToLinear(fRawRgb));
break;
}
return fLuminance;
}
FfxFloat32 RawRGBToPerceivedLuma(FfxFloat32x3 fRawRgb)
{
FfxFloat32 fLuminance = RawRGBToLuminance(fRawRgb);
FfxFloat32 fPercievedLuminance = 0;
if (fLuminance <= 216.0f / 24389.0f)
{
fPercievedLuminance = fLuminance * (24389.0f / 27.0f);
}
else
{
fPercievedLuminance = ffxPow(fLuminance, 1.0f / 3.0f) * 116.0f - 16.0f;
}
return fPercievedLuminance * 0.01f;
}
struct BilinearSamplingData
{
FfxInt32x2 iOffsets[4];
FfxFloat32 fWeights[4];
FfxInt32x2 iBasePos;
};
BilinearSamplingData GetBilinearSamplingData(FfxFloat32x2 fUv, FfxInt32x2 iSize)
{
BilinearSamplingData data;
FfxFloat32x2 fPxSample = (fUv * iSize) - FfxFloat32x2(0.5f, 0.5f);
data.iBasePos = FfxInt32x2(floor(fPxSample));
FfxFloat32x2 fPxFrac = ffxFract(fPxSample);
data.iOffsets[0] = FfxInt32x2(0, 0);
data.iOffsets[1] = FfxInt32x2(1, 0);
data.iOffsets[2] = FfxInt32x2(0, 1);
data.iOffsets[3] = FfxInt32x2(1, 1);
data.fWeights[0] = (1 - fPxFrac.x) * (1 - fPxFrac.y);
data.fWeights[1] = (fPxFrac.x) * (1 - fPxFrac.y);
data.fWeights[2] = (1 - fPxFrac.x) * (fPxFrac.y);
data.fWeights[3] = (fPxFrac.x) * (fPxFrac.y);
return data;
}
#if defined(FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION)
FfxFloat32 ConvertFromDeviceDepthToViewSpace(FfxFloat32 fDeviceDepth)
{
const FfxFloat32x4 deviceToViewDepth = DeviceToViewSpaceTransformFactors();
return deviceToViewDepth[1] / (fDeviceDepth - deviceToViewDepth[0]);
}
FfxFloat32x2 ComputeNdc(FfxFloat32x2 fPxPos, FfxInt32x2 iSize)
{
return fPxPos / FfxFloat32x2(iSize) * FfxFloat32x2(2.0f, -2.0f) + FfxFloat32x2(-1.0f, 1.0f);
}
FfxFloat32x3 GetViewSpacePosition(FfxInt32x2 iViewportPos, FfxInt32x2 iViewportSize, FfxFloat32 fDeviceDepth)
{
const FfxFloat32x4 fDeviceToViewDepth = DeviceToViewSpaceTransformFactors();
const FfxFloat32 Z = ConvertFromDeviceDepthToViewSpace(fDeviceDepth);
const FfxFloat32x2 fNdcPos = ComputeNdc(iViewportPos, iViewportSize);
const FfxFloat32 X = fDeviceToViewDepth[2] * fNdcPos.x * Z;
const FfxFloat32 Y = fDeviceToViewDepth[3] * fNdcPos.y * Z;
return FfxFloat32x3(X, Y, Z);
}
#endif
FfxBoolean IsOnScreen(FfxInt32x2 pos, FfxInt32x2 size)
{
return all(FFX_LESS_THAN(FfxUInt32x2(pos), FfxUInt32x2(size)));
}
FfxBoolean IsUvInside(FfxFloat32x2 fUv)
{
return (fUv.x > 0.0f && fUv.x < 1.0f) && (fUv.y > 0.0f && fUv.y < 1.0f);
}
FfxBoolean IsInRect(FfxInt32x2 pos, FfxInt32x2 iRectCorner, FfxInt32x2 iRectSize)
{
return (pos.x >= iRectCorner.x && pos.x < (iRectSize.x + iRectCorner.x) && pos.y >= iRectCorner.y && pos.y < (iRectSize.y + iRectCorner.y));
}
FfxFloat32 MinDividedByMax(const FfxFloat32 v0, const FfxFloat32 v1)
{
const FfxFloat32 m = ffxMax(v0, v1);
return m != 0 ? ffxMin(v0, v1) / m : 0;
}
FfxFloat32 NormalizedDot3(const FfxFloat32x3 v0, const FfxFloat32x3 v1)
{
FfxFloat32 fMaxLength = ffxMax(length(v0), length(v1));
return fMaxLength > 0.0f ? dot(v0 / fMaxLength, v1 / fMaxLength) : 1.0f;
}
FfxFloat32 NormalizedDot2(const FfxFloat32x2 v0, const FfxFloat32x2 v1)
{
FfxFloat32 fMaxLength = ffxMax(length(v0), length(v1));
return fMaxLength > 0.0f ? dot(v0 / fMaxLength, v1 / fMaxLength) : 1.0f;
}
FfxFloat32 CalculateStaticContentFactor(FfxFloat32x3 fCurrentInterpolationSource, FfxFloat32x3 fPresentColor)
{
const FfxFloat32x3 fFactor = ffxSaturate(FfxFloat32x3(
ffxSaturate((1.0f - MinDividedByMax(fCurrentInterpolationSource.r, fPresentColor.r)) / 0.1f),
ffxSaturate((1.0f - MinDividedByMax(fCurrentInterpolationSource.g, fPresentColor.g)) / 0.1f),
ffxSaturate((1.0f - MinDividedByMax(fCurrentInterpolationSource.b, fPresentColor.b)) / 0.1f)
));
return max(fFactor.x, max(fFactor.y, fFactor.z));
}
//
// MOTION VECTOR FIELD
//
FFX_STATIC const FfxUInt32 MOTION_VECTOR_FIELD_ENTRY_BIT_COUNT = 32;
// Make sure all bit counts add up to MOTION_VECTOR_FIELD_ENTRY_BIT_COUNT
FFX_STATIC const FfxUInt32 MOTION_VECTOR_FIELD_VECTOR_COEFFICIENT_BIT_COUNT = 16;
FFX_STATIC const FfxUInt32 MOTION_VECTOR_FIELD_PRIORITY_LOW_BIT_COUNT = 5;
FFX_STATIC const FfxUInt32 MOTION_VECTOR_FIELD_PRIORITY_HIGH_BIT_COUNT = 10;
FFX_STATIC const FfxUInt32 MOTION_VECTOR_PRIMARY_VECTOR_INDICATION_BIT_COUNT = 1;
FFX_STATIC const FfxUInt32 MOTION_VECTOR_FIELD_PRIMARY_VECTOR_INDICATION_BIT = (1U << (MOTION_VECTOR_FIELD_ENTRY_BIT_COUNT - 1));
FFX_STATIC const FfxUInt32 PRIORITY_LOW_MAX = (1U << MOTION_VECTOR_FIELD_PRIORITY_LOW_BIT_COUNT) - 1;
FFX_STATIC const FfxUInt32 PRIORITY_HIGH_MAX = (1U << MOTION_VECTOR_FIELD_PRIORITY_HIGH_BIT_COUNT) - 1;
FFX_STATIC const FfxUInt32 PRIORITY_LOW_OFFSET = MOTION_VECTOR_FIELD_VECTOR_COEFFICIENT_BIT_COUNT;
FFX_STATIC const FfxUInt32 PRIORITY_HIGH_OFFSET = PRIORITY_LOW_OFFSET + MOTION_VECTOR_FIELD_PRIORITY_LOW_BIT_COUNT;
FFX_STATIC const FfxUInt32 PRIMARY_VECTOR_INDICATION_OFFSET = PRIORITY_HIGH_OFFSET + MOTION_VECTOR_FIELD_PRIORITY_HIGH_BIT_COUNT;
struct VectorFieldEntry
{
FfxFloat32x2 fMotionVector;
FfxFloat32 uHighPriorityFactor;
FfxFloat32 uLowPriorityFactor;
FfxBoolean bValid;
FfxBoolean bPrimary;
FfxBoolean bSecondary;
FfxBoolean bInPainted;
FfxFloat32 fVelocity;
FfxBoolean bNegOutside;
FfxBoolean bPosOutside;
};
VectorFieldEntry NewVectorFieldEntry()
{
VectorFieldEntry vfe;
vfe.fMotionVector = FfxFloat32x2(0.0, 0.0);
vfe.uHighPriorityFactor = 0.0;
vfe.uLowPriorityFactor = 0.0;
vfe.bValid = false;
vfe.bPrimary = false;
vfe.bSecondary = false;
vfe.bInPainted = false;
vfe.fVelocity = 0.0;
vfe.bNegOutside = false;
vfe.bPosOutside = false;
return vfe;
}
FfxBoolean PackedVectorFieldEntryIsPrimary(FfxUInt32 packedEntry)
{
return ((packedEntry & MOTION_VECTOR_FIELD_PRIMARY_VECTOR_INDICATION_BIT) != 0);
}
FfxUInt32x2 PackVectorFieldEntries(FfxBoolean bIsPrimary, FfxUInt32 uHighPriorityFactor, FfxUInt32 uLowPriorityFactor, FfxFloat32x2 fMotionVector)
{
const FfxUInt32 uPriority =
(FfxUInt32(bIsPrimary) * MOTION_VECTOR_FIELD_PRIMARY_VECTOR_INDICATION_BIT)
| ((uHighPriorityFactor & PRIORITY_HIGH_MAX) << PRIORITY_HIGH_OFFSET)
| ((uLowPriorityFactor & PRIORITY_LOW_MAX) << PRIORITY_LOW_OFFSET);
FfxUInt32 packedX = uPriority | ffxF32ToF16(fMotionVector.x);
FfxUInt32 packedY = uPriority | ffxF32ToF16(fMotionVector.y);
return FfxUInt32x2(packedX, packedY);
}
void UnpackVectorFieldEntries(FfxUInt32x2 packed, out VectorFieldEntry vfElement)
{
vfElement.uHighPriorityFactor = FfxFloat32((packed.x >> PRIORITY_HIGH_OFFSET) & PRIORITY_HIGH_MAX) / PRIORITY_HIGH_MAX;
vfElement.uLowPriorityFactor = FfxFloat32((packed.x >> PRIORITY_LOW_OFFSET) & PRIORITY_LOW_MAX) / PRIORITY_LOW_MAX;
vfElement.bPrimary = PackedVectorFieldEntryIsPrimary(packed.x);
vfElement.bValid = (vfElement.uHighPriorityFactor > 0.0f);
vfElement.bSecondary = vfElement.bValid && !vfElement.bPrimary;
// Reverse priority factor for secondary vectors
if (vfElement.bSecondary)
{
vfElement.uHighPriorityFactor = 1.0f - vfElement.uHighPriorityFactor;
}
vfElement.fMotionVector.x = ffxUnpackF32(packed.x).x;
vfElement.fMotionVector.y = ffxUnpackF32(packed.y).x;
vfElement.bInPainted = false;
}
//
// MOTION VECTOR FIELD
//
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_INPAINTING_PYRAMID)
FfxFloat32x4 ComputeMvInpaintingLevel(FfxFloat32x2 fUv, const FfxInt32 iMipLevel, const FfxInt32x2 iTexSize)
{
BilinearSamplingData bilinearInfo = GetBilinearSamplingData(fUv, iTexSize);
FfxFloat32 fSum = 0.0f;
FfxFloat32x4 fColor = FfxFloat32x4(0.0, 0.0, 0.0, 0.0);
fColor.z = 0;
const FfxFloat32 fMaxPriorityFactor = 1.0f;
for (FfxInt32 iSampleIndex = 0; iSampleIndex < 4; iSampleIndex++)
{
const FfxInt32x2 iOffset = bilinearInfo.iOffsets[iSampleIndex];
const FfxInt32x2 iSamplePos = bilinearInfo.iBasePos + iOffset;
if (IsOnScreen(iSamplePos, iTexSize))
{
FfxFloat32x4 fSample = LoadInpaintingPyramid(iMipLevel, iSamplePos);
const FfxFloat32 fPriorityFactor = fSample.z;
const FfxFloat32 fValidMvFactor = FfxFloat32(fSample.z > 0);
const FfxFloat32 fSampleWeight = bilinearInfo.fWeights[iSampleIndex] * fValidMvFactor * fPriorityFactor;
fSum += fSampleWeight;
fColor += fSample * fSampleWeight;
}
}
fColor /= (fSum > 0.0f) ? fSum : 1.0f;
return fColor;
}
#if defined(FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION) && \
defined(FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_X) && \
defined(FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_Y)
void LoadInpaintedGameFieldMv(FfxFloat32x2 fUv, out VectorFieldEntry vfElement)
{
FfxInt32x2 iPxSample = FfxInt32x2(fUv * RenderSize());
FfxUInt32x2 packedGameFieldMv = LoadGameFieldMv(iPxSample);
UnpackVectorFieldEntries(packedGameFieldMv, vfElement);
if (!vfElement.bValid)
{
//FfxFloat32x2 fUv = (FfxFloat32x2(iPxSample) + 0.5f) / RenderSize();
FfxInt32x2 iTexSize = RenderSize();
FfxFloat32x4 fInPaintedVector = FfxFloat32x4(0.0, 0.0, 0.0, 0.0);
for (FfxInt32 iMipLevel = 0; iMipLevel < 11 && (fInPaintedVector.w == 0.0f); iMipLevel++)
{
iTexSize /= 2;
fInPaintedVector = ComputeMvInpaintingLevel(fUv, iMipLevel, iTexSize);
}
vfElement.fMotionVector = fInPaintedVector.xy;
vfElement.uHighPriorityFactor = fInPaintedVector.z;
vfElement.uLowPriorityFactor = fInPaintedVector.w;
vfElement.bInPainted = true;
}
vfElement.bNegOutside = !IsUvInside(fUv - vfElement.fMotionVector);
vfElement.bPosOutside = !IsUvInside(fUv + vfElement.fMotionVector);
vfElement.fVelocity = length(vfElement.fMotionVector);
}
#endif
#endif
#if defined(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X) && \
defined(FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y) && \
defined(FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION)
void SampleOpticalFlowMotionVectorField(FfxFloat32x2 fUv, out VectorFieldEntry vfElement)
{
const FfxFloat32 scaleFactor = 1.0f;
BilinearSamplingData bilinearInfo = GetBilinearSamplingData(fUv, FfxInt32x2(GetOpticalFlowSize2() * scaleFactor));
vfElement = NewVectorFieldEntry();
FfxFloat32 fWeightSum = 0.0f;
for (FfxInt32 iSampleIndex = 0; iSampleIndex < 4; iSampleIndex++)
{
const FfxInt32x2 iOffset = bilinearInfo.iOffsets[iSampleIndex];
const FfxInt32x2 iSamplePos = bilinearInfo.iBasePos + iOffset;
if (IsOnScreen(iSamplePos, FfxInt32x2(GetOpticalFlowSize2() * scaleFactor)))
{
const FfxFloat32 fWeight = bilinearInfo.fWeights[iSampleIndex];
VectorFieldEntry fOfVectorSample = NewVectorFieldEntry();
FfxInt32x2 packedOpticalFlowMv = FfxInt32x2(LoadOpticalFlowFieldMv(iSamplePos));
UnpackVectorFieldEntries(packedOpticalFlowMv, fOfVectorSample);
vfElement.fMotionVector += fOfVectorSample.fMotionVector * fWeight;
vfElement.uHighPriorityFactor += fOfVectorSample.uHighPriorityFactor * fWeight;
vfElement.uLowPriorityFactor += fOfVectorSample.uLowPriorityFactor * fWeight;
fWeightSum += fWeight;
}
}
if (fWeightSum > 0.0f)
{
vfElement.fMotionVector /= fWeightSum;
vfElement.uHighPriorityFactor /= fWeightSum;
vfElement.uLowPriorityFactor /= fWeightSum;
}
vfElement.bNegOutside = !IsUvInside(fUv - vfElement.fMotionVector);
vfElement.bPosOutside = !IsUvInside(fUv + vfElement.fMotionVector);
vfElement.fVelocity = length(vfElement.fMotionVector);
}
#endif
FfxFloat32x3 Tonemap(FfxFloat32x3 fRgb)
{
return fRgb / (ffxMax(ffxMax(0.f, fRgb.r), ffxMax(fRgb.g, fRgb.b)) + 1.f).xxx;
}
FfxFloat32x3 InverseTonemap(FfxFloat32x3 fRgb)
{
return fRgb / ffxMax(FFX_TONEMAP_EPSILON, 1.f - ffxMax(fRgb.r, ffxMax(fRgb.g, fRgb.b))).xxx;
}
FfxInt32x2 ComputeHrPosFromLrPos(FfxInt32x2 iPxLrPos)
{
FfxFloat32x2 fSrcJitteredPos = FfxFloat32x2(iPxLrPos) + 0.5f - Jitter();
FfxFloat32x2 fLrPosInHr = (fSrcJitteredPos / RenderSize()) * DisplaySize();
FfxInt32x2 iPxHrPos = FfxInt32x2(floor(fLrPosInHr));
return iPxHrPos;
}
#if FFX_HALF
FFX_MIN16_I2 ComputeHrPosFromLrPos(FFX_MIN16_I2 iPxLrPos)
{
FFX_MIN16_F2 fSrcJitteredPos = FFX_MIN16_F2(iPxLrPos) + FFX_MIN16_F(0.5f) - FFX_MIN16_F2(Jitter());
FFX_MIN16_F2 fLrPosInHr = (fSrcJitteredPos / FFX_MIN16_F2(RenderSize())) * FFX_MIN16_F2(DisplaySize());
FFX_MIN16_I2 iPxHrPos = FFX_MIN16_I2(floor(fLrPosInHr));
return iPxHrPos;
}
#endif
#endif //!defined(FFX_FRAMEINTERPOLATION_COMMON_H)
@@ -0,0 +1,121 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_COMPUTE_GAME_VECTOR_FIELD_INPAINTING_PYRAMID_H
#define FFX_FRAMEINTERPOLATION_COMPUTE_GAME_VECTOR_FIELD_INPAINTING_PYRAMID_H
#include "ffx_frameinterpolation_common.h"
//--------------------------------------------------------------------------------------
// Buffer definitions - global atomic counter
//--------------------------------------------------------------------------------------
FFX_GROUPSHARED FfxUInt32 spdCounter;
FFX_GROUPSHARED FfxFloat32 spdIntermediateR[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateG[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateB[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateA[16][16];
FfxFloat32x4 SpdLoadSourceImage(FfxInt32x2 tex, FfxUInt32 slice)
{
VectorFieldEntry gameMv;
FfxUInt32x2 packedGameFieldMv = LoadGameFieldMv(tex);
UnpackVectorFieldEntries(packedGameFieldMv, gameMv);
return FfxFloat32x4(gameMv.fMotionVector, gameMv.uHighPriorityFactor, gameMv.uLowPriorityFactor) * FfxFloat32(DisplaySize().x > 0);
}
FfxFloat32x4 SpdLoad(FfxInt32x2 tex, FfxUInt32 slice)
{
return RWLoadInpaintingPyramid(tex, 5);
}
void SpdStore(FfxInt32x2 pix, FfxFloat32x4 outValue, FfxUInt32 index, FfxUInt32 slice)
{
StoreInpaintingPyramid(pix, outValue, index);
}
void SpdIncreaseAtomicCounter(FfxUInt32 slice)
{
AtomicIncreaseCounter(COUNTER_SPD, spdCounter);
}
FfxUInt32 SpdGetAtomicCounter()
{
return spdCounter;
}
void SpdResetAtomicCounter(FfxUInt32 slice)
{
StoreCounter(COUNTER_SPD, 0);
}
FfxFloat32x4 SpdLoadIntermediate(FfxUInt32 x, FfxUInt32 y)
{
return FfxFloat32x4(
spdIntermediateR[x][y],
spdIntermediateG[x][y],
spdIntermediateB[x][y],
spdIntermediateA[x][y]);
}
void SpdStoreIntermediate(FfxUInt32 x, FfxUInt32 y, FfxFloat32x4 value)
{
spdIntermediateR[x][y] = value.x;
spdIntermediateG[x][y] = value.y;
spdIntermediateB[x][y] = value.z;
spdIntermediateA[x][y] = value.w;
}
FfxFloat32x4 SpdReduce4(FfxFloat32x4 v0, FfxFloat32x4 v1, FfxFloat32x4 v2, FfxFloat32x4 v3)
{
FfxFloat32x4 vec = FfxFloat32x4(0,0,0,0);
FfxFloat32 fWeightSum = 0.0f;
#define ADD(SAMPLE) { \
FfxFloat32 fWeight = FfxFloat32(SAMPLE.z > 0.0f); \
vec += SAMPLE * fWeight; \
fWeightSum += fWeight; \
}
ADD(v0);
ADD(v1);
ADD(v2);
ADD(v3);
vec /= (fWeightSum > FFX_FRAMEINTERPOLATION_EPSILON) ? fWeightSum : 1.0f;
return vec;
}
#include "spd/ffx_spd.h"
void computeFrameinterpolationGameVectorFieldInpaintingPyramid(FfxInt32x3 iGroupId, FfxInt32 iLocalIndex)
{
SpdDownsample(
FfxUInt32x2(iGroupId.xy),
FfxUInt32(iLocalIndex),
FfxUInt32(NumMips()),
FfxUInt32(NumWorkGroups()),
FfxUInt32(iGroupId.z),
FfxUInt32x2(WorkGroupOffset()));
}
#endif // FFX_FRAMEINTERPOLATION_COMPUTE_GAME_VECTOR_FIELD_INPAINTING_PYRAMID_H
@@ -0,0 +1,120 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_COMPUTE_INPAINTING_PYRAMID_H
#define FFX_FRAMEINTERPOLATION_COMPUTE_INPAINTING_PYRAMID_H
//--------------------------------------------------------------------------------------
// Buffer definitions - global atomic counter
//--------------------------------------------------------------------------------------
FFX_GROUPSHARED FfxUInt32 spdCounter;
FFX_GROUPSHARED FfxFloat32 spdIntermediateR[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateG[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateB[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateA[16][16];
FfxFloat32x4 SpdLoadSourceImage(FfxInt32x2 tex, FfxUInt32 slice)
{
FfxFloat32x4 fColor = LoadFrameInterpolationOutput(tex) * FfxFloat32(DisplaySize().x > 0);
// reverse sample weights
fColor.w = ffxSaturate(1.0f - fColor.w);
if (tex.x < InterpolationRectBase().x || tex.x >= (InterpolationRectSize().x + InterpolationRectBase().x) || tex.y < InterpolationRectBase().y ||
tex.y >= (InterpolationRectSize().y + InterpolationRectBase().y))
{
fColor.w = 0.0f; // don't take contributions from outside of the interpolation rect
}
return fColor;
}
FfxFloat32x4 SpdLoad(FfxInt32x2 tex, FfxUInt32 slice)
{
return RWLoadInpaintingPyramid(tex, 5);
}
void SpdStore(FfxInt32x2 pix, FfxFloat32x4 outValue, FfxUInt32 index, FfxUInt32 slice)
{
StoreInpaintingPyramid(pix, outValue, index);
}
void SpdIncreaseAtomicCounter(FfxUInt32 slice)
{
AtomicIncreaseCounter(COUNTER_SPD, spdCounter);
}
FfxUInt32 SpdGetAtomicCounter()
{
return spdCounter;
}
void SpdResetAtomicCounter(FfxUInt32 slice)
{
StoreCounter(COUNTER_SPD, 0);
}
FfxFloat32x4 SpdLoadIntermediate(FfxUInt32 x, FfxUInt32 y)
{
return FfxFloat32x4(
spdIntermediateR[x][y],
spdIntermediateG[x][y],
spdIntermediateB[x][y],
spdIntermediateA[x][y]);
}
void SpdStoreIntermediate(FfxUInt32 x, FfxUInt32 y, FfxFloat32x4 value)
{
spdIntermediateR[x][y] = value.x;
spdIntermediateG[x][y] = value.y;
spdIntermediateB[x][y] = value.z;
spdIntermediateA[x][y] = value.w;
}
FfxFloat32x4 SpdReduce4(FfxFloat32x4 v0, FfxFloat32x4 v1, FfxFloat32x4 v2, FfxFloat32x4 v3)
{
FfxFloat32x4 w = FfxFloat32x4(v0.w, v1.w, v2.w, v3.w);
FfxFloat32 sum = (w[0] + w[1] + w[2] + w[3]);
if (sum == 0.0f) {
return FfxFloat32x4(0.0, 0.0, 0.0, 0.0);
}
return (v0 * w[0] + v1 * w[1] + v2 * w[2] + v3 * w[3]) / sum;
}
#include "spd/ffx_spd.h"
void computeFrameinterpolationInpaintingPyramid(FfxInt32x3 iGroupId, FfxInt32 iLocalIndex)
{
SpdDownsample(
FfxUInt32x2(iGroupId.xy),
FfxUInt32(iLocalIndex),
FfxUInt32(NumMips()),
FfxUInt32(NumWorkGroups()),
FfxUInt32(iGroupId.z),
FfxUInt32x2(WorkGroupOffset()));
}
#endif // FFX_FRAMEINTERPOLATION_COMPUTE_INPAINTING_PYRAMID_H
@@ -0,0 +1,172 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_DEBUG_VIEW_H
#define FFX_FRAMEINTERPOLATION_DEBUG_VIEW_H
struct FfxFrameInterpolationDebugViewport
{
FfxInt32x2 offset;
FfxInt32x2 size;
};
// Macro to cull and draw debug viewport
#define DRAW_VIEWPORT(function, pos, vp) \
{ \
if (pointIsInsideViewport(pos, vp)) \
{ \
function(pos, vp); \
} \
}
FfxFloat32x2 getTransformedUv(FfxInt32x2 iPxPos, FfxFrameInterpolationDebugViewport vp)
{
FfxFloat32x2 fUv = (FfxFloat32x2(iPxPos - vp.offset) + 0.5f) / vp.size;
return fUv;
}
FfxFloat32x4 getMotionVectorColor(FfxFloat32x2 fMotionVector)
{
return FfxFloat32x4(0.5f + fMotionVector * DisplaySize() * 0.1f, 0.5f, 1.0f);
}
FfxFloat32x4 getUnusedIndicationColor(FfxInt32x2 iPxPos, FfxFrameInterpolationDebugViewport vp)
{
FfxInt32x2 basePos = iPxPos - vp.offset;
FfxFloat32 ar = FfxFloat32(vp.size.x) / FfxFloat32(vp.size.y);
return FfxFloat32x4(basePos.x == FfxInt32(basePos.y * ar), 0, 0, 1);
}
void drawGameMotionVectorFieldVectors(FfxInt32x2 iPxPos, FfxFrameInterpolationDebugViewport vp)
{
FfxFloat32x2 fUv = getTransformedUv(iPxPos, vp);
VectorFieldEntry gameMv;
LoadInpaintedGameFieldMv(fUv, gameMv);
StoreFrameinterpolationOutput(iPxPos, getMotionVectorColor(gameMv.fMotionVector));
}
void drawGameMotionVectorFieldDepthPriority(FfxInt32x2 iPxPos, FfxFrameInterpolationDebugViewport vp)
{
FfxFloat32x2 fUv = getTransformedUv(iPxPos, vp);
VectorFieldEntry gameMv;
LoadInpaintedGameFieldMv(fUv, gameMv);
StoreFrameinterpolationOutput(iPxPos, FfxFloat32x4(0, gameMv.uHighPriorityFactor, 0, 1));
}
void drawOpticalFlowMotionVectorField(FfxInt32x2 iPxPos, FfxFrameInterpolationDebugViewport vp)
{
FfxFloat32x2 fUv = getTransformedUv(iPxPos, vp);
VectorFieldEntry ofMv;
SampleOpticalFlowMotionVectorField(fUv, ofMv);
StoreFrameinterpolationOutput(iPxPos, getMotionVectorColor(ofMv.fMotionVector));
}
void drawDisocclusionMask(FfxInt32x2 iPxPos, FfxFrameInterpolationDebugViewport vp)
{
FfxFloat32x2 fUv = getTransformedUv(iPxPos, vp);
FfxFloat32x2 fLrUv = fUv * (FfxFloat32x2(RenderSize()) / GetMaxRenderSize());
FfxFloat32x2 fDisocclusionFactor = ffxSaturate(SampleDisocclusionMask(fLrUv).xy);
StoreFrameinterpolationOutput(iPxPos, FfxFloat32x4(fDisocclusionFactor, 0, 1));
}
FfxFloat32x4 getDistortionField(FfxInt32x2 iPxPos, FfxFrameInterpolationDebugViewport vp)
{
FfxFloat32x2 fUv = getTransformedUv(iPxPos, vp);
FfxFloat32x2 fDistortionFieldUv = abs(SampleDistortionField(fUv).xy);
return FfxFloat32x4(fDistortionFieldUv * 10.0f, 0.0f, 1.0f);
}
void drawPresentBackbuffer(FfxInt32x2 iPxPos, FfxFrameInterpolationDebugViewport vp)
{
FfxFloat32x2 fUv = getTransformedUv(iPxPos, vp);
FfxFloat32x4 fPresentColor = getDistortionField(iPxPos, vp);
if (GetHUDLessAttachedFactor() == 1)
{
fPresentColor = SamplePresentBackbuffer(fUv);
}
StoreFrameinterpolationOutput(iPxPos, fPresentColor);
}
void drawCurrentInterpolationSource(FfxInt32x2 iPxPos, FfxFrameInterpolationDebugViewport vp)
{
FfxFloat32x2 fUv = getTransformedUv(iPxPos, vp);
FfxFloat32x4 fCurrentBackBuffer = FfxFloat32x4(SampleCurrentBackbuffer(fUv), 1.0f);
StoreFrameinterpolationOutput(iPxPos, fCurrentBackBuffer);
}
FfxBoolean pointIsInsideViewport(FfxInt32x2 iPxPos, FfxFrameInterpolationDebugViewport vp)
{
FfxInt32x2 extent = vp.offset + vp.size;
return (iPxPos.x >= vp.offset.x && iPxPos.x < extent.x) && (iPxPos.y >= vp.offset.y && iPxPos.y < extent.y);
}
void computeDebugView(FfxInt32x2 iPxPos)
{
#define VIEWPORT_GRID_SIZE_X 3
#define VIEWPORT_GRID_SIZE_Y 3
FfxFloat32x2 fViewportScale = FfxFloat32x2(1.0f / VIEWPORT_GRID_SIZE_X, 1.0f / VIEWPORT_GRID_SIZE_Y);
FfxInt32x2 iViewportSize = FfxInt32x2(DisplaySize() * fViewportScale);
// compute grid [y][x] for easier placement of viewports
FfxFrameInterpolationDebugViewport vp[VIEWPORT_GRID_SIZE_Y][VIEWPORT_GRID_SIZE_X];
for (FfxInt32 y = 0; y < VIEWPORT_GRID_SIZE_Y; y++)
{
for (FfxInt32 x = 0; x < VIEWPORT_GRID_SIZE_X; x++)
{
vp[y][x].offset = iViewportSize * FfxInt32x2(x, y);
vp[y][x].size = iViewportSize;
}
}
// top row
DRAW_VIEWPORT(drawGameMotionVectorFieldVectors, iPxPos, vp[0][0]);
DRAW_VIEWPORT(drawGameMotionVectorFieldDepthPriority, iPxPos, vp[0][1]);
DRAW_VIEWPORT(drawOpticalFlowMotionVectorField, iPxPos, vp[0][2]);
// bottom row
DRAW_VIEWPORT(drawDisocclusionMask, iPxPos, vp[2][0]);
DRAW_VIEWPORT(drawCurrentInterpolationSource, iPxPos, vp[2][1]);
DRAW_VIEWPORT(drawPresentBackbuffer, iPxPos, vp[2][2]);
}
#endif // FFX_FRAMEINTERPOLATION_DEBUG_VIEW_H
@@ -0,0 +1,146 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_DISOCCLUSION_MASK_H
#define FFX_FRAMEINTERPOLATION_DISOCCLUSION_MASK_H
FFX_STATIC const FfxFloat32 DepthClipBaseScale = 1.0f;
FfxFloat32 ComputeSampleDepthClip(FfxInt32x2 iPxSamplePos, FfxFloat32 fPreviousDepth, FfxFloat32 fPreviousDepthBilinearWeight, FfxFloat32 fCurrentDepthViewSpace)
{
FfxFloat32 fPrevNearestDepthViewSpace = ConvertFromDeviceDepthToViewSpace(fPreviousDepth);
// Depth separation logic ref: See "Minimum Triangle Separation for Correct Z-Buffer Occlusion"
// Intention: worst case of formula in Figure4 combined with Ksep factor in Section 4
const FfxFloat32 fHalfViewportWidth = RenderSize().x * 0.5f;
FfxFloat32 fDepthThreshold = ffxMax(fCurrentDepthViewSpace, fPrevNearestDepthViewSpace);
// WARNING: Ksep only works with reversed-z with infinite projection.
const FfxFloat32 Ksep = 1.37e-05f;
FfxFloat32 fRequiredDepthSeparation = Ksep * fDepthThreshold * TanHalfFoV() * fHalfViewportWidth;
FfxFloat32 fDepthDiff = fCurrentDepthViewSpace - fPrevNearestDepthViewSpace;
FfxFloat32 fDepthClipFactor = (fDepthDiff > 0) ? ffxSaturate(fRequiredDepthSeparation / fDepthDiff) : 1.0f;
return fPreviousDepthBilinearWeight * fDepthClipFactor * ffxLerp(1.0f, DepthClipBaseScale, ffxSaturate(fDepthDiff * fDepthDiff));
}
FfxFloat32 LoadEstimatedDepth(FfxUInt32 estimatedIndex, FfxInt32x2 iSamplePos)
{
const FfxFloat32x2 fUv = FfxFloat32x2(iSamplePos + 0.5f) / RenderSize();
const FfxFloat32x2 fDistortionFieldUv = SampleDistortionField(fUv);
FfxInt32x2 iDistortionPixelOffset = FfxInt32x2(fDistortionFieldUv.xy * RenderSize());
if (estimatedIndex == 0)
{
return LoadReconstructedDepthPreviousFrame(iSamplePos + iDistortionPixelOffset);
}
else if (estimatedIndex == 1)
{
return LoadDilatedDepth(iSamplePos + iDistortionPixelOffset);
}
return 0;
}
FfxFloat32 ComputeDepthClip(FfxUInt32 estimatedIndex, FfxFloat32x2 fUvSample, FfxFloat32 fCurrentDepthSample)
{
FfxFloat32 fCurrentDepthViewSpace = ConvertFromDeviceDepthToViewSpace(fCurrentDepthSample);
BilinearSamplingData bilinearInfo = GetBilinearSamplingData(fUvSample, RenderSize());
FfxFloat32 fDilatedSum = 0.0f;
FfxFloat32 fDepth = 0.0f;
FfxFloat32 fWeightSum = 0.0f;
for (FfxInt32 iSampleIndex = 0; iSampleIndex < 4; iSampleIndex++) {
const FfxInt32x2 iOffset = bilinearInfo.iOffsets[iSampleIndex];
const FfxInt32x2 iSamplePos = bilinearInfo.iBasePos + iOffset;
if (IsOnScreen(iSamplePos, RenderSize())) {
const FfxFloat32 fWeight = bilinearInfo.fWeights[iSampleIndex];
if (fWeight > fReconstructedDepthBilinearWeightThreshold) {
const FfxFloat32 fPrevDepthSample = LoadEstimatedDepth(estimatedIndex, iSamplePos);
const FfxFloat32 fPrevNearestDepthViewSpace = ConvertFromDeviceDepthToViewSpace(fPrevDepthSample);
const FfxFloat32 fDepthDiff = fCurrentDepthViewSpace - fPrevNearestDepthViewSpace;
if (fDepthDiff > 0.0f) {
#if FFX_FRAMEINTERPOLATION_OPTION_INVERTED_DEPTH
const FfxFloat32 fPlaneDepth = ffxMin(fPrevDepthSample, fCurrentDepthSample);
#else
const FfxFloat32 fPlaneDepth = ffxMax(fPrevDepthSample, fCurrentDepthSample);
#endif
const FfxFloat32x3 fCenter = GetViewSpacePosition(FfxInt32x2(RenderSize() * 0.5f), RenderSize(), fPlaneDepth);
const FfxFloat32x3 fCorner = GetViewSpacePosition(FfxInt32x2(0, 0), RenderSize(), fPlaneDepth);
const FfxFloat32 fHalfViewportWidth = length(FfxFloat32x2(RenderSize()));
const FfxFloat32 fDepthThreshold = ffxMin(fCurrentDepthViewSpace, fPrevNearestDepthViewSpace);
const FfxFloat32 Ksep = 1.37e-05f;
const FfxFloat32 Kfov = length(fCorner) / length(fCenter);
const FfxFloat32 fRequiredDepthSeparation = Ksep * Kfov * fHalfViewportWidth * fDepthThreshold;
const FfxFloat32 fResolutionFactor = ffxSaturate(length(FfxFloat32x2(RenderSize())) / length(FfxFloat32x2(1920.0f, 1080.0f)));
const FfxFloat32 fPower = ffxLerp(1.0f, 3.0f, fResolutionFactor);
fDepth += FfxFloat32((fRequiredDepthSeparation / fDepthDiff) >= 1.0f) * fWeight;
fWeightSum += fWeight;
}
}
}
}
return (fWeightSum > 0.0f) ? ffxSaturate(1.0f - fDepth / fWeightSum) : 0.0f;
}
void computeDisocclusionMask(FfxInt32x2 iPxPos)
{
FfxFloat32 fDilatedDepth = LoadEstimatedInterpolationFrameDepth(iPxPos);
FfxFloat32x2 fDepthUv = (iPxPos + 0.5f) / RenderSize();
FfxFloat32 fCurrentDepthViewSpace = ConvertFromDeviceDepthToViewSpace(fDilatedDepth);
VectorFieldEntry gameMv;
LoadInpaintedGameFieldMv(fDepthUv, gameMv);
const FfxFloat32 fDepthClipInterpolatedToPrevious = 1.0f - ComputeDepthClip(0, fDepthUv + gameMv.fMotionVector, fDilatedDepth);
const FfxFloat32 fDepthClipInterpolatedToCurrent = 1.0f - ComputeDepthClip(1, fDepthUv - gameMv.fMotionVector, fDilatedDepth);
FfxFloat32x2 fDisocclusionMask = FfxFloat32x2(fDepthClipInterpolatedToPrevious, fDepthClipInterpolatedToCurrent);
fDisocclusionMask = FfxFloat32x2(FFX_GREATER_THAN_EQUAL(fDisocclusionMask, ffxBroadcast2(FFX_FRAMEINTERPOLATION_EPSILON)));
// Avoid false disocclusion if primary game vector pointer outside screen area
const FfxFloat32x2 fSrcMotionVector = gameMv.fMotionVector * 2.0f;
const FfxInt32x2 iSamplePosPrevious = FfxInt32x2((fDepthUv + fSrcMotionVector) * RenderSize());
fDisocclusionMask.x = ffxSaturate(fDisocclusionMask.x + FfxFloat32(!IsOnScreen(iSamplePosPrevious, RenderSize())));
const FfxInt32x2 iSamplePosCurrent = FfxInt32x2((fDepthUv - fSrcMotionVector) * RenderSize());
fDisocclusionMask.y = ffxSaturate(fDisocclusionMask.y + FfxFloat32(!IsOnScreen(iSamplePosCurrent, RenderSize())));
StoreDisocclusionMask(iPxPos, fDisocclusionMask);
}
#endif // FFX_FRAMEINTERPOLATION_DISOCCLUSION_MASK_H
@@ -0,0 +1,123 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_GAME_MOTION_VECTOR_FIELD_H
#define FFX_FRAMEINTERPOLATION_GAME_MOTION_VECTOR_FIELD_H
FfxUInt32 getPriorityFactorFromViewSpaceDepth(FfxFloat32 fViewSpaceDepthInMeters)
{
fViewSpaceDepthInMeters = ffxPow(fViewSpaceDepthInMeters, 0.33f);
FfxUInt32 uPriorityFactor = FfxUInt32(FfxFloat32(1 - (fViewSpaceDepthInMeters * (1.0f / (1.0f + fViewSpaceDepthInMeters)))) * PRIORITY_HIGH_MAX);
return ffxMax(1, uPriorityFactor);
}
void computeGameFieldMvs(FfxInt32x2 iPxPos)
{
const FfxFloat32x2 fUvInScreenSpace = (FfxFloat32x2(iPxPos) + 0.5f) / RenderSize();
const FfxFloat32x2 fDistortionFieldUv = SampleDistortionField(fUvInScreenSpace);
FfxInt32x2 iDistortionPixelOffset = FfxInt32x2(fDistortionFieldUv.xy * RenderSize());
const FfxFloat32x2 fUvInInterpolationRectStart = FfxFloat32x2(InterpolationRectBase()) / DisplaySize();
const FfxFloat32x2 fUvLetterBoxScale = FfxFloat32x2(InterpolationRectSize()) / DisplaySize();
const FfxFloat32x2 fUvInInterpolationRect = fUvInInterpolationRectStart + fUvInScreenSpace * fUvLetterBoxScale;
const FfxFloat32 fDepthSample = LoadDilatedDepth(iPxPos + iDistortionPixelOffset);
const FfxFloat32x2 fGameMotionVector = LoadDilatedMotionVector(iPxPos + iDistortionPixelOffset);
const FfxFloat32x2 fMotionVectorHalf = fGameMotionVector * 0.5f;
const FfxFloat32x2 fInterpolatedLocationUv = fUvInScreenSpace + fMotionVectorHalf;
const FfxFloat32 fViewSpaceDepth = ConvertFromDeviceDepthToViewSpace(fDepthSample);
const FfxUInt32 uHighPriorityFactorPrimary = getPriorityFactorFromViewSpaceDepth(fViewSpaceDepth);
// pixel position in current frame + Game Motion Vector -> pixel position in previous frame
FfxFloat32x3 prevBackbufferCol = SamplePreviousBackbuffer(fUvInInterpolationRect+ fGameMotionVector * fUvLetterBoxScale).xyz; //returns color of current frame's pixel in previous frame buffer
FfxFloat32x3 curBackbufferCol = SampleCurrentBackbuffer(fUvInInterpolationRect).xyz; // returns color of current frame's pixel in current frame buffer
FfxFloat32 prevLuma = 0.001f + RawRGBToLuminance(prevBackbufferCol);
FfxFloat32 currLuma = 0.001f + RawRGBToLuminance(curBackbufferCol);
FfxUInt32 uLowPriorityFactor = FfxUInt32(ffxRound(ffxPow(MinDividedByMax(prevLuma, currLuma), 1.0f / 1.0f) * PRIORITY_LOW_MAX))
* FfxUInt32(IsUvInside(fUvInInterpolationRect + fGameMotionVector * fUvLetterBoxScale));
// Update primary motion vectors
{
const FfxUInt32x2 packedVectorPrimary = PackVectorFieldEntries(true, uHighPriorityFactorPrimary, uLowPriorityFactor, fMotionVectorHalf);
BilinearSamplingData bilinearInfo = GetBilinearSamplingData(fInterpolatedLocationUv, RenderSize());
for (FfxInt32 iSampleIndex = 0; iSampleIndex < 4; iSampleIndex++)
{
const FfxInt32x2 iOffset = bilinearInfo.iOffsets[iSampleIndex];
const FfxInt32x2 iSamplePos = bilinearInfo.iBasePos + iOffset;
if (IsOnScreen(iSamplePos, RenderSize()))
{
UpdateGameMotionVectorField(iSamplePos, packedVectorPrimary);
}
}
}
// Update secondary vectors
// Main purpose of secondary vectors is to improve quality of inpainted vectors
const FfxBoolean bWriteSecondaryVectors = length(fMotionVectorHalf * RenderSize()) > FFX_FRAMEINTERPOLATION_EPSILON;
if (bWriteSecondaryVectors)
{
FfxBoolean bWriteSecondary = true;
FfxUInt32 uNumPrimaryHits = 0;
const FfxFloat32 fSecondaryStepScale = length(1.0f / RenderSize());
const FfxFloat32x2 fStepMv = normalize(fGameMotionVector);
const FfxFloat32 fBreakDist = ffxMin(length(fMotionVectorHalf), length(FfxFloat32x2(0.5f, 0.5f)));
for (FfxFloat32 fMvScale = fSecondaryStepScale; fMvScale <= fBreakDist && bWriteSecondary; fMvScale += fSecondaryStepScale)
{
const FfxFloat32x2 fSecondaryLocationUv = fInterpolatedLocationUv - fStepMv * fMvScale;
BilinearSamplingData bilinearInfo = GetBilinearSamplingData(fSecondaryLocationUv, RenderSize());
// Reverse depth prio for secondary vectors
FfxUInt32 uHighPriorityFactorSecondary = ffxMax(1, PRIORITY_HIGH_MAX - uHighPriorityFactorPrimary);
const FfxFloat32x2 fToCenter = normalize(FfxFloat32x2(0.5f, 0.5f) - fSecondaryLocationUv);
uLowPriorityFactor = FfxUInt32(ffxMax(0.0f, dot(fToCenter, fStepMv)) * PRIORITY_LOW_MAX);
const FfxUInt32x2 packedVectorSecondary = PackVectorFieldEntries(false, uHighPriorityFactorSecondary, uLowPriorityFactor, fMotionVectorHalf);
// Only write secondary mvs to single bilinear location
for (FfxInt32 iSampleIndex = 0; iSampleIndex < 1; iSampleIndex++)
{
const FfxInt32x2 iOffset = bilinearInfo.iOffsets[iSampleIndex];
const FfxInt32x2 iSamplePos = bilinearInfo.iBasePos + iOffset;
bWriteSecondary = bWriteSecondary && IsOnScreen(iSamplePos, RenderSize());
if (bWriteSecondary)
{
const FfxUInt32 uExistingVectorFieldEntry = UpdateGameMotionVectorFieldEx(iSamplePos, packedVectorSecondary);
uNumPrimaryHits += FfxUInt32(PackedVectorFieldEntryIsPrimary(uExistingVectorFieldEntry));
bWriteSecondary = bWriteSecondary && (uNumPrimaryHits <= 3);
}
}
}
}
}
#endif // FFX_FRAMEINTERPOLATION_GAME_MOTION_VECTOR_FIELD_H
@@ -0,0 +1,150 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_INPAINTING_H
#define FFX_FRAMEINTERPOLATION_INPAINTING_H
FfxFloat32x4 ComputeInpaintingLevel(FfxFloat32x2 fUv, const FfxInt32 iMipLevel, const FfxInt32x2 iTexSize)
{
BilinearSamplingData bilinearInfo = GetBilinearSamplingData(fUv, iTexSize);
FfxFloat32x4 fColor = FfxFloat32x4(0.0, 0.0, 0.0, 0.0);
for (FfxInt32 iSampleIndex = 0; iSampleIndex < 4; iSampleIndex++) {
const FfxInt32x2 iOffset = bilinearInfo.iOffsets[iSampleIndex];
const FfxInt32x2 iSamplePos = bilinearInfo.iBasePos + iOffset;
if (IsOnScreen(iSamplePos, iTexSize)) {
FfxFloat32x4 fSample = LoadInpaintingPyramid(iMipLevel, iSamplePos);
const FfxFloat32 fWeight = bilinearInfo.fWeights[iSampleIndex] * FfxFloat32(fSample.w > 0.0f);
fColor += FfxFloat32x4(fSample.rgb * fWeight, fWeight);
}
}
return fColor;
}
FfxFloat32x3 ComputeInpainting(FfxInt32x2 iPxPos)
{
FfxFloat32x2 fUv = (iPxPos + 0.5f) / (DisplaySize());
FfxFloat32x4 fColor = FfxFloat32x4(0.0, 0.0, 0.0, 0.0);
FfxFloat32 fWeightSum = 0.0f;
FfxInt32x2 iTexSize = DisplaySize();
for (FfxInt32 iMipLevel = 0; iMipLevel < 10; iMipLevel++) {
iTexSize /= 2;
FfxFloat32x4 fMipColor = ComputeInpaintingLevel(fUv, iMipLevel, iTexSize);
if (fMipColor.w > 0.0f) {
const FfxFloat32x3 fNormalizedMipColor = fMipColor.rgb / fMipColor.w;
const FfxFloat32 fMipWeight = ffxPow(1.0f - iMipLevel / 10.0f, 3.0f) * fMipColor.w;
fColor += FfxFloat32x4(fNormalizedMipColor, 1.0f) * fMipWeight;
}
}
return fColor.rgb / fColor.w;
}
void drawDebugTearLines(FfxInt32x2 iPxPos, inout FfxFloat32x3 fColor, inout FfxBoolean bWriteColor)
{
if (iPxPos.x < 16)
{
fColor.g = 1.f;
bWriteColor = true;
}
else if (iPxPos.x > DisplaySize().x - 16)
{
fColor += GetDebugBarColor();
bWriteColor = true;
}
}
void drawDebugResetIndicators(FfxInt32x2 iPxPos, inout FfxFloat32x3 fColor, inout FfxBoolean bWriteColor)
{
if (iPxPos.y < 32 && Reset())
{
fColor.r = 1.f;
bWriteColor = true;
}
else if (iPxPos.y > 32 && iPxPos.y < 64 && HasSceneChanged())
{
fColor.b = 1.f;
bWriteColor = true;
}
}
void computeInpainting(FfxInt32x2 iPxPos)
{
FfxBoolean bWriteColor = false;
FfxFloat32x4 fInterpolatedColor = RWLoadFrameinterpolationOutput(iPxPos);
const FfxFloat32 fInPaintingWeight = fInterpolatedColor.w;
if (fInPaintingWeight > FFX_FRAMEINTERPOLATION_EPSILON)
{
fInterpolatedColor.rgb = ffxLerp(fInterpolatedColor.rgb, ComputeInpainting(iPxPos) * FfxFloat32(DisplaySize().x > 0), fInPaintingWeight);
bWriteColor = true;
}
if (GetHUDLessAttachedFactor() == 1)
{
const FfxFloat32x3 fCurrentInterpolationSource = LoadCurrentBackbuffer(iPxPos).rgb;
const FfxFloat32x3 fPresentColor = LoadPresentBackbuffer(iPxPos).rgb;
if (any(FFX_GREATER_THAN(abs(fCurrentInterpolationSource - fPresentColor), FfxFloat32x3(0.0, 0.0, 0.0))))
{
const FfxFloat32 fStaticFactor = CalculateStaticContentFactor(RawRGBToLinear(fCurrentInterpolationSource), RawRGBToLinear(fPresentColor));
if (fStaticFactor > FFX_FRAMEINTERPOLATION_EPSILON)
{
fInterpolatedColor.rgb = ffxLerp(fInterpolatedColor.rgb, fPresentColor, fStaticFactor);
bWriteColor = true;
}
}
}
if ((GetDispatchFlags() & FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_TEAR_LINES) != 0)
{
drawDebugTearLines(iPxPos, fInterpolatedColor.rgb, bWriteColor);
}
if ((GetDispatchFlags() & FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_RESET_INDICATORS) != 0)
{
drawDebugResetIndicators(iPxPos, fInterpolatedColor.rgb, bWriteColor);
}
if (bWriteColor)
{
StoreFrameinterpolationOutput(iPxPos, FfxFloat32x4(fInterpolatedColor.rgb, 1.0f));
}
}
#endif // FFX_FRAMEINTERPOLATION_INPAINTING_H
@@ -0,0 +1,123 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_OPTICAL_FLOW_VECTOR_FIELD_H
#define FFX_FRAMEINTERPOLATION_OPTICAL_FLOW_VECTOR_FIELD_H
void computeOpticalFlowFieldMvs(FfxUInt32x2 dtID, FfxFloat32x2 fOpticalFlowVector)
{
FfxFloat32x2 fUv = FfxFloat32x2(FfxFloat32x2(dtID)+0.5f) / GetOpticalFlowSize2();
const FfxFloat32 scaleFactor = 1.0f;
FfxFloat32x2 fMotionVectorHalf = fOpticalFlowVector * 0.5f;
// pixel position in current frame + fOpticalFlowVector-> pixel position in previous frame
FfxFloat32x3 prevBackbufferCol = SamplePreviousBackbuffer(fUv + fOpticalFlowVector).xyz; // returns previous backbuffer color of current frame pixel position in previous frame
FfxFloat32x3 curBackbufferCol = SampleCurrentBackbuffer(fUv).xyz; // returns current backbuffer color at current frame pixel position
FfxFloat32 prevLuma = 0.001f + RawRGBToLuminance(prevBackbufferCol);
FfxFloat32 currLuma = 0.001f + RawRGBToLuminance(curBackbufferCol);
FfxFloat32 fVelocity = length(fOpticalFlowVector * InterpolationRectSize());
FfxUInt32 uHighPriorityFactor = FfxUInt32(fVelocity > 1.0f) * FfxUInt32(ffxSaturate(fVelocity / length(InterpolationRectSize() * 0.05f)) * PRIORITY_HIGH_MAX);
if(uHighPriorityFactor > 0) {
FfxUInt32 uLowPriorityFactor = FfxUInt32(ffxRound(ffxPow(MinDividedByMax(prevLuma, currLuma), 1.0f / 1.0f) * PRIORITY_LOW_MAX))
* FfxUInt32(IsUvInside(fUv + fOpticalFlowVector));
// Project current depth into previous frame locations.
// Push to all pixels having some contribution if reprojection is using bilinear logic.
const FfxUInt32x2 packedVectorPrimary = PackVectorFieldEntries(true, uHighPriorityFactor, uLowPriorityFactor, fMotionVectorHalf);
BilinearSamplingData bilinearInfo = GetBilinearSamplingData(fUv + fMotionVectorHalf, GetOpticalFlowSize2());
for (FfxInt32 iSampleIndex = 0; iSampleIndex < 4; iSampleIndex++)
{
const FfxInt32x2 iOffset = bilinearInfo.iOffsets[iSampleIndex];
const FfxInt32x2 iSamplePos = bilinearInfo.iBasePos + iOffset;
if (IsOnScreen(iSamplePos, GetOpticalFlowSize2()))
{
UpdateOpticalflowMotionVectorField(iSamplePos, packedVectorPrimary);
}
}
}
}
void computeOpticalFlowVectorField(FfxInt32x2 iPxPos)
{
FfxFloat32x2 fOpticalFlowVector = FfxFloat32x2(0.0, 0.0);
FfxFloat32x2 fOpticalFlowVector3x3Avg = FfxFloat32x2(0.0, 0.0);
FfxInt32 size = 1;
FfxFloat32 sw = 0.0f;
for(FfxInt32 y = -size; y <= size; y++) {
for(FfxInt32 x = -size; x <= size; x++) {
FfxInt32x2 samplePos = iPxPos + FfxInt32x2(x, y);
FfxFloat32x2 vs = LoadOpticalFlow(samplePos);
FfxFloat32 fConfidenceFactor = ffxMax(FFX_FRAMEINTERPOLATION_EPSILON, LoadOpticalFlowConfidence(samplePos));
FfxFloat32 len = length(vs * InterpolationRectSize());
FfxFloat32 len_factor = ffxMax(0.0f, 512.0f - len) * FfxFloat32(len > 1.0f);
FfxFloat32 w = len_factor;
fOpticalFlowVector3x3Avg += vs * w;
sw += w;
}
}
fOpticalFlowVector3x3Avg /= sw;
sw = 0.0f;
for(FfxInt32 y = -size; y <= size; y++) {
for(FfxInt32 x = -size; x <= size; x++) {
FfxInt32x2 samplePos = iPxPos + FfxInt32x2(x, y);
FfxFloat32x2 vs = LoadOpticalFlow(samplePos);
FfxFloat32 fConfidenceFactor = ffxMax(FFX_FRAMEINTERPOLATION_EPSILON, LoadOpticalFlowConfidence(samplePos));
FfxFloat32 len = length(vs * InterpolationRectSize());
FfxFloat32 len_factor = ffxMax(0.0f, 512.0f - len) * FfxFloat32(len > 1.0f);
FfxFloat32 w = ffxMax(0.0f, ffxPow(dot(fOpticalFlowVector3x3Avg, vs), 1.25f)) * len_factor;
fOpticalFlowVector += vs * w;
sw += w;
}
}
if (sw > FFX_FRAMEINTERPOLATION_EPSILON)
{
fOpticalFlowVector /= sw;
}
computeOpticalFlowFieldMvs(iPxPos, fOpticalFlowVector);
}
#endif // FFX_FRAMEINTERPOLATION_OPTICAL_FLOW_VECTOR_FIELD_H
@@ -0,0 +1,123 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_RECONSTRUCT_DILATED_VELOCITY_AND_PREVIOUS_DEPTH_H
#define FFX_FRAMEINTERPOLATION_RECONSTRUCT_DILATED_VELOCITY_AND_PREVIOUS_DEPTH_H
void ReconstructPrevDepth(FfxInt32x2 iPxPos, FfxFloat32 fDepth, FfxFloat32x2 fMotionVector, FfxInt32x2 iPxDepthSize)
{
fMotionVector *= FfxFloat32(length(fMotionVector * DisplaySize()) > 0.1f);
FfxFloat32x2 fUv = (iPxPos + FfxFloat32(0.5)) / iPxDepthSize;
FfxFloat32x2 fReprojectedUv = fUv + fMotionVector;
BilinearSamplingData bilinearInfo = GetBilinearSamplingData(fReprojectedUv, RenderSize());
// Project current depth into previous frame locations.
// Push to all pixels having some contribution if reprojection is using bilinear logic.
for (FfxInt32 iSampleIndex = 0; iSampleIndex < 4; iSampleIndex++) {
const FfxInt32x2 iOffset = bilinearInfo.iOffsets[iSampleIndex];
FfxFloat32 fWeight = bilinearInfo.fWeights[iSampleIndex];
if (fWeight > fReconstructedDepthBilinearWeightThreshold) {
FfxInt32x2 iStorePos = bilinearInfo.iBasePos + iOffset;
if (IsOnScreen(iStorePos, iPxDepthSize)) {
UpdateReconstructedDepthPreviousFrame(iStorePos, fDepth);
}
}
}
}
void FindNearestDepth(FFX_PARAMETER_IN FfxInt32x2 iPxPos, FFX_PARAMETER_IN FfxInt32x2 iPxSize, FFX_PARAMETER_OUT FfxFloat32 fNearestDepth, FFX_PARAMETER_OUT FfxInt32x2 fNearestDepthCoord)
{
const FfxInt32 iSampleCount = 9;
const FfxInt32x2 iSampleOffsets[iSampleCount] = {
FfxInt32x2(+0, +0),
FfxInt32x2(+1, +0),
FfxInt32x2(+0, +1),
FfxInt32x2(+0, -1),
FfxInt32x2(-1, +0),
FfxInt32x2(-1, +1),
FfxInt32x2(+1, +1),
FfxInt32x2(-1, -1),
FfxInt32x2(+1, -1),
};
// pull out the depth loads to allow SC to batch them
FfxFloat32 depth[9];
FfxInt32 iSampleIndex = 0;
FFX_UNROLL
for (iSampleIndex = 0; iSampleIndex < iSampleCount; ++iSampleIndex) {
FfxInt32x2 iPos = iPxPos + iSampleOffsets[iSampleIndex];
depth[iSampleIndex] = LoadInputDepth(iPos);
}
// find closest depth
fNearestDepthCoord = iPxPos;
fNearestDepth = depth[0];
FFX_UNROLL
for (iSampleIndex = 1; iSampleIndex < iSampleCount; ++iSampleIndex) {
FfxInt32x2 iPos = iPxPos + iSampleOffsets[iSampleIndex];
if (IsOnScreen(iPos, iPxSize)) {
FfxFloat32 fNdDepth = depth[iSampleIndex];
#if FFX_FRAMEINTERPOLATION_OPTION_INVERTED_DEPTH
if (fNdDepth > fNearestDepth) {
#else
if (fNdDepth < fNearestDepth) {
#endif
fNearestDepthCoord = iPos;
fNearestDepth = fNdDepth;
}
}
}
}
void ReconstructAndDilate(FfxInt32x2 iPxLrPos)
{
FfxFloat32 fDilatedDepth;
FfxInt32x2 iNearestDepthCoord;
FindNearestDepth(iPxLrPos, RenderSize(), fDilatedDepth, iNearestDepthCoord);
#if FFX_FRAMEINTERPOLATION_OPTION_LOW_RES_MOTION_VECTORS
FfxInt32x2 iSamplePos = iPxLrPos;
FfxInt32x2 iMotionVectorPos = iNearestDepthCoord;
#else
FfxInt32x2 iSamplePos = ComputeHrPosFromLrPos(iPxLrPos);
FfxInt32x2 iMotionVectorPos = ComputeHrPosFromLrPos(iNearestDepthCoord);
#endif
FfxFloat32x2 fDilatedMotionVector = LoadInputMotionVector(iMotionVectorPos);
StoreDilatedDepth(iPxLrPos, fDilatedDepth);
StoreDilatedMotionVectors(iPxLrPos, fDilatedMotionVector);
ReconstructPrevDepth(iPxLrPos, fDilatedDepth, fDilatedMotionVector, RenderSize());
}
#endif //!defined( FFX_FRAMEINTERPOLATION_RECONSTRUCT_DILATED_VELOCITY_AND_PREVIOUS_DEPTH_H )
@@ -0,0 +1,63 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_RECONSTRUCT_PREVIOUS_DEPTH_H
#define FFX_FRAMEINTERPOLATION_RECONSTRUCT_PREVIOUS_DEPTH_H
void ReconstructPrevDepth(FfxInt32x2 iPxPos, FfxUInt32 depthTarget, FfxFloat32 fDepth, FfxFloat32x2 fMotionVector, FfxInt32x2 iPxDepthSize)
{
const FfxFloat32x2 fUv = (iPxPos + FfxFloat32(0.5)) / iPxDepthSize;
// Project current depth into previous frame locations.
// Push to all pixels having some contribution if reprojection is using bilinear logic.
BilinearSamplingData bilinearInfo = GetBilinearSamplingData(fUv + fMotionVector, RenderSize());
for (FfxInt32 iSampleIndex = 0; iSampleIndex < 4; iSampleIndex++)
{
const FfxInt32x2 iOffset = bilinearInfo.iOffsets[iSampleIndex];
const FfxInt32x2 iSamplePos = bilinearInfo.iBasePos + iOffset;
const FfxFloat32 fSampleWeight = bilinearInfo.fWeights[iSampleIndex];
if (fSampleWeight > fReconstructedDepthBilinearWeightThreshold)
{
if (IsOnScreen(iSamplePos, RenderSize()))
{
if (depthTarget != 0) {
UpdateReconstructedDepthInterpolatedFrame(iSamplePos, fDepth);
}
}
}
}
}
void reconstructPreviousDepth(FfxInt32x2 iPxPos)
{
const FfxFloat32x2 fUv = (iPxPos + FfxFloat32(0.5f)) / RenderSize();
const FfxFloat32x2 fDistortionFieldUv = SampleDistortionField(fUv);
FfxInt32x2 iDistortionPixelOffset = FfxInt32x2(fDistortionFieldUv.xy * RenderSize());
FfxFloat32x2 fMotionVector = LoadDilatedMotionVector(iPxPos + iDistortionPixelOffset);
FfxFloat32 fDilatedDepth = LoadDilatedDepth(iPxPos + iDistortionPixelOffset);
ReconstructPrevDepth(iPxPos, 1, fDilatedDepth, fMotionVector * 0.5f, RenderSize());
}
#endif // FFX_FRAMEINTERPOLATION_RECONSTRUCT_PREVIOUS_DEPTH_H
@@ -0,0 +1,95 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_RESOURCES_H
#define FFX_FRAMEINTERPOLATION_RESOURCES_H
#if defined(FFX_CPU) || defined(FFX_GPU)
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_NULL 0
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_OUTPUT 1
//#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_BACKBUFFER 2
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_PREVIOUS_INTERPOLATION_SOURCE 3
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_CURRENT_INTERPOLATION_SOURCE 4
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_DEPTH 5
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_MOTION_VECTORS 6
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_RESERVED_2 7
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_RESERVED_3 8
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_RESERVED_4 9
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_DILATED_DEPTH 10
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_DILATED_MOTION_VECTORS 11
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_RECONSTRUCTED_DEPTH_PREVIOUS_FRAME 12
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_RECONSTRUCTED_DEPTH_INTERPOLATED_FRAME 13
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_DISOCCLUSION_MASK 14
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_GAME_MOTION_VECTOR_FIELD_X 15
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_GAME_MOTION_VECTOR_FIELD_Y 16
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X 17
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y 18
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_OPTICAL_FLOW_VECTOR 19
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_RESERVED_5 20
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_OPTICAL_FLOW_CONFIDENCE 21
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_OPTICAL_FLOW_GLOBAL_MOTION 22
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCENE_CHANGE_DETECTION 23
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_RESERVED_6 25
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_RESERVED_7 26
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_DEBUG_OUTPUT_0 27
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_DEBUG_OUTPUT_1 28
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_DEBUG_OUTPUT 29
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_MASK 30
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_PRESENT_BACKBUFFER 31
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_COUNTERS 32
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID 33 // same as FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_0
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_0 33
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_1 34
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_2 35
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_3 36
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_4 37
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_5 38
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_6 39
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_7 40
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_8 41
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_9 42
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_10 43
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_11 44
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_INPAINTING_PYRAMID_MIPMAP_12 45
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_DEFAULT_DISTORTION_FIELD 46
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_DISTORTION_FIELD 47
#define FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_COUNT 48
#define FFX_FRAMEINTERPOLATION_CONSTANTBUFFER_IDENTIFIER 0
#define FFX_FRAMEINTERPOLATION_INPAINTING_PYRAMID_CONSTANTBUFFER_IDENTIFIER 1
#define FFX_FRAMEINTERPOLATION_CONSTANTBUFFER_COUNT 2
#endif // #if defined(FFX_CPU) || defined(FFX_GPU)
#endif //!defined( FFX_FRAMEINTERPOLATION_RESOURCES_H )
@@ -0,0 +1,50 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_FRAMEINTERPOLATION_SETUP_H
#define FFX_FRAMEINTERPOLATION_SETUP_H
void setupFrameinterpolationResources(FfxInt32x2 iPxPos)
{
// Update reset counters
StoreCounter(COUNTER_SPD, 0);
if (all(FFX_EQUAL(iPxPos, FfxInt32x2(0, 0))))
{
if(Reset() || HasSceneChanged()) {
StoreCounter(COUNTER_FRAME_INDEX_SINCE_LAST_RESET, 0);
} else {
FfxUInt32 counter = RWLoadCounter(COUNTER_FRAME_INDEX_SINCE_LAST_RESET);
StoreCounter(COUNTER_FRAME_INDEX_SINCE_LAST_RESET, counter + 1);
}
}
// Reset resources
StoreGameMotionVectorFieldX(iPxPos, 0);
StoreGameMotionVectorFieldY(iPxPos, 0);
StoreOpticalflowMotionVectorFieldX(iPxPos, 0);
StoreOpticalflowMotionVectorFieldY(iPxPos, 0);
StoreDisocclusionMask(iPxPos, FfxFloat32x2(0.0, 0.0));
}
#endif // FFX_FRAMEINTERPOLATION_SETUP_H
@@ -0,0 +1,578 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_OPTICALFLOW_CALLBACKS_HLSL_H
#define FFX_OPTICALFLOW_CALLBACKS_HLSL_H
#include "opticalflow/ffx_opticalflow_resources.h"
// no msad4 in glsl
#define FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION 0
#define FFX_OPTICALFLOW_FIX_TOP_LEFT_BIAS 1
#define FFX_OPTICALFLOW_USE_HEURISTICS 1
#define FFX_OPTICALFLOW_BLOCK_SIZE 8
#define FFX_LOCAL_SEARCH_FALLBACK 1
// perf optimization for h/w not supporting accelerated msad4()
//#if !defined(FFX_PREFER_WAVE64) && defined(FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION)
//#undef FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION
//#endif
#if defined(FFX_GPU)
#include "ffx_core.h"
#endif // #if defined(FFX_GPU)
#if defined(FFX_GPU)
#ifndef FFX_PREFER_WAVE64
#define FFX_PREFER_WAVE64
#endif // #if defined(FFX_GPU)
#include "opticalflow/ffx_opticalflow_common.h"
#if defined(FFX_OPTICALFLOW_BIND_CB_COMMON)
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_CB_COMMON, std140) uniform cbOF_t
{
FfxInt32x2 iInputLumaResolution;
FfxUInt32 uOpticalFlowPyramidLevel;
FfxUInt32 uOpticalFlowPyramidLevelCount;
FfxUInt32 iFrameIndex;
FfxUInt32 backbufferTransferFunction;
FfxFloat32x2 minMaxLuminance;
} cbOF;
FfxInt32x2 DisplaySize()
{
return cbOF.iInputLumaResolution;
}
FfxUInt32 FrameIndex()
{
return cbOF.iFrameIndex;
}
FfxUInt32 BackbufferTransferFunction()
{
return cbOF.backbufferTransferFunction;
}
FfxFloat32x2 MinMaxLuminance()
{
return cbOF.minMaxLuminance;
}
FfxBoolean CrossedSceneChangeThreshold(FfxFloat32 sceneChangeValue)
{
return sceneChangeValue > 0.45f;
}
FfxUInt32 OpticalFlowPyramidLevel()
{
return cbOF.uOpticalFlowPyramidLevel;
}
FfxUInt32 OpticalFlowPyramidLevelCount()
{
return cbOF.uOpticalFlowPyramidLevelCount;
}
FfxInt32x2 OpticalFlowHistogramMaxVelocity()
{
const FfxInt32 searchRadius = 8;
FfxInt32 scale = FfxInt32(1) << (OpticalFlowPyramidLevelCount() - 1 - OpticalFlowPyramidLevel());
FfxInt32 maxVelocity = searchRadius * scale;
return FfxInt32x2(maxVelocity, maxVelocity);
}
#endif //FFX_OPTICALFLOW_BIND_CB_COMMON
#if defined(FFX_OPTICALFLOW_BIND_CB_SPD)
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_CB_SPD, std140) uniform cbOF_SPD_t
{
FfxUInt32 mips;
FfxUInt32 numWorkGroups;
FfxUInt32x2 workGroupOffset;
FfxUInt32 numWorkGroupOpticalFlowInputPyramid;
FfxUInt32 pad0_;
FfxUInt32 pad1_;
FfxUInt32 pad2_;
} cbOF_SPD;
uint NumWorkGroups()
{
return cbOF_SPD.numWorkGroupOpticalFlowInputPyramid;
}
#endif // defined(FFX_OPTICALFLOW_BIND_CB_SPD)
#if defined FFX_OPTICALFLOW_BIND_SRV_INPUT_COLOR
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_SRV_INPUT_COLOR) uniform texture2D r_input_color;
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_INPUT_MOTION_VECTORS
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_SRV_INPUT_MOTION_VECTORS) uniform texture2D r_input_motion_vectors;
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_INPUT
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_INPUT) uniform utexture2D r_optical_flow_input;
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS_INPUT
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS_INPUT) uniform utexture2D r_optical_flow_previous_input;
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW) uniform itexture2D r_optical_flow;
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS) uniform itexture2D r_optical_flow_previous;
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO) uniform utexture2D r_optical_flow_additional_info;
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO_PREVIOUS
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO_PREVIOUS) uniform utexture2D r_optical_flow_additional_info_previous;
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_HISTOGRAM
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_HISTOGRAM) uniform utexture2D r_optical_flow_histogram;
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH) uniform utexture2D r_optical_flow_global_motion_search;
#endif
// UAV declarations
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT, r8ui) uniform uimage2D rw_optical_flow_input;
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_1
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_1, r8ui) uniform uimage2D rw_optical_flow_input_level_1;
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_2
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_2, r8ui) uniform uimage2D rw_optical_flow_input_level_2;
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_3
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_3, r8ui) uniform uimage2D rw_optical_flow_input_level_3;
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_4
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_4, r8ui) uniform uimage2D rw_optical_flow_input_level_4;
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_5
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_5, r8ui) uniform uimage2D rw_optical_flow_input_level_5;
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_6
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_6, r8ui) uniform uimage2D rw_optical_flow_input_level_6;
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW, rg16i) uniform iimage2D rw_optical_flow;
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_NEXT_LEVEL
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_NEXT_LEVEL, rg16i) uniform iimage2D rw_optical_flow_next_level;
#endif
//#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO
// RWTexture2D<FfxUInt32x2> rw_optical_flow_additional_info : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO);
// layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO, r32ui) uniform uimage2D rw_optical_flow_additional_info;
//#endif
//#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO_NEXT_LEVEL
// RWTexture2D<FfxUInt32x2> rw_optical_flow_additional_info_next_level : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO_NEXT_LEVEL);
// layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO_NEXT_LEVEL, r32ui) uniform uimage2D rw_optical_flow_additional_info_next_level;
//#endif
//#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_HISTOGRAM
// RWTexture2D<FfxUInt32> rw_optical_flow_histogram : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_HISTOGRAM);
// layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_HISTOGRAM, r32ui) uniform uimage2D rw_optical_flow_histogram;
//#endif
//#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH
// globallycoherent RWTexture2D<FfxUInt32> rw_optical_flow_global_motion_search: FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH);
// layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH, r32ui) coherent uniform uimage2D rw_optical_flow_global_motion_search;
//#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM, r32ui) uniform uimage2D rw_optical_flow_scd_histogram;
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM, r32f) uniform image2D rw_optical_flow_scd_previous_histogram;
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_TEMP
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_TEMP, r32ui) uniform uimage2D rw_optical_flow_scd_temp;
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT
layout (set = 0, binding = FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT, r32ui) uniform uimage2D rw_optical_flow_scd_output;
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_INPUT_COLOR)
FfxFloat32x4 LoadInputColor(FfxUInt32x2 iPxHistory)
{
return texelFetch(r_input_color, FfxInt32x2(iPxHistory), 0);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_INPUT_MOTION_VECTORS)
FfxFloat32x2 LoadGameMotionVector(FfxInt32x2 iPxPos)
{
FfxFloat32x2 positionScale = FfxFloat32x2(RenderSize()) / DisplaySize();
return texelFetch(r_input_motion_vectors, FfxInt32x2(iPxPos * positionScale), 0).xy * motionVectorScale / positionScale;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT)
void StoreOpticalFlowInput(FfxInt32x2 iPxPos, FfxUInt32 fLuma)
{
imageStore(rw_optical_flow_input, iPxPos, FfxUInt32x4(fLuma, 0, 0, 0));
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_INPUT)
FfxUInt32 LoadOpticalFlowInput(FfxInt32x2 iPxPos)
{
#if FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION == 1
return max(1, texelFetch(r_optical_flow_input, iPxPos, 0).x);
#else
return texelFetch(r_optical_flow_input, iPxPos, 0).x;
#endif
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT)
FfxUInt32 LoadRwOpticalFlowInput(FfxInt32x2 iPxPos)
{
return imageLoad(rw_optical_flow_input, iPxPos).x;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS_INPUT)
FfxUInt32 LoadOpticalFlowPreviousInput(FfxInt32x2 iPxPos)
{
#if FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION == 1
return max(1, texelFetch(r_optical_flow_previous_input, iPxPos, 0).x);
#else
return texelFetch(r_optical_flow_previous_input, iPxPos, 0).x;
#endif
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW)
FfxInt32x2 LoadOpticalFlow(FfxInt32x2 iPxPos)
{
return texelFetch(r_optical_flow, iPxPos, 0).xy;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW)
FfxInt32x2 LoadRwOpticalFlow(FfxInt32x2 iPxPos)
{
return imageLoad(rw_optical_flow, iPxPos).xy;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS)
FfxInt32x2 LoadPreviousOpticalFlow(FfxInt32x2 iPxPos)
{
return texelFetch(r_optical_flow_previous, iPxPos, 0).xy;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW)
void StoreOpticalFlow(FfxInt32x2 iPxPos, FfxInt32x2 motionVector)
{
imageStore(rw_optical_flow, iPxPos, FfxInt32x4(motionVector, 0, 0));
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_NEXT_LEVEL)
void StoreOpticalFlowNextLevel(FfxInt32x2 iPxPos, FfxInt32x2 motionVector)
{
imageStore(rw_optical_flow_next_level, iPxPos, FfxInt32x4(motionVector, 0, 0));
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO)
FfxUInt32x2 LoadOpticalFlowAdditionalInfo(FfxInt32x2 iPxPos)
{
return texelFetch(r_optical_flow_additional_info, iPxPos, 0).xy;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO)
FfxUInt32x2 LoadRwOpticalFlowAdditionalInfo(FfxInt32x2 iPxPos)
{
return imageLoad(rw_optical_flow_additional_info, iPxPos).xy;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO_PREVIOUS)
FfxUInt32x2 LoadPreviousOpticalFlowAdditionalInfo(FfxInt32x2 iPxPos)
{
return texelFetch(r_optical_flow_additional_info_previous, iPxPos, 0).xy;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO)
void StoreOpticalFlowAdditionalInfo(FfxInt32x2 iPxPos, FfxUInt32x2 additionalInfo)
{
imageStore(rw_optical_flow_additional_info, iPxPos, FfxUInt32x4(additionalInfo, 0, 0));
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO_NEXT_LEVEL)
void StoreOpticalFlowNextLevelAdditionalInfo(FfxInt32x2 iPxPos, FfxUInt32x2 additionalInfo)
{
imageStore(rw_optical_flow_additional_info_next_level, iPxPos, FfxUInt32x4(additionalInfo, 0, 0));
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_HISTOGRAM)
FfxUInt32 LoadOpticalFlowHistogram(FfxInt32x2 iBucketId)
{
return texelFetch(r_optical_flow_histogram, iBucketId, 0).x;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_HISTOGRAM)
void AtomicIncrementOpticalFlowHistogram(FfxInt32x2 iBucketId)
{
imageAtomicAdd(rw_optical_flow_histogram, iBucketId, 1);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH)
FfxInt32x2 LoadGlobalMotionVector()
{
FfxInt32 vx = FfxInt32(texelFetch(r_optical_flow_global_motion_search, FfxInt32x2(0, 0), 0).x);
FfxInt32 vy = FfxInt32(texelFetch(r_optical_flow_global_motion_search, FfxInt32x2(1, 0), 0).x);
return FfxInt32x2(vx, vy);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH)
FfxInt32x2 LoadRwGlobalMotionVector()
{
FfxInt32 vx = FfxInt32(imageLoad(rw_optical_flow_global_motion_search, FfxInt32x2(0, 0)).x);
FfxInt32 vy = FfxInt32(imageLoad(rw_optical_flow_global_motion_search, FfxInt32x2(1, 0)).x);
return FfxInt32x2(vx, vy);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH)
FfxUInt32 LoadGlobalMotionValue(FfxInt32 index)
{
return imageLoad(rw_optical_flow_global_motion_search, FfxInt32x2(index, 0)).x;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH)
void StoreGlobalMotionValue(FfxInt32 index, FfxUInt32 value)
{
imageStore(rw_optical_flow_global_motion_search, FfxInt32x2(index, 0), FfxUInt32x4(value, 0, 0, 0));
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH)
FfxUInt32 AtomicIncrementGlobalMotionValue(FfxInt32 index)
{
return imageAtomicAdd(rw_optical_flow_global_motion_search, FfxInt32x2(index, 0), 1);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM)
FfxUInt32 LoadRwSCDHistogram(FfxInt32 iIndex)
{
return imageLoad(rw_optical_flow_scd_histogram, FfxInt32x2(iIndex, 0)).x;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM)
void StoreSCDHistogram(FfxInt32 iIndex, FfxUInt32 value)
{
imageStore(rw_optical_flow_scd_histogram, FfxInt32x2(iIndex, 0), FfxUInt32x4(value, 0, 0, 0));
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM)
void AtomicIncrementSCDHistogram(FfxInt32 iIndex, FfxUInt32 valueToAdd)
{
imageAtomicAdd(rw_optical_flow_scd_histogram, FfxInt32x2(iIndex, 0), valueToAdd);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM)
FfxFloat32 LoadRwSCDPreviousHistogram(FfxInt32 iIndex)
{
return imageLoad(rw_optical_flow_scd_previous_histogram, FfxInt32x2(iIndex, 0)).x;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM)
void StoreSCDPreviousHistogram(FfxInt32 iIndex, FfxFloat32 value)
{
imageStore(rw_optical_flow_scd_previous_histogram, FfxInt32x2(iIndex, 0), FfxFloat32x4(value, 0.0, 0.0, 0.0));
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_TEMP)
FfxUInt32 LoadRwSCDTemp(FfxInt32 iIndex)
{
return imageLoad(rw_optical_flow_scd_temp, FfxInt32x2(iIndex, 0)).x;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_TEMP)
void AtomicIncrementSCDTemp(FfxInt32 iIndex, FfxUInt32 valueToAdd)
{
imageAtomicAdd(rw_optical_flow_scd_temp, FfxInt32x2(iIndex, 0), valueToAdd);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_TEMP)
void ResetSCDTemp()
{
imageStore(rw_optical_flow_scd_temp, FfxInt32x2(0, 0), FfxUInt32x4(0, 0, 0, 0));
imageStore(rw_optical_flow_scd_temp, FfxInt32x2(1, 0), FfxUInt32x4(0, 0, 0, 0));
imageStore(rw_optical_flow_scd_temp, FfxInt32x2(2, 0), FfxUInt32x4(0, 0, 0, 0));
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT)
FfxUInt32 LoadRwSCDOutput(FfxInt32 iIndex)
{
return imageLoad(rw_optical_flow_scd_output, FfxInt32x2(iIndex, 0)).x;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT)
void StoreSCDOutput(FfxInt32 iIndex, FfxUInt32 value)
{
imageStore(rw_optical_flow_scd_output, FfxInt32x2(iIndex, 0), FfxUInt32x4(value, 0, 0, 0));
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT)
FfxUInt32 AtomicIncrementSCDOutput(FfxInt32 iIndex, FfxUInt32 valueToAdd)
{
return imageAtomicAdd(rw_optical_flow_scd_output, FfxInt32x2(iIndex, 0), valueToAdd);
}
#endif
//#if defined(FFX_OPTICALFLOW_BIND_UAV_DEBUG_VISUALIZATION)
//void StoreDebugVisualization(FfxUInt32x2 iPxPos, FfxFloat32x3 fColor)
//{
// imageStore(rw_debug_visualization, iPxPos, FfxFloat32x4(fColor, 1.f));
//}
//#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT)
FfxFloat32 GetSceneChangeValue()
{
if (FrameIndex() <= 5)
return 1.0;
else
return ffxAsFloat(LoadRwSCDOutput(SCD_OUTPUT_SCENE_CHANGE_SLOT));
}
FfxBoolean IsSceneChanged()
{
if (FrameIndex() <= 5)
{
return true;
}
else
{
return (LoadRwSCDOutput(SCD_OUTPUT_HISTORY_BITS_SLOT) & 0xfu) != 0;
}
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_INPUT)
FfxUInt32 LoadFirstImagePackedLuma(FfxInt32x2 iPxPos)
{
const FfxInt32 lumaTextureWidth = DisplaySize().x >> OpticalFlowPyramidLevel();
const FfxInt32 lumaTextureHeight = DisplaySize().y >> OpticalFlowPyramidLevel();
FfxInt32x2 adjustedPos = FfxInt32x2(
ffxClamp(iPxPos.x, 0, lumaTextureWidth - 4),
ffxClamp(iPxPos.y, 0, lumaTextureHeight - 1)
);
FfxUInt32 luma0 = LoadOpticalFlowInput(adjustedPos + FfxInt32x2(0, 0));
FfxUInt32 luma1 = LoadOpticalFlowInput(adjustedPos + FfxInt32x2(1, 0));
FfxUInt32 luma2 = LoadOpticalFlowInput(adjustedPos + FfxInt32x2(2, 0));
FfxUInt32 luma3 = LoadOpticalFlowInput(adjustedPos + FfxInt32x2(3, 0));
return GetPackedLuma(lumaTextureWidth, iPxPos.x, luma0, luma1, luma2, luma3);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS_INPUT)
FfxUInt32 LoadSecondImagePackedLuma(FfxInt32x2 iPxPos)
{
const FfxInt32 lumaTextureWidth = DisplaySize().x >> OpticalFlowPyramidLevel();
const FfxInt32 lumaTextureHeight = DisplaySize().y >> OpticalFlowPyramidLevel();
FfxInt32x2 adjustedPos = FfxInt32x2(
ffxClamp(iPxPos.x, 0, lumaTextureWidth - 4),
ffxClamp(iPxPos.y, 0, lumaTextureHeight - 1)
);
FfxUInt32 luma0 = LoadOpticalFlowPreviousInput(adjustedPos + FfxInt32x2(0, 0));
FfxUInt32 luma1 = LoadOpticalFlowPreviousInput(adjustedPos + FfxInt32x2(1, 0));
FfxUInt32 luma2 = LoadOpticalFlowPreviousInput(adjustedPos + FfxInt32x2(2, 0));
FfxUInt32 luma3 = LoadOpticalFlowPreviousInput(adjustedPos + FfxInt32x2(3, 0));
return GetPackedLuma(lumaTextureWidth, iPxPos.x, luma0, luma1, luma2, luma3);
}
#endif
void SPD_SetMipmap(FfxInt32x2 iPxPos, FfxUInt32 index, FfxFloat32 value)
{
FfxUInt32x4 value4 = FfxUInt32x4(value, 0.0, 0.0, 0.0);
switch (index)
{
case 0:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_1
imageStore(rw_optical_flow_input_level_1, iPxPos, value4);
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_1
break;
case 1:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_2
imageStore(rw_optical_flow_input_level_2, iPxPos, value4);
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_2
break;
case 2:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_3
imageStore(rw_optical_flow_input_level_3, iPxPos, value4);
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_3
break;
case 3:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_4
imageStore(rw_optical_flow_input_level_4, iPxPos, value4);
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_4
break;
case 4:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_5
imageStore(rw_optical_flow_input_level_5, iPxPos, value4);
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_5
break;
case 5:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_6
imageStore(rw_optical_flow_input_level_6, iPxPos, value4);
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_6
break;
}
}
#endif // #if defined(FFX_GPU)
#endif // FFX_OPTICALFLOW_CALLBACKS_HLSL_H
@@ -0,0 +1,634 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_OPTICALFLOW_CALLBACKS_HLSL_H
#define FFX_OPTICALFLOW_CALLBACKS_HLSL_H
#if defined(FFX_GPU)
#ifdef __hlsl_dx_compiler
#pragma dxc diagnostic push
#pragma dxc diagnostic ignored "-Wambig-lit-shift"
#endif //__hlsl_dx_compiler
#include "ffx_core.h"
#ifdef __hlsl_dx_compiler
#pragma dxc diagnostic pop
#endif //__hlsl_dx_compiler
#define FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION 1
#define FFX_OPTICALFLOW_FIX_TOP_LEFT_BIAS 1
#define FFX_OPTICALFLOW_USE_HEURISTICS 1
#define FFX_OPTICALFLOW_BLOCK_SIZE 8
#define FFX_LOCAL_SEARCH_FALLBACK 1
// perf optimization for h/w not supporting accelerated msad4()
#if !defined(FFX_PREFER_WAVE64) && defined(FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION)
#undef FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION
#endif
#include "opticalflow/ffx_opticalflow_common.h"
#ifndef FFX_PREFER_WAVE64
#define FFX_PREFER_WAVE64
#endif
#pragma warning(disable: 3205) // conversion from larger type to smaller
#define DECLARE_SRV_REGISTER(regIndex) t##regIndex
#define DECLARE_UAV_REGISTER(regIndex) u##regIndex
#define DECLARE_CB_REGISTER(regIndex) b##regIndex
#define FFX_OPTICALFLOW_DECLARE_SRV(regIndex) register(DECLARE_SRV_REGISTER(regIndex))
#define FFX_OPTICALFLOW_DECLARE_UAV(regIndex) register(DECLARE_UAV_REGISTER(regIndex))
#define FFX_OPTICALFLOW_DECLARE_CB(regIndex) register(DECLARE_CB_REGISTER(regIndex))
#if defined(FFX_OPTICALFLOW_BIND_CB_COMMON)
cbuffer cbOF : FFX_OPTICALFLOW_DECLARE_CB(FFX_OPTICALFLOW_BIND_CB_COMMON)
{
FfxInt32x2 iInputLumaResolution;
FfxUInt32 uOpticalFlowPyramidLevel;
FfxUInt32 uOpticalFlowPyramidLevelCount;
FfxUInt32 iFrameIndex;
FfxUInt32 backbufferTransferFunction;
FfxFloat32x2 minMaxLuminance;
};
#define FFX_OPTICALFLOW_CONSTANT_BUFFER_1_SIZE 8
#endif //FFX_OPTICALFLOW_BIND_CB_COMMON
#if defined(FFX_OPTICALFLOW_BIND_CB_SPD)
cbuffer cbOF_SPD : FFX_OPTICALFLOW_DECLARE_CB(FFX_OPTICALFLOW_BIND_CB_SPD) {
FfxUInt32 mips;
FfxUInt32 numWorkGroups;
FfxUInt32x2 workGroupOffset;
FfxUInt32 numWorkGroupOpticalFlowInputPyramid;
FfxUInt32 pad0_;
FfxUInt32 pad1_;
FfxUInt32 pad2_;
};
FfxUInt32 NumWorkGroups()
{
return numWorkGroupOpticalFlowInputPyramid;
}
#endif //FFX_OPTICALFLOW_BIND_CB_SPD
#define FFX_OPTICALFLOW_CONSTANT_BUFFER_2_SIZE 8
#define FFX_OPTICALFLOW_DESCRIPTOR_COUNT 32
#define FFX_OPTICALFLOW_ROOTSIG_STRINGIFY(p) FFX_OPTICALFLOW_ROOTSIG_STR(p)
#define FFX_OPTICALFLOW_ROOTSIG_STR(p) #p
#define FFX_OPTICALFLOW_ROOTSIG [RootSignature( "DescriptorTable(UAV(u0, numDescriptors = " FFX_OPTICALFLOW_ROOTSIG_STRINGIFY(FFX_OPTICALFLOW_DESCRIPTOR_COUNT) ")), " \
"DescriptorTable(SRV(t0, numDescriptors = " FFX_OPTICALFLOW_ROOTSIG_STRINGIFY(FFX_OPTICALFLOW_DESCRIPTOR_COUNT) ")), " \
"CBV(b0), " \
"StaticSampler(s0, filter = FILTER_MIN_MAG_MIP_POINT, " \
"addressU = TEXTURE_ADDRESS_CLAMP, " \
"addressV = TEXTURE_ADDRESS_CLAMP, " \
"addressW = TEXTURE_ADDRESS_CLAMP, " \
"comparisonFunc = COMPARISON_NEVER, " \
"borderColor = STATIC_BORDER_COLOR_TRANSPARENT_BLACK), " \
"StaticSampler(s1, filter = FILTER_MIN_MAG_MIP_LINEAR, " \
"addressU = TEXTURE_ADDRESS_CLAMP, " \
"addressV = TEXTURE_ADDRESS_CLAMP, " \
"addressW = TEXTURE_ADDRESS_CLAMP, " \
"comparisonFunc = COMPARISON_NEVER, " \
"borderColor = STATIC_BORDER_COLOR_TRANSPARENT_BLACK)" )]
#define FFX_OPTICALFLOW_CB2_ROOTSIG [RootSignature( "DescriptorTable(UAV(u0, numDescriptors = " FFX_OPTICALFLOW_ROOTSIG_STRINGIFY(FFX_OPTICALFLOW_DESCRIPTOR_COUNT) ")), " \
"DescriptorTable(SRV(t0, numDescriptors = " FFX_OPTICALFLOW_ROOTSIG_STRINGIFY(FFX_OPTICALFLOW_DESCRIPTOR_COUNT) ")), " \
"CBV(b0), " \
"StaticSampler(s0, filter = FILTER_MIN_MAG_MIP_POINT, " \
"addressU = TEXTURE_ADDRESS_CLAMP, " \
"addressV = TEXTURE_ADDRESS_CLAMP, " \
"addressW = TEXTURE_ADDRESS_CLAMP, " \
"comparisonFunc = COMPARISON_NEVER, " \
"borderColor = STATIC_BORDER_COLOR_TRANSPARENT_BLACK), " \
"StaticSampler(s1, filter = FILTER_MIN_MAG_MIP_LINEAR, " \
"addressU = TEXTURE_ADDRESS_CLAMP, " \
"addressV = TEXTURE_ADDRESS_CLAMP, " \
"addressW = TEXTURE_ADDRESS_CLAMP, " \
"comparisonFunc = COMPARISON_NEVER, " \
"borderColor = STATIC_BORDER_COLOR_TRANSPARENT_BLACK)" )]
#if defined(FFX_OPTICALFLOW_EMBED_ROOTSIG)
#define FFX_OPTICALFLOW_EMBED_ROOTSIG_CONTENT FFX_OPTICALFLOW_ROOTSIG
#define FFX_OPTICALFLOW_EMBED_CB2_ROOTSIG_CONTENT FFX_OPTICALFLOW_CB2_ROOTSIG
#else
#define FFX_OPTICALFLOW_EMBED_ROOTSIG_CONTENT
#define FFX_OPTICALFLOW_EMBED_CB2_ROOTSIG_CONTENT
#endif // #if FFX_OPTICALFLOW_EMBED_ROOTSIG
FfxInt32x2 DisplaySize()
{
return iInputLumaResolution;
}
FfxUInt32 FrameIndex()
{
return iFrameIndex;
}
FfxUInt32 BackbufferTransferFunction()
{
return backbufferTransferFunction;
}
FfxFloat32x2 MinMaxLuminance()
{
return minMaxLuminance;
}
FfxBoolean CrossedSceneChangeThreshold(FfxFloat32 sceneChangeValue)
{
return sceneChangeValue > 0.45f;
}
FfxUInt32 OpticalFlowPyramidLevel()
{
return uOpticalFlowPyramidLevel;
}
FfxUInt32 OpticalFlowPyramidLevelCount()
{
return uOpticalFlowPyramidLevelCount;
}
FfxInt32x2 OpticalFlowHistogramMaxVelocity()
{
const FfxInt32 searchRadius = 8;
FfxInt32 scale = FfxInt32(1) << (OpticalFlowPyramidLevelCount() - 1 - OpticalFlowPyramidLevel());
FfxInt32 maxVelocity = searchRadius * scale;
return FfxInt32x2(maxVelocity, maxVelocity);
}
#if defined FFX_OPTICALFLOW_BIND_SRV_INPUT_COLOR
Texture2D<FfxFloat32x4> r_input_color : FFX_OPTICALFLOW_DECLARE_SRV(FFX_OPTICALFLOW_BIND_SRV_INPUT_COLOR);
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_INPUT_MOTION_VECTORS
Texture2D<FfxFloat32x2> r_input_motion_vectors : FFX_OPTICALFLOW_DECLARE_SRV(FFX_OPTICALFLOW_BIND_SRV_INPUT_MOTION_VECTORS);
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_INPUT
Texture2D<FfxUInt32> r_optical_flow_input : FFX_OPTICALFLOW_DECLARE_SRV(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_INPUT);
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS_INPUT
Texture2D<FfxUInt32> r_optical_flow_previous_input : FFX_OPTICALFLOW_DECLARE_SRV(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS_INPUT);
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW
Texture2D<FfxInt32x2> r_optical_flow : FFX_OPTICALFLOW_DECLARE_SRV(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW);
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS
Texture2D<FfxInt32x2> r_optical_flow_previous : FFX_OPTICALFLOW_DECLARE_SRV(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS);
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO
Texture2D<FfxUInt32x2> r_optical_flow_additional_info : FFX_OPTICALFLOW_DECLARE_SRV(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO);
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO_PREVIOUS
Texture2D<FfxUInt32x2> r_optical_flow_additional_info_previous : FFX_OPTICALFLOW_DECLARE_SRV(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO_PREVIOUS);
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_HISTOGRAM
Texture2D<FfxUInt32> r_optical_flow_histogram : FFX_OPTICALFLOW_DECLARE_SRV(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_HISTOGRAM);
#endif
#if defined FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH
Texture2D<FfxUInt32> r_optical_flow_global_motion_search : FFX_OPTICALFLOW_DECLARE_SRV(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH);
#endif
// UAV declarations
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT
RWTexture2D<FfxUInt32> rw_optical_flow_input : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_1
globallycoherent RWTexture2D<FfxUInt32> rw_optical_flow_input_level_1 : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_1);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_2
globallycoherent RWTexture2D<FfxUInt32> rw_optical_flow_input_level_2 : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_2);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_3
globallycoherent RWTexture2D<FfxUInt32> rw_optical_flow_input_level_3 : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_3);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_4
globallycoherent RWTexture2D<FfxUInt32> rw_optical_flow_input_level_4 : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_4);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_5
globallycoherent RWTexture2D<FfxUInt32> rw_optical_flow_input_level_5 : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_5);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_6
globallycoherent RWTexture2D<FfxUInt32> rw_optical_flow_input_level_6 : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_6);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW
RWTexture2D<FfxInt32x2> rw_optical_flow : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_NEXT_LEVEL
RWTexture2D<FfxInt32x2> rw_optical_flow_next_level : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_NEXT_LEVEL);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO
RWTexture2D<FfxUInt32x2> rw_optical_flow_additional_info : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO_NEXT_LEVEL
RWTexture2D<FfxUInt32x2> rw_optical_flow_additional_info_next_level : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO_NEXT_LEVEL);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_HISTOGRAM
RWTexture2D<FfxUInt32> rw_optical_flow_histogram : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_HISTOGRAM);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH
globallycoherent RWTexture2D<FfxUInt32> rw_optical_flow_global_motion_search: FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM
RWTexture2D<FfxUInt32> rw_optical_flow_scd_histogram : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM
RWTexture2D<FfxFloat32> rw_optical_flow_scd_previous_histogram : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_TEMP
RWTexture2D<FfxUInt32> rw_optical_flow_scd_temp : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_TEMP);
#endif
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT
RWTexture2D<FfxUInt32> rw_optical_flow_scd_output : FFX_OPTICALFLOW_DECLARE_UAV(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT);
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_INPUT_COLOR)
FfxFloat32x4 LoadInputColor(FfxUInt32x2 iPxHistory)
{
return r_input_color[iPxHistory];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_INPUT_MOTION_VECTORS)
FfxFloat32x2 LoadGameMotionVector(FfxInt32x2 iPxPos)
{
FfxFloat32x2 positionScale = FfxFloat32x2(RenderSize()) / DisplaySize();
return r_input_motion_vectors[iPxPos * positionScale] * motionVectorScale / positionScale;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT)
void StoreOpticalFlowInput(FfxInt32x2 iPxPos, FfxUInt32 fLuma)
{
rw_optical_flow_input[iPxPos] = fLuma;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_INPUT)
FfxUInt32 LoadOpticalFlowInput(FfxInt32x2 iPxPos)
{
#if FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION == 1
return max(1, r_optical_flow_input[iPxPos]);
#else
return r_optical_flow_input[iPxPos];
#endif
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT)
FfxUInt32 LoadRwOpticalFlowInput(FfxInt32x2 iPxPos)
{
return rw_optical_flow_input[iPxPos];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS_INPUT)
FfxUInt32 LoadOpticalFlowPreviousInput(FfxInt32x2 iPxPos)
{
#if FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION == 1
return max(1, r_optical_flow_previous_input[iPxPos]);
#else
return r_optical_flow_previous_input[iPxPos];
#endif
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW)
FfxInt32x2 LoadOpticalFlow(FfxInt32x2 iPxPos)
{
return r_optical_flow[iPxPos];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW)
FfxInt32x2 LoadRwOpticalFlow(FfxInt32x2 iPxPos)
{
return rw_optical_flow[iPxPos];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS)
FfxInt32x2 LoadPreviousOpticalFlow(FfxInt32x2 iPxPos)
{
return r_optical_flow_previous[iPxPos];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW)
void StoreOpticalFlow(FfxInt32x2 iPxPos, FfxInt32x2 motionVector)
{
rw_optical_flow[iPxPos] = motionVector;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_NEXT_LEVEL)
void StoreOpticalFlowNextLevel(FfxInt32x2 iPxPos, FfxInt32x2 motionVector)
{
rw_optical_flow_next_level[iPxPos] = motionVector;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO)
FfxUInt32x2 LoadOpticalFlowAdditionalInfo(FfxInt32x2 iPxPos)
{
return r_optical_flow_additional_info[iPxPos];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO)
FfxUInt32x2 LoadRwOpticalFlowAdditionalInfo(FfxInt32x2 iPxPos)
{
return rw_optical_flow_additional_info[iPxPos];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_ADDITIONAL_INFO_PREVIOUS)
FfxUInt32x2 LoadPreviousOpticalFlowAdditionalInfo(FfxInt32x2 iPxPos)
{
return r_optical_flow_additional_info_previous[iPxPos];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO)
void StoreOpticalFlowAdditionalInfo(FfxInt32x2 iPxPos, FfxUInt32x2 additionalInfo)
{
rw_optical_flow_additional_info[iPxPos] = additionalInfo;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_ADDITIONAL_INFO_NEXT_LEVEL)
void StoreOpticalFlowNextLevelAdditionalInfo(FfxInt32x2 iPxPos, FfxUInt32x2 additionalInfo)
{
rw_optical_flow_additional_info_next_level[iPxPos] = additionalInfo;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_HISTOGRAM)
FfxUInt32 LoadOpticalFlowHistogram(FfxInt32x2 iBucketId)
{
return r_optical_flow_histogram[iBucketId];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_HISTOGRAM)
void AtomicIncrementOpticalFlowHistogram(FfxInt32x2 iBucketId)
{
InterlockedAdd(rw_optical_flow_histogram[iBucketId], 1);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH)
FfxInt32x2 LoadGlobalMotionVector()
{
FfxInt32 vx = FfxInt32(r_optical_flow_global_motion_search[FfxInt32x2(0, 0)]);
FfxInt32 vy = FfxInt32(r_optical_flow_global_motion_search[FfxInt32x2(1, 0)]);
return FfxInt32x2(vx, vy);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH)
FfxInt32x2 LoadRwGlobalMotionVector()
{
FfxInt32 vx = FfxInt32(rw_optical_flow_global_motion_search[FfxInt32x2(0, 0)]);
FfxInt32 vy = FfxInt32(rw_optical_flow_global_motion_search[FfxInt32x2(1, 0)]);
return FfxInt32x2(vx, vy);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH)
FfxUInt32 LoadGlobalMotionValue(FfxInt32 index)
{
return rw_optical_flow_global_motion_search[FfxInt32x2(index, 0)];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH)
void StoreGlobalMotionValue(FfxInt32 index, FfxUInt32 value)
{
rw_optical_flow_global_motion_search[FfxInt32x2(index, 0)] = value;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_GLOBAL_MOTION_SEARCH)
FfxUInt32 AtomicIncrementGlobalMotionValue(FfxInt32 index)
{
FfxUInt32 initialValue;
InterlockedAdd(rw_optical_flow_global_motion_search[FfxInt32x2(index, 0)], 1, initialValue);
return initialValue;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM)
FfxUInt32 LoadRwSCDHistogram(FfxInt32 iIndex)
{
return rw_optical_flow_scd_histogram[FfxInt32x2(iIndex, 0)];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM)
void StoreSCDHistogram(FfxInt32 iIndex, FfxUInt32 value)
{
rw_optical_flow_scd_histogram[FfxInt32x2(iIndex, 0)] = value;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM)
void AtomicIncrementSCDHistogram(FfxInt32 iIndex, FfxUInt32 valueToAdd)
{
InterlockedAdd(rw_optical_flow_scd_histogram[FfxInt32x2(iIndex, 0)], valueToAdd);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM)
FfxFloat32 LoadRwSCDPreviousHistogram(FfxInt32 iIndex)
{
return rw_optical_flow_scd_previous_histogram[FfxInt32x2(iIndex, 0)];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM)
void StoreSCDPreviousHistogram(FfxInt32 iIndex, FfxFloat32 value)
{
rw_optical_flow_scd_previous_histogram[FfxInt32x2(iIndex, 0)] = value;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_TEMP)
FfxUInt32 LoadRwSCDTemp(FfxInt32 iIndex)
{
return rw_optical_flow_scd_temp[FfxInt32x2(iIndex, 0)];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_TEMP)
void AtomicIncrementSCDTemp(FfxInt32 iIndex, FfxUInt32 valueToAdd)
{
InterlockedAdd(rw_optical_flow_scd_temp[FfxInt32x2(iIndex, 0)], valueToAdd);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_TEMP)
void ResetSCDTemp()
{
rw_optical_flow_scd_temp[FfxInt32x2(0, 0)] = 0;
rw_optical_flow_scd_temp[FfxInt32x2(1, 0)] = 0;
rw_optical_flow_scd_temp[FfxInt32x2(2, 0)] = 0;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT)
FfxUInt32 LoadRwSCDOutput(FfxInt32 iIndex)
{
return rw_optical_flow_scd_output[FfxInt32x2(iIndex, 0)];
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT)
void StoreSCDOutput(FfxInt32 iIndex, FfxUInt32 value)
{
rw_optical_flow_scd_output[FfxInt32x2(iIndex, 0)] = value;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT)
FfxUInt32 AtomicIncrementSCDOutput(FfxInt32 iIndex, FfxUInt32 valueToAdd)
{
FfxUInt32 initialValue;
InterlockedAdd(rw_optical_flow_scd_output[FfxInt32x2(iIndex, 0)], valueToAdd, initialValue);
return initialValue;
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_DEBUG_VISUALIZATION)
void StoreDebugVisualization(FfxUInt32x2 iPxPos, FfxFloat32x3 fColor)
{
rw_debug_visualization[iPxPos] = FfxFloat32x4(fColor, 1.f);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT)
FfxFloat32 GetSceneChangeValue()
{
if (FrameIndex() <= 5)
return 1.0;
else
return ffxAsFloat(LoadRwSCDOutput(SCD_OUTPUT_SCENE_CHANGE_SLOT));
}
FfxBoolean IsSceneChanged()
{
if (FrameIndex() <= 5)
{
return 1.0;
}
else
{
return (LoadRwSCDOutput(SCD_OUTPUT_HISTORY_BITS_SLOT) & 0xfu) != 0;
}
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_INPUT)
FfxUInt32 LoadFirstImagePackedLuma(FfxInt32x2 iPxPos)
{
const FfxInt32 lumaTextureWidth = DisplaySize().x >> OpticalFlowPyramidLevel();
const FfxInt32 lumaTextureHeight = DisplaySize().y >> OpticalFlowPyramidLevel();
FfxInt32x2 adjustedPos = FfxInt32x2(
ffxClamp(iPxPos.x, 0, lumaTextureWidth - 4),
ffxClamp(iPxPos.y, 0, lumaTextureHeight - 1)
);
FfxUInt32 luma0 = LoadOpticalFlowInput(adjustedPos + FfxInt32x2(0, 0));
FfxUInt32 luma1 = LoadOpticalFlowInput(adjustedPos + FfxInt32x2(1, 0));
FfxUInt32 luma2 = LoadOpticalFlowInput(adjustedPos + FfxInt32x2(2, 0));
FfxUInt32 luma3 = LoadOpticalFlowInput(adjustedPos + FfxInt32x2(3, 0));
return GetPackedLuma(lumaTextureWidth, iPxPos.x, luma0, luma1, luma2, luma3);
}
#endif
#if defined(FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS_INPUT)
FfxUInt32 LoadSecondImagePackedLuma(FfxInt32x2 iPxPos)
{
const FfxInt32 lumaTextureWidth = DisplaySize().x >> OpticalFlowPyramidLevel();
const FfxInt32 lumaTextureHeight = DisplaySize().y >> OpticalFlowPyramidLevel();
FfxInt32x2 adjustedPos = FfxInt32x2(
ffxClamp(iPxPos.x, 0, lumaTextureWidth - 4),
ffxClamp(iPxPos.y, 0, lumaTextureHeight - 1)
);
FfxUInt32 luma0 = LoadOpticalFlowPreviousInput(adjustedPos + FfxInt32x2(0, 0));
FfxUInt32 luma1 = LoadOpticalFlowPreviousInput(adjustedPos + FfxInt32x2(1, 0));
FfxUInt32 luma2 = LoadOpticalFlowPreviousInput(adjustedPos + FfxInt32x2(2, 0));
FfxUInt32 luma3 = LoadOpticalFlowPreviousInput(adjustedPos + FfxInt32x2(3, 0));
return GetPackedLuma(lumaTextureWidth, iPxPos.x, luma0, luma1, luma2, luma3);
}
#endif
void SPD_SetMipmap(int2 iPxPos, int index, float value)
{
switch (index)
{
case 0:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_1
rw_optical_flow_input_level_1[iPxPos] = value;
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_1
break;
case 1:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_2
rw_optical_flow_input_level_2[iPxPos] = value;
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_2
break;
case 2:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_3
rw_optical_flow_input_level_3[iPxPos] = value;
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_3
break;
case 3:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_4
rw_optical_flow_input_level_4[iPxPos] = value;
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_4
break;
case 4:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_5
rw_optical_flow_input_level_5[iPxPos] = value;
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_5
break;
case 5:
#if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_6
rw_optical_flow_input_level_6[iPxPos] = value;
#endif // #if defined FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_6
break;
}
}
#endif // #if defined(FFX_GPU)
#endif // FFX_OPTICALFLOW_CALLBACKS_HLSL_H
@@ -0,0 +1,99 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#if !defined(FFX_OPTICALFLOW_COMMON_H)
#define FFX_OPTICALFLOW_COMMON_H
#if defined(FFX_GPU)
#define SCD_OUTPUT_SCENE_CHANGE_SLOT 0
#define SCD_OUTPUT_HISTORY_BITS_SLOT 1
#define SCD_OUTPUT_COMPLETED_WORKGROUPS_SLOT 2
#define ffxClamp(x, a, b) (ffxMax(a, ffxMin(b, x)))
FfxUInt32 GetPackedLuma(FfxInt32 width, FfxInt32 x, FfxUInt32 luma0, FfxUInt32 luma1, FfxUInt32 luma2, FfxUInt32 luma3)
{
FfxUInt32 packedLuma = luma0 | (luma1 << 8) | (luma2 << 16) | (luma3 << 24);
if (x < 0)
{
FfxUInt32 outOfScreenFiller = packedLuma & 0xffu;
if (x <= -1)
packedLuma = (packedLuma << 8) | outOfScreenFiller;
if (x <= -2)
packedLuma = (packedLuma << 8) | outOfScreenFiller;
if (x <= -3)
packedLuma = (packedLuma << 8) | outOfScreenFiller;
}
else if (x > width - 4)
{
FfxUInt32 outOfScreenFiller = packedLuma & 0xff000000u;
if (x >= width - 3)
packedLuma = (packedLuma >> 8) | outOfScreenFiller;
if (x >= width - 2)
packedLuma = (packedLuma >> 8) | outOfScreenFiller;
if (x >= width - 1)
packedLuma = (packedLuma >> 8) | outOfScreenFiller;
}
return packedLuma;
}
FfxUInt32 Sad(FfxUInt32 a, FfxUInt32 b)
{
#if FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION == 1
return msad4(a, FfxUInt32x2(b, 0), FfxUInt32x4(0, 0, 0, 0)).x;
#else
return abs(FfxInt32((a >> 0) & 0xffu) - FfxInt32((b >> 0) & 0xffu)) +
abs(FfxInt32((a >> 8) & 0xffu) - FfxInt32((b >> 8) & 0xffu)) +
abs(FfxInt32((a >> 16) & 0xffu) - FfxInt32((b >> 16) & 0xffu)) +
abs(FfxInt32((a >> 24) & 0xffu) - FfxInt32((b >> 24) & 0xffu));
#endif
}
FfxUInt32x4 QSad(FfxUInt32 a0, FfxUInt32 a1, FfxUInt32 b)
{
#if FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION == 1
return msad4(b, FfxUInt32x2(a0, a1), FfxUInt32x4(0, 0, 0, 0));
#else
FfxUInt32x4 sad;
sad.x = Sad(a0, b);
a0 = (a0 >> 8) | ((a1 & 0xffu) << 24);
a1 >>= 8;
sad.y = Sad(a0, b);
a0 = (a0 >> 8) | ((a1 & 0xffu) << 24);
a1 >>= 8;
sad.z = Sad(a0, b);
a0 = (a0 >> 8) | ((a1 & 0xffu) << 24);
sad.w = Sad(a0, b);
return sad;
#endif
}
#endif // #if defined(FFX_GPU)
#endif //!defined(FFX_OPTICALFLOW_COMMON_H)
@@ -0,0 +1,107 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_OPTICALFLOW_COMPUTE_LUMINANCE_PYRAMID_H
#define FFX_OPTICALFLOW_COMPUTE_LUMINANCE_PYRAMID_H
FFX_GROUPSHARED FfxFloat32 spdIntermediateR[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateG[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateB[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateA[16][16];
void SPD_IncreaseAtomicCounter(inout FfxUInt32 spdCounter)
{
}
void SPD_ResetAtomicCounter()
{
}
FfxFloat32x4 SpdLoadSourceImage(FfxFloat32x2 tex, FfxUInt32 slice)
{
FfxFloat32 luma = LoadRwOpticalFlowInput(FfxInt32x2(tex));
return FfxFloat32x4(luma, 0, 0, 0);
}
FfxFloat32x4 SpdLoad(FfxInt32x2 tex, FfxUInt32 slice)
{
return FfxFloat32x4(0, 0, 0, 0);
}
void SpdStore(FfxInt32x2 pix, FfxFloat32x4 outValue, FfxUInt32 index, FfxUInt32 slice)
{
SPD_SetMipmap(pix, index, outValue.r);
}
void SpdIncreaseAtomicCounter(FfxUInt32 slice)
{
}
FfxUInt32 SpdGetAtomicCounter()
{
return 0;
}
void SpdResetAtomicCounter(FfxUInt32 slice)
{
SPD_ResetAtomicCounter();
}
FfxFloat32x4 SpdLoadIntermediate(FfxUInt32 x, FfxUInt32 y)
{
return FfxFloat32x4(
spdIntermediateR[x][y],
spdIntermediateG[x][y],
spdIntermediateB[x][y],
spdIntermediateA[x][y]);
}
void SpdStoreIntermediate(FfxUInt32 x, FfxUInt32 y, FfxFloat32x4 value)
{
spdIntermediateR[x][y] = value.x;
spdIntermediateG[x][y] = value.y;
spdIntermediateB[x][y] = value.z;
spdIntermediateA[x][y] = value.w;
}
FfxFloat32x4 SpdReduce4(FfxFloat32x4 v0, FfxFloat32x4 v1, FfxFloat32x4 v2, FfxFloat32x4 v3)
{
return (v0 + v1 + v2 + v3) * 0.25;
}
#ifdef FFX_HALF
#undef FFX_HALF
#endif
// https://github.com/GPUOpen-Effects/FidelityFX-SPD/blob/master/docs/FidelityFX_SPD.pdf
#include "spd/ffx_spd.h"
void ComputeOpticalFlowInputPyramid(FfxInt32x2 iGroupId, FfxInt32 iLocalIndex)
{
SpdDownsample(
FfxUInt32x2(iGroupId.xy),
FfxUInt32(iLocalIndex),
6, // mip levels to generate
FfxUInt32(NumWorkGroups()),
1 // single slice
);
}
#endif // FFX_OPTICALFLOW_COMPUTE_LUMINANCE_PYRAMID_H
@@ -0,0 +1,279 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_OPTICALFLOW_COMPUTE_OPTICAL_FLOW_V5_H
#define FFX_OPTICALFLOW_COMPUTE_OPTICAL_FLOW_V5_H
#define CompareSize (4 * 2)
#define BlockSizeY 8
#define BlockSizeX 8
#define ThreadCount (4 * 16)
#define SearchRadiusX (8)
#define SearchRadiusY (8)
#define BlockCount 2
#define SearchBufferSizeX ((CompareSize + SearchRadiusX*2)/4)
#define SearchBufferSizeY (CompareSize + SearchRadiusY*2)
FFX_GROUPSHARED FfxUInt32 pixels[CompareSize][CompareSize / 4];
FFX_GROUPSHARED FfxUInt32 searchBuffer[1][SearchBufferSizeY * SearchBufferSizeX];
#define bankBreaker 1
FFX_GROUPSHARED FfxUInt32 sadMapBuffer[4][SearchRadiusY * 2][(SearchRadiusX * 2) / 4 + bankBreaker];
#define MaxWaves 2
FFX_GROUPSHARED FfxUInt32 sWaveSad[MaxWaves];
FFX_GROUPSHARED FfxUInt32 sWaveMin[MaxWaves];
FfxUInt32 BlockSad64(FfxUInt32 blockSadSum, FfxInt32 iLocalIndex, FfxInt32 iLaneToBlockId, FfxInt32 block)
{
if (iLaneToBlockId != block)
{
blockSadSum = 0u;
}
blockSadSum = ffxWaveSum(blockSadSum);
if (ffxWaveLaneCount() == 32)
{
FfxInt32 waveId = iLocalIndex >> 5u;
if (ffxWaveIsFirstLane())
{
sWaveSad[waveId] = blockSadSum;
}
FFX_GROUP_MEMORY_BARRIER;
blockSadSum += sWaveSad[waveId ^ 1];
}
return blockSadSum;
}
FfxUInt32 SadMapMinReduction256(FfxInt32x2 iSearchId, FfxInt32 iLocalIndex)
{
FfxUInt32 min01 = ffxMin(sadMapBuffer[0][iSearchId.y][iSearchId.x], sadMapBuffer[1][iSearchId.y][iSearchId.x]);
FfxUInt32 min23 = ffxMin(sadMapBuffer[2][iSearchId.y][iSearchId.x], sadMapBuffer[3][iSearchId.y][iSearchId.x]);
FfxUInt32 min0123 = ffxMin(min01, min23);
min0123 = ffxWaveMin(min0123);
if (ffxWaveLaneCount() == 32)
{
FfxInt32 waveId = iLocalIndex >> 5u;
if (ffxWaveIsFirstLane())
{
sWaveMin[waveId] = min0123;
}
FFX_GROUP_MEMORY_BARRIER;
min0123 = ffxMin(min0123, sWaveMin[waveId ^ 1]);
}
return min0123;
}
void LoadSearchBuffer(FfxInt32 iLocalIndex, FfxInt32x2 iPxPosShifted)
{
FfxInt32 baseX = (iPxPosShifted.x - SearchRadiusX);
FfxInt32 baseY = (iPxPosShifted.y - SearchRadiusY);
for (FfxInt32 id = iLocalIndex; id < SearchBufferSizeX * SearchBufferSizeY; id += ThreadCount)
{
FfxInt32 idx = id % SearchBufferSizeX;
FfxInt32 idy = id / SearchBufferSizeX;
FfxInt32 x = baseX + idx * 4;
FfxInt32 y = baseY + idy;
searchBuffer[0][id] = LoadSecondImagePackedLuma(FfxInt32x2(x, y));
}
FFX_GROUP_MEMORY_BARRIER;
}
FfxUInt32x4 CalculateQSads2(FfxInt32x2 iSearchId)
{
FfxUInt32x4 sad = ffxBroadcast4(0u);
#if FFX_OPTICALFLOW_USE_MSAD4_INSTRUCTION == 1
FfxInt32 idx = iSearchId.y * 6 + iSearchId.x;
sad = msad4(pixels[0][0], FfxUInt32x2(searchBuffer[0][idx], searchBuffer[0][idx + 1]), sad);
sad = msad4(pixels[0][1], FfxUInt32x2(searchBuffer[0][idx + 1], searchBuffer[0][idx + 2]), sad);
idx += 6;
sad = msad4(pixels[1][0], FfxUInt32x2(searchBuffer[0][idx], searchBuffer[0][idx + 1]), sad);
sad = msad4(pixels[1][1], FfxUInt32x2(searchBuffer[0][idx + 1], searchBuffer[0][idx + 2]), sad);
idx += 6;
sad = msad4(pixels[2][0], FfxUInt32x2(searchBuffer[0][idx], searchBuffer[0][idx + 1]), sad);
sad = msad4(pixels[2][1], FfxUInt32x2(searchBuffer[0][idx + 1], searchBuffer[0][idx + 2]), sad);
idx += 6;
sad = msad4(pixels[3][0], FfxUInt32x2(searchBuffer[0][idx], searchBuffer[0][idx + 1]), sad);
sad = msad4(pixels[3][1], FfxUInt32x2(searchBuffer[0][idx + 1], searchBuffer[0][idx + 2]), sad);
idx += 6;
sad = msad4(pixels[4][0], FfxUInt32x2(searchBuffer[0][idx], searchBuffer[0][idx + 1]), sad);
sad = msad4(pixels[4][1], FfxUInt32x2(searchBuffer[0][idx + 1], searchBuffer[0][idx + 2]), sad);
idx += 6;
sad = msad4(pixels[5][0], FfxUInt32x2(searchBuffer[0][idx], searchBuffer[0][idx + 1]), sad);
sad = msad4(pixels[5][1], FfxUInt32x2(searchBuffer[0][idx + 1], searchBuffer[0][idx + 2]), sad);
idx += 6;
sad = msad4(pixels[6][0], FfxUInt32x2(searchBuffer[0][idx], searchBuffer[0][idx + 1]), sad);
sad = msad4(pixels[6][1], FfxUInt32x2(searchBuffer[0][idx + 1], searchBuffer[0][idx + 2]), sad);
idx += 6;
sad = msad4(pixels[7][0], FfxUInt32x2(searchBuffer[0][idx], searchBuffer[0][idx + 1]), sad);
sad = msad4(pixels[7][1], FfxUInt32x2(searchBuffer[0][idx + 1], searchBuffer[0][idx + 2]), sad);
#else
for (FfxInt32 dy = 0; dy < CompareSize; dy++)
{
FfxInt32 rowOffset = (iSearchId.y + dy) * SearchBufferSizeX;
FfxUInt32 a0 = searchBuffer[0][rowOffset + iSearchId.x];
FfxUInt32 a1 = searchBuffer[0][rowOffset + iSearchId.x + 1];
FfxUInt32 a2 = searchBuffer[0][rowOffset + iSearchId.x + 2];
sad += QSad(a0, a1, pixels[dy][0]);
sad += QSad(a1, a2, pixels[dy][1]);
}
#endif
return sad;
}
FfxUInt32x2 abs_2(FfxInt32x2 val)
{
FfxInt32x2 tmp = val;
FfxInt32x2 mask = tmp >> 31;
FfxUInt32x2 res = (tmp + mask) ^ mask;
return res;
}
FfxUInt32 EncodeSearchCoord(FfxInt32x2 coord)
{
#if FFX_OPTICALFLOW_FIX_TOP_LEFT_BIAS == 1
FfxUInt32x2 absCoord = FfxUInt32x2(abs_2(coord - 8));
return FfxUInt32(absCoord.y << 12) | FfxUInt32(absCoord.x << 8) | FfxUInt32(coord.y << 4) | FfxUInt32(coord.x);
#else //FFX_OPTICALFLOW_FIX_TOP_LEFT_BIAS == 1
return FfxUInt32(coord.y << 8) | FfxUInt32(coord.x);
#endif //FFX_OPTICALFLOW_FIX_TOP_LEFT_BIAS == 1
}
FfxInt32x2 DecodeSearchCoord(FfxUInt32 bits)
{
#if FFX_OPTICALFLOW_FIX_TOP_LEFT_BIAS == 1
FfxInt32 dx = FfxInt32(bits & 0xfu) - SearchRadiusX;
FfxInt32 dy = FfxInt32((bits >> 4) & 0xfu) - SearchRadiusY;
return FfxInt32x2(dx, dy);
#else
FfxInt32 dx = FfxInt32(bits & 0xffu) - SearchRadiusX;
FfxInt32 dy = FfxInt32((bits >> 8) & 0xffu) - SearchRadiusY;
return FfxInt32x2(dx, dy);
#endif
}
void PrepareSadMap(FfxInt32x2 iSearchId, FfxUInt32x4 qsad)
{
sadMapBuffer[0][iSearchId.y][iSearchId.x] = (qsad.x << 16) | EncodeSearchCoord(FfxInt32x2(iSearchId.x * 4 + 0, iSearchId.y));
sadMapBuffer[1][iSearchId.y][iSearchId.x] = (qsad.y << 16) | EncodeSearchCoord(FfxInt32x2(iSearchId.x * 4 + 1, iSearchId.y));
sadMapBuffer[2][iSearchId.y][iSearchId.x] = (qsad.z << 16) | EncodeSearchCoord(FfxInt32x2(iSearchId.x * 4 + 2, iSearchId.y));
sadMapBuffer[3][iSearchId.y][iSearchId.x] = (qsad.w << 16) | EncodeSearchCoord(FfxInt32x2(iSearchId.x * 4 + 3, iSearchId.y));
FFX_GROUP_MEMORY_BARRIER;
}
uint ABfe(uint src, uint off, uint bits) { uint mask = (1u << bits) - 1u; return (src >> off) & mask; }
uint ABfi(uint src, uint ins, uint mask) { return (ins & mask) | (src & (~mask)); }
uint ABfiM(uint src, uint ins, uint bits) { uint mask = (1u << bits) - 1u; return (ins & mask) | (src & (~mask)); }
void MapThreads(in FfxInt32x2 iGroupId, in FfxInt32 iLocalIndex,
out FfxInt32x2 iSearchId, out FfxInt32x2 iPxPos, out FfxInt32 iLaneToBlockId)
{
iSearchId = FfxInt32x2(ABfe(iLocalIndex, 0u, 2u), ABfe(iLocalIndex, 2u, 4u));
iLaneToBlockId = FfxInt32(ABfe(iLocalIndex, 1u, 1u) | (ABfe(iLocalIndex, 5u, 1u) << 1u));
iPxPos = (iGroupId << 4u) + iSearchId * FfxInt32x2(4, 1);
}
void ComputeOpticalFlowAdvanced(FfxInt32x2 iGlobalId, FfxInt32x2 iLocalId, FfxInt32x2 iGroupId, FfxInt32 iLocalIndex)
{
FfxInt32x2 iSearchId;
FfxInt32x2 iPxPos;
FfxInt32 iLaneToBlockId;
MapThreads(iGroupId, iLocalIndex, iSearchId, iPxPos, iLaneToBlockId);
FfxInt32x2 currentOFPos = iPxPos >> 3u;
if (IsSceneChanged())
{
if ((iSearchId.y & 0x7) == 0 && (iSearchId.x & 0x1) == 0)
{
StoreOpticalFlow(currentOFPos, FfxInt32x2(0, 0));
}
return;
}
const FfxBoolean bUsePredictionFromPreviousLevel = (OpticalFlowPyramidLevel() != OpticalFlowPyramidLevelCount() - 1);
FfxUInt32 packedLuma_4blocks = LoadFirstImagePackedLuma(iPxPos);
#if FFX_LOCAL_SEARCH_FALLBACK == 1
FfxUInt32 prevPackedLuma_4blocks = LoadSecondImagePackedLuma(iPxPos);
FfxUInt32 sad_4blocks = Sad(packedLuma_4blocks, prevPackedLuma_4blocks);
#endif //FFX_LOCAL_SEARCH_FALLBACK
FfxInt32x2 ofGroupOffset = iGroupId << 1u;
FfxInt32x2 pixelGroupOffset = iGroupId << 4u;
FfxInt32x2 blockId;
for (blockId.y = 0; blockId.y < BlockCount; blockId.y++)
{
for (blockId.x = 0; blockId.x < BlockCount; blockId.x++)
{
FfxInt32x2 currentVector = LoadRwOpticalFlow(ofGroupOffset + blockId);
if (!bUsePredictionFromPreviousLevel)
{
currentVector = FfxInt32x2(0, 0);
}
if (iLaneToBlockId == blockId.y * 2 + blockId.x)
{
pixels[iSearchId.y & 0x7][iSearchId.x & 0x1] = packedLuma_4blocks;
}
LoadSearchBuffer(iLocalIndex, pixelGroupOffset + blockId * 8 + currentVector);
FfxUInt32x4 qsad = CalculateQSads2(iSearchId);
PrepareSadMap(iSearchId, qsad);
FfxUInt32 minSad = SadMapMinReduction256(iSearchId, iLocalIndex);
FfxInt32x2 minSadCoord = DecodeSearchCoord(minSad);
FfxInt32x2 newVector = currentVector + minSadCoord;
#if FFX_LOCAL_SEARCH_FALLBACK == 1
FfxUInt32 blockSadSum = BlockSad64(sad_4blocks, iLocalIndex, iLaneToBlockId, blockId.x + blockId.y * 2);
if (OpticalFlowPyramidLevel() == 0 && blockSadSum <= (minSad >> 16u))
{
newVector = FfxInt32x2(0, 0);
}
#endif //FFX_LOCAL_SEARCH_FALLBACK
{
StoreOpticalFlow(ofGroupOffset + blockId, newVector);
}
}
}
}
#endif // FFX_OPTICALFLOW_COMPUTE_OPTICAL_FLOW_V5_H
@@ -0,0 +1,159 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_OPTICALFLOW_COMPUTE_SCD_DIVERGENCE_H
#define FFX_OPTICALFLOW_COMPUTE_SCD_DIVERGENCE_H
FFX_GROUPSHARED FfxFloat32 sourceHistogram[256];
FFX_GROUPSHARED FfxFloat32 filteredHistogram[256];
FFX_GROUPSHARED FfxFloat32 tempBuffer[256];
FFX_GROUPSHARED FfxFloat32x2 tempBuffer2[256];
void ComputeSCDHistogramsDivergence(FfxInt32x3 iGlobalId, FfxInt32x2 iLocalId, FfxInt32 iLocalIndex, FfxInt32x2 iGroupId, FfxInt32x2 iGroupSize)
{
FFX_STATIC const FfxFloat32 Factor = 1000000.0;
FFX_STATIC const FfxInt32 WhereToStop = 3*9 - 1;
FFX_STATIC const FfxInt32 HistogramCount = 3 * 3;
FFX_STATIC const FfxFloat32 Kernel[] = {
0.0088122291, 0.027143577, 0.065114059, 0.12164907, 0.17699835, 0.20056541
};
sourceHistogram[iLocalIndex] = FfxFloat32(LoadRwSCDHistogram(iGlobalId.x));
FFX_GROUP_MEMORY_BARRIER;
const FfxInt32 kernelShift = -5;
const FfxInt32 indexToRead = iLocalIndex + kernelShift;
FfxFloat32 val = 0.0;
val += Kernel[0] * sourceHistogram[ffxClamp(indexToRead + 0, 0, 255)];
val += Kernel[1] * sourceHistogram[ffxClamp(indexToRead + 1, 0, 255)];
val += Kernel[2] * sourceHistogram[ffxClamp(indexToRead + 2, 0, 255)];
val += Kernel[3] * sourceHistogram[ffxClamp(indexToRead + 3, 0, 255)];
val += Kernel[4] * sourceHistogram[ffxClamp(indexToRead + 4, 0, 255)];
val += Kernel[5] * sourceHistogram[ffxClamp(indexToRead + 5, 0, 255)];
val += Kernel[4] * sourceHistogram[ffxClamp(indexToRead + 6, 0, 255)];
val += Kernel[3] * sourceHistogram[ffxClamp(indexToRead + 7, 0, 255)];
val += Kernel[2] * sourceHistogram[ffxClamp(indexToRead + 8, 0, 255)];
val += Kernel[1] * sourceHistogram[ffxClamp(indexToRead + 9, 0, 255)];
val += Kernel[0] * sourceHistogram[ffxClamp(indexToRead + 10, 0, 255)];
val += 1.0;
if (iGlobalId.y == 0)
{
if (iLocalIndex == 0)
filteredHistogram[255] = 1.0;
else
filteredHistogram[iLocalIndex - 1] = val;
}
else if (iGlobalId.y == 1)
{
filteredHistogram[iLocalIndex] = val;
}
else if (iGlobalId.y == 2)
{
if (iLocalIndex == 255)
filteredHistogram[0] = 1.0;
else
filteredHistogram[iLocalIndex + 1] = val;
}
FFX_GROUP_MEMORY_BARRIER;
tempBuffer[iLocalIndex] = filteredHistogram[iLocalIndex];
FFX_GROUP_MEMORY_BARRIER;
if (iLocalIndex < 128) tempBuffer[iLocalIndex] += tempBuffer[iLocalIndex + 128];
FFX_GROUP_MEMORY_BARRIER;
if (iLocalIndex < 64) tempBuffer[iLocalIndex] += tempBuffer[iLocalIndex + 64];
FFX_GROUP_MEMORY_BARRIER;
if (iLocalIndex < 32) tempBuffer[iLocalIndex] += tempBuffer[iLocalIndex + 32];
if (iLocalIndex < 16) tempBuffer[iLocalIndex] += tempBuffer[iLocalIndex + 16];
if (iLocalIndex < 8 ) tempBuffer[iLocalIndex] += tempBuffer[iLocalIndex + 8];
if (iLocalIndex < 4 ) tempBuffer[iLocalIndex] += tempBuffer[iLocalIndex + 4];
if (iLocalIndex < 2 ) tempBuffer[iLocalIndex] += tempBuffer[iLocalIndex + 2];
if (iLocalIndex < 1 ) tempBuffer[iLocalIndex] += tempBuffer[iLocalIndex + 1];
FFX_GROUP_MEMORY_BARRIER;
filteredHistogram[iLocalIndex] /= tempBuffer[0];
FfxFloat32 currentFilteredHistogramsValue = filteredHistogram[iLocalIndex];
FfxFloat32 previousHistogramsValue = LoadRwSCDPreviousHistogram(iGlobalId.x);
tempBuffer2[iLocalIndex] = FfxFloat32x2(
currentFilteredHistogramsValue * log(currentFilteredHistogramsValue / previousHistogramsValue),
previousHistogramsValue * log(previousHistogramsValue / currentFilteredHistogramsValue)
);
FFX_GROUP_MEMORY_BARRIER;
if (iLocalIndex < 128) tempBuffer2[iLocalIndex] += tempBuffer2[iLocalIndex + 128];
FFX_GROUP_MEMORY_BARRIER;
if (iLocalIndex < 64) tempBuffer2[iLocalIndex] += tempBuffer2[iLocalIndex + 64];
FFX_GROUP_MEMORY_BARRIER;
if (iLocalIndex < 32) tempBuffer2[iLocalIndex] += tempBuffer2[iLocalIndex + 32];
if (iLocalIndex < 16) tempBuffer2[iLocalIndex] += tempBuffer2[iLocalIndex + 16];
if (iLocalIndex < 8 ) tempBuffer2[iLocalIndex] += tempBuffer2[iLocalIndex + 8];
if (iLocalIndex < 4 ) tempBuffer2[iLocalIndex] += tempBuffer2[iLocalIndex + 4];
if (iLocalIndex < 2 ) tempBuffer2[iLocalIndex] += tempBuffer2[iLocalIndex + 2];
if (iLocalIndex == 0)
{
FfxFloat32x2 sum = tempBuffer2[0] + tempBuffer2[1];
FfxFloat32 resFloat = 1 - exp(-(abs(sum.x) + abs(sum.y)));
FfxUInt32 resUInt = FfxUInt32((resFloat / FfxFloat32(HistogramCount)) * Factor);
AtomicIncrementSCDTemp(iGlobalId.y, resUInt);
FfxUInt32 oldFinishedGroupCount = AtomicIncrementSCDOutput(SCD_OUTPUT_COMPLETED_WORKGROUPS_SLOT, 1);
if (oldFinishedGroupCount == WhereToStop)
{
FfxUInt32 res0 = LoadRwSCDTemp(0);
FfxUInt32 res1 = LoadRwSCDTemp(1);
FfxUInt32 res2 = LoadRwSCDTemp(2);
FfxFloat32 sceneChangeValue = ffxMin(res0, ffxMin(res1, res2)) / Factor;
FfxUInt32 history = LoadRwSCDOutput(SCD_OUTPUT_HISTORY_BITS_SLOT) << 1;
if (CrossedSceneChangeThreshold(sceneChangeValue))
{
history |= 1;
}
StoreSCDOutput(SCD_OUTPUT_SCENE_CHANGE_SLOT, ffxAsUInt32(sceneChangeValue));
StoreSCDOutput(SCD_OUTPUT_HISTORY_BITS_SLOT, history);
StoreSCDOutput(SCD_OUTPUT_COMPLETED_WORKGROUPS_SLOT, 0);
ResetSCDTemp();
}
}
if (iGlobalId.y == 1)
{
StoreSCDPreviousHistogram(iGlobalId.x, currentFilteredHistogramsValue);
StoreSCDHistogram(iGlobalId.x, 0);
}
}
#endif // FFX_OPTICALFLOW_COMPUTE_SCD_DIVERGENCE_H
@@ -0,0 +1,58 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_OPTICALFLOW_FILTER_OPTICAL_FLOW_V5_H
#define FFX_OPTICALFLOW_FILTER_OPTICAL_FLOW_V5_H
void FilterOpticalFlow(FfxInt32x2 iGlobalId, FfxInt32x2 iLocalId, FfxInt32x2 iGroupId, FfxInt32 iLocalIndex)
{
FfxInt32x2 tmpMV[9];
FfxInt32 idx = 0;
for (FfxInt32 xx = -1; xx < 2; xx++)
{
for (FfxInt32 yy = -1; yy < 2; yy++)
{
tmpMV[idx] = LoadPreviousOpticalFlow(iGlobalId + FfxInt32x2(xx, yy));
idx++;
}
}
FfxUInt32 ret = 0xFFFFFFFF;
for (FfxInt32 i = 0; i < 9; ++i)
{
FfxUInt32 tmp = 0;
for (FfxInt32 j = 0; j < 9; ++j)
{
FfxInt32x2 delta = tmpMV[i] - tmpMV[j];
tmp = delta.x * delta.x + (delta.y * delta.y + tmp);
}
ret = min(((tmp) << 4) | i, ret);
}
FfxUInt32 minIdx = ret & 0xF;
StoreOpticalFlow(iGlobalId, tmpMV[minIdx]);
}
#endif // FFX_OPTICALFLOW_FILTER_OPTICAL_FLOW_V5_H
@@ -0,0 +1,92 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_OPTICALFLOW_GENERATE_SCD_HISTOGRAM_H
#define FFX_OPTICALFLOW_GENERATE_SCD_HISTOGRAM_H
#define LBASE 10
FFX_GROUPSHARED FfxUInt32 scdBuffer[256 * LBASE];
void GenerateSceneChangeDetectionHistogram(FfxInt32x3 iGlobalId, FfxInt32x2 iLocalId, FfxInt32 iLocalIndex, FfxInt32x2 iGroupId, FfxInt32x2 iGroupSize)
{
FFX_STATIC const FfxUInt32 HistogramsPerDim = 3;
FfxUInt32 divX = DisplaySize().x / HistogramsPerDim;
FfxUInt32 divY = DisplaySize().y / HistogramsPerDim;
FfxUInt32 nx = iGlobalId.z % HistogramsPerDim;
FfxUInt32 ny = iGlobalId.z / HistogramsPerDim;
FfxUInt32 startX = divX * nx;
FfxUInt32 startY = divY * ny;
FfxUInt32 stopX = startX + divX;
FfxUInt32 stopY = startY + divY;
const FfxUInt32 bufferOffset = iLocalIndex * LBASE;
for (FfxInt32 i = 0; i < LBASE; i++)
{
scdBuffer[bufferOffset + i] = 0;
}
FFX_GROUP_MEMORY_BARRIER;
FfxInt32x2 coord = FfxInt32x2(startX + (4 * iGlobalId.x), startY + iGlobalId.y);
if (coord.x < stopX)
{
for (; coord.y < stopY; coord.y += 128)
{
FfxUInt32x4 color = FfxUInt32x4(
LoadOpticalFlowInput(coord + FfxInt32x2(0, 0)),
LoadOpticalFlowInput(coord + FfxInt32x2(1, 0)),
LoadOpticalFlowInput(coord + FfxInt32x2(2, 0)),
LoadOpticalFlowInput(coord + FfxInt32x2(3, 0))
);
color *= LBASE;
FfxUInt32 scramblingOffset = iLocalIndex % LBASE;
#if defined(FFX_HLSL)
InterlockedAdd(scdBuffer[color.x + scramblingOffset], 1);
InterlockedAdd(scdBuffer[color.y + scramblingOffset], 1);
InterlockedAdd(scdBuffer[color.z + scramblingOffset], 1);
InterlockedAdd(scdBuffer[color.w + scramblingOffset], 1);
#elif defined(FFX_GLSL)
atomicAdd(scdBuffer[color.x + scramblingOffset], 1);
atomicAdd(scdBuffer[color.y + scramblingOffset], 1);
atomicAdd(scdBuffer[color.z + scramblingOffset], 1);
atomicAdd(scdBuffer[color.w + scramblingOffset], 1);
#endif
}
}
FFX_GROUP_MEMORY_BARRIER;
FfxUInt32 value = 0;
for (FfxInt32 i = 0; i < LBASE; i++)
{
value += scdBuffer[bufferOffset + i];
}
FfxUInt32 histogramStart = (iGroupSize.x * iGroupSize.y) * iGlobalId.z;
AtomicIncrementSCDHistogram(FfxInt32(histogramStart + iLocalIndex), value);
}
#endif // FFX_OPTICALFLOW_GENERATE_SCD_HISTOGRAM_H
@@ -0,0 +1,106 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_OPTICALFLOW_PREPARE_LUMA_H
#define FFX_OPTICALFLOW_PREPARE_LUMA_H
FfxFloat32 LuminanceToPerceivedLuminance(FfxFloat32 fLuminance)
{
FfxFloat32 fPercievedLuminance = 0;
if (fLuminance <= 216.0f / 24389.0f) {
fPercievedLuminance = fLuminance * (24389.0f / 27.0f);
}
else {
fPercievedLuminance = ffxPow(fLuminance, 1.0f / 3.0f) * 116.0f - 16.0f;
}
return fPercievedLuminance * 0.01f;
}
FfxFloat32 LinearLdrToLuminance(FfxFloat32x3 linearRec709RGB)
{
FfxFloat32 fY = 0.2126 * linearRec709RGB.x + 0.7152 * linearRec709RGB.y + 0.0722 * linearRec709RGB.z;
return fY;
}
FfxFloat32 LinearRec2020ToLuminance(FfxFloat32x3 linearRec2020RGB)
{
FfxFloat32 fY = 0.2627 * linearRec2020RGB.x + 0.678 * linearRec2020RGB.y + 0.0593 * linearRec2020RGB.z;
return fY;
}
FfxFloat32 PQCorrectedHdrToLuminance(FfxFloat32x3 pq, FfxFloat32 maxLuminance)
{
FfxFloat32 fY = LinearRec2020ToLuminance(ffxLinearFromPQ(pq) * (10000.0f / maxLuminance));
return fY;
}
FfxFloat32x3 ffxscRGBToLinear(FfxFloat32x3 value, FfxFloat32 minLuminance, FfxFloat32 maxLuminance)
{
FfxFloat32x3 p = value - ffxBroadcast3(minLuminance / 80.0f);
return p / ffxBroadcast3((maxLuminance - minLuminance) / 80.0f);
}
FfxFloat32 SCRGBCorrectedHdrToLuminance(FfxFloat32x3 scRGB, FfxFloat32 minLuminance, FfxFloat32 maxLuminance)
{
FfxFloat32 fY = LinearLdrToLuminance(ffxscRGBToLinear(scRGB, minLuminance, maxLuminance));
return fY;
}
void PrepareLuma(FfxInt32x2 iGlobalId, FfxInt32 iLocalIndex)
{
#define PixelsPerThreadX 2
#define PixelsPerThreadY 2
#pragma unroll
for (FfxInt32 y = 0; y < PixelsPerThreadY; y++)
{
#pragma unroll
for (FfxInt32 x = 0; x < PixelsPerThreadX; x++)
{
FfxInt32x2 pos = iGlobalId * FfxInt32x2(PixelsPerThreadX, PixelsPerThreadY) + FfxInt32x2(x, y);
FfxInt32x2 iPxHrPos = pos;
FfxFloat32 fY = 0.0;
FfxFloat32x3 inputColor = LoadInputColor(iPxHrPos).rgb;
FfxUInt32 backbufferTransferFunction = BackbufferTransferFunction();
if (backbufferTransferFunction == 0)
{
fY = LinearLdrToLuminance(inputColor);
}
else if (backbufferTransferFunction == 1)
{
fY = PQCorrectedHdrToLuminance(inputColor, MinMaxLuminance()[1]);
fY = LuminanceToPerceivedLuminance(fY);
}
else if (backbufferTransferFunction == 2)
{
fY = SCRGBCorrectedHdrToLuminance(inputColor, MinMaxLuminance()[0], MinMaxLuminance()[1]);
fY = LuminanceToPerceivedLuminance(fY);
}
StoreOpticalFlowInput(pos, FfxUInt32(fY * 255));
}
}
}
#endif // FFX_OPTICALFLOW_PREPARE_LUMA_H
@@ -0,0 +1,74 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_OPTICALFLOW_RESOURCES_H
#define FFX_OPTICALFLOW_RESOURCES_H
#if defined(FFX_CPU) || defined(FFX_GPU)
#define FFX_OF_RESOURCE_IDENTIFIER_NULL 0
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1 1
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_1 2
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_2 3
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_3 4
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_4 5
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_5 6
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_6 7
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2 8
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_1 9
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_2 10
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_3 11
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_4 12
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_5 13
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_6 14
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1 15
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_1 16
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_2 17
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_3 18
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_4 19
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_5 20
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_6 21
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2 22
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_1 23
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_2 24
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_3 25
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_4 26
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_5 27
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_6 28
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_HISTOGRAM 29
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM 30
#define FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_TEMP 31
#define FFX_OF_RESOURCE_IDENTIFIER_COUNT 32
#define FFX_OPTICALFLOW_CONSTANTBUFFER_IDENTIFIER 0
#define FFX_OPTICALFLOW_CONSTANTBUFFER_IDENTIFIER_SPD 1
#define FFX_OPTICALFLOW_CONSTANTBUFFER_COUNT 2
#endif // #if defined(FFX_CPU) || defined(FFX_GPU)
#endif //!defined( FFX_OPTICALFLOW_RESOURCES_H )
@@ -0,0 +1,99 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_OPTICALFLOW_SCALE_OPTICAL_FLOW_ADVANCED_V5_H
#define FFX_OPTICALFLOW_SCALE_OPTICAL_FLOW_ADVANCED_V5_H
#define WG_WIDTH FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#define WG_HEIGHT FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#define WG_DEPTH FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
FFX_GROUPSHARED FfxInt32x2 nearestVectors[4][WG_HEIGHT][WG_WIDTH];
FFX_GROUPSHARED FfxUInt32 localRegion[4][WG_HEIGHT][WG_WIDTH];
FFX_GROUPSHARED FfxUInt32 sads[4][WG_HEIGHT][WG_WIDTH];
void ScaleOpticalFlowAdvanced(FfxInt32x3 iGlobalId, FfxInt32x3 iLocalId)
{
if (IsSceneChanged())
{
StoreOpticalFlowNextLevel(iGlobalId.xy, FfxInt32x2(0, 0));
return;
}
int xOffset = (iLocalId.z % 2) - 1 + iGlobalId.x % 2;
int yOffset = (iLocalId.z / 2) - 1 + iGlobalId.y % 2;
FfxInt32x2 srcOFPos = FfxInt32x2(
(iGlobalId.x / 2) + xOffset,
(iGlobalId.y / 2) + yOffset
);
FfxInt32x2 nearestVector = LoadOpticalFlow(srcOFPos);
nearestVectors[iLocalId.z][iLocalId.y][iLocalId.x] = nearestVector * 2;
int maxY = 4;
for (int n = iLocalId.z; n < maxY; n += WG_DEPTH)
{
{
FfxInt32x2 lumaPos = FfxInt32x2((iGlobalId.x) * 4, iGlobalId.y * maxY + n);
FfxUInt32 firstPixel = LoadFirstImagePackedLuma(lumaPos);
localRegion[n][iLocalId.y][iLocalId.x] = firstPixel;
}
}
FFX_GROUP_MEMORY_BARRIER;
uint sad = 0;
for (int n = 0; n < maxY; n++)
{
{
FfxInt32x2 lumaPos = FfxInt32x2((iGlobalId.x) * 4, (iGlobalId.y * maxY + n)) + nearestVector;
FfxUInt32 secondPixel = LoadSecondImagePackedLuma(lumaPos);
sad += Sad(localRegion[n][iLocalId.y][iLocalId.x], secondPixel);
}
}
sads[iLocalId.z][iLocalId.y][iLocalId.x] = sad;
FFX_GROUP_MEMORY_BARRIER;
{
if (iLocalId.z == 0)
{
uint bestSad = 0xffffffff;
uint bestId = 0;
for (int n = 0; n < 4; n++)
{
if ((sads[n][iLocalId.y][iLocalId.x]) < bestSad)
{
bestSad = sads[n][iLocalId.y][iLocalId.x];
bestId = n;
}
}
FfxInt32x2 outputVector = nearestVectors[bestId][iLocalId.y][iLocalId.x];
StoreOpticalFlowNextLevel(iGlobalId.xy, outputVector);
}
}
}
#endif // FFX_OPTICALFLOW_SCALE_OPTICAL_FLOW_ADVANCED_V5_H
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,181 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#include "ffx_spd_resources.h"
#if defined(FFX_GPU)
#include "ffx_core.h"
#ifndef FFX_PREFER_WAVE64
#define FFX_PREFER_WAVE64
#endif // #ifndef FFX_PREFER_WAVE64
#if defined(FFX_SPD_BIND_CB_SPD)
layout (set = 0, binding = FFX_SPD_BIND_CB_SPD, std140) uniform cbFSR1_t
{
FfxUInt32 mips;
FfxUInt32 numWorkGroups;
FfxUInt32x2 workGroupOffset;
FfxFloat32x2 invInputSize; // Only used for linear sampling mode
FfxFloat32x2 padding;
} cbFSR1;
#endif
FfxUInt32 Mips()
{
return cbFSR1.mips;
}
FfxUInt32 NumWorkGroups()
{
return cbFSR1.numWorkGroups;
}
FfxUInt32x2 WorkGroupOffset()
{
return cbFSR1.workGroupOffset;
}
FfxFloat32x2 InvInputSize()
{
return cbFSR1.invInputSize;
}
layout (set = 0, binding = 1000) uniform sampler s_LinearClamp;
// SRVs
#if defined FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC
layout (set = 0, binding = FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC) uniform texture2DArray r_input_downsample_src;
#endif
// UAV declarations
#if defined FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC
layout (set = 0, binding = FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC, std430) coherent buffer rw_internal_global_atomic_t
{
FfxUInt32 counter[6];
} rw_internal_global_atomic;
#endif
#if defined FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP
layout (set = 0, binding = FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP, rgba32f) coherent uniform image2DArray rw_input_downsample_src_mid_mip;
#endif
#if defined FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS
layout (set = 0, binding = FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS, rgba32f) uniform image2DArray rw_input_downsample_src_mips[SPD_MAX_MIP_LEVELS+1];
#endif
#if FFX_HALF
#if defined(FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC)
FfxFloat16x4 SampleSrcImageH(FfxFloat32x2 uv, FfxUInt32 slice)
{
FfxFloat32x2 textureCoord = FfxFloat32x2(uv) * InvInputSize() + InvInputSize();
FfxFloat32x4 result = textureLod(sampler2DArray(r_input_downsample_src, s_LinearClamp), FfxFloat32x3(textureCoord, slice), 0);
return FfxFloat16x4(ffxSrgbFromLinear(result.x), ffxSrgbFromLinear(result.y), ffxSrgbFromLinear(result.z), result.w);
}
#endif // defined(FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
FfxFloat16x4 LoadSrcImageH(FfxFloat32x2 uv, FfxUInt32 slice)
{
return FfxFloat16x4(imageLoad(rw_input_downsample_src_mips[0], FfxInt32x3(uv, slice)));
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
void StoreSrcMipH(FfxFloat16x4 value, FfxInt32x2 uv, FfxUInt32 slice, FfxUInt32 mip)
{
imageStore(rw_input_downsample_src_mips[mip], FfxInt32x3(uv, slice), FfxFloat32x4(value));
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
FfxFloat16x4 LoadMidMipH(FfxInt32x2 uv, FfxUInt32 slice)
{
return FfxFloat16x4(imageLoad(rw_input_downsample_src_mid_mip, FfxInt32x3(uv, slice)));
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
void StoreMidMipH(FfxFloat16x4 value, FfxInt32x2 uv, FfxUInt32 slice)
{
imageStore(rw_input_downsample_src_mid_mip, FfxInt32x3(uv, slice), FfxFloat32x4(value));\
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
#else // FFX_HALF
#if defined(FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC)
FfxFloat32x4 SampleSrcImage(FfxInt32x2 uv, FfxUInt32 slice)
{
FfxFloat32x2 textureCoord = FfxFloat32x2(uv) * InvInputSize() + InvInputSize();
FfxFloat32x4 result = textureLod(sampler2DArray(r_input_downsample_src, s_LinearClamp), FfxFloat32x3(textureCoord, slice), 0);
return FfxFloat32x4(ffxSrgbFromLinear(result.x), ffxSrgbFromLinear(result.y), ffxSrgbFromLinear(result.z), result.w);
}
#endif // defined(FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
FfxFloat32x4 LoadSrcImage(FfxInt32x2 uv, FfxUInt32 slice)
{
return imageLoad(rw_input_downsample_src_mips[0], FfxInt32x3(uv, slice));
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
void StoreSrcMip(FfxFloat32x4 value, FfxInt32x2 uv, FfxUInt32 slice, FfxUInt32 mip)
{
imageStore(rw_input_downsample_src_mips[mip], FfxInt32x3(uv, slice), value);
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
FfxFloat32x4 LoadMidMip(FfxInt32x2 uv, FfxUInt32 slice)
{
return imageLoad(rw_input_downsample_src_mid_mip, FfxInt32x3(uv, slice));
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
void StoreMidMip(FfxFloat32x4 value, FfxInt32x2 uv, FfxUInt32 slice)
{
imageStore(rw_input_downsample_src_mid_mip, FfxInt32x3(uv, slice), value);
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
#endif // FFX_HALF
#if defined(FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC)
void IncreaseAtomicCounter(FFX_PARAMETER_IN FfxUInt32 slice, FFX_PARAMETER_INOUT FfxUInt32 counter)
{
counter = atomicAdd(rw_internal_global_atomic.counter[slice], 1);
}
#endif // defined(FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC)
#if defined(FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC)
void ResetAtomicCounter(FFX_PARAMETER_IN FfxUInt32 slice)
{
rw_internal_global_atomic.counter[slice] = 0;
}
#endif // defined(FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC)
#endif // #if defined(FFX_GPU)
@@ -0,0 +1,218 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#include "ffx_spd_resources.h"
#if defined(FFX_GPU)
#ifdef __hlsl_dx_compiler
#pragma dxc diagnostic push
#pragma dxc diagnostic ignored "-Wambig-lit-shift"
#endif //__hlsl_dx_compiler
#include "ffx_core.h"
#ifdef __hlsl_dx_compiler
#pragma dxc diagnostic pop
#endif //__hlsl_dx_compiler
#ifndef FFX_PREFER_WAVE64
#define FFX_PREFER_WAVE64
#endif // #ifndef FFX_PREFER_WAVE64
#pragma warning(disable: 3205) // conversion from larger type to smaller
#define FFX_DECLARE_SRV_REGISTER(regIndex) t##regIndex
#define FFX_DECLARE_UAV_REGISTER(regIndex) u##regIndex
#define FFX_DECLARE_CB_REGISTER(regIndex) b##regIndex
#define FFX_SPD_DECLARE_SRV(regIndex) register(FFX_DECLARE_SRV_REGISTER(regIndex))
#define FFX_SPD_DECLARE_UAV(regIndex) register(FFX_DECLARE_UAV_REGISTER(regIndex))
#define FFX_SPD_DECLARE_CB(regIndex) register(FFX_DECLARE_CB_REGISTER(regIndex))
#if defined(FFX_SPD_BIND_CB_SPD)
cbuffer cbSPD : FFX_SPD_DECLARE_CB(FFX_SPD_BIND_CB_SPD)
{
FfxUInt32 mips;
FfxUInt32 numWorkGroups;
FfxUInt32x2 workGroupOffset;
FfxFloat32x2 invInputSize; // Only used for linear sampling mode
FfxFloat32x2 padding;
#define FFX_SPD_CONSTANT_BUFFER_1_SIZE 8 // Number of 32-bit values. This must be kept in sync with the cbSPD size.
};
#else
#define mips 0
#define numWorkGroups 0
#define workGroupOffset 0
#define invInputSize 0
#define padding 0
#endif
#define FFX_SPD_ROOTSIG_STRINGIFY(p) FFX_SPD_ROOTSIG_STR(p)
#define FFX_SPD_ROOTSIG_STR(p) #p
#define FFX_SPD_ROOTSIG [RootSignature( "DescriptorTable(UAV(u0, numDescriptors = " FFX_SPD_ROOTSIG_STRINGIFY(FFX_SPD_RESOURCE_IDENTIFIER_COUNT) ")), " \
"DescriptorTable(SRV(t0, numDescriptors = " FFX_SPD_ROOTSIG_STRINGIFY(FFX_SPD_RESOURCE_IDENTIFIER_COUNT) ")), " \
"CBV(b0), " \
"StaticSampler(s0, filter = FILTER_MIN_MAG_LINEAR_MIP_POINT, " \
"addressU = TEXTURE_ADDRESS_CLAMP, " \
"addressV = TEXTURE_ADDRESS_CLAMP, " \
"addressW = TEXTURE_ADDRESS_CLAMP, " \
"comparisonFunc = COMPARISON_NEVER, " \
"borderColor = STATIC_BORDER_COLOR_TRANSPARENT_BLACK)" )]
#if defined(FFX_SPD_EMBED_ROOTSIG)
#define FFX_SPD_EMBED_ROOTSIG_CONTENT FFX_SPD_ROOTSIG
#else
#define FFX_SPD_EMBED_ROOTSIG_CONTENT
#endif // #if FFX_SPD_EMBED_ROOTSIG
FfxUInt32 Mips()
{
return mips;
}
FfxUInt32 NumWorkGroups()
{
return numWorkGroups;
}
FfxUInt32x2 WorkGroupOffset()
{
return workGroupOffset;
}
FfxFloat32x2 InvInputSize()
{
return invInputSize;
}
SamplerState s_LinearClamp : register(s0);
// SRVs
#if defined(FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC)
Texture2DArray<FfxFloat32x4> r_input_downsample_src : FFX_SPD_DECLARE_SRV(FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC);
#endif
// UAV declarations
#if defined(FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC)
struct SpdGlobalAtomicBuffer { FfxUInt32 counter[6]; };
globallycoherent RWStructuredBuffer<SpdGlobalAtomicBuffer> rw_internal_global_atomic : FFX_SPD_DECLARE_UAV(FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC);
#endif
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
globallycoherent RWTexture2DArray<FfxFloat32x4> rw_input_downsample_src_mid_mip : FFX_SPD_DECLARE_UAV(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP);
#endif
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
RWTexture2DArray<FfxFloat32x4> rw_input_downsample_src_mips[SPD_MAX_MIP_LEVELS+1] : FFX_SPD_DECLARE_UAV(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS);
#endif
#if FFX_HALF
#if defined(FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC)
FfxFloat16x4 SampleSrcImageH(FfxFloat32x2 uv, FfxUInt32 slice)
{
FfxFloat32x2 textureCoord = FfxFloat32x2(uv) * InvInputSize() + InvInputSize();
FfxFloat32x4 result = r_input_downsample_src.SampleLevel(s_LinearClamp, FfxFloat32x3(textureCoord, slice), 0);
return FfxFloat16x4(ffxSrgbFromLinear(result.x), ffxSrgbFromLinear(result.y), ffxSrgbFromLinear(result.z), result.w);
}
#endif // defined(FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
FfxFloat16x4 LoadSrcImageH(FfxFloat32x2 uv, FfxUInt32 slice)
{
return FfxFloat16x4(rw_input_downsample_src_mips[0][FfxUInt32x3(uv, slice)]);
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
void StoreSrcMipH(FfxFloat16x4 value, FfxInt32x2 uv, FfxUInt32 slice, FfxUInt32 mip)
{
rw_input_downsample_src_mips[mip][FfxUInt32x3(uv, slice)] = FfxFloat32x4(value);
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
FfxFloat16x4 LoadMidMipH(FfxInt32x2 uv, FfxUInt32 slice)
{
return FfxFloat16x4(rw_input_downsample_src_mid_mip[FfxUInt32x3(uv, slice)]);
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
void StoreMidMipH(FfxFloat16x4 value, FfxInt32x2 uv, FfxUInt32 slice)
{
rw_input_downsample_src_mid_mip[FfxUInt32x3(uv, slice)] = FfxFloat32x4(value);
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
#else // FFX_HALF
#if defined(FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC)
FfxFloat32x4 SampleSrcImage(FfxInt32x2 uv, FfxUInt32 slice)
{
FfxFloat32x2 textureCoord = FfxFloat32x2(uv) * InvInputSize() + InvInputSize();
FfxFloat32x4 result = r_input_downsample_src.SampleLevel(s_LinearClamp, FfxFloat32x3(textureCoord, slice), 0);
return FfxFloat32x4(ffxSrgbFromLinear(result.x), ffxSrgbFromLinear(result.y), ffxSrgbFromLinear(result.z), result.w);
}
#endif // defined(FFX_SPD_BIND_SRV_INPUT_DOWNSAMPLE_SRC)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
FfxFloat32x4 LoadSrcImage(FfxInt32x2 uv, FfxUInt32 slice)
{
return rw_input_downsample_src_mips[0][FfxUInt32x3(uv, slice)];
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
void StoreSrcMip(FfxFloat32x4 value, FfxInt32x2 uv, FfxUInt32 slice, FfxUInt32 mip)
{
rw_input_downsample_src_mips[mip][FfxUInt32x3(uv, slice)] = value;
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MIPS)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
FfxFloat32x4 LoadMidMip(FfxInt32x2 uv, FfxUInt32 slice)
{
return rw_input_downsample_src_mid_mip[FfxUInt32x3(uv, slice)];
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
#if defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
void StoreMidMip(FfxFloat32x4 value, FfxInt32x2 uv, FfxUInt32 slice)
{
rw_input_downsample_src_mid_mip[FfxUInt32x3(uv, slice)] = value;
}
#endif // defined(FFX_SPD_BIND_UAV_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP)
#endif // FFX_HALF
#if defined(FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC)
void IncreaseAtomicCounter(FFX_PARAMETER_IN FfxUInt32 slice, FFX_PARAMETER_INOUT FfxUInt32 counter)
{
InterlockedAdd(rw_internal_global_atomic[0].counter[slice], 1, counter);
}
#endif // defined(FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC)
#if defined(FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC)
void ResetAtomicCounter(FFX_PARAMETER_IN FfxUInt32 slice)
{
rw_internal_global_atomic[0].counter[slice] = 0;
}
#endif // defined(FFX_SPD_BIND_UAV_INTERNAL_GLOBAL_ATOMIC)
#endif // #if defined(FFX_GPU)
@@ -0,0 +1,171 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#include "ffx_core.h"
#if FFX_HALF
#define FFX_SPD_PACKED_ONLY 1
#endif // FFX_HALF
#if FFX_SPD_OPTION_LINEAR_SAMPLE
#define SPD_LINEAR_SAMPLER 1
#endif // FFX_SPD_OPTION_LINEAR_SAMPLE
#if FFX_SPD_OPTION_WAVE_INTEROP_LDS
#define FFX_SPD_NO_WAVE_OPERATIONS 1
#endif // FFX_SPD_OPTION_WAVE_INTEROP_LDS
FFX_GROUPSHARED FfxUInt32 spdCounter;
void SpdIncreaseAtomicCounter(FfxUInt32 slice)
{
IncreaseAtomicCounter(slice, spdCounter);
}
FfxUInt32 SpdGetAtomicCounter()
{
return spdCounter;
}
void SpdResetAtomicCounter(FfxUInt32 slice)
{
ResetAtomicCounter(slice);
}
#if FFX_HALF
FFX_GROUPSHARED FfxFloat16x2 spdIntermediateRG[16][16];
FFX_GROUPSHARED FfxFloat16x2 spdIntermediateBA[16][16];
FfxFloat16x4 SpdLoadSourceImageH(FfxInt32x2 tex, FfxUInt32 slice)
{
#if defined SPD_LINEAR_SAMPLER
return SampleSrcImageH(tex, slice);
#else
return LoadSrcImageH(tex, slice);
#endif // SPD_LINEAR_SAMPLER
}
FfxFloat16x4 SpdLoadH(FfxInt32x2 p, FfxUInt32 slice)
{
return LoadMidMipH(p, slice);
}
void SpdStoreH(FfxInt32x2 pix, FfxFloat16x4 value, FfxUInt32 mip, FfxUInt32 slice)
{
if (mip == 5)
StoreMidMipH(value, pix, slice);
else
StoreSrcMipH(value, pix, slice, mip + 1);
}
FfxFloat16x4 SpdLoadIntermediateH(FfxUInt32 x, FfxUInt32 y)
{
return FfxFloat16x4(
spdIntermediateRG[x][y].x,
spdIntermediateRG[x][y].y,
spdIntermediateBA[x][y].x,
spdIntermediateBA[x][y].y);
}
void SpdStoreIntermediateH(FfxUInt32 x, FfxUInt32 y, FfxFloat16x4 value)
{
spdIntermediateRG[x][y] = value.xy;
spdIntermediateBA[x][y] = value.zw;
}
FfxFloat16x4 SpdReduce4H(FfxFloat16x4 v0, FfxFloat16x4 v1, FfxFloat16x4 v2, FfxFloat16x4 v3)
{
#if FFX_SPD_OPTION_DOWNSAMPLE_FILTER == 1
return min(min(v0, v1), min(v2, v3));
#elif FFX_SPD_OPTION_DOWNSAMPLE_FILTER == 2
return max(max(v0, v1), max(v2, v3));
#else
return (v0 + v1 + v2 + v3) * FfxFloat16(0.25);
#endif
}
#else
FFX_GROUPSHARED FfxFloat32 spdIntermediateR[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateG[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateB[16][16];
FFX_GROUPSHARED FfxFloat32 spdIntermediateA[16][16];
FfxFloat32x4 SpdLoadSourceImage(FfxInt32x2 tex, FfxUInt32 slice)
{
#if defined SPD_LINEAR_SAMPLER
return SampleSrcImage(tex, slice);
#else
return LoadSrcImage(tex, slice);
#endif // SPD_LINEAR_SAMPLER
}
FfxFloat32x4 SpdLoad(FfxInt32x2 tex, FfxUInt32 slice)
{
return LoadMidMip(tex, slice);
}
void SpdStore(FfxInt32x2 pix, FfxFloat32x4 outValue, FfxUInt32 mip, FfxUInt32 slice)
{
if (mip == 5)
StoreMidMip(outValue, pix, slice);
else
StoreSrcMip(outValue, pix, slice, mip + 1);
}
FfxFloat32x4 SpdLoadIntermediate(FfxUInt32 x, FfxUInt32 y)
{
return FfxFloat32x4(spdIntermediateR[x][y], spdIntermediateG[x][y], spdIntermediateB[x][y], spdIntermediateA[x][y]);
}
void SpdStoreIntermediate(FfxUInt32 x, FfxUInt32 y, FfxFloat32x4 value)
{
spdIntermediateR[x][y] = value.x;
spdIntermediateG[x][y] = value.y;
spdIntermediateB[x][y] = value.z;
spdIntermediateA[x][y] = value.w;
}
FfxFloat32x4 SpdReduce4(FfxFloat32x4 v0, FfxFloat32x4 v1, FfxFloat32x4 v2, FfxFloat32x4 v3)
{
#if FFX_SPD_OPTION_DOWNSAMPLE_FILTER == 1
return ffxMin(ffxMin(v0, v1), ffxMin(v2, v3));
#elif FFX_SPD_OPTION_DOWNSAMPLE_FILTER == 2
return ffxMax(ffxMax(v0, v1), ffxMax(v2, v3));
#else
return (v0 + v1 + v2 + v3) * 0.25;
#endif
}
#endif // FFX_HALF
#include "spd/ffx_spd.h"
void DOWNSAMPLE(FfxUInt32 LocalThreadId, FfxUInt32x3 WorkGroupId)
{
#if FFX_HALF
SpdDownsampleH(WorkGroupId.xy, LocalThreadId, Mips(), NumWorkGroups(), WorkGroupId.z, WorkGroupOffset());
#else
SpdDownsample(WorkGroupId.xy, LocalThreadId, Mips(), NumWorkGroups(), WorkGroupId.z, WorkGroupOffset());
#endif // FFX_HALF
}
@@ -0,0 +1,58 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#ifndef FFX_SPD_RESOURCES_H
#define FFX_SPD_RESOURCES_H
#if defined(FFX_CPU) || defined(FFX_GPU)
// Assumes a maximum on 12 mips. If larger base resolution support is added,
// extra mip resources need to also be added
#define SPD_MAX_MIP_LEVELS 12
#define FFX_SPD_RESOURCE_IDENTIFIER_NULL 0
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_GLOBAL_ATOMIC 1
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MID_MIPMAP 2
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC 3 // same as FFX_SPD_RESOURCE_DOWNSAMPLE_SRC_MIPMAP_0
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_0 3
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_1 4
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_2 5
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_3 6
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_4 7
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_5 8
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_6 9
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_7 10
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_8 11
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_9 12
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_10 13
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_11 14
#define FFX_SPD_RESOURCE_IDENTIFIER_INPUT_DOWNSAMPLE_SRC_MIPMAP_12 15
#define FFX_SPD_RESOURCE_IDENTIFIER_INTERNAL_GLOBAL_ATOMIC 16
#define FFX_SPD_RESOURCE_IDENTIFIER_COUNT 17
// CBV resource definitions
#define FFX_SPD_CONSTANTBUFFER_IDENTIFIER_SPD 0
#endif // #if defined(FFX_CPU) || defined(FFX_GPU)
#endif // FFX_SPD_RESOURCES_H
@@ -0,0 +1,370 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
/// @defgroup VKBackend Vulkan Backend
/// FidelityFX SDK native backend implementation for Vulkan.
///
/// @ingroup Backends
#pragma once
#include <vulkan/vulkan.h>
#include <FidelityFX/host/ffx_interface.h>
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// FFX specific callback type when submitting a command buffer to a queue.
typedef VkResult (*PFN_vkQueueSubmitFFX)(uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence);
typedef struct VkQueueInfoFFX
{
VkQueue queue;
uint32_t familyIndex;
PFN_vkQueueSubmitFFX submitFunc;
} VkQueueInfoFFX;
typedef enum VkCompositonModeFFX
{
VK_COMPOSITION_MODE_NOT_FORCED_FFX,
VK_COMPOSITION_MODE_GAME_QUEUE_FFX,
VK_COMPOSITION_MODE_PRESENT_QUEUE_FFX,
} VkCompositonModeFFX;
/// Structure holding additional information to effectively replace the game swapchain by the frame interpolation one.
/// Some notes on the queues:
/// - please pass the queue, its family (for queue family ownership transfer purposes) and an optional function if you want to control concurrent submissions
/// - game queue: the queue where the replacement of vkQueuePresentKHR is called. This queue should have Graphics and Compute capabilities (Transfer is implied as per Vulkan specification).
/// It can be shared with the engine. No Submit function is necessary.
/// The code assumes that the UI texture is owned by that queue family when present is called.
/// - async compute queue: optional queue with Compute capability (Transfer is implied as per Vulkan specification). If used by the engine, prefer not to enable the async compute path of FSR3 Frame interpolation.
/// - present queue: queue with Graphics, Compute or Transfer capability, and Present support. This queue cannot be used by the engine. Otherwise, some deadlock can occur.
/// - image acquire queue: this one doesn't need any capability. Strongly prefer a queue not used by the engine. The main graphics queue can work too but it might delay the signaling of the semaphore/fence when acquiring a new image, negatively impacting the performance.
typedef struct VkFrameInterpolationInfoFFX
{
VkPhysicalDevice physicalDevice;
VkDevice device;
VkQueueInfoFFX gameQueue;
VkQueueInfoFFX asyncComputeQueue;
VkQueueInfoFFX presentQueue;
VkQueueInfoFFX imageAcquireQueue;
VkCompositonModeFFX compositionMode;
const VkAllocationCallbacks* pAllocator;
} VkFrameInterpolationInfoFFX;
/// Query how much memory is required for the Vulkan backend's scratch buffer.
///
/// @param [in] physicalDevice A pointer to the VkPhysicalDevice device.
/// @param [in] maxContexts The maximum number of simultaneous effect contexts that will share the backend.
/// (Note that some effects contain internal contexts which count towards this maximum)
///
/// @returns
/// The size (in bytes) of the required scratch memory buffer for the VK backend.
///
/// @ingroup VKBackend
FFX_API size_t ffxGetScratchMemorySizeVK(VkPhysicalDevice physicalDevice, size_t maxContexts);
/// 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;
/// Create a <c><i>FfxDevice</i></c> from a <c><i>VkDevice</i></c>.
///
/// @param [in] vkDeviceContext A pointer to a VKDeviceContext that holds all needed information
///
/// @returns
/// An abstract FidelityFX device.
///
/// @ingroup VKBackend
FFX_API FfxDevice ffxGetDeviceVK(VkDeviceContext* vkDeviceContext);
/// Populate an interface with pointers for the VK backend.
///
/// @param [out] backendInterface A pointer to a <c><i>FfxInterface</i></c> structure to populate with pointers.
/// @param [in] device A pointer to the VkDevice device.
/// @param [in] scratchBuffer A pointer to a buffer of memory which can be used by the DirectX(R)12 backend.
/// @param [in] scratchBufferSize The size (in bytes) of the buffer pointed to by <c><i>scratchBuffer</i></c>.
/// @param [in] maxContexts The maximum number of simultaneous effect contexts that will share the backend.
/// (Note that some effects contain internal contexts which count towards this maximum)
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_INVALID_POINTER The <c><i>interface</i></c> pointer was <c><i>NULL</i></c>.
///
/// @ingroup VKBackend
FFX_API FfxErrorCode ffxGetInterfaceVK(
FfxInterface* backendInterface,
FfxDevice device,
void* scratchBuffer,
size_t scratchBufferSize,
size_t maxContexts);
/// Create a <c><i>FfxCommandList</i></c> from a <c><i>VkCommandBuffer</i></c>.
///
/// @param [in] cmdBuf A pointer to the Vulkan command buffer.
///
/// @returns
/// An abstract FidelityFX command list.
///
/// @ingroup VKBackend
FFX_API FfxCommandList ffxGetCommandListVK(VkCommandBuffer cmdBuf);
/// Create a <c><i>FfxPipeline</i></c> from a <c><i>VkPipeline</i></c>.
///
/// @param [in] pipeline A pointer to the Vulkan pipeline.
///
/// @returns
/// An abstract FidelityFX pipeline.
///
/// @ingroup VKBackend
FFX_API FfxPipeline ffxGetPipelineVK(VkPipeline pipeline);
/// Fetch a <c><i>FfxResource</i></c> from a <c><i>GPUResource</i></c>.
///
/// @param [in] vkResource A pointer to the (agnostic) VK resource.
/// @param [in] ffxResDescription An <c><i>FfxResourceDescription</i></c> for the resource representation.
/// @param [in] ffxResName (optional) A name string to identify the resource in debug mode.
/// @param [in] state The state the resource is currently in.
///
/// @returns
/// An abstract FidelityFX resources.
///
/// @ingroup VKBackend
FFX_API FfxResource ffxGetResourceVK(void* vkResource,
FfxResourceDescription ffxResDescription,
const wchar_t* ffxResName,
FfxResourceStates state = FFX_RESOURCE_STATE_COMPUTE_READ);
/// Fetch a <c><i>FfxSurfaceFormat</i></c> from a VkFormat.
///
/// @param [in] format The VkFormat to convert to <c><i>FfxSurfaceFormat</i></c>.
///
/// @returns
/// An <c><i>FfxSurfaceFormat</i></c>.
///
/// @ingroup VKBackend
FFX_API FfxSurfaceFormat ffxGetSurfaceFormatVK(VkFormat format);
/// Fetch a <c><i>FfxResourceDescription</i></c> from an existing VkBuffer.
///
/// @param [in] buffer The VkBuffer resource to create a <c><i>FfxResourceDescription</i></c> for.
/// @param [in] createInfo The VkBufferCreateInfo of the buffer
/// @param [in] additionalUsages Optional <c><i>FfxResourceUsage</i></c> flags needed for select resource mapping.
///
/// @returns
/// An <c><i>FfxResourceDescription</i></c>.
///
/// @ingroup VKBackend
FFX_API FfxResourceDescription ffxGetBufferResourceDescriptionVK(const VkBuffer buffer,
const VkBufferCreateInfo createInfo,
FfxResourceUsage additionalUsages = FFX_RESOURCE_USAGE_READ_ONLY);
/// Fetch a <c><i>FfxResourceDescription</i></c> from an existing VkImage.
///
/// @param [in] image The VkImage resource to create a <c><i>FfxResourceDescription</i></c> for.
/// @param [in] createInfo The VkImageCreateInfo of the buffer
/// @param [in] additionalUsages Optional <c><i>FfxResourceUsage</i></c> flags needed for select resource mapping.
///
/// @returns
/// An <c><i>FfxResourceDescription</i></c>.
///
/// @ingroup VKBackend
FFX_API FfxResourceDescription ffxGetImageResourceDescriptionVK(const VkImage image,
const VkImageCreateInfo createInfo,
FfxResourceUsage additionalUsages = FFX_RESOURCE_USAGE_READ_ONLY);
/// Fetch a <c><i>FfxCommandQueue</i></c> from an existing VkQueue.
///
/// @param [in] commandQueue The VkQueue to create a <c><i>FfxCommandQueue</i></c> from.
///
/// @returns
/// An <c><i>FfxCommandQueue</i></c>.
///
/// @ingroup VKBackend
FFX_API FfxCommandQueue ffxGetCommandQueueVK(VkQueue commandQueue);
/// Fetch a <c><i>FfxSwapchain</i></c> from an existing VkSwapchainKHR.
///
/// @param [in] pSwapchain The VkSwapchainKHR to create a <c><i>FfxSwapchain</i></c> from.
///
/// @returns
/// An <c><i>FfxSwapchain</i></c>.
///
/// @ingroup VKBackend
FFX_API FfxSwapchain ffxGetSwapchainVK(VkSwapchainKHR swapchain);
/// Fetch a VkSwapchainKHR from an existing <c><i>FfxSwapchain</i></c>.
///
/// @param [in] ffxSwapchain The <c><i>FfxSwapchain</i></c> to fetch an VkSwapchainKHR from.
///
/// @returns
/// An VkSwapchainKHR object.
///
/// @ingroup VKBackend
FFX_API VkSwapchainKHR ffxGetVKSwapchain(FfxSwapchain ffxSwapchain);
/// Replaces the current swapchain with the provided <c><i>FfxSwapchain</i></c>.
///
/// @param [in] gameQueue The <c><i>FfxCommandQueue</i></c> presentation will occur on.
/// @param [in,out] gameSwapChain The current <c><i>FfxSwapchain</i></c> to replace, optional. If not NULL, the swapchain will be destroyed. On return, it will hold the <c><i>FfxSwapchain</i></c> to use for frame interpolation presentation.
/// @param [in] swapchainCreateInfo The <c><i>VkSwapchainCreateInfoKHR</i></c> of the current swapchain. Its oldSwapchain member should be VK_NULL_HANDLE or the same as gameSwapChain.
/// @param [in] frameInterpolationInfo The <c><i>VkFrameInterpolationInfoFFX</i></c> containing additional information for swapchain replacement.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT One of the parameters is invalid. If the returned <c><i>gameSwapChain</i></c> is NULL, the old swapchain has been destroyed.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR Internal generic error. If the returned <c><i>gameSwapChain</i></c> is NULL, the old swapchain has been destroyed.
///
/// @ingroup VKFrameInterpolation
FFX_API FfxErrorCode ffxReplaceSwapchainForFrameinterpolationVK(FfxCommandQueue gameQueue,
FfxSwapchain& gameSwapChain,
const VkSwapchainCreateInfoKHR* swapchainCreateInfo,
const VkFrameInterpolationInfoFFX* frameInterpolationInfo);
/// Waits for the <c><i>FfxSwapchain</i></c> to complete presentation.
///
/// @param [in] gameSwapChain The <c><i>FfxSwapchain</i></c> to wait on.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT Could not query the interface for the frame interpolation swap chain.
///
/// @ingroup VKFrameInterpolation
FFX_API FfxErrorCode ffxWaitForPresents(FfxSwapchain gameSwapChain);
/// Registers a <c><i>FfxResource</i></c> to use for UI with the provided <c><i>FfxSwapchain</i></c>.
///
/// @param [in] gameSwapChain The <c><i>FfxSwapchain</i></c> to to register the UI resource with.
/// @param [in] uiResource The <c><i>FfxResource</i></c> representing the UI resource.
/// @param [in] flags A set of <c><i>FfxUiCompositionFlags</i></c>.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT Could not query the interface for the frame interpolation swap chain.
///
/// @ingroup VKFrameInterpolation
FFX_API FfxErrorCode ffxRegisterFrameinterpolationUiResourceVK(FfxSwapchain gameSwapChain, FfxResource uiResource, uint32_t flags);
/// Fetches a <c><i>FfxCommandList</i></c> from the <c><i>FfxSwapchain</i></c>.
///
/// @param [in] gameSwapChain The <c><i>FfxSwapchain</i></c> to get a <c><i>FfxCommandList</i></c> from.
/// @param [out] gameCommandlist The <c><i>FfxCommandList</i></c> from the provided <c><i>FfxSwapchain</i></c>.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT Could not query the interface for the frame interpolation swap chain.
///
/// @ingroup VKFrameInterpolation
FFX_API FfxErrorCode ffxGetFrameinterpolationCommandlistVK(FfxSwapchain gameSwapChain, FfxCommandList& gameCommandlist);
/// Fetches a <c><i>FfxResource</i></c> representing the backbuffer from the <c><i>FfxSwapchain</i></c>.
///
/// @param [in] gameSwapChain The <c><i>FfxSwapchain</i></c> to get a <c><i>FfxResource</i></c> backbuffer from.
///
/// @returns
/// An abstract FidelityFX resources for the swapchain backbuffer.
///
/// @ingroup VKFrameInterpolation
FFX_API FfxResource ffxGetFrameinterpolationTextureVK(FfxSwapchain gameSwapChain);
/// Sets a <c><i>FfxFrameGenerationConfig</i></c> to the internal FrameInterpolationSwapChain (in the backend).
///
/// @param [in] config The <c><i>FfxFrameGenerationConfig</i></c> to set.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT Could not query the interface for the frame interpolation swap chain.
///
/// @ingroup VKFrameInterpolation
FFX_API FfxErrorCode ffxSetFrameGenerationConfigToSwapchainVK(FfxFrameGenerationConfig const* config);
//enum values should match enum FfxApiConfigureFrameGenerationSwapChainKeyVK
typedef enum FfxFrameInterpolationSwapchainConfigureKey
{
FFX_FI_SWAPCHAIN_CONFIGURE_KEY_WAITCALLBACK = 0,
FFX_FI_SWAPCHAIN_CONFIGURE_KEY_FRAMEPACINGTUNING = 2,
} FfxFrameInterpolationSwapchainConfigureKey;
/// Configures <c><i>FfxSwapchain</i></c> via KeyValue API post <c><i>FfxSwapchain</i></c> context creation
///
/// @param [in] gameSwapChain The <c><i>FfxSwapchain</i></c> to configure via KeyValue API
/// @param [in] key The <c><i>FfxFrameInterpolationSwapchainConfigureKey</i></c> is key
/// @param [in] valuePtr The <c><i><void *></i></c> pointer to value. What this pointer deference to depends on key.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT Could not query the interface for the frame interpolation swap chain.
///
/// @ingroup VKFrameInterpolation
FFX_API FfxErrorCode ffxConfigureFrameInterpolationSwapchainVK(FfxSwapchain gameSwapChain, FfxFrameInterpolationSwapchainConfigureKey key, void* valuePtr);
/// Query how much GPU memory created by <c><i>FfxSwapchain</i></c>. This excludes GPU memory created by the VkSwapchain (ie. size of backbuffers).
///
/// @param [in] gameSwapChain The <c><i>FfxSwapchain</i></c> to configure via KeyValue API
/// @param [in out] vramUsage The <c><i>FfxEffectMemoryUsage</i></c> is the GPU memory created by FrameInterpolationSwapchain
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT Could not query the interface for the frame interpolation swap chain.
///
/// @ingroup VKFrameInterpolation
FFX_API FfxErrorCode ffxFrameInterpolationSwapchainGetGpuMemoryUsageVK(FfxSwapchain gameSwapChain, FfxEffectMemoryUsage* vramUsage);
typedef VkResult (*PFN_vkCreateSwapchainFFX)(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain, const VkFrameInterpolationInfoFFX* pFrameInterpolationInfo);
/// Function to get he number of presents. This is useful when using frame interpolation
typedef uint64_t (*PFN_getLastPresentCountFFX)(VkSwapchainKHR);
/// Structure holding the replacement function pointers for frame interpolation to work
/// Not all extensions are supported for now
/// Regarding specific functions:
/// - queuePresentKHR: when using this one, the presenting image should be in VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL state
/// - getLastPresentCount: this function isn't part of Vulkan but the engine can use it to get the real number of presented frames since the swapchain creation
struct FfxSwapchainReplacementFunctions
{
PFN_vkCreateSwapchainFFX createSwapchainFFX;
PFN_vkDestroySwapchainKHR destroySwapchainKHR;
PFN_vkGetSwapchainImagesKHR getSwapchainImagesKHR;
PFN_vkAcquireNextImageKHR acquireNextImageKHR;
PFN_vkQueuePresentKHR queuePresentKHR;
PFN_vkSetHdrMetadataEXT setHdrMetadataEXT;
PFN_getLastPresentCountFFX getLastPresentCountFFX;
};
FFX_API FfxErrorCode ffxGetSwapchainReplacementFunctionsVK(FfxDevice device, FfxSwapchainReplacementFunctions* functions);
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,151 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 <FidelityFX/host/ffx_types.h>
#include <FidelityFX/host/ffx_util.h>
#ifdef __cplusplus
extern "C" {
#endif // #ifdef __cplusplus
/// @defgroup Asserts Asserts
/// Asserts used by FidelityFX SDK functions
///
/// @ingroup ffxHost
#ifdef _DEBUG
#ifdef _WIN32
#ifdef DISABLE_FFX_DEBUG_BREAK
#define FFX_DEBUG_BREAK \
{ \
}
#else
/// Macro to force the debugger to break at this point in the code.
///
/// @ingroup Asserts
#define FFX_DEBUG_BREAK __debugbreak();
#endif
#else
#define FFX_DEBUG_BREAK \
{ \
}
#endif
#else
// don't allow debug break in release builds.
#define FFX_DEBUG_BREAK
#endif
/// A typedef for the callback function for assert printing.
///
/// This can be used to re-route printing of assert messages from the FFX backend
/// to another destination. For example instead of the default behaviour of printing
/// the assert messages to the debugger's TTY the message can be re-routed to a
/// MessageBox in a GUI application.
///
/// @param [in] message The message generated by the assert.
///
/// @ingroup Asserts
typedef void (*FfxAssertCallback)(const char* message);
/// Function to report an assert.
///
/// @param [in] file The name of the file as a string.
/// @param [in] line The index of the line in the file.
/// @param [in] condition The boolean condition that was tested.
/// @param [in] msg The optional message to print.
///
/// @returns
/// Always returns true.
///
/// @ingroup Asserts
FFX_API bool ffxAssertReport(const char* file, int32_t line, const char* condition, const char* msg);
/// Provides the ability to set a callback for assert messages.
///
/// @param [in] callback The callback function that will receive assert messages.
///
/// @ingroup Asserts
FFX_API void ffxAssertSetPrintingCallback(FfxAssertCallback callback);
#ifdef _DEBUG
/// Standard assert macro.
///
/// @ingroup Asserts
#define FFX_ASSERT(condition) \
do \
{ \
if (!(condition) && ffxAssertReport(__FILE__, __LINE__, #condition, NULL)) \
FFX_DEBUG_BREAK \
} while (0)
/// Assert macro with message.
///
/// @ingroup Asserts
#define FFX_ASSERT_MESSAGE(condition, msg) \
do \
{ \
if (!(condition) && ffxAssertReport(__FILE__, __LINE__, #condition, msg)) \
FFX_DEBUG_BREAK \
} while (0)
/// Assert macro that always fails.
///
/// @ingroup Asserts
#define FFX_ASSERT_FAIL(message) \
do \
{ \
ffxAssertReport(__FILE__, __LINE__, NULL, message); \
FFX_DEBUG_BREAK \
} while (0)
#else
// asserts disabled
#define FFX_ASSERT(condition) \
do \
{ \
FFX_UNUSED(condition); \
} while (0)
#define FFX_ASSERT_MESSAGE(condition, message) \
do \
{ \
FFX_UNUSED(condition); \
FFX_UNUSED(message); \
} while (0)
#define FFX_ASSERT_FAIL(message) \
do \
{ \
FFX_UNUSED(message); \
} while (0)
#endif // #if _DEBUG
/// Simple static assert.
///
/// @ingroup Asserts
#define FFX_STATIC_ASSERT(condition) static_assert(condition, #condition)
#ifdef __cplusplus
}
#endif // #ifdef __cplusplus
@@ -0,0 +1,200 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
/// @defgroup ffxBlur FidelityFX Blur
/// FidelityFX Blur runtime library
///
/// @ingroup SDKComponents
//------------------------------------------------------------------------------------------------------------------------------
//
// ABOUT
// =====
// AMD FidelityFX Blur is a collection of blurring effects implemented on compute shaders, hand-optimized for maximum performance.
// FFX-Blur includes
// - Gaussian Blur w/ large kernel support (up to 21x21)
//
//==============================================================================================================================
#pragma once
#include <FidelityFX/host/ffx_interface.h>
/// FidelityFX Blur major version.
///
/// @ingroup ffxBlur
#define FFX_BLUR_VERSION_MAJOR (1)
/// FidelityFX Blur minor version.
///
/// @ingroup ffxBlur
#define FFX_BLUR_VERSION_MINOR (1)
/// FidelityFX Blur patch version.
///
/// @ingroup ffxBlur
#define FFX_BLUR_VERSION_PATCH (0)
/// FidelityFX Blur context count
///
/// Defines the number of internal effect contexts required by Blur
///
/// @ingroup ffxBlur
#define FFX_BLUR_CONTEXT_COUNT 1
/// The size of the context specified in uint32_t units.
///
/// @ingroup ffxBlur
#define FFX_BLUR_CONTEXT_SIZE (1024)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// Enum to specify which blur pass (currently only one).
///
/// @ingroup ffxBlur
typedef enum FfxBlurPass
{
FFX_BLUR_PASS_BLUR = 0, ///< A pass which which blurs the input
FFX_BLUR_PASS_COUNT ///< The number of passes in the Blur effect
} FfxBlurPass;
/// Use this macro for FfxBlurContextDescription::kernelSizes to enable all kernel sizes.
///
/// @ingroup ffxBlur
#define FFX_BLUR_KERNEL_SIZE_ALL ((1 << FFX_BLUR_KERNEL_SIZE_COUNT) - 1)
typedef enum FfxBlurKernelPermutation
{
FFX_BLUR_KERNEL_PERMUTATION_0 = (1 << 0), ///< Sigma value of 1.6 used for generation of Gaussian kernel.
FFX_BLUR_KERNEL_PERMUTATION_1 = (1 << 1), ///< Sigma value of 2.8 used for generation of Gaussian kernel.
FFX_BLUR_KERNEL_PERMUTATION_2 = (1 << 2), ///< Sigma value of 4.0 used for generation of Gaussian kernel.
} FfxBlurKernelPermutation;
#define FFX_BLUR_KERNEL_PERMUTATION_COUNT 3
/// Use this macro for FfxBlurContextDescription::sigmaPermutations to enable all sigma permutations.
///
/// @ingroup ffxBlur
#define FFX_BLUR_KERNEL_PERMUTATIONS_ALL ((1 << FFX_BLUR_KERNEL_PERMUTATION_COUNT) - 1)
/// Enum to specify the size of the blur kernel. Use logical OR to enable multiple kernels
/// when setting the FfxBlurContextDescription::kernelSizes parameter prior to calling
/// ffxBlurContextCreate.
///
/// @ingroup ffxBlur
typedef enum FfxBlurKernelSize
{
FFX_BLUR_KERNEL_SIZE_3x3 = (1 << 0),
FFX_BLUR_KERNEL_SIZE_5x5 = (1 << 1),
FFX_BLUR_KERNEL_SIZE_7x7 = (1 << 2),
FFX_BLUR_KERNEL_SIZE_9x9 = (1 << 3),
FFX_BLUR_KERNEL_SIZE_11x11 = (1 << 4),
FFX_BLUR_KERNEL_SIZE_13x13 = (1 << 5),
FFX_BLUR_KERNEL_SIZE_15x15 = (1 << 6),
FFX_BLUR_KERNEL_SIZE_17x17 = (1 << 7),
FFX_BLUR_KERNEL_SIZE_19x19 = (1 << 8),
FFX_BLUR_KERNEL_SIZE_21x21 = (1 << 9)
} FfxBlurKernelSize;
#define FFX_BLUR_KERNEL_SIZE_COUNT 10
/// Enum to specify whether to initialize the FP32 or FP16 bit permutation of the blur shader(s).
/// Use this when setting the FfxBlurContextDescription::floatPrecision parameter prior to calling
/// ffxBlurContextCreate.
///
/// @ingroup ffxBlur
typedef enum FfxBlurFloatPrecision
{
FFX_BLUR_FLOAT_PRECISION_32BIT = 0,
FFX_BLUR_FLOAT_PRECISION_16BIT = 1,
FFX_BLUR_FLOAT_PRECISION_COUNT = 2
} FfxBlurFloatPrecision;
typedef uint32_t FfxBlurKernelPermutations;
typedef uint32_t FfxBlurKernelSizes;
/// FfxBlurContextDescription struct is used to create/initialize an FfxBlurContext.
///
/// @ingroup ffxBlur
typedef struct FfxBlurContextDescription
{
FfxBlurKernelPermutations kernelPermutations; ///< A bit mask of FfxBlurKernelPermutation values to indicate which kernels to enable for use.
FfxBlurKernelSizes kernelSizes; ///< A bit mask of FfxBlurKernelSize values to indicated which kernel sizes to enable for use.
FfxBlurFloatPrecision floatPrecision; ///< A flag indicating the desired floating point precision for use in ffxBlurContextDispatch
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX.
} FfxBlurContextDescription;
/// FfxBlurContext must be created via ffxBlurContextCreate to use the FFX Blur effect.
///
/// @ingroup ffxBlur
typedef struct FfxBlurContext
{
uint32_t data[FFX_BLUR_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxBlurContext;
/// Create and initialize the FfxBlurContext.
///
/// @param [out] pContext The FfxBlurContext to create and initialize.
/// @param [in] pContextDescription The initialization configuration parameters.
///
/// @ingroup ffxBlur
FFX_API FfxErrorCode ffxBlurContextCreate(FfxBlurContext* pContext, const FfxBlurContextDescription* pContextDescription);
/// Destroy and free resources associated with the FfxBlurContext.
///
/// @param [inout] pContext The FfxBlurContext to destroy.
///
/// @ingroup ffxBlur
FFX_API FfxErrorCode ffxBlurContextDestroy(FfxBlurContext* pContext);
/// FfxBlurDispatchDescription struct defines configuration of a blur dispatch (see ffxBlurContextDispatch).
///
/// @ingroup ffxBlur
typedef struct FfxBlurDispatchDescription
{
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record rendering commands into.
FfxBlurKernelPermutation kernelPermutation; ///< The permutation of the kernel (must be the one specified in FfxBlurContextDescription::kernelPermutations).
FfxBlurKernelSize kernelSize; ///< The kernel size to use for blurring (must be one specified in FfxBlurContextDescription::kernelSizes).
FfxDimensions2D inputAndOutputSize; ///< The width and height in pixels of the input and output resources.
FfxResource input; ///< The <c><i>FfxResource</i></c> to blur.
FfxResource output; ///< The <c><i>FfxResource</i></c> containing the output buffer for the blurred output.
} FfxBlurDispatchDescription;
/// Create and initialize the FfxBlurContext.
///
/// @param [in] pContext The FfxBlurContext to use for the dispatch.
/// @param [in] pDispatchDescription The dispatch configuration parameters (see FfxBlurDispatchDescription).
///
/// @ingroup ffxBlur
FFX_API FfxErrorCode ffxBlurContextDispatch(FfxBlurContext* pContext, const FfxBlurDispatchDescription* pDispatchDescription);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxBlur
FFX_API FfxVersionNumber ffxBlurGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus
@@ -0,0 +1,487 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
/// @defgroup ffxBreadcrumbs FidelityFX Breadcrumbs
/// FidelityFX Breadcrumbs runtime library
///
/// @ingroup SDKComponents
#pragma once
// Include the interface for the backend of the Breadcrumbs API.
#include <FidelityFX/host/ffx_interface.h>
/// FidelityFX Breadcrumbs major version.
///
/// @ingroup ffxBreadcrumbs
#define FFX_BREADCRUMBS_VERSION_MAJOR (1)
/// FidelityFX Breadcrumbs minor version.
///
/// @ingroup ffxBreadcrumbs
#define FFX_BREADCRUMBS_VERSION_MINOR (0)
/// FidelityFX Breadcrumbs patch version.
///
/// @ingroup ffxBreadcrumbs
#define FFX_BREADCRUMBS_VERSION_PATCH (1)
/// FidelityFX Breadcrumbs context count
///
/// Defines the number of internal effect contexts required by Breadcrumbs
///
/// @ingroup ffxBreadcrumbs
#define FFX_BREADCRUMBS_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup ffxBreadcrumbs
#define FFX_BREADCRUMBS_CONTEXT_SIZE (128)
/// Maximal number of markers that can be written into single memory block.
///
/// @ingroup ffxBreadcrumbs
#define FFX_BREADCRUMBS_MAX_MARKERS_PER_BLOCK ((1U << 31) - 1U)
/// List of marker types to be used in X() macro.
///
/// @ingroup ffxBreadcrumbs
#define FFX_BREADCRUMBS_MARKER_LIST \
X(BEGIN_EVENT) \
X(BEGIN_QUERY) \
X(CLEAR_DEPTH_STENCIL) \
X(CLEAR_RENDER_TARGET) \
X(CLEAR_STATE) \
X(CLEAR_UNORDERED_ACCESS_FLOAT) \
X(CLEAR_UNORDERED_ACCESS_UINT) \
X(CLOSE) \
X(COPY_BUFFER_REGION) \
X(COPY_RESOURCE) \
X(COPY_TEXTURE_REGION) \
X(COPY_TILES) \
X(DISCARD_RESOURCE) \
X(DISPATCH) \
X(DRAW_INDEXED_INSTANCED) \
X(DRAW_INSTANCED) \
X(END_EVENT) \
X(END_QUERY) \
X(EXECUTE_BUNDLE) \
X(EXECUTE_INDIRECT) \
X(RESET) \
X(RESOLVE_QUERY_DATA) \
X(RESOLVE_SUBRESOURCE) \
X(RESOURCE_BARRIER) \
X(SET_COMPUTE_ROOT_SIGNATURE) \
X(SET_DESCRIPTORS_HEAP) \
X(SET_GRAPHICS_ROOT_SIGNATURE) \
X(SET_PIPELINE_STATE) \
X(SET_PREDICATION) \
X(ATOMIC_COPY_BUFFER_UINT) \
X(ATOMIC_COPY_BUFFER_UINT64) \
X(RESOLVE_SUBRESOURCE_REGION) \
X(SET_SAMPLE_POSITION) \
X(SET_VIEW_INSTANCE_MASK) \
X(WRITE_BUFFER_IMMEDIATE) \
X(SET_PROTECTED_RESOURCE_SESSION) \
X(BEGIN_RENDER_PASS) \
X(BUILD_RAY_TRACING_ACCELERATION_STRUCTURE) \
X(COPY_RAY_TRACING_ACCELERATION_STRUCTURE) \
X(DISPATCH_RAYS) \
X(EMIT_RAY_TRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO) \
X(END_RENDER_PASS) \
X(EXECUTE_META_COMMANDS) \
X(INITIALIZE_META_COMMANDS) \
X(SET_RAY_TRACING_STATE) \
X(SET_SHADING_RATE) \
X(SET_SHADING_RATE_IMAGE) \
X(BEGIN_CONDITIONAL_RENDERING_EXT) \
X(BEGIN_DEBUG_UTILS_LABEL_EXT) \
X(BEGIN_QUERY_INDEXED_EXT) \
X(BEGIN_RENDER_PASS_2) \
X(BEGIN_TRANSFORM_FEEDBACK_EXT) \
X(BIND_DESCRIPTOR_SETS) \
X(BIND_PIPELINES) \
X(BIND_SHADING_RATE_IMAGE_NV) \
X(BLIT_IMAGE) \
X(BUILD_ACCELERATION_STRUCTURE_NV) \
X(CLEAR_ATTACHMENTS) \
X(CLEAR_COLOR_IMAGE) \
X(CLEAR_DEPTH_STENCIL_IMAGE) \
X(COPY_ACCELERATION_STRUCTURE_NV) \
X(COPY_BUFFER) \
X(COPY_BUFFER_TO_IMAGE) \
X(COPY_IMAGE) \
X(COPY_IMAGE_TO_BUFFER) \
X(DEBUG_MARKER_BEGIN_EXT) \
X(DEBUG_MARKER_END_EXT) \
X(DEBUG_MARKER_INSERT_EXT) \
X(DISPATCH_BASE) \
X(DISPATCH_INDIRECT) \
X(DRAW) \
X(DRAW_INDEXED) \
X(DRAW_INDEXED_INDIRECT) \
X(DRAW_INDEXED_INDIRECT_COUNT) \
X(DRAW_INDIRECT) \
X(DRAW_INDIRECT_BYTE_COUNT_EXT) \
X(DRAW_INDIRECT_COUNT) \
X(DRAW_MESH_TASKS_INDIRECT_COUNT_NV) \
X(DRAW_MESH_TASKS_INDIRECT_NV) \
X(DRAW_MESH_TASKS_NV) \
X(END_CONDITIONAL_RENDERING_EXT) \
X(END_DEBUG_UTILS_LABEL_EXT) \
X(END_QUERY_INDEXED_EXT) \
X(END_RENDER_PASS_2) \
X(END_TRANSFORM_FEEDBACK_EXT) \
X(EXECUTE_COMMANDS) \
X(FILL_BUFFER) \
X(INSERT_DEBUG_UTILS_LABEL_EXT) \
X(NEXT_SUBPASS) \
X(NEXT_SUBPASS_2) \
X(PIPELINE_BARRIER) \
X(PROCESS_COMMANDS_NVX) \
X(RESERVE_SPACE_FOR_COMMANDS_NVX) \
X(RESET_EVENT) \
X(RESET_QUERY_POOL) \
X(RESOLVE_IMAGE) \
X(SET_CHECKPOINT_NV) \
X(SET_EVENT) \
X(SET_PERFORMANCE_MARKER_INTEL) \
X(SET_PERFORMANCE_OVERRIDE_INTEL) \
X(SET_PERFORMANCE_STREAM_MARKER_INTEL) \
X(SET_SAMPLE_LOCATIONS_EXT) \
X(SET_VIEWPORT_SHADING_RATE_PALETTE_NV) \
X(TRACE_RAYS_NV) \
X(UPDATE_BUFFER) \
X(WAIT_EVENTS) \
X(WRITE_ACCELERATION_STRUCTURES_PROPERTIES_NV) \
X(WRITE_BUFFER_MARKER_AMD) \
X(WRITE_BUFFER_MARKER_2_AMD) \
X(WRITE_TIMESTAMP)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of bit flags used when creating a
/// <c><i>FfxBreadcrumbsContext</i></c>. See <c><i>FfxBreadcrumbsContextDescription</i></c>.
///
/// @ingroup ffxBreadcrumbs
typedef enum FfxBreadcrumbsInitializationFlagBits {
FFX_BREADCRUMBS_PRINT_FINISHED_LISTS = (1<<0), ///< A bit indicating that fully finished command lists will be expanded during status printing (otherwise their entries will be collapsed).
FFX_BREADCRUMBS_PRINT_NOT_STARTED_LISTS = (1<<1), ///< A bit indicating that command lists that haven't started execution on GPU yet will be expanded during status printing (otherwise their entries will be collapsed).
FFX_BREADCRUMBS_PRINT_FINISHED_NODES = (1<<3), ///< A bit indicating that nested markers which already have finished execution will be expanded during status printing (otherwise they will merged into top level marker).
FFX_BREADCRUMBS_PRINT_NOT_STARTED_NODES = (1<<4), ///< A bit indicating that nested markers which haven't started execution yet will be expanded during status printing (otherwise they will merged into top level marker).
FFX_BREADCRUMBS_PRINT_EXTENDED_DEVICE_INFO = (1<<5), ///< A bit indicating that additional info about active GPU will be printed into output status.
FFX_BREADCRUMBS_PRINT_SKIP_DEVICE_INFO = (1<<6), ///< A bit indicating that no info about active GPU will be printed into outpus status.
FFX_BREADCRUMBS_PRINT_SKIP_PIPELINE_INFO = (1<<7), ///< A bit indicating no info about pipelines used for commands recorded between markers will be printed into output status.
FFX_BREADCRUMBS_ENABLE_THREAD_SYNCHRONIZATION = (1<<8), ///< A bit indicating if internal synchronization should be applied (when using Breadcrumbs concurrently from multiple threads).
} FfxBreadcrumbsInitializationFlagBits;
/// Type of currently recorded marker, purely informational.
///
/// based on available methods of `ID3D12GraphicsCommandListX`, values of `D3D12_AUTO_BREADCRUMB_OP` and Vulkan `vkCmd*()` functions.
/// When using <c><i>FFX_BREADCRUMBS_MARKER_PASS</i></c> it is required to supply custom name for recording this type of marker. Otherwise it can
/// be left out as <c><i>NULL</i></c> and the Breadcrumbs will use default tag for this marker. It can be useful when recording multiple similar
/// commands in a row. Breadcrumbs will automatically add numbering to them so it's not needed to create your own numbered dynamic string.
///
/// @ingroup ffxBreadcrumbs
typedef enum FfxBreadcrumbsMarkerType {
FFX_BREADCRUMBS_MARKER_PASS, ///< Marker for grouping sets of commands. It is required to supply custom name for this type.
#define X(marker) FFX_BREADCRUMBS_MARKER_##marker,
FFX_BREADCRUMBS_MARKER_LIST
#undef X
} FfxBreadcrumbsMarkerType;
/// A structure encapsulating the parameters required to initialize FidelityFX Breadcrumbs.
///
/// @ingroup ffxBreadcrumbs
typedef struct FfxBreadcrumbsContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxBreadcrumbsInitializationFlagBits</i></c>.
uint32_t frameHistoryLength; ///< Number of frames to records markers for. Have to be larger than 0.
uint32_t maxMarkersPerMemoryBlock; ///< Controls the number of markers saved in single memory block. Have to be in range of [1..<c><i>FFX_BREADCRUMBS_MAX_MARKERS_PER_BLOCK</i></c>].
uint32_t usedGpuQueuesCount; ///< Number of entries in <c><i>pUsedGpuQueues</i></c>. Have to be larger than 0.
uint32_t* pUsedGpuQueues; ///< Pointer to an array of unique indices representing GPU queues used for command lists used with AMD FidelityFX Breadcrumbs Library.
FfxAllocationCallbacks allocCallbacks; ///< Callbacks for managing memory in the library.
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX SDK.
} FfxBreadcrumbsContextDescription;
/// Wrapper for custom Breadcrumbs name tags with indicator whether to perform copy on them.
///
/// When custom name is supplied <c><i>isNameExternallyOwned</i></c> field controls whether to perform copy on the string.
/// If string memory is managed by the application (ex. static string) the copy can be omitted to save memory.
///
/// @ingroup ffxBreadcrumbs
typedef struct FfxBreadcrumbsNameTag
{
const char* pName; ///< Custom name for the object. By default optional, can be left to <c><i>NULL</i></c>.
bool isNameExternallyOwned; ///< Controls if AMD FidelityFX Breadcrumbs Library should copy a custom name with backed-up memory.
} FfxBreadcrumbsNameTag;
/// Description for new command list to be enabled for writing AMD FidelityFX Breadcrumbs Library markers.
///
/// @ingroup ffxBreadcrumbs
typedef struct FfxBreadcrumbsCommandListDescription {
FfxCommandList commandList; ///< Handle to the command list that will be used with breadcrumbs operations.
uint32_t queueType; ///< Type of queue that list is used on.
FfxBreadcrumbsNameTag name; ///< Custom name for the command list.
FfxPipeline pipeline; ///< Optional pipeline state to associate with newly registered command list (can be set later).
uint16_t submissionIndex; ///< Information about submit number that command list is sent to GPU. Purely informational to help in analysing output later.
} FfxBreadcrumbsCommandListDescription;
/// Description for pipeline state that will be used to tag breadcrumbs markers.
///
/// @ingroup ffxBreadcrumbs
typedef struct FfxBreadcrumbsPipelineStateDescription
{
FfxPipeline pipeline; ///< Pipeline state that will be associated with set of Breadcrumbs markers.
FfxBreadcrumbsNameTag name; ///< Custom name for the pipeline state.
FfxBreadcrumbsNameTag vertexShader; ///< Name of used Vertex Shader. Part of classic geometry processing pipeline, cannot be set together with compute, ray tracing or new mesh processing pipeline.
FfxBreadcrumbsNameTag hullShader; ///< Name of used Hull Shader. Part of classic geometry processing pipeline, cannot be set together with compute, ray tracing or new mesh processing pipeline.
FfxBreadcrumbsNameTag domainShader; ///< Name of used Domain Shader. Part of classic geometry processing pipeline, cannot be set together with compute, ray tracing or new mesh processing pipeline.
FfxBreadcrumbsNameTag geometryShader; ///< Name of used Geometry Shader. Part of classic geometry processing pipeline, cannot be set together with compute, ray tracing or new mesh processing pipeline.
FfxBreadcrumbsNameTag meshShader; ///< Name of used Mesh Shader. Part of new mesh processing pipeline, cannot be set together with compute, ray tracing or classic geometry processing pipeline.
FfxBreadcrumbsNameTag amplificationShader; ///< Name of used Amplification Shader. Part of new mesh processing pipeline, cannot be set together with compute, ray tracing or classic geometry processing pipeline.
FfxBreadcrumbsNameTag pixelShader; ///< Name of used Pixel Shader. Cannot be set together with <c><i>computeShader</i></c> or <c><i>rayTracingShader</i></c>.
FfxBreadcrumbsNameTag computeShader; ///< Name of used Compute Shader. Have to be set exclusively to other shader names (indicates compute pipeline).
FfxBreadcrumbsNameTag rayTracingShader; ///< Name of used Ray Tracing Shader. Have to be set exclusively to other shader names (indicates ray tracing pipeline).
} FfxBreadcrumbsPipelineStateDescription;
/// Output with current AMD FidelityFX Breadcrumbs Library markers log for post-mortem analysis.
///
/// @ingroup ffxBreadcrumbs
typedef struct FfxBreadcrumbsMarkersStatus
{
size_t bufferSize; ///< Size of the status buffer.
char* pBuffer; ///< UTF-8 encoded buffer with log about markers execution. Have to be released with <c><i>FFX_FREE</i></c>.
} FfxBreadcrumbsMarkersStatus;
/// A structure encapsulating the FidelityFX Breadcrumbs context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by AMD FidelityFX Breadcrumbs Library.
///
/// The <c><i>FfxBreadcrumbsContext</i></c> object should have a lifetime matching
/// your use of Breadcrumbs. Before destroying the Breadcrumbs context care should be taken
/// to ensure the GPU is not accessing the resources created or used by Breadcrumbs.
/// It is therefore recommended that the GPU is idle before destroying the
/// Breadcrumbs context.
///
/// @ingroup ffxBreadcrumbs
typedef struct FfxBreadcrumbsContext
{
uint32_t data[FFX_BREADCRUMBS_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxBreadcrumbsContext;
/// Create a FidelityFX Breadcrumbs context from the parameters
/// programmed to the <c><i>FfxBreadcrumbsContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the Breadcrumbs
/// API, and is responsible for the management of the internal buffers used
/// by the Breadcrumbs algorithm. For each provided queue there will be created
/// a buffer that will hold contents of the saved markers, awaiting for retrieval
/// per call to <c><i>ffxBreadcrumbsPrintStatus()</i></c>
///
/// When choosing the number of frames to save markers for,
/// specified in the <c><i>frameHistoryLength</i></c> field of
/// <c><i>FfxBreadcrumbsContextDescription</i></c>, typically can be set to the number of
/// frames in flight in the application, but for longer history it can be increased.
///
/// Buffers for markers are allocated at fixed size, allowing for certain
/// number of markers to be saved in them. The size of this buffers are
/// determined by <c><i>maxMarkersPerMemoryBlock</i></c> field of
/// <c><i>FfxBreadcrumbsContextDescription</i></c>. When needed new ones are created but to avoid
/// multiple allocations you can estimate how many markers will be used in single frame.
///
/// The <c><i>FfxBreadcrumbsContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded. To destroy the Breadcrumbs context
/// you should call <c><i>ffxBreadcrumbsContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxBreadcrumbsContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxBreadcrumbsContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because either <c><i>pContext</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxBreadcrumbsContextDescription.backendInterface</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxBreadcrumbs
FFX_API FfxErrorCode ffxBreadcrumbsContextCreate(FfxBreadcrumbsContext* pContext, const FfxBreadcrumbsContextDescription* pContextDescription);
/// Destroy the FidelityFX Breadcrumbs context.
///
/// Should always be called from a single thread for same context.
///
/// @param [out] pContext A pointer to a <c><i>FfxBreadcrumbsContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because either <c><i>pContext</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBreadcrumbs
FFX_API FfxErrorCode ffxBreadcrumbsContextDestroy(FfxBreadcrumbsContext* pContext);
/// Begins new frame of execution for FidelityFX Breadcrumbs.
///
/// Should always be called from a single thread for same context.
///
/// @param [in] pContext A pointer to a <c><i>FfxBreadcrumbsContext</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because either <c><i>pContext</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBreadcrumbs
FFX_API FfxErrorCode ffxBreadcrumbsStartFrame(FfxBreadcrumbsContext* pContext);
/// Register new command list for current frame FidelityFX Breadcrumbs operations.
///
/// After call to <c><i>ffxBreadcrumbsStartFrame()</i></c> every previously used list has to be registered again.
///
/// @param [in] pContext A pointer to a <c><i>FfxBreadcrumbsContext</i></c> structure.
/// @param [in] pCommandListDescription A pointer to a <c><i>FfxBreadcrumbsCommandListDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because either <c><i>pContext</i></c> or <c><i>pCommandListDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT The operation failed because given command list has been already registered.
///
/// @ingroup ffxBreadcrumbs
FFX_API FfxErrorCode ffxBreadcrumbsRegisterCommandList(FfxBreadcrumbsContext* pContext, const FfxBreadcrumbsCommandListDescription* pCommandListDescription);
/// Register new pipeline state to associate later with FidelityFX Breadcrumbs operations.
///
/// Information about pipeline is preserved across frames so only single call after creation of pipeline is needed.
///
/// @param [in] pContext A pointer to a <c><i>FfxBreadcrumbsContext</i></c> structure.
/// @param [in] pPipelineDescription A pointer to a <c><i>FfxBreadcrumbsPipelineStateDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because either <c><i>pContext</i></c> or <c><i>pPipelineDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT The operation failed because given pipeline has been already registered or <c><i>pPipelineDescription</i></c> contains incorrect data.
///
/// @ingroup ffxBreadcrumbs
FFX_API FfxErrorCode ffxBreadcrumbsRegisterPipeline(FfxBreadcrumbsContext* pContext, const FfxBreadcrumbsPipelineStateDescription* pPipelineDescription);
/// Associate specific pipeline state with following FidelityFX Breadcrumbs markers.
///
/// When recorded commands use specific pipelines you can save this information, associating said pipelines
/// with recorded markers, so later on additional information can be displayed when using <c><i>ffxBreadcrumbsPrintStatus()</i></c>.
/// To reset currently used pipeline just pass <c><i>NULL</i></c> as <c><i>pipeline</i></c> param.
///
/// @param [in] pContext A pointer to a <c><i>FfxBreadcrumbsContext</i></c> structure.
/// @param [in] commandList Previously registered command list.
/// @param [in] pipeline Previously registered pipeline.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because either <c><i>context</i></c> or <c><i>commandList</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT The operation failed because given pipeline or command list has not been registered yet.
///
/// @ingroup ffxBreadcrumbs
FFX_API FfxErrorCode ffxBreadcrumbsSetPipeline(FfxBreadcrumbsContext* pContext, FfxCommandList commandList, FfxPipeline pipeline);
/// Begin new FidelityFX Breadcrumbs marker section.
///
/// New section has to be ended with <c><i>ffxBreadcrumbsEndMarker()</i></c>
/// but multiple <c><i>ffxBreadcrumbsBeginMarker()</i></c> nesting calls are possible.
///
/// @param [in] pContext A pointer to a <c><i>FfxBreadcrumbsContext</i></c> structure.
/// @param [in] commandList Previously registered command list.
/// @param [in] type Type of the marker section.
/// @param [in] pName Custom name for the marker section. Have to contain correct string if <c><i>type</i></c> is <c><i>FFX_BREADCRUMBS_MARKER_PASS()</i></c>.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because either <c><i>pContext</i></c> or <c><i>pName</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT The operation failed because given command list has not been registered yet or <c><i>pName</i></c> doesn't contain correct string.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxBreadcrumbs
FFX_API FfxErrorCode ffxBreadcrumbsBeginMarker(FfxBreadcrumbsContext* pContext, FfxCommandList commandList, FfxBreadcrumbsMarkerType type, const FfxBreadcrumbsNameTag* pName);
/// End FidelityFX Breadcrumbs marker section.
///
/// Has to be preceeded by <c><i>ffxBreadcrumbsBeginMarker()</i></c>.
///
/// @param [in] pContext A pointer to a <c><i>FfxBreadcrumbsContext</i></c> structure.
/// @param [in] commandList Previously registered command list.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>pContext</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT The operation failed because given command list has not been registered yet.
///
/// @ingroup ffxBreadcrumbs
FFX_API FfxErrorCode ffxBreadcrumbsEndMarker(FfxBreadcrumbsContext* pContext, FfxCommandList commandList);
/// Gather information about current FidelityFX Breadcrumbs markers status.
///
/// After receiving device lost error on GPU you can use this method to print post-mortem log of markers execution
/// to determine which commands in which frame were in flight during the crash.
/// Should always be called from a single thread.
///
/// @param [in] pContext A pointer to a <c><i>FfxBreadcrumbsContext</i></c> structure.
/// @param [out] pMarkersStatus Buffer with post-mortem log of Breadcrumbs markers.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because either <c><i>pContext</i></c> or <c><i>pMarkersStatus</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBreadcrumbs
FFX_API FfxErrorCode ffxBreadcrumbsPrintStatus(FfxBreadcrumbsContext* pContext, FfxBreadcrumbsMarkersStatus* pMarkersStatus);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxBreadcrumbs
FFX_API FfxVersionNumber ffxBreadcrumbsGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,339 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 <FidelityFX/host/ffx_brixelizer_raw.h>
/// The size of the context specified in 32bit values.
///
/// @ingroup ffxBrixelizer
#define FFX_BRIXELIZER_CONTEXT_SIZE (5938838)
/// The size of the update description specified in 32bit values.
///
/// @ingroup ffxBrixelizer
#define FFX_BRIXELIZER_UPDATE_DESCRIPTION_SIZE 2099376
#ifdef __cplusplus
extern "C" {
#endif
/// A structure encapsulating the FidelityFX Brixelizer context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by Brixelizer.
///
/// The <c><i>FfxBrixelizerContext</i></c> object should have a lifetime matching
/// your use of Brixelizer. Before destroying the Brixelizer context care
/// should be taken to ensure the GPU is not accessing the resources created
/// or used by Brixelizer. It is therefore recommended that the GPU is idle
/// before destroying the Brixelizer context.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerContext {
uint32_t data[FFX_BRIXELIZER_CONTEXT_SIZE];
} FfxBrixelizerContext;
/// A structure representing an axis aligned bounding box for use with Brixelizer.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerAABB {
float min[3]; ///< The minimum bounds of the AABB.
float max[3]; ///< The maximum bounds of the AABB.
} FfxBrixelizerAABB;
/// Flags used for cascade creation. A cascade may be specified
/// as having static geometry, dynamic geometry, or both by combining these flags.
///
/// @ingroup ffxBrixelizer
typedef enum FfxBrixelizerCascadeFlag {
FFX_BRIXELIZER_CASCADE_STATIC = (1 << 0),
FFX_BRIXELIZER_CASCADE_DYNAMIC = (1 << 1),
} FfxBrixelizerCascadeFlag;
/// A structure encapsulating the parameters for cascade creation.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerCascadeDescription {
FfxBrixelizerCascadeFlag flags; ///< Flags for cascade creation. See <c><i>FfxBrixelizerCascadeFlag</i></c>.
float voxelSize; ///< The edge size of voxels in world space for the cascade.
} FfxBrixelizerCascadeDescription;
/// A structure encapsulating the parameters for creating a Brixelizer context.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerContextDescription {
float sdfCenter[3]; ///< The point in world space around which to center the cascades.
uint32_t numCascades; ///< The number of cascades managed by the Brixelizer context.
FfxBrixelizerContextFlags flags; ///< A combination of <c><i>FfxBrixelizerContextFlags</i></c> specifying options for the context.
FfxBrixelizerCascadeDescription cascadeDescs[FFX_BRIXELIZER_MAX_CASCADES]; ///< Parameters describing each of the cascades, see <c><i>FfxBrixelizerCascadeDescription</i></c>.
FfxInterface backendInterface; ///< An implementation of the FidelityFX backend for use with Brixelizer.
} FfxBrixelizerContextDescription;
/// Flags used for setting which AABBs to draw in a debug visualization of Brixelizer
///
/// @ingroup ffxBrixelizer
typedef enum FfxBrixelizerPopulateDebugAABBsFlags {
FFX_BRIXELIZER_POPULATE_AABBS_NONE = 0, ///< Draw no AABBs.
FFX_BRIXELIZER_POPULATE_AABBS_STATIC_INSTANCES = 1 << 0, ///< Draw AABBs for all static instances.
FFX_BRIXELIZER_POPULATE_AABBS_DYNAMIC_INSTANCES = 1 << 1, ///< Draw AABBs for all dynamic instances.
FFX_BRIXELIZER_POPULATE_AABBS_INSTANCES = FFX_BRIXELIZER_POPULATE_AABBS_STATIC_INSTANCES | FFX_BRIXELIZER_POPULATE_AABBS_DYNAMIC_INSTANCES, ///< Draw AABBs for all instances.
FFX_BRIXELIZER_POPULATE_AABBS_CASCADE_AABBS = 1 << 2, ///< Draw AABBs for all cascades.
} FfxBrixelizerPopulateDebugAABBsFlags;
/// A structure containing the statistics for a Brixelizer context readable after an update of the Brixelizer API.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerContextStats {
uint32_t brickAllocationsAttempted; ///< Total number of brick allocations attempted this frame.
uint32_t brickAllocationsSucceeded; ///< Total number of brick allocations succeeded this frame.
uint32_t bricksCleared; ///< Total number of bricks cleared in SDF atlas at the beginning of this frame.
uint32_t bricksMerged; ///< Total number of bricks merged this frame.
uint32_t freeBricks; ///< The number of free bricks in the Brixelizer context.
} FfxBrixelizerContextStats;
/// A structure containing the statistics for a Brixelizer cascade readable after an update of the Brixelizer API.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerCascadeStats {
uint32_t trianglesAllocated; ///< The number of triangle allocations that were attempted to the cascade in a given frame.
uint32_t referencesAllocated; ///< The number of reference allocations that were attempted to the cascade in a given frame.
uint32_t bricksAllocated; ///< The number of brick allocations that were attempted to the cascade in a given frame.
} FfxBrixelizerCascadeStats;
/// A structure containing the statistics readable after an update of the Brixelizer API.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerStats {
uint32_t cascadeIndex; ///< The index of the cascade that the statisticss have been collected for.
FfxBrixelizerCascadeStats staticCascadeStats; ///< The statistics for the static cascade.
FfxBrixelizerCascadeStats dynamicCascadeStats; ///< The statistics for the dynamic cascade.
FfxBrixelizerContextStats contextStats; ///< The statistics for the Brixelizer context.
} FfxBrixelizerStats;
/// A structure encapsulating the parameters used for computing an update by the
/// Brixelizer context.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerUpdateDescription {
FfxBrixelizerResources resources; ///< Structure containing all resources to be used by the Brixelizer context.
uint32_t frameIndex; ///< The index of the current frame.
float sdfCenter[3]; ///< The center of the cascades.
FfxBrixelizerPopulateDebugAABBsFlags populateDebugAABBsFlags; ///< Flags determining which AABBs to draw in a debug visualization. See <c><i>FfxBrixelizerPopulateDebugAABBsFlag</i></c>.
FfxBrixelizerDebugVisualizationDescription *debugVisualizationDesc; ///< An optional debug visualization description. If this parameter is set to <c><i>NULL</i></c> no debug visualization is drawn.
uint32_t maxReferences; ///< The maximum number of triangle voxel references to be stored in the update.
uint32_t triangleSwapSize; ///< The size of the swap space available to be used for storing triangles in the update.
uint32_t maxBricksPerBake; ///< The maximum number of bricks to be updated.
size_t *outScratchBufferSize; ///< An optional pointer to a <c><i>size_t</i></c> to receive the size of the GPU scratch buffer needed to process the update.
FfxBrixelizerStats *outStats; ///< An optional pointer to an <c><i>FfxBrixelizerStats</i></c> struct to receive statistics for the update. Note, stats read back after a call to update do not correspond to the same frame that the stats were requested, as reading of stats requires readback from GPU buffers which is performed with a delay.
} FfxBrixelizerUpdateDescription;
/// A structure generated by Brixelizer from an <c><i>FfxBrixelizerUpdateDescription</i></c> structure
/// used for storing parameters necessary for an update with the underlying raw Brixelizer API.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerBakedUpdateDescription {
uint32_t data[FFX_BRIXELIZER_UPDATE_DESCRIPTION_SIZE];
} FfxBrixelizerBakedUpdateDescription;
/// Flags used for specifying instance properties.
///
/// @ingroup ffxBrixelizer
typedef enum FfxBrixelizerInstanceFlags {
FFX_BRIXELIZER_INSTANCE_FLAG_NONE = 0, ///< No instance flags set.
FFX_BRIXELIZER_INSTANCE_FLAG_DYNAMIC = 1 << 0, ///< This flag is set for any instance which should be added to the dynamic cascade. Indicates that this instance will be resubmitted every frame.
} FfxBrixelizerInstanceFlags;
/// A structure encapsulating the parameters necessary to create an instance with Brixelizer.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerInstanceDescription {
uint32_t maxCascade; ///< The index of the highest cascade this instance will be submitted to. This helps avoid submitting many small objects to least detailed cascades.
FfxBrixelizerAABB aabb; ///< An AABB surrounding the instance.
FfxFloat32x3x4 transform; ///< A transform of the instance into world space. The transform is in row major order.
FfxIndexFormat indexFormat; ///< The format of the index buffer. Accepted formats are FFX_INDEX_UINT16 or FFX_INDEX_UINT32.
uint32_t indexBuffer; ///< The index of the index buffer set with ffxBrixelizerContextSetBuffer.
uint32_t indexBufferOffset; ///< An offset into the index buffer.
uint32_t triangleCount; ///< The count of triangles in the index buffer.
uint32_t vertexBuffer; ///< The index of the vertex buffer set with ffxBrixelizerContextSetBuffer.
uint32_t vertexStride; ///< The stride of the vertex buffer in bytes.
uint32_t vertexBufferOffset; ///< An offset into the vertex buffer.
uint32_t vertexCount; ///< The count of vertices in the vertex buffer.
FfxSurfaceFormat vertexFormat; ///< The format of vertices in the vertex buffer. Accepted values are FFX_SURFACE_FORMAT_R16G16B16A16_FLOAT and FFX_SURFACE_FORMAT_R32G32B32_FLOAT.
FfxBrixelizerInstanceFlags flags; ///< Flags specifying properties of the instance. See <c><i>FfxBrixelizerInstanceFlags</i></c>.
FfxBrixelizerInstanceID *outInstanceID; ///< A pointer to an <c><i>FfxBrixelizerInstanceID</i></c> storing the ID of the created instance.
} FfxBrixelizerInstanceDescription;
/// Get the size in bytes needed for an <c><i>FfxBrixelizerContext</i></c> struct.
/// Note that this function is provided for consistency, and the size of the
/// <c><i>FfxBrixelizerContext</i></c> is a known compile time value which can be
/// obtained using <c><i>sizeof(FfxBrixelizerContext)</i></c>.
///
/// @return The size in bytes of an <c><i>FfxBrixelizerContext</i></c> struct.
///
/// @ingroup ffxBrixelizer
inline size_t ffxBrixelizerGetContextSize()
{
return sizeof(FfxBrixelizerContext);
}
/// Create a FidelityFX Brixelizer context from the parameters
/// specified to the <c><i>FfxBrixelizerContextDesc</i></c> struct.
///
/// The context structure is the main object used to interact with the Brixelizer
/// API, and is responsible for the management of the internal resources used by the
/// Brixelizer algorithm. When this API is called, multiple calls will be made via
/// the pointers contained in the <b><i>backendInterface</i></b> structure. This
/// backend will attempt to retrieve the device capabilities, and create the internal
/// resources, and pipelines required by Brixelizer.
///
/// Depending on the parameters passed in via the <b><i>contextDescription</b></i> a
/// different set of resources and pipelines may be requested by the callback functions.
///
/// The <c><i>FfxBrixelizerContext</i></c> should be destroyed when use of it is completed.
/// To destroy the context you should call <c><i>ffxBrixelizerContextDestroy</i></c>.
///
/// @param [in] desc An <c><i>FfxBrixelizerContextDescription</i></c> structure with the parameters for context creation.
/// @param [out] outContext An <c><i>FfxBrixelizerContext</i></c> structure for receiving the initialized Brixelizer context.
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerContextCreate(const FfxBrixelizerContextDescription* desc, FfxBrixelizerContext* outContext);
/// Delete the Brixelizer context associated with the <c><i>FfxBrixelizerContext</i></c> struct.
///
/// @param [inout] context An <c><i>FfxBrixelizerContext</i></c> containing the Brixelizer context.
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerContextDestroy(FfxBrixelizerContext* context);
/// Fill in an <c><i>FfxBrixelizerContextInfo</i></c> struct for necessary for updating a constant buffer for use
/// by Brixelizer when ray marching.
///
/// @param [inout] context An <c><i>FfxBrixelizerContext</i></c> containing the Brixelizer context.
/// @param [out] contextInfo An <c><i>FfxBrixelizerContextInfo</i></c> struct to be filled.
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerGetContextInfo(FfxBrixelizerContext* context, FfxBrixelizerContextInfo* contextInfo);
/// Build an <c><i>FfxBrixelizerBakedUpdateDescription</i></c> struct from an <c><i>FfxBrixelizerUpdateDescription</i></c> struct
/// for use in doing a Brixelizer update.
///
/// @param [inout] context An <c><i>FfxBrixelizerContext</i></c> containing the Brixelizer context.
/// @param [in] desc An <c><i>FfxBrixelizerUpdateDescription</i></c> struct containing the parameters for the update.
/// @param [out] outDesc An <c><i>FfxBrixelizerBakedUpdateDescription</i></c> struct to be filled in.
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerBakeUpdate(FfxBrixelizerContext* context, const FfxBrixelizerUpdateDescription* desc, FfxBrixelizerBakedUpdateDescription* outDesc);
/// Perform an update of Brixelizer, recording GPU commands to a command list.
///
/// @param [inout] context An <c><i>FfxBrixelizerContext</i></c> containing the Brixelizer context.
/// @param [in] desc An <c><i>FfxBrixelizerBakedUpdateDescription</i></c> describing the update to compute.
/// @param [out] scratchBuffer An <c><i>FfxResource</i></c> to be used as scratch space by the update.
/// @param [out] commandList An <c><i>FfxCommandList</i></c> to write GPU commands to.
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerUpdate(FfxBrixelizerContext* context, FfxBrixelizerBakedUpdateDescription* desc, FfxResource scratchBuffer, FfxCommandList commandList);
/// Register a vertex or index buffer to use with Brixelizer.
///
/// @param [inout] context An <c><i>FfxBrixelizerContext</i></c> containing the Brixelizer context.
/// @param [in] buffer An <c><i>FfxResource</i></c> of the vertex or index buffer.
/// @param [out] index The index of the registered buffer.
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRegisterBuffers(FfxBrixelizerContext* context, const FfxBrixelizerBufferDescription* bufferDescs, uint32_t numBufferDescs);
/// Unregister a previously registered vertex or index buffer.
///
/// @param [inout] context An <c><i>FfxBrixelizerContext</i></c> containing the Brixelizer context.
/// @param [in] index The index of the buffer to unregister.
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerUnregisterBuffers(FfxBrixelizerContext* context, const uint32_t* indices, uint32_t numIndices);
/// Create a static instance for a Brixelizer context.
///
/// @param [inout] context An <c><i>FfxBrixelizerContext</i></c> containing the Brixelizer context.
/// @param [in] descs An array of <c><i>FfxBrixelizerInstanceDescription</i></c> structs with the parameters for instance creation.
/// @param [in] numDescs The number of entries in the array passed in by <c><i>descs</i></c>.
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerCreateInstances(FfxBrixelizerContext* context, const FfxBrixelizerInstanceDescription* descs, uint32_t numDescs);
/// Delete a static instance from a Brixelizer context.
///
/// @param [inout] context An <c><i>FfxBrixelizerContext</i></c> containing the Brixelizer context.
/// @param [in] instanceIDs An array of <c><i>FfxBrixelizerInstanceID</i></c>s corresponding to instances to be destroyed.
/// @param [in] numInstnaceIDs The number of elements in the array passed in by <c><i>instanceIDs</i></c>.
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerDeleteInstances(FfxBrixelizerContext* context, const FfxBrixelizerInstanceID* instanceIDs, uint32_t numInstanceIDs);
/// Get a pointer to the underlying Brixelizer raw context from a Brixelizer context.
///
/// @param [inout] context An <c><i>FfxBrixelizerContext</i></c> containing the Brixelizer context.
/// @param [out] outContext A <c><i>FfxBrixelizerRawContext</i></c> representing the underlying Brixelizer raw context.
///
/// @return
/// FFX_ERROR_INVALID_POINTER The pointer given was invalid.
/// @return
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerGetRawContext(FfxBrixelizerContext* context, FfxBrixelizerRawContext** outContext);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,681 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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
/// @defgroup ffxBrixelizer FidelityFX Brixelizer
/// FidelityFX Brixelizer runtime library
///
/// @ingroup SDKComponents
// Include the interface for the backend of the Brixelizer API.
#include <FidelityFX/host/ffx_interface.h>
#include <FidelityFX/gpu/brixelizer/ffx_brixelizer_host_gpu_shared.h>
/// FidelityFX Brixelizer major version.
///
/// @ingroup ffxBrixelizer
#define FFX_BRIXELIZER_VERSION_MAJOR (1)
/// FidelityFX Brixelizer minor version.
///
/// @ingroup ffxBrixelizer
#define FFX_BRIXELIZER_VERSION_MINOR (0)
/// FidelityFX Brixelizer patch version.
///
/// @ingroup ffxBrixelizer
#define FFX_BRIXELIZER_VERSION_PATCH (0)
/// FidelityFX Brixelizer context count
///
/// Defines the number of internal effect contexts required by Brixelizer
///
/// @ingroup ffxBrixelizer
#define FFX_BRIXELIZER_CONTEXT_COUNT 1
/// The size of the raw context specified in 32bit values.
///
/// @ingroup ffxBrixelizer
#define FFX_BRIXELIZER_RAW_CONTEXT_SIZE (2924058)
#ifdef __cplusplus
extern "C" {
#endif
/// An enumeration of all the passes which constitute the Brixelizer algorithm.
///
/// Brixelizer is implemented as a composite of several compute passes each
/// computing a key part of the final result. Each call to the
/// <c><i>FfxBrixelizerScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single pass included in <c><i>FfxBrixelizerPass</i></c>. For a
/// more comprehensive description of each pass, please refer to the Brixelizer
/// reference documentation.
///
/// @ingroup ffxBrixelizer
typedef enum FfxBrixelizerPass
{
FFX_BRIXELIZER_PASS_CONTEXT_CLEAR_COUNTERS,
FFX_BRIXELIZER_PASS_CONTEXT_COLLECT_CLEAR_BRICKS,
FFX_BRIXELIZER_PASS_CONTEXT_PREPARE_CLEAR_BRICKS,
FFX_BRIXELIZER_PASS_CONTEXT_CLEAR_BRICK,
FFX_BRIXELIZER_PASS_CONTEXT_COLLECT_DIRTY_BRICKS,
FFX_BRIXELIZER_PASS_CONTEXT_PREPARE_EIKONAL_ARGS,
FFX_BRIXELIZER_PASS_CONTEXT_EIKONAL,
FFX_BRIXELIZER_PASS_CONTEXT_MERGE_CASCADES,
FFX_BRIXELIZER_PASS_CONTEXT_PREPARE_MERGE_BRICKS_ARGS,
FFX_BRIXELIZER_PASS_CONTEXT_MERGE_BRICKS,
FFX_BRIXELIZER_PASS_CASCADE_CLEAR_BUILD_COUNTERS,
FFX_BRIXELIZER_PASS_CASCADE_RESET_CASCADE,
FFX_BRIXELIZER_PASS_CASCADE_SCROLL_CASCADE,
FFX_BRIXELIZER_PASS_CASCADE_CLEAR_REF_COUNTERS,
FFX_BRIXELIZER_PASS_CASCADE_CLEAR_JOB_COUNTER,
FFX_BRIXELIZER_PASS_CASCADE_INVALIDATE_JOB_AREAS,
FFX_BRIXELIZER_PASS_CASCADE_COARSE_CULLING,
FFX_BRIXELIZER_PASS_CASCADE_SCAN_JOBS,
FFX_BRIXELIZER_PASS_CASCADE_VOXELIZE,
FFX_BRIXELIZER_PASS_CASCADE_SCAN_REFERENCES,
FFX_BRIXELIZER_PASS_CASCADE_COMPACT_REFERENCES,
FFX_BRIXELIZER_PASS_CASCADE_CLEAR_BRICK_STORAGE,
FFX_BRIXELIZER_PASS_CASCADE_EMIT_SDF,
FFX_BRIXELIZER_PASS_CASCADE_COMPRESS_BRICK,
FFX_BRIXELIZER_PASS_CASCADE_INITIALIZE_CASCADE,
FFX_BRIXELIZER_PASS_CASCADE_MARK_UNINITIALIZED,
FFX_BRIXELIZER_PASS_CASCADE_BUILD_TREE_AABB,
FFX_BRIXELIZER_PASS_CASCADE_FREE_CASCADE,
FFX_BRIXELIZER_PASS_DEBUG_VISUALIZATION,
FFX_BRIXELIZER_PASS_DEBUG_INSTANCE_AABBS,
FFX_BRIXELIZER_PASS_DEBUG_AABB_TREE,
FFX_BRIXELIZER_PASS_COUNT ///< The number of passes performed by Brixelizer.
} FfxBrixelizerPass;
/// An ID value for an instance created with Brixelizer.
///
/// @ingroup ffxBrixelizer
typedef uint32_t FfxBrixelizerInstanceID;
/// A structure representing the external resources needed for a Brixelizer cascade.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerCascadeResources
{
FfxResource aabbTree; ///< An FfxResource for storing the AABB tree of the cascade. This should be a structured buffer of size FFX_BRIXELIZER_CASCADE_AABB_TREE_SIZE and stride FFX_BRIXELIZER_CASCADE_AABB_TREE_STRIDE.
FfxResource brickMap; ///< An FfxResource for storing the brick map of the cascade. This should be a structured buffer of size FFX_BRIXELIZER_CASCADE_BRICK_MAP_SIZE and stride FFX_BRIXELIZER_CASCADE_BRICK_MAP_STRIDE.
} FfxBrixelizerCascadeResources;
/// A structure representing all external resources for use with Brixelizer.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerResources
{
FfxResource sdfAtlas; ///< An FfxResource for storing the SDF atlas. This should be a 512x512x512 3D texture of 8-bit unorm values.
FfxResource brickAABBs; ///< An FfxResource for storing the brick AABBs. This should be a structured buffer containing 64*64*64 32-bit values.
FfxBrixelizerCascadeResources cascadeResources[FFX_BRIXELIZER_MAX_CASCADES]; ///< Cascade resources.
} FfxBrixelizerResources;
/// A structure encapsulating the parameters necessary to register a buffer with
/// the Brixelizer API.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerBufferDescription {
FfxResource buffer; ///< An <c><i>FfxResource</i></c> of the buffer.
uint32_t *outIndex; ///< A pointer to a <c><i>uint32_t</i></c> to receive the index assigned to the buffer.
} FfxBrixelizerBufferDescription;
/// Flags used for specifying debug drawing of AABBs.
///
/// @ingroup ffxBrixelizer
typedef enum FfxBrixelizerCascadeDebugAABB {
FFX_BRIXELIZER_CASCADE_DEBUG_AABB_NONE,
FFX_BRIXELIZER_CASCADE_DEBUG_AABB_BOUNDING_BOX,
FFX_BRIXELIZER_CASCADE_DEBUG_AABB_AABB_TREE,
} FfxBrixelizerCascadeDebugAABB;
/// A structure encapsulating the parameters for drawing a debug visualization.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerDebugVisualizationDescription
{
float inverseViewMatrix[16]; ///< Inverse view matrix for the scene in row major order.
float inverseProjectionMatrix[16]; ///< Inverse projection matrix for the scene in row major order.
FfxBrixelizerTraceDebugModes debugState; ///< An FfxBrixelizerTraceDebugModes determining what kind of debug output to draw.
uint32_t startCascadeIndex; ///< The index of the most detailed cascade in the cascade chain.
uint32_t endCascadeIndex; ///< The index of the least detailed cascade in the cascade chain.
float sdfSolveEps; ///< The epsilon value used in SDF ray marching.
float tMin; ///< The tMin value for minimum ray intersection.
float tMax; ///< The tMax value for maximum ray intersection.
uint32_t renderWidth; ///< The width of the output resource.
uint32_t renderHeight; ///< The height of the output resource.
FfxResource output; ///< An FfxResource to draw the debug visualization to.
FfxCommandList commandList; ///< An FfxCommandList to write the draw commands to.
uint32_t numDebugAABBInstanceIDs; ///< The number of FfxBrixelizerInstanceIDs in the debugAABBInstanceIDs array.
const FfxBrixelizerInstanceID *debugAABBInstanceIDs; ///< An array of FfxBrixelizerInstanceIDs for instances to draw the bounding boxes of.
FfxBrixelizerCascadeDebugAABB cascadeDebugAABB[FFX_BRIXELIZER_MAX_CASCADES]; ///< An array of flags showing what AABB debug output to draw for each cascade.
} FfxBrixelizerDebugVisualizationDescription;
/// Flags for options for Brixelizer context creation.
///
/// @ingroup ffxBrixelizer
typedef enum FfxBrixelizerContextFlags
{
FFX_BRIXELIZER_CONTEXT_FLAG_DEBUG_CONTEXT_READBACK_BUFFERS = (1 << 0), ///< Create a context with context readback buffers enabled. Needed to use <c><i>ffxBrixelizerContextGetDebugCounters</i></c>.
FFX_BRIXELIZER_CONTEXT_FLAG_DEBUG_CASCADE_READBACK_BUFFERS = (1 << 1), ///< Create a context with cascade readback buffers enabled. Needed to use <c><i>ffxBrixelizerContextGetCascadeCounters</i></c>.
FFX_BRIXELIZER_CONTEXT_FLAG_DEBUG_AABBS = (1 << 2), ///< Create a context with debug AABBs enabled.
FFX_BRIXELIZER_CONTEXT_FLAG_ALL_DEBUG = FFX_BRIXELIZER_CONTEXT_FLAG_DEBUG_CONTEXT_READBACK_BUFFERS | FFX_BRIXELIZER_CONTEXT_FLAG_DEBUG_CASCADE_READBACK_BUFFERS | FFX_BRIXELIZER_CONTEXT_FLAG_DEBUG_AABBS, ///< Create a context with all debugging features enabled.
} FfxBrixelizerContextFlags;
/// Flags used for creating Brixelizer jobs. Determines whether a job is a submission of geometry or invalidating
/// an area described by an AABB.
///
/// @ingroup ffxBrixelizer
typedef enum FfxBrixelizerRawJobFlags {
FFX_BRIXELIZER_RAW_JOB_FLAG_NONE = 0u,
FFX_BRIXELIZER_RAW_JOB_FLAG_INVALIDATE = 1u << 2u,
} FfxBrixelizerRawJobFlags;
/// Flags used for creating Brixelizer instances.
///
/// @ingroup ffxBrixelizer
typedef enum FfxBrixelizerRawInstanceFlags {
FFX_BRIXELIZER_RAW_INSTANCE_FLAG_NONE = 0u,
FFX_BRIXELIZER_RAW_INSTANCE_FLAG_USE_INDEXLESS_QUAD_LIST = 1u << 1u,
} FfxBrixelizerRawInstanceFlags;
/// A structure encapsulating the FidelityFX Brixelizer context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by Brixelizer.
///
/// The <c><i>FfxBrixelizerRawContext</i></c> object should have a lifetime matching
/// your use of Brixelizer. Before destroying the Brixelizer context care
/// should be taken to ensure the GPU is not accessing the resources created
/// or used by Brixelizer. It is therefore recommended that the GPU is idle
/// before destroying the Brixelizer context.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerRawContext
{
uint32_t data[FFX_BRIXELIZER_RAW_CONTEXT_SIZE];
} FfxBrixelizerRawContext;
/// A structure encapsulating the parameters for creating a Brixelizer context.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerRawContextDescription
{
size_t maxDebugAABBs; ///< The maximum number of AABBs that can be drawn in debug mode. Note to use debug AABBs the flag <c><i>FFX_BRIXELIZER_CONTEXT_FLAG</i></c> must be passed at context creation.
FfxBrixelizerContextFlags flags; ///< A combination of <c><i>FfxBrixelizerContextFlags</i></c> specifying options for the context.
FfxInterface backendInterface; ///< An FfxInterface representing the FidelityFX backend interface.
} FfxBrixelizerRawContextDescription;
/// A structure encapsulating the parameters for creating a Brixelizer cascade.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerRawCascadeDescription
{
float brickSize; ///< The edge size of a brick in world units.
float cascadeMin[3]; ///< Corner of the first brick.
uint32_t index; ///< Index of the cascade.
} FfxBrixelizerRawCascadeDescription;
/// A structure describing a Brixelizer job.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerRawJobDescription
{
float aabbMin[3]; ///< The mimimum corner of the AABB of the job.
float aabbMax[3]; ///< The maximum corner of the AABB of the job.
uint32_t flags; ///< Flags for the job (to be set from FfxBrixelizerRawJobFlags).
uint32_t instanceIdx; ///< The ID for an instance for the job.
} FfxBrixelizerRawJobDescription;
/// A structure encapsulating the parameters for updating a Brixelizer cascade.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerRawCascadeUpdateDescription
{
uint32_t maxReferences; ///< storage for triangle->voxel references
uint32_t triangleSwapSize; ///< scratch storage for triangles
uint32_t maxBricksPerBake; ///< max SDF brick baked per update
int32_t cascadeIndex; ///< Target Cascade
const FfxBrixelizerRawJobDescription *jobs; ///< A pointer to an array of jobs.
size_t numJobs; ///< The number of jobs in the array pointed to by jobs.
float cascadeMin[3]; ///< Lower corner of the first brick in world space.
int32_t clipmapOffset[3]; ///< Changing that invalidates portion of the cascade. it's an offset in the voxel->brick table.
uint32_t flags; ///< See FfxBrixelizerCascadeUpdateFlags.
} FfxBrixelizerRawCascadeUpdateDescription;
/// A structure encapsulating the parameters for an instance to be added to a
/// Brixelizer context.
///
/// @ingroup ffxBrixelizer
typedef struct FfxBrixelizerRawInstanceDescription
{
float aabbMin[3]; ///< The minimum coordinates of an AABB surrounding the instance.
float aabbMax[3]; ///< The maximum coordinates of an AABB surrounding the instance.
FfxFloat32x3x4 transform; ///< A tranform of the instance into world space. The transform is in row major order.
FfxIndexFormat indexFormat; ///< The format of the index buffer. Accepted formats are FFX_INDEX_UINT16 or FFX_INDEX_UINT32.
uint32_t indexBuffer; ///< The index of the index buffer set with ffxBrixelizerContextSetBuffer.
uint32_t indexBufferOffset; ///< An offset into the index buffer.
uint32_t triangleCount; ///< The count of triangles in the index buffer.
uint32_t vertexBuffer; ///< The index of the vertex buffer set with ffxBrixelizerContextSetBuffer.
uint32_t vertexStride; ///< The stride of the vertex buffer in bytes.
uint32_t vertexBufferOffset; ///< An offset into the vertex buffer.
uint32_t vertexCount; ///< The count of vertices in the vertex buffer.
FfxSurfaceFormat vertexFormat; ///< The format of vertices in the vertex buffer. Accepted values are FFX_SURFACE_FORMAT_R16G16B16A16_FLOAT and FFX_SURFACE_FORMAT_R32G32B32A32_FLOAT.
uint32_t flags; ///< Flags for the instance. See <c><i>FfxBrixelizerRawInstanceFlags</i></c>.
FfxBrixelizerInstanceID *outInstanceID; ///< A pointer to an <c><i>FfxBrixelizerInstanceID</i></c> to be filled with the instance ID assigned for the instance.
} FfxBrixelizerRawInstanceDescription;
/// Get the size in bytes needed for an <c><i>FfxBrixelizerRawContext</i></c> struct.
/// Note that this function is provided for consistency, and the size of the
/// <c><i>FfxBrixelizerRawContext</i></c> is a known compile time value which can be
/// obtained using <c><i>sizeof(FfxBrixelizerRawContext)</i></c>.
///
/// @return The size in bytes of an <c><i>FfxBrixelizerRawContext</i></c> struct.
///
/// @ingroup ffxBrixelizer
inline size_t ffxBrixelizerRawGetContextSize()
{
return sizeof(FfxBrixelizerRawContext);
}
/// Create a FidelityFX Brixelizer context from the parameters
/// specified to the <c><i>FfxBrixelizerRawContextDescription</i></c> struct.
///
/// The context structure is the main object used to interact with the Brixelizer API,
/// and is responsible for the management of the internal resources used by the
/// Brixelizer algorithm. When this API is called, multiple calls will be made via
/// the pointers contained in the <b><i>backendInterface</i></b> structure. This
/// backend will attempt to retrieve the device capabilities, and create the internal
/// resources, and pipelines required by Brixelizer.
///
/// Depending on the parameters passed in via the <b><i>contextDescription</b></i> a
/// different set of resources and pipelines may be requested by the callback functions.
///
/// The <c><i>FfxBrixelizerRawContext</i></c> should be destroyed when use of it is completed.
/// To destroy the context you should call <c><i>ffxBrixelizerContextDestroy</i></c>.
///
/// @param [out] context A pointer to a <c><i>FfxBrixelizerRawContext</i></c> to populate.
/// @param [in] contextDescription A pointer to a <c><i>FfxBrixelizerRawContextDescription</i></c> specifying the parameters for context creation.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because <c><i>contextDescription->backendInterface</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error from the backend.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextCreate(FfxBrixelizerRawContext* context, const FfxBrixelizerRawContextDescription* contextDescription);
/// Destroy the FidelityFX Brixelizer context.
///
/// @param [out] context A pointer to a <c><i>FfxBrixelizerRawContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The <c><i>context</i></c> pointer provided was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextDestroy(FfxBrixelizerRawContext* context);
/// Get an <c><i>FfxBrixelizerContextInfo</i></c> structure with the details for <c><i>context</i></c>.
/// This call is intended to be used to fill in a constant buffer necessary for making ray
/// queries.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to receive the <c><i>FfxBrixelizerContextInfo</i></c> of.
/// @param [out] contextInfo A <c><i>FfxBrixelizerContextInfo</i></c> struct to be filled in.
///
/// @retval
/// FFX_OK The operation was successful.
/// @retval
/// FFX_ERROR_INVALID_POINTER The <c><i>context</i></c> pointer provided was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextGetInfo(FfxBrixelizerRawContext* context, FfxBrixelizerContextInfo* contextInfo);
/// Create a cascade for use with Brixelizer.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to create a cascade for.
/// @param [in] cascadeDescription A <c><i>FfxBrixelizerRawCascadeDescription</i></c> struct specifying the parameters for cascade creation.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because one of <c><i>context</i></c>, <c><i>cascadeDescription</i></c>, c><i>cascadeDescription->aabbTree</i></c> or c><i>cascadeDescription->brickMap</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation encountered an error in the backend.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextCreateCascade(FfxBrixelizerRawContext* context, const FfxBrixelizerRawCascadeDescription* cascadeDescription);
/// Destroy a cascade previously created with <c><i>ffxBrixelizerContextCreateCascade</i></c>.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to delete a cascade for.
/// @param [in] cascadeIndex The index of the cascade to delete.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextDestroyCascade(FfxBrixelizerRawContext* context, uint32_t cascadeIndex);
/// Reset a cascade previously created with <c><i>ffxBrixelizerContextCreateCascade</i></c>.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to reset a cascade for.
/// @param [in] cascadeIndex The index of the cascade to reset.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT No cascade with index <c><i>cascadeIndex</i></c> exists.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextResetCascade(FfxBrixelizerRawContext* context, uint32_t cascadeIndex);
/// Begin constructing GPU commands for updating SDF acceleration structures with Brixelizer.
/// Must be called between calls to <c><i>ffxBrixelizerContextBegin</i></c> and <c><i>ffxBrixelizerContextEnd</i></c>.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to begin a frame for.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the <c><i>FfxDevice</i></c> provided to the <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextBegin(FfxBrixelizerRawContext* context, FfxBrixelizerResources resources);
/// End construcring GPU commands for updating the SDF acceleration structures with Brixelizer.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to end a frame for.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the <c><i>FfxDevice</i></c> provided to the <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextEnd(FfxBrixelizerRawContext* context);
/// Record GPU commands to a <c><i>FfxCommandList</i></c> for updating acceleration structures with Brixelizer.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to record GPU commands from.
/// @param [out] cmdList The <c><i>FfxCommandList</i></c> to record commands to.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the <c><i>FfxDevice</i></c> provided to the <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextSubmit(FfxBrixelizerRawContext* context, FfxCommandList cmdList);
/// Get the size in bytes needed from a <c><i>FfxResource</i></c> to be used as a scratch buffer in a cascade update.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to calculate the required scratch buffer size for.
/// @param [in] cascadeUpdateDescription A <c><i>FfxBrixelizerRawCascadeUpdateDescription</i></c> struct with the parameters for the cascade update.
/// @param [out] size A <c><i>size_t</i></c> to store the required scratch buffer size to.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> or <c><i>cascadeUpdateDescription</c></i> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the <c><i>FfxDevice</i></c> provided to the <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextGetScratchMemorySize(FfxBrixelizerRawContext* context, const FfxBrixelizerRawCascadeUpdateDescription* cascadeUpdateDescription, size_t* size);
/// Update a cascade in a Brixelizer context.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to perform the cascade update on.
/// @param [in] cascadeUpdateDescription A <c><i>FfxBrixelizerRawCascadeUpdateDescription</i></c> struct with the parameters for the cascade update.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> or <c><i>cascadeUpdateDescription</c></i> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the <c><i>FfxDevice</i></c> provided to the <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextUpdateCascade(FfxBrixelizerRawContext* context, const FfxBrixelizerRawCascadeUpdateDescription* cascadeUpdateDescription);
/// Merge two cascades in a Brixelizer context.
/// Must be called between calls to <c><i>ffxBrixelizerRawContextBegin</i></c> and <c><i>ffxBrixelizerRawContextEnd</i></c>.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to merge cascades for.
/// @param [in] srcCascadeAIdx The index of the first source cascade.
/// @param [in] srcCascadeBIdx A <c><i>FfxResource</i></c> to store the required scratch buffer size to.
/// @param [in] dstCascadeIdx A <c><i>FfxResource</i></c> to store the required scratch buffer size to.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the <c><i>FfxDevice</i></c> provided to the <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextMergeCascades(FfxBrixelizerRawContext* context, uint32_t src_cascade_A_idx, uint32_t src_cascade_B_idx, uint32_t dst_cascade_idx);
/// Build an AABB tree for a cascade in a Brixelizer context.
/// Must be called between calls to <c><i>ffxBrixelizerRawContextBegin</i></c> and <c><i>ffxBrixelizerRawContextEnd</i></c>.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to build an AABB tree for.
/// @param [in] cascadeIndex The index of the cascade to build the AABB tree of.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the <c><i>FfxDevice</i></c> provided to the <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextBuildAABBTree(FfxBrixelizerRawContext* context, uint32_t cascadeIndex);
/// Create a debug visualization output of a Brixelizer context.
/// Must be called between calls to <c><i>ffxBrixelizerRawContextBegin</i></c> and <c><i>ffxBrixelizerRawContextEnd</i></c>.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to create a debug visualization for.
/// @param [in] debugVisualizationDescription A <c><i>FfxBrixelizerDebugVisualizationDescription</i></c> providing the parameters for the debug visualization.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> or <c><i>debugVisualizationDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the <c><i>FfxDevice</i></c> provided to the <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextDebugVisualization(FfxBrixelizerRawContext* context, const FfxBrixelizerDebugVisualizationDescription* debugVisualizationDescription);
/// Get the debug counters from a Brixelizer context.
/// Note to use this function the flag <c><i>FFX_BRIXELIZER_CONTEXT_FLAG_DEBUG_CONTEXT_READBACK_BUFFERS</i></c> must
/// be passed at context creation.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to read the debug counters of.
/// @param [out] debugCounters A <c><i>FfxBrixelizerDebugCounters</i></c> struct to read the debug counters to.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> or <c><i>debugCounters</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextGetDebugCounters(FfxBrixelizerRawContext* context, FfxBrixelizerDebugCounters* debugCounters);
/// Get the cascade counters from a Brixelizer context.
/// Note to use this function the flag <c><i>FFX_BRIXELIZER_CONTEXT_FLAG_DEBUG_CASCADE_READBACK_BUFFERS</i></c> must
/// be passed at context creation.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to read the cascade counters of.
/// @param [in] cascadeIndex The index of the cascade to read the cascade counters of.
/// @param [out] counters A <c><i>FfxBrixelizerScratchCounters</i></c> struct to read the cascade counters to.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> or <c><i>counters</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextGetCascadeCounters(FfxBrixelizerRawContext* context, uint32_t cascadeIndex, FfxBrixelizerScratchCounters* counters);
/// Create an instance in a Brixelizer context.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to create an instance for.
/// @param [in] instanceDescription A <c><i>FfxBrixelizerRawInstanceDescription</i></c> struct with the parameters for the instance to create.
/// @param [out] numInstanceDescriptions A <c><i>FfxBrixelizerInstanceID</i></c> to read the instance ID to.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> or <c><i>instanceDescription</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextCreateInstances(FfxBrixelizerRawContext* context, const FfxBrixelizerRawInstanceDescription* instanceDescriptions, uint32_t numInstanceDescriptions);
/// Destroy an instance in a Brixelizer context.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to delete an instance for.
/// @param [in] instanceId The <c><i>FfxBrixelizerInstanceID</i></c> of the instance to delete.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextDestroyInstances(FfxBrixelizerRawContext* context, const FfxBrixelizerInstanceID* instanceIDs, uint32_t numInstanceIDs);
/// Flush all instances added to the Brixelizer context with <c><i>ffxBrixelizerRawContextCreateInstance</i></c> to the GPU.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to flush the instances for.
/// @param [in] cmdList An <c><i>FfxCommandList</i></c> to record GPU commands to.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextFlushInstances(FfxBrixelizerRawContext* context, FfxCommandList cmdList);
/// Register a vertex or index buffer for use with Brixelizer.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to register a buffer for.
/// @param [in] buffer An <c><i>FfxResource</i></c> with the buffer to be set.
/// @param [out] index The index of the registered buffer.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextRegisterBuffers(FfxBrixelizerRawContext* context, const FfxBrixelizerBufferDescription* bufferDescs, uint32_t numBufferDescs);
/// Unregister a previously registered vertex or index buffer.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to unregister the buffer from
/// @param [in] index The index of the buffer to unregister.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextUnregisterBuffers(FfxBrixelizerRawContext* context, const uint32_t* indices, uint32_t numIndices);
/// Get the index of the recommended cascade to update given the total number of cascades and current frame.
/// Follows the pattern 0 1 0 2 0 1 0 3 0 etc. If 0 is the most detailed cascade and <c><i>maxCascades - 1</i></c>
/// is the least detailed cascade this ordering updates more detailed cascades more often.
///
/// @param [out] context The <c><i>FfxBrixelizerRawContext</i></c> to set a buffer for.
/// @param [in] scratchBuffer A <c><i>FfxResource</i></c> for use as a scratch buffer.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API FfxErrorCode ffxBrixelizerRawContextRegisterScratchBuffer(FfxBrixelizerRawContext* context, FfxResource scratchBuffer);
/// Get the index of the recommended cascade to update given the total number of cascades and current frame.
/// Follows the pattern 0 1 0 2 0 1 0 3 0 etc. If 0 is the most detailed cascade and <c><i>maxCascades - 1</i></c>
/// is the least detailed cascade this ordering updates more detailed cascades more often.
///
/// @param [in] frameIndex The current frame index.
/// @param [in] maxCascades The total number of cascades.
///
/// @retval The index of the cascade to update.
///
/// @ingroup ffxBrixelizer
FFX_API uint32_t ffxBrixelizerRawGetCascadeToUpdate(uint32_t frameIndex, uint32_t maxCascades);
/// Check whether an <c><i>FfxResource</i></c> is <c><i>NULL</i></c>.
///
/// @param [in] resource An <c><i>FfxResource</i></c> to check for nullness.
///
/// @retval <c><i>true</c></i> if <c><i>resource</i></c> is <c><i>NULL</i></c> else <c><i>false</i></c>.
///
/// @ingroup ffxBrixelizer
FFX_API bool ffxBrixelizerRawResourceIsNull(FfxResource resource);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxBrixelizer
FFX_API FfxVersionNumber ffxBrixelizerGetEffectVersion();
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,329 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 the interface for the backend of the Brixelizer GI API.
#include <FidelityFX/host/ffx_interface.h>
#include <FidelityFX/host/ffx_brixelizer_raw.h>
/// @defgroup ffxBrixgi FidelityFX Brixelizer GI
/// FidelityFX Brixelizer GI runtime library
///
/// @ingroup SDKComponents
/// FidelityFX Brixelizer GI major version.
///
/// @ingroup ffxBrixgi
#define FFX_BRIXELIZER_GI_VERSION_MAJOR (1)
/// FidelityFX Brixelizer GI minor version.
///
/// @ingroup ffxBrixgi
#define FFX_BRIXELIZER_GI_VERSION_MINOR (0)
/// FidelityFX Brixelizer GI patch version.
///
/// @ingroup ffxBrixgi
#define FFX_BRIXELIZER_GI_VERSION_PATCH (1)
/// The size of the context specified in 32bit values.
///
/// @ingroup ffxBrixgi
#define FFX_BRIXELIZER_GI_CONTEXT_SIZE (210000)
/// FidelityFX Brixelizer GI context count
///
/// Defines the number of internal effect contexts required by Brixelizer
///
/// @ingroup ffxBrixgi
#define FFX_BRIXELIZER_GI_CONTEXT_COUNT 1
#ifdef __cplusplus
extern "C" {
#endif
/// A structure encapsulating the FidelityFX Brixelizer GI context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by Brixelizer GI.
///
/// The <c><i>FfxBrixelizerGIContext</i></c> object should have a lifetime matching
/// your use of Brixelizer GI. Before destroying the Brixelizer GI context care
/// should be taken to ensure the GPU is not accessing the resources created
/// or used by Brixelizer GI. It is therefore recommended that the GPU is idle
/// before destroying the Brixelizer GI context.
///
/// @ingroup ffxBrixgi
typedef struct FfxBrixelizerGIContext
{
uint32_t data[FFX_BRIXELIZER_GI_CONTEXT_SIZE];
} FfxBrixelizerGIContext;
/// An enumeration of flag bits used when creating an <c><i>FfxBrixelizerGIContext</i></c>.
/// See <c><i>FfxBrixelizerGIContextDescription</i></c>.
///
/// @ingroup ffxBrixgi
typedef enum FfxBrixelizerGIFlags
{
FFX_BRIXELIZER_GI_FLAG_DEPTH_INVERTED = (1 << 0), ///< Indicates input resources were generated with inverted depth.
FFX_BRIXELIZER_GI_FLAG_DISABLE_SPECULAR = (1 << 1), ///< Disable specular GI.
FFX_BRIXELIZER_GI_FLAG_DISABLE_DENOISER = (1 << 2), ///< Disable denoising. Only allowed at native resolution.
} FfxBrixelizerGIFlags;
/// An enumeration of the quality modes supported by FidelityFX Brixelizer GI.
///
/// @ingroup ffxBrixgi
typedef enum FfxBrixelizerGIInternalResolution
{
FFX_BRIXELIZER_GI_INTERNAL_RESOLUTION_NATIVE, ///< Output GI at native resolution.
FFX_BRIXELIZER_GI_INTERNAL_RESOLUTION_75_PERCENT, ///< Output GI at 75% of native resolution.
FFX_BRIXELIZER_GI_INTERNAL_RESOLUTION_50_PERCENT, ///< Output GI at 50% of native resolution.
FFX_BRIXELIZER_GI_INTERNAL_RESOLUTION_25_PERCENT, ///< Output GI at 25% of native resolution.
} FfxBrixelizerGIInternalResolution;
/// A structure encapsulating the parameters used for creating an
/// <c><i>FfxBrixelizerGIContext</i></c>.
///
/// @ingroup ffxBrixgi
typedef struct FfxBrixelizerGIContextDescription
{
FfxBrixelizerGIFlags flags; ///< A bit field representings various options.
FfxBrixelizerGIInternalResolution internalResolution; ///< The scale at which Brixelizer GI will output GI at internally. The output will be internally upscaled to the specified displaySize.
FfxDimensions2D displaySize; ///< The size of the presentation resolution targeted by the upscaling process.
FfxInterface backendInterface; ///< An implementation of the FidelityFX backend for use with Brixelizer.
} FfxBrixelizerGIContextDescription;
/// A structure encapsulating the parameters used for computing a dispatch by the
/// Brixelizer GI context.
///
/// @ingroup ffxBrixgi
typedef struct FfxBrixelizerGIDispatchDescription
{
FfxFloat32x4x4 view; ///< The view matrix for the scene in row major order.
FfxFloat32x4x4 projection; ///< The projection matrix for the scene in row major order.
FfxFloat32x4x4 prevView; ///< The view matrix for the previous frame of the scene in row major order.
FfxFloat32x4x4 prevProjection; ///< The projection matrix for the scene in row major order.
FfxFloat32x3 cameraPosition; ///< A 3-dimensional vector representing the position of the camera.
FfxUInt32 startCascade; ///< The index of the start cascade for use with ray marching with Brixelizer.
FfxUInt32 endCascade; ///< The index of the end cascade for use with ray marching with Brixelizer.
FfxFloat32 rayPushoff; ///< The distance from a surface along the normal vector to offset the diffuse ray origin.
FfxFloat32 sdfSolveEps; ///< The epsilon value for ray marching to be used with Brixelizer for diffuse rays.
FfxFloat32 specularRayPushoff; ///< The distance from a surface along the normal vector to offset the specular ray origin.
FfxFloat32 specularSDFSolveEps; ///< The epsilon value for ray marching to be used with Brixelizer for specular rays.
FfxFloat32 tMin; ///< The TMin value for use with Brixelizer.
FfxFloat32 tMax; ///< The TMax value for use with Brixelizer.
FfxResource environmentMap; ///< The environment map.
FfxResource prevLitOutput; ///< The lit output from the previous frame.
FfxResource depth; ///< The input depth buffer.
FfxResource historyDepth; ///< The previous frame input depth buffer.
FfxResource normal; ///< The input normal buffer.
FfxResource historyNormal; ///< The previous frame input normal buffer.
FfxResource roughness; ///< The resource containing roughness information.
FfxResource motionVectors; ///< The input motion vectors texture.
FfxResource noiseTexture; ///< The input blue noise texture.
FfxFloat32 normalsUnpackMul; ///< A multiply factor to transform the normal to the space expected by Brixelizer GI.
FfxFloat32 normalsUnpackAdd; ///< An offset to transform the normal to the space expected by Brixelizer GI.
FfxBoolean isRoughnessPerceptual; ///< A boolean to describe the space used to store roughness in the materialParameters texture. If false, we assume roughness squared was stored in the Gbuffer.
FfxUInt32 roughnessChannel; ///< The channel to read the roughness from the roughness texture
FfxFloat32 roughnessThreshold; ///< Regions with a roughness value greater than this threshold won't spawn specular rays.
FfxFloat32 environmentMapIntensity;///< The value to scale the contribution from the environment map.
FfxFloatCoords2D motionVectorScale; ///< The scale factor to apply to motion vectors.
FfxResource sdfAtlas; ///< The SDF Atlas resource used by Brixelizer.
FfxResource bricksAABBs; ///< The brick AABBs resource used by Brixelizer.
FfxResource cascadeAABBTrees[24]; ///< The cascade AABB tree resources used by Brixelizer.
FfxResource cascadeBrickMaps[24]; ///< The cascade brick map resources used by Brixelizer.
FfxResource outputDiffuseGI; ///< A texture to write the output diffuse GI calculated by Brixelizer GI.
FfxResource outputSpecularGI; ///< A texture to write the output specular GI calculated by Brixelizer GI.
FfxBrixelizerRawContext *brixelizerContext; ///< A pointer to the Brixelizer context for use with Brixelizer GI.
} FfxBrixelizerGIDispatchDescription;
/// An enumeration of which output mode to be used by Brixelizer GI debug visualization.
/// See <c><i>FfxBrixelizerGIDebugDescription</i></c>.
///
/// @ingroup ffxBrixgi
typedef enum FfxBrixelizerGIDebugMode
{
FFX_BRIXELIZER_GI_DEBUG_MODE_RADIANCE_CACHE, ///< Draw the radiance cache.
FFX_BRIXELIZER_GI_DEBUG_MODE_IRRADIANCE_CACHE, ///< Draw the irradiance cache.
} FfxBrixelizerGIDebugMode;
/// A structure encapsulating the parameters for drawing a debug visualization.
///
/// @ingroup ffxBrixgi
typedef struct FfxBrixelizerGIDebugDescription
{
FfxFloat32x4x4 view; ///< The view matrix for the scene in row major order.
FfxFloat32x4x4 projection; ///< The projection matrix for the scene in row major order.
FfxUInt32 startCascade; ///< The index of the start cascade for use with ray marching with Brixelizer.
FfxUInt32 endCascade; ///< The index of the end cascade for use with ray marching with Brixelizer.
FfxUInt32 outputSize[2]; ///< The dimensions of the output texture.
FfxBrixelizerGIDebugMode debugMode; ///< The mode for the debug visualization. See <c><i>FfxBrixelizerGIDebugMode</i></c>.
FfxFloat32 normalsUnpackMul; ///< A multiply factor to transform the normal to the space expected by Brixelizer GI.
FfxFloat32 normalsUnpackAdd; ///< An offset to transform the normal to the space expected by Brixelizer GI.
FfxResource depth; ///< The input depth buffer.
FfxResource normal; ///< The input normal buffer.
FfxResource sdfAtlas; ///< The SDF Atlas resource used by Brixelizer.
FfxResource bricksAABBs; ///< The brick AABBs resource used by Brixelizer.
FfxResource cascadeAABBTrees[24]; ///< The cascade AABB tree resources used by Brixelizer.
FfxResource cascadeBrickMaps[24]; ///< The cascade brick map resources used by Brixelizer.
FfxResource outputDebug; ///< The output texture for the debug visualization.
FfxBrixelizerRawContext* brixelizerContext; ///< A pointer to the Brixelizer context for use with Brixelizer GI.
} FfxBrixelizerGIDebugDescription;
/// An enumeration of all the passes which constitute the Brixelizer algorithm.
///
/// Brixelizer GI is implemented as a composite of several compute passes each
/// computing a key part of the final result. Each call to the
/// <c><i>FfxBrixelizerScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single pass included in <c><i>FfxBrixelizerPass</i></c>. For a
/// more comprehensive description of each pass, please refer to the Brixelizer
/// reference documentation.
///
/// @ingroup ffxBrixgi
typedef enum FfxBrixelizerGIPass
{
FFX_BRIXELIZER_GI_PASS_BLUR_X,
FFX_BRIXELIZER_GI_PASS_BLUR_Y,
FFX_BRIXELIZER_GI_PASS_CLEAR_CACHE,
FFX_BRIXELIZER_GI_PASS_EMIT_IRRADIANCE_CACHE,
FFX_BRIXELIZER_GI_PASS_EMIT_PRIMARY_RAY_RADIANCE,
FFX_BRIXELIZER_GI_PASS_FILL_SCREEN_PROBES,
FFX_BRIXELIZER_GI_PASS_INTERPOLATE_SCREEN_PROBES,
FFX_BRIXELIZER_GI_PASS_PREPARE_CLEAR_CACHE,
FFX_BRIXELIZER_GI_PASS_PROJECT_SCREEN_PROBES,
FFX_BRIXELIZER_GI_PASS_PROPAGATE_SH,
FFX_BRIXELIZER_GI_PASS_REPROJECT_GI,
FFX_BRIXELIZER_GI_PASS_REPROJECT_SCREEN_PROBES,
FFX_BRIXELIZER_GI_PASS_SPAWN_SCREEN_PROBES,
FFX_BRIXELIZER_GI_PASS_SPECULAR_PRE_TRACE,
FFX_BRIXELIZER_GI_PASS_SPECULAR_TRACE,
FFX_BRIXELIZER_GI_PASS_DEBUG_VISUALIZATION,
FFX_BRIXELIZER_GI_PASS_GENERATE_DISOCCLUSION_MASK,
FFX_BRIXELIZER_GI_PASS_DOWNSAMPLE,
FFX_BRIXELIZER_GI_PASS_UPSAMPLE,
FFX_BRIXELIZER_GI_PASS_COUNT ///< The number of passes performed by Brixelizer GI.
} FfxBrixelizerGIPass;
/// Get the size in bytes needed for an <c><i>FfxBrixelizerGIContext</i></c> struct.
/// Note that this function is provided for consistency, and the size of the
/// <c><i>FfxBrixelizerGIContext</i></c> is a known compile time value which can be
/// obtained using <c><i>sizeof(FfxBrixelizerGIContext)</i></c>.
///
/// @return The size in bytes of an <c><i>FfxBrixelizerGIContext</i></c> struct.
///
/// @ingroup ffxBrixgi
inline size_t ffxBrixelizerGIGetContextSize()
{
return sizeof(FfxBrixelizerGIContext);
}
/// Create a FidelityFX Brixelizer GI context from the parameters
/// specified to the <c><i>FfxBrixelizerGIContextDescription</i></c> struct.
///
/// The context structure is the main object used to interact with the Brixelizer GI API,
/// and is responsible for the management of the internal resources used by the
/// Brixelizer GI algorithm. When this API is called, multiple calls will be made via
/// the pointers contained in the <b><i>backendInterface</i></b> structure. This
/// backend will attempt to retrieve the device capabilities, and create the internal
/// resources, and pipelines required by Brixelizer GI.
///
/// Depending on the parameters passed in via the <b><i>pContextDescription</b></i> a
/// different set of resources and pipelines may be requested by the callback functions.
///
/// The <c><i>FfxBrixelizerGIContext</i></c> should be destroyed when use of it is completed.
/// To destroy the context you should call <c><i>ffxBrixelizerGIContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxBrixelizerGIContext</i></c> to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxBrixelizerGIContextDescription</i></c> specifying the parameters for context creation.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The operation failed because either <c><i>pContext</i></c> or <c><i>pContextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because <c><i>pContextDescription->backendInterface</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error from the backend.
///
/// @ingroup ffxBrixgi
FFX_API FfxErrorCode ffxBrixelizerGIContextCreate(FfxBrixelizerGIContext* pContext, const FfxBrixelizerGIContextDescription* pContextDescription);
/// Destroy the FidelityFX Brixelizer GI context.
///
/// @param [out] pContext A pointer to a <c><i>FfxBrixelizerGIContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER The <c><i>pContext</i></c> pointer provided was <c><i>NULL</i></c>.
///
/// @ingroup ffxBrixgi
FFX_API FfxErrorCode ffxBrixelizerGIContextDestroy(FfxBrixelizerGIContext* pContext);
/// Perform an update of Brixelizer GI, recording GPU commands to a command list.
///
/// @param [inout] context An <c><i>FfxBrixelizerGIContext</i></c> containing the Brixelizer GI context.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxBrixelizerGIDispatchDescription</i></c> describing the dispatch to compute.
/// @param [inout] pCommandList An <c><i>FfxCommandList</i></c> to write GPU commands to.
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixgi
FFX_API FfxErrorCode ffxBrixelizerGIContextDispatch(FfxBrixelizerGIContext* pContext, const FfxBrixelizerGIDispatchDescription* pDispatchDescription, FfxCommandList pCommandList);
/// Make a debug visualization from the <c><i>FfxBrixelizerGIContext</i></c>.
///
/// @param [inout] context An <c><i>FfxBrixelizerGIContext</i></c> containing the Brixelizer GI context.
/// @param [in] pDebugDescription A pointer to a <c><i>FfxBrixelizerGIDebugDescription</i></c> describing the debug visualization to draw.
/// @param [inout] pCommandList An <c><i>FfxCommandList</i></c> to write GPU commands to.
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxBrixgi
FFX_API FfxErrorCode ffxBrixelizerGIContextDebugVisualization(FfxBrixelizerGIContext* pContext, const FfxBrixelizerGIDebugDescription* pDebugDescription, FfxCommandList pCommandList);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxBrixgi
FFX_API FfxVersionNumber ffxBrixelizerGIGetEffectVersion();
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,533 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 the interface for the backend of the API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup FfxCacao FidelityFX CACAO
/// FidelityFX Combined Adaptive Compute Ambient Occlusion runtime library.
///
/// @ingroup SDKComponents
/// FidelityFX CACAO major version.
///
/// @ingroup FfxCacao
#define FFX_CACAO_VERSION_MAJOR (1)
/// FidelityFX CACAO minor version.
///
/// @ingroup FfxCacao
#define FFX_CACAO_VERSION_MINOR (4)
/// FidelityFX CACAO patch version.
///
/// @ingroup FfxCacao
#define FFX_CACAO_VERSION_PATCH (0)
// ============================================================================
// Prepare
/// Width of the PREPARE_DEPTHS_AND_MIPS pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_PREPARE_DEPTHS_AND_MIPS_WIDTH 8
/// Height of the PREPARE_DEPTHS_AND_MIPS pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_PREPARE_DEPTHS_AND_MIPS_HEIGHT 8
/// Width of the PREPARE_DEPTHS pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_PREPARE_DEPTHS_WIDTH 8
/// Height of the PREPARE_DEPTHS pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_PREPARE_DEPTHS_HEIGHT 8
/// Width of the PREPARE_DEPTHS_HALF pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_PREPARE_DEPTHS_HALF_WIDTH 8
/// Height of the PREPARE_DEPTHS_HALF pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_PREPARE_DEPTHS_HALF_HEIGHT 8
/// Width of the PREPARE_NORMALS pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_PREPARE_NORMALS_WIDTH 8
/// Height of the PREPARE_NORMALS pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_PREPARE_NORMALS_HEIGHT 8
/// Width of the PREPARE_NORMALS_FROM_INPUT_NORMALS pass tile size.
///
/// @ingroup FfxCacao
#define PREPARE_NORMALS_FROM_INPUT_NORMALS_WIDTH 8
/// Height of the PREPARE_NORMALS_FROM_INPUT_NORMALS pass tile size.
///
/// @ingroup FfxCacao
#define PREPARE_NORMALS_FROM_INPUT_NORMALS_HEIGHT 8
// ============================================================================
// SSAO Generation
/// Width of the GENERATE_SPARSE pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_GENERATE_SPARSE_WIDTH 4
/// Height of the GENERATE_SPARSE pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_GENERATE_SPARSE_HEIGHT 16
/// Width of the GENERATE pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_GENERATE_WIDTH 8
/// Height of the GENERATE pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_GENERATE_HEIGHT 8
// ============================================================================
// Importance Map
/// Width of the IMPORTANCE_MAP pass tile size.
///
/// @ingroup FfxCacao
#define IMPORTANCE_MAP_WIDTH 8
/// Height of the IMPORTANCE_MAP pass tile size.
///
/// @ingroup FfxCacao
#define IMPORTANCE_MAP_HEIGHT 8
/// Width of the IMPORTANCE_MAP_A pass tile size.
///
/// @ingroup FfxCacao
#define IMPORTANCE_MAP_A_WIDTH 8
/// Height of the IMPORTANCE_MAP_A pass tile size.
///
/// @ingroup FfxCacao
#define IMPORTANCE_MAP_A_HEIGHT 8
/// Width of the IMPORTANCE_MAP_B pass tile size.
///
/// @ingroup FfxCacao
#define IMPORTANCE_MAP_B_WIDTH 8
/// Height of the IMPORTANCE_MAP_B pass tile size.
///
/// @ingroup FfxCacao
#define IMPORTANCE_MAP_B_HEIGHT 8
// ============================================================================
// Edge Sensitive Blur
/// Width of the BLUR pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_BLUR_WIDTH 16
/// Height of the BLUR pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_BLUR_HEIGHT 16
// ============================================================================
// Apply
/// Width of the APPLY pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_APPLY_WIDTH 8
/// Height of the APPLY pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_APPLY_HEIGHT 8
// ============================================================================
// Bilateral Upscale
/// Width of the BILATERAL_UPSCALE pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_BILATERAL_UPSCALE_WIDTH 8
/// Height of the BILATERAL_UPSCALE pass tile size.
///
/// @ingroup FfxCacao
#define FFX_CACAO_BILATERAL_UPSCALE_HEIGHT 8
/// The size of the context specified in 32bit values.
///
/// @ingroup FfxCacao
#define FFX_CACAO_CONTEXT_SIZE (301054)
/// FidelityFX CACAO context count.
///
/// Defines the number of internal effect contexts required by CACAO.
///
/// @ingroup FfxCacao
#define FFX_CACAO_CONTEXT_COUNT 1
/// An enumeration of the passes which constitutes the CACAO algorithm.
///
/// @ingroup FfxCacao
typedef enum FfxCacaoPass
{
FFX_CACAO_PASS_CLEAR_LOAD_COUNTER = 0, ///<
FFX_CACAO_PASS_PREPARE_DOWNSAMPLED_DEPTHS = 1, ///<
FFX_CACAO_PASS_PREPARE_NATIVE_DEPTHS = 2, ///<
FFX_CACAO_PASS_PREPARE_DOWNSAMPLED_DEPTHS_AND_MIPS = 3, ///<
FFX_CACAO_PASS_PREPARE_NATIVE_DEPTHS_AND_MIPS = 4, ///<
FFX_CACAO_PASS_PREPARE_DOWNSAMPLED_NORMALS = 5, ///<
FFX_CACAO_PASS_PREPARE_NATIVE_NORMALS = 6, ///<
FFX_CACAO_PASS_PREPARE_DOWNSAMPLED_NORMALS_FROM_INPUT_NORMALS = 7, ///<
FFX_CACAO_PASS_PREPARE_NATIVE_NORMALS_FROM_INPUT_NORMALS = 8, ///<
FFX_CACAO_PASS_PREPARE_DOWNSAMPLED_DEPTHS_HALF = 9, ///<
FFX_CACAO_PASS_PREPARE_NATIVE_DEPTHS_HALF = 10, ///<
FFX_CACAO_PASS_GENERATE_Q0 = 11, ///<
FFX_CACAO_PASS_GENERATE_Q1 = 12, ///<
FFX_CACAO_PASS_GENERATE_Q2 = 13, ///<
FFX_CACAO_PASS_GENERATE_Q3 = 14, ///<
FFX_CACAO_PASS_GENERATE_Q3_BASE = 15, ///<
FFX_CACAO_PASS_GENERATE_IMPORTANCE_MAP = 16, ///<
FFX_CACAO_PASS_POST_PROCESS_IMPORTANCE_MAP_A = 17, ///<
FFX_CACAO_PASS_POST_PROCESS_IMPORTANCE_MAP_B = 18, ///<
FFX_CACAO_PASS_EDGE_SENSITIVE_BLUR_1 = 19, ///<
FFX_CACAO_PASS_EDGE_SENSITIVE_BLUR_2 = 20, ///<
FFX_CACAO_PASS_EDGE_SENSITIVE_BLUR_3 = 21, ///<
FFX_CACAO_PASS_EDGE_SENSITIVE_BLUR_4 = 22, ///<
FFX_CACAO_PASS_EDGE_SENSITIVE_BLUR_5 = 23, ///<
FFX_CACAO_PASS_EDGE_SENSITIVE_BLUR_6 = 24, ///<
FFX_CACAO_PASS_EDGE_SENSITIVE_BLUR_7 = 25, ///<
FFX_CACAO_PASS_EDGE_SENSITIVE_BLUR_8 = 26, ///<
FFX_CACAO_PASS_APPLY_NON_SMART_HALF = 27, ///<
FFX_CACAO_PASS_APPLY_NON_SMART = 28, ///<
FFX_CACAO_PASS_APPLY = 29, ///<
FFX_CACAO_PASS_UPSCALE_BILATERAL_5X5 = 30,
FFX_CACAO_PASS_COUNT ///< The number of passes in CACAO
} FfxCacaoPass;
/// The quality levels that FidelityFX CACAO can generate SSAO at. This affects the number of samples taken for generating SSAO.
///
/// @ingroup FfxCacao
typedef enum FfxCacaoQuality {
FFX_CACAO_QUALITY_LOWEST = 0,
FFX_CACAO_QUALITY_LOW = 1,
FFX_CACAO_QUALITY_MEDIUM = 2,
FFX_CACAO_QUALITY_HIGH = 3,
FFX_CACAO_QUALITY_HIGHEST = 4,
} FfxCacaoQuality;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxCacaoContext</i></c>. See <c><i>FfxCacaoContextDescription</i></c>.
///
/// @ingroup FfxCacao
typedef enum FfxCacaoInitializationFlagBits {
FFX_CACAO_ENABLE_APPLY_SMART = (1<<0), ///< A bit indicating to use smart application
} FfxCacaoInitializationFlagBits;
/// A structure for the settings used by FidelityFX CACAO. These settings may be updated with each draw call.
///
/// @ingroup FfxCacao
typedef struct FfxCacaoSettings {
float radius; ///< [0.0, ~ ] World (view) space size of the occlusion sphere.
float shadowMultiplier; ///< [0.0, 5.0] Effect strength linear multiplier.
float shadowPower; ///< [0.5, 5.0] Effect strength pow modifier.
float shadowClamp; ///< [0.0, 1.0] Effect max limit (applied after multiplier but before blur).
float horizonAngleThreshold; ///< [0.0, 0.2] Limits self-shadowing (makes the sampling area less of a hemisphere, more of a spherical cone, to avoid self-shadowing and various artifacts due to low tessellation and depth buffer imprecision, etc.).
float fadeOutFrom; ///< [0.0, ~ ] Distance to start fading out the effect.
float fadeOutTo; ///< [0.0, ~ ] Distance at which the effect is faded out.
FfxCacaoQuality qualityLevel; ///< Effect quality, affects number of taps etc.
float adaptiveQualityLimit; ///< [0.0, 1.0] (only for quality level FFX_CACAO_QUALITY_HIGHEST).
uint32_t blurPassCount; ///< [ 0, 8] Number of edge-sensitive smart blur passes to apply.
float sharpness; ///< [0.0, 1.0] How much to bleed over edges; 1: not at all, 0.5: half-half; 0.0: completely ignore edges.
float temporalSupersamplingAngleOffset; ///< [0.0, PI] Used to rotate sampling kernel; If using temporal AA / supersampling, suggested to rotate by ( (frame%3)/3.0*PI ) or similar. Kernel is already symmetrical, which is why we use PI and not 2*PI.
float temporalSupersamplingRadiusOffset; ///< [0.0, 2.0] Used to scale sampling kernel; If using temporal AA / supersampling, suggested to scale by ( 1.0f + (((frame%3)-1.0)/3.0)*0.1 ) or similar.
float detailShadowStrength; ///< [0.0, 5.0] Used for high-res detail AO using neighboring depth pixels: adds a lot of detail but also reduces temporal stability (adds aliasing).
bool generateNormals; ///< This option should be set to FFX_CACAO_TRUE if FidelityFX-CACAO should reconstruct a normal buffer from the depth buffer. It is required to be FFX_CACAO_TRUE if no normal buffer is provided.
float bilateralSigmaSquared; ///< [0.0, ~ ] Sigma squared value for use in bilateral upsampler giving Gaussian blur term. Should be greater than 0.0.
float bilateralSimilarityDistanceSigma; ///< [0.0, ~ ] Sigma squared value for use in bilateral upsampler giving similarity weighting for neighbouring pixels. Should be greater than 0.0.
} FfxCacaoSettings;
/// The default settings used by FidelityFX CACAO.
///
/// @ingroup FfxCacao
static const FfxCacaoSettings FFX_CACAO_DEFAULT_SETTINGS = {
/* radius */ 1.2f,
/* shadowMultiplier */ 1.0f,
/* shadowPower */ 1.50f,
/* shadowClamp */ 0.98f,
/* horizonAngleThreshold */ 0.06f,
/* fadeOutFrom */ 50.0f,
/* fadeOutTo */ 300.0f,
/* qualityLevel */ FFX_CACAO_QUALITY_HIGHEST,
/* adaptiveQualityLimit */ 0.45f,
/* blurPassCount */ 2,
/* sharpness */ 0.98f,
/* temporalSupersamplingAngleOffset */ 0.0f,
/* temporalSupersamplingRadiusOffset */ 0.0f,
/* detailShadowStrength */ 0.5f,
/* generateNormals */ false,
/* bilateralSigmaSquared */ 5.0f,
/* bilateralSimilarityDistanceSigma */ 0.01f,
};
/// A structure for the constant buffer used by FidelityFX CACAO.
///
/// @ingroup FfxCacao
typedef struct FfxCacaoConstants {
float DepthUnpackConsts[2]; /// Multiply and add values for clip to view depth conversion.
float CameraTanHalfFOV[2]; /// tan(fov/2) for the x and y dimensions.
float NDCToViewMul[2]; /// Multiplication value for normalized device coordinates (NDC) to View conversion.
float NDCToViewAdd[2]; /// Addition value for NDC to view conversion.
float DepthBufferUVToViewMul[2]; /// Multiplication value for the depth buffer's UV to View conversion.
float DepthBufferUVToViewAdd[2]; /// Addition value for the depth buffer's UV to view conversion.
float EffectRadius; /// The radius in world space of the occlusion sphere. A larger radius will make further objects contribute to the ambient occlusion of a point.
float EffectShadowStrength; /// The linear multiplier for shadows. Higher values intensify the shadow.
float EffectShadowPow; /// The exponent for shadow values. Larger values create darker shadows.
float EffectShadowClamp; /// Clamps the shadow values to be within a certain range.
float EffectFadeOutMul; /// Multiplication value for effect fade out.
float EffectFadeOutAdd; /// Addition value for effect fade out.
float EffectHorizonAngleThreshold; /// Minimum angle necessary between geometry and a point to create occlusion. Adjusting this value helps reduce self-shadowing.
float EffectSamplingRadiusNearLimitRec; /// Default: EffectRadius*1.2. Used to set limit on the sampling disk size when near.
float DepthPrecisionOffsetMod; /// Default: 0.9992. Offset used to prevent artifacts due to imprecision.
float NegRecEffectRadius; /// Negative reciprocal of the effect radius.
float LoadCounterAvgDiv; /// Multiplier value to get average from loadcounter value.
float AdaptiveSampleCountLimit; /// Limits the total number of samples taken at adaptive quality levels.
float InvSharpness; /// The sharpness controls how much blur should bleed over edges.
int BlurNumPasses; /// Number of blur passes. Default uses 4, with lowest quality using 2.
float BilateralSigmaSquared; /// Only affects downsampled SSAO. Higher values create a larger blur.
float BilateralSimilarityDistanceSigma; /// Only affects downsampled SSAO. Lower values create sharper edges.
float PatternRotScaleMatrices[4][5][4]; /// Sampling pattern rotation/scale matrices.
float NormalsUnpackMul; /// Multiplication value to unpack normals. Set to 1 if normals are already in [-1,1] range.
float NormalsUnpackAdd; /// Addition value to unpack normals. Set to 0 if normals are already in [-1,1]range.
float DetailAOStrength; /// Adds in more detailed shadows based on edges. These are less temporally stable.
float Dummy0;
float SSAOBufferDimensions[2]; /// Dimensions of SSAO buffer.
float SSAOBufferInverseDimensions[2];
float DepthBufferDimensions[2]; /// Dimensions of the depth buffer.
float DepthBufferInverseDimensions[2];
int DepthBufferOffset[2]; /// Default is (0,0). Read offset for depth buffer.
int Pad[2];
float PerPassFullResUVOffset[4*4]; /// UV Offsets used in adaptive approach.
float InputOutputBufferDimensions[2]; /// Dimensions of the output AO buffer.
float InputOutputBufferInverseDimensions[2];
float ImportanceMapDimensions[2]; /// Dimensions of the importance map.
float ImportanceMapInverseDimensions[2];
float DeinterleavedDepthBufferDimensions[2]; /// Dimensions of the deinterleaved depth buffer.
float DeinterleavedDepthBufferInverseDimensions[2];
float DeinterleavedDepthBufferOffset[2]; /// Default is (0,0). Read offset for the deinterleaved depth buffer.
float DeinterleavedDepthBufferNormalisedOffset[2]; /// Default is (0,0). Normalized read offset for the deinterleaved depth buffer.
FfxFloat32x4x4 NormalsWorldToViewspaceMatrix; /// Normal matrix.
} FfxCacaoConstants;
/// A structure encapsulating the parameters required to initialize FidelityFX CACAO.
///
/// @ingroup FfxCacao
typedef struct FfxCacaoContextDescription
{
uint32_t width; ///< width of the input/output buffers
uint32_t height; ///< height of the input/output buffers
bool useDownsampledSsao; ///< Whether SSAO should be generated at native resolution or half resolution. It is recommended to enable this setting for improved performance.
FfxInterface backendInterface;
} FfxCacaoContextDescription;
/// A structure encapsulating the parameters and resources required to dispatch FidelityFX CACAO.
///
/// @ingroup FfxCacao
typedef struct FfxCacaoDispatchDescription
{
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record CACAO rendering commands into.
FfxResource depthBuffer; ///< A <c><i>FfxResource</i></c> containing the depth buffer for the current frame.
FfxResource normalBuffer; ///< A <c><i>FfxResource</i></c> containing the normal buffer for the current frame.
FfxResource outputBuffer; ///< A <c><i>FfxResource</i></c> containing the output color buffer for CACAO.
FfxFloat32x4x4* proj; ///< A <c><i>FfxFloat32x4x4</i></c> containing the projection matrix for the current frame.
FfxFloat32x4x4* normalsToView; ///< A <c><i>FfxFloat32x4x4</i></c> containing the normal matrix for the current frame.
float normalUnpackMul; /// Multiplication value to unpack normals. Set to 1 if normals are already in [-1,1] range.
float normalUnpackAdd; /// Addition value to unpack normals. Set to 0 if normals are already in [-1,1]range.
} FfxCacaoDispatchDescription;
/// A structure containing sizes of each of the buffers used by FidelityFX CACAO.
///
/// @ingroup FfxCacao
typedef struct FfxCacaoBufferSizeInfo {
uint32_t inputOutputBufferWidth; ///< width of the input/output buffers
uint32_t inputOutputBufferHeight; ///< height of the input/output buffers
uint32_t ssaoBufferWidth; ///< width of the ssao buffer
uint32_t ssaoBufferHeight; ///< height of the ssao buffer
uint32_t depthBufferXOffset; ///< x-offset to use when sampling depth buffer
uint32_t depthBufferYOffset; ///< y-offset to use when sampling depth buffer
uint32_t depthBufferWidth; ///< width of the passed in depth buffer
uint32_t depthBufferHeight; ///< height of the passed in depth buffer
uint32_t deinterleavedDepthBufferXOffset; ///< x-offset to use when sampling de-interleaved depth buffer
uint32_t deinterleavedDepthBufferYOffset; ///< y-offset to use when sampling de-interleaved depth buffer
uint32_t deinterleavedDepthBufferWidth; ///< width of the de-interleaved depth buffer
uint32_t deinterleavedDepthBufferHeight; ///< height of the de-interleaved depth buffer
uint32_t importanceMapWidth; ///< width of the importance map buffer
uint32_t importanceMapHeight; ///< height of the importance map buffer
uint32_t downsampledSsaoBufferWidth; ///< width of the downsampled ssao buffer
uint32_t downsampledSsaoBufferHeight; ///< height of the downsampled ssao buffer
} FfxCacaoBufferSizeInfo;
/// An enumeration of bit flags used when dispatching FidelityFX CACAO
///
/// @ingroup FfxCacao
typedef enum FfxCacaoDispatchFlagsBits {
FFX_CACAO_SRV_SSAO_REMAP_TO_PONG = (1<<0), ///< A bit indicating the SRV maps to pong texture
FFX_CACAO_UAV_SSAO_REMAP_TO_PONG = (1<<1), ///< A bit indicating the UAV maps to pong texture
} FfxCacaoDispatchFlagsBits;
/// A structure encapsulating the FidelityFX CACAO context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by CACAO.
///
/// The <c><i>FfxCacaoContext</i></c> object should have a lifetime matching
/// your use of CACAO. Before destroying the CACAO context care should be taken
/// to ensure the GPU is not accessing the resources created or used by CACAO.
/// It is therefore recommended that the GPU is idle before destroying the
/// CACAO context.
///
/// @ingroup FfxCacao
typedef struct FfxCacaoContext
{
uint32_t data[FFX_CACAO_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxCacaoContext;
/// Create a FidelityFX CACAO context from the parameters
/// programmed to the <c><i>FfxCacaoContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the CACAO
/// API, and is responsible for the management of the internal resources
/// used by the CACAO algorithm. When this API is called, multiple calls
/// will be made via the pointers contained in the <c><i>backendInterface</i></c>
/// structure. This backend will attempt to retrieve the device capabilities,
/// and create the internal resources, and pipelines required by CACAO to function.
/// Depending on the precise configuration used when
/// creating the <c><i>FfxCacaoContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The <c><i>FfxCacaoContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or CACAO
/// upscaling is disabled by a user. To destroy the CACAO context you
/// should call <c><i>ffxCacaoContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxCacaoContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxCacaoContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxCacaoContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxCacao
FFX_API FfxErrorCode ffxCacaoContextCreate(FfxCacaoContext* context, const FfxCacaoContextDescription* contextDescription);
/// Dispatches work to the FidelityFX CACAO context
///
/// @param [out] pContext A pointer to a <c><i>FfxCacaoContext</i></c> structure to populate.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxCacaoDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxCacao
FFX_API FfxErrorCode ffxCacaoContextDispatch(FfxCacaoContext* context, const FfxCacaoDispatchDescription* dispatchDescription);
/// Destroy the FidelityFX CACAO context.
///
/// @param [out] pContext A pointer to a <c><i>FfxCacaoContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FfxCacao
FFX_API FfxErrorCode ffxCacaoContextDestroy(FfxCacaoContext* context);
/// Updates the settings used by CACAO.
/// @param [in] context A pointer to a <c><i>FfxCacaoContext</i></c> structure to change settings for.
/// @param [in] settings A pointer to a <c><i>FfxCacaoSettings</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>settings</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FfxCacao
FFX_API FfxErrorCode ffxCacaoUpdateSettings(FfxCacaoContext* context, const FfxCacaoSettings* settings, const bool useDownsampledSsao);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup FfxCacao
FFX_API FfxVersionNumber ffxCacaoGetEffectVersion();
@@ -0,0 +1,209 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
// @defgroup CAS
#pragma once
// Include the interface for the backend of the CAS API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup ffxCas FidelityFX Cas
/// FidelityFX Contrast Adaptive Sharpening runtime library
///
/// @ingroup SDKComponents
/// Contrast Adaptive Sharpening major version.
///
/// @ingroup ffxCas
#define FFX_CAS_VERSION_MAJOR (1)
/// Contrast Adaptive Sharpening minor version.
///
/// @ingroup ffxCas
#define FFX_CAS_VERSION_MINOR (2)
/// Contrast Adaptive Sharpening patch version.
///
/// @ingroup ffxCas
#define FFX_CAS_VERSION_PATCH (0)
/// FidelityFX CAS context count
///
/// Defines the number of internal effect contexts required by CAS
///
/// @ingroup ffxCas
#define FFX_CAS_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup ffxCas
#define FFX_CAS_CONTEXT_SIZE (9206)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of all the passes which constitute the CAS algorithm.
///
/// CAS has only one pass. For a more comprehensive description
/// of this pass, please refer to the CAS reference documentation.
///
/// @ingroup ffxCas
typedef enum FfxCasPass
{
FFX_CAS_PASS_SHARPEN = 0, ///< A pass which sharpens only or upscales the color buffer.
FFX_CAS_PASS_COUNT ///< The number of passes performed by CAS.
} FfxCasPass;
/// An enumeration of color space conversions used when creating a
/// <c><i>FfxCASContext</i></c>. See <c><i>FfxCASContextDescription</i></c>.
///
/// @ingroup ffxCas
typedef enum FfxCasColorSpaceConversion
{
FFX_CAS_COLOR_SPACE_LINEAR = 0, ///< Linear color space, will do nothing.
FFX_CAS_COLOR_SPACE_GAMMA20 = 1, ///< Convert gamma 2.0 to linear for input and linear to gamma 2.0 for output.
FFX_CAS_COLOR_SPACE_GAMMA22 = 2, ///< Convert gamma 2.2 to linear for input and linear to gamma 2.2 for output.
FFX_CAS_COLOR_SPACE_SRGB_OUTPUT = 3, ///< Only do sRGB conversion for output (input conversion will be done automatically).
FFX_CAS_COLOR_SPACE_SRGB_INPUT_OUTPUT = 4 ///< Convert sRGB to linear for input and linear to sRGB for output.
} FfxCasColorSpaceConversion;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxCASContext</i></c>. See <c><i>FfxCASContextDescription</i></c>.
///
/// @ingroup ffxCas
typedef enum FfxCasInitializationFlagBits
{
FFX_CAS_SHARPEN_ONLY = (1 << 0) ///< A bit indicating if we sharpen only.
} FfxCasInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize FidelityFX CAS
///
/// @ingroup ffxCas
typedef struct FfxCasContextDescription
{
uint32_t flags; ///< A collection of <c><i>FfxCasInitializationFlagBits</i></c>.
FfxCasColorSpaceConversion colorSpaceConversion; ///< An enumeration indicates which color space conversion is used.
FfxDimensions2D maxRenderSize; ///< The maximum size that rendering will be performed at.
FfxDimensions2D displaySize; ///< The size of the presentation resolution targeted by the upscaling process.
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for CAS.
} FfxCasContextDescription;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX CAS
///
/// @ingroup ffxCas
typedef struct FfxCasDispatchDescription
{
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record CAS rendering commands into.
FfxResource color; ///< A <c><i>FfxResource</i></c> containing the color buffer for the current frame (at render resolution).
FfxResource output; ///< A <c><i>FfxResource</i></c> containing the output color buffer for the current frame (at presentation resolution).
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resource.
float sharpness; ///< The sharpness value between 0 and 1, where 0 is no additional sharpness and 1 is maximum additional sharpness.
} FfxCasDispatchDescription;
/// A structure encapsulating the FidelityFX CAS context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by CAS.
///
/// The <c><i>FfxCasContext</i></c> object should have a lifetime matching
/// your use of CAS. Before destroying the CAS context care should be taken
/// to ensure the GPU is not accessing the resources created or used by CAS.
/// It is therefore recommended that the GPU is idle before destroying the
/// CAS context.
///
/// @ingroup ffxCas
typedef struct FfxCasContext
{
uint32_t data[FFX_CAS_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxCasContext;
/// Create a FidelityFX CAS context from the parameters
/// programmed to the <c><i>FfxCasContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the CAS,
/// and is responsible for the management of the internal resources
/// used by the CAS algorithm. When this API is called, multiple calls
/// will be made via the pointers contained in the <c><i>callbacks</i></c>
/// structure. These callbacks will attempt to retreive the device capabilities,
/// , and pipelines required by CAS frame-to-frame function. Depending on configuration
/// used when creating the <c><i>FfxCasContext</i></c> a different set of pipelines
/// might be requested via the callback functions.
///
/// The <c><i>FfxCasContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or CAS is disabled by a user.
/// To destroy the CAS context you should call <c><i>ffxCasContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxCasContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxCasContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxCasContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxCas
FFX_API FfxErrorCode ffxCasContextCreate(FfxCasContext* pContext, const FfxCasContextDescription* pContextDescription);
/// @param [out] pContext A pointer to a <c><i>FfxCasContext</i></c> structure to populate.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxCasDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxCas
FFX_API FfxErrorCode ffxCasContextDispatch(FfxCasContext* pContext, const FfxCasDispatchDescription* pDispatchDescription);
/// Destroy the FidelityFX CAS context.
///
/// @param [out] pContext A pointer to a <c><i>FfxCasContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxCas
FFX_API FfxErrorCode ffxCasContextDestroy(FfxCasContext* pContext);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxCas
FFX_API FfxVersionNumber ffxCasGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,288 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
// @defgroup Classifier
#pragma once
#define FFX_CLASSIFIER_MAX_SHADOW_MAP_TEXTURES_COUNT 4
// Include the interface for the backend of the FSR2 API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup ffxClassifier FidelityFX Classifier
/// FidelityFX Classifier runtime library
///
/// @ingroup SDKComponents
/// FidelityFX Classifier major version.
///
/// @ingroup ffxClassifier
#define FFX_CLASSIFIER_VERSION_MAJOR (1)
/// FidelityFX Classifier minor version.
///
/// @ingroup ffxClassifier
#define FFX_CLASSIFIER_VERSION_MINOR (3)
/// FidelityFX Classifier patch version.
///
/// @ingroup ffxClassifier
#define FFX_CLASSIFIER_VERSION_PATCH (0)
/// FidelityFX Classifier context count
///
/// Defines the number of internal effect contexts required by Classifier
///
/// @ingroup ffxClassifier
#define FFX_CLASSIFIER_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup ffxClassifier
#define FFX_CLASSIFIER_CONTEXT_SIZE (18500)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// Enum to specify which blur pass (currently only one).
///
/// @ffxClassifier
typedef enum FfxClassifierPass
{
FFX_CLASSIFIER_SHADOW_PASS_CLASSIFIER = 0, ///< The Tile Classification Pass
FFX_CLASSIFIER_REFLECTION_PASS_TILE_CLASSIFIER = 1, ///< Reflections tile classification pass
FFX_CLASSIFIER_PASS_COUNT ///< The number of passes in the Classifier effect
} FfxClassifierPass;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxClassifierContext</i></c>. See <c><i>FfxClassifierContextDescription</i></c>.
/// Currently, no flags exist.
///
/// @ingroup ffxClassifier
typedef enum FfxClassifierInitializationFlagBits {
FFX_CLASSIFIER_SHADOW = (1 << 0), ///< A bit indicating the intent is to classify shadows
FFX_CLASSIFIER_CLASSIFY_BY_NORMALS = (1 << 1), ///< A bit indicating the intent is to classify by normals
FFX_CLASSIFIER_CLASSIFY_BY_CASCADES = (1 << 2), ///< A bit indicating the intent is to classify by cascades
FFX_CLASSIFIER_ENABLE_DEPTH_INVERTED = (1 << 3), ///< A bit indicating that the input depth buffer data provided is inverted [1..0].
FFX_CLASSIFIER_REFLECTION = (1 << 4), ///< A bit indicating the intent is to classify reflections
} FfxClassifierInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Classifier.
///
/// @ingroup ffxClassifier
typedef struct FfxClassifierContextDescription {
uint32_t flags; ///< A collection of @ref FfxClassifierInitializationFlagBits
FfxDimensions2D resolution; ///< Resolution of the shadow dispatch call
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX Classifier
} FfxClassifierContextDescription;
/// A structure encapsulating the parameters for dispatching
/// of FidelityFX Classifier for shadows
///
/// @ingroup ffxClassifier
typedef struct FfxClassifierShadowDispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record Classifier rendering commands into.
FfxResource depth; ///< The <c><i>FfxResource</i></c> (SRV Texture 0)containing depth information
FfxResource normals; ///< The <c><i>FfxResource</i></c> (SRV Texture 1)containing normals information
FfxResource shadowMaps[FFX_CLASSIFIER_MAX_SHADOW_MAP_TEXTURES_COUNT]; ///< The <c><i>FfxResource</i></c> (SRV Texture 2)containing shadowMap(s) information
FfxResource workQueue; ///< The <c><i>FfxResource</i></c> (UAV Buffer 0)Work Queue: rwsb_tiles.
FfxResource workQueueCount; ///< The <c><i>FfxResource</i></c> (UAV Buffer 1)Work Queue Counter: rwb_tileCount
FfxResource rayHitTexture; ///< The <c><i>FfxResource</i></c> (UAV Texture 0)Ray Hit Texture
FfxFloat32 normalsUnPackMul; ///< A multiply factor to transform the normal to the space expected by the Classifier
FfxFloat32 normalsUnPackAdd; ///< An offset to transform the normal to the space expected by the Classifier
// Constant Data
FfxFloat32x3 lightDir; ///< The light direction
FfxFloat32 sunSizeLightSpace; ///< The sun size
FfxUInt32 tileCutOff; ///< The tile cutoff
FfxBoolean bRejectLitPixels; ///< UI Setting, selects wheter to reject lit pixels in the shadows maps
FfxUInt32 cascadeCount; ///< The number of cascades
FfxFloat32 blockerOffset; ///< UI Setting, the blocker offsett
FfxBoolean bUseCascadesForRayT; ///< UI Setting, selects whether to use the classifier to save ray intervals
FfxFloat32 cascadeSize; ///< The cascade size
FfxFloat32x4 cascadeScale[4]; ///< A multiply factor for each cascade
FfxFloat32x4 cascadeOffset[4]; ///< An offeset factor for each cascade
// Matrices
FfxFloat32 viewToWorld[16];
FfxFloat32 lightView[16];
FfxFloat32 inverseLightView[16];
} FfxClassifierShadowDispatchDescription;
/// A structure encapsulating the parameters for dispatching
/// of FidelityFX Classifier for reflections
///
/// @ingroup ffxClassifier
typedef struct FfxClassifierReflectionDispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record Hybrid Reflections rendering commands into.
FfxResource depth; ///< A <c><i>FfxResource</i></c> containing the depth buffer for the current frame (at render resolution).
FfxResource motionVectors; ///< A <c><i>FfxResource</i></c> containing the motion vectors buffer for the current frame (at render resolution).
FfxResource normal; ///< A <c><i>FfxResource</i></c> containing the normal buffer for the current frame (at render resolution).
FfxResource materialParameters; ///< A <c><i>FfxResource</i></c> containing the aoRoughnessMetallic buffer for the current frame (at render resolution).
FfxResource environmentMap; ///< A <c><i>FfxResource</i></c> containing the environment map to fallback to when screenspace data is not sufficient
FfxResource radiance;
FfxResource varianceHistory;
FfxResource hitCounter;
FfxResource hitCounterHistory;
FfxResource rayList;
FfxResource rayListHW;
FfxResource extractedRoughness;
FfxResource rayCounter;
FfxResource denoiserTileList;
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
float invViewProjection[16]; ///< An array containing the inverse of the view projection matrix in column major layout.
float projection[16]; ///< An array containing the projection matrix in column major layout.
float invProjection[16]; ///< An array containing the inverse of the projection matrix in column major layout.
float view[16]; ///< An array containing the view matrix in column major layout.
float invView[16]; ///< An array containing the inverse of the view matrix in column major layout.
float prevViewProjection[16]; ///< An array containing the previous frame's view projection matrix in column major layout.
float iblFactor; ///< A factor to control the intensity of the image based lighting. Set to 1 for an HDR probe.
uint32_t frameIndex;
uint32_t samplesPerQuad;
uint32_t temporalVarianceGuidedTracingEnabled;
float globalRoughnessThreshold;
float rtRoughnessThreshold;
uint32_t mask;
uint32_t reflectionWidth;
uint32_t reflectionHeight;
float hybridMissWeight;
float hybridSpawnRate;
float vrtVarianceThreshold;
float reflectionsBackfacingThreshold;
uint32_t randomSamplesPerPixel;
float motionVectorScale[2];
float normalsUnpackMul;
float normalsUnpackAdd;
uint32_t roughnessChannel;
bool isRoughnessPerceptual;
} FfxClassifierReflectionDispatchDescription;
/// A structure encapsulating the FidelityFX Classifier context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by the Classifier.
///
/// The <c><i>FfxClassifierContext</i></c> object should have a lifetime matching
/// your use of the Classifier. Before destroying the Classifier context care should be taken
/// to ensure the GPU is not accessing the resources created or used by the Classifier.
/// It is therefore recommended that the GPU is idle before destroying the
/// Classifier context.
///
/// @ingroup ffxClassifier
typedef struct FfxClassifierContext {
uint32_t data[FFX_CLASSIFIER_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxClassifierContext;
/// Create a FidelityFX Classifier context from the parameters
/// programmed to the <c><i>FfxClassifierContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the Classifier
/// API, and is responsible for the management of the internal resources
/// used by the Classifier. When this API is called, multiple calls
/// will be made via the pointers contained in the <c><i>backendInterface</i></c>
/// structure. This backend will attempt to retrieve the device capabilities,
/// and create the internal resources, and pipelines required by the Classifier to function.
/// Depending on the precise configuration used when
/// creating the <c><i>FfxClassifierContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The <c><i>FfxClassifierContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or the Classifier
/// is disabled by a user. To destroy the Classifier context you
/// should call <c><i>FfxClassifierContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxClassifierContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxClassifierContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxClassifierContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxClassifier
FFX_API FfxErrorCode ffxClassifierContextCreate(FfxClassifierContext* pContext, const FfxClassifierContextDescription* pContextDescription);
/// Dispatches work to the FidelityFX Classifier context for shadows
///
/// @param [in] pContext A pointer to a <c><i>FfxClassifierContext</i></c> structure.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxClassifierShadowDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxClassifier
FFX_API FfxErrorCode ffxClassifierContextShadowDispatch(FfxClassifierContext* pContext, const FfxClassifierShadowDispatchDescription* pDispatchDescription);
/// Dispatches work to the FidelityFX Classifier context for reflections
///
/// @param [in] pContext A pointer to a <c><i>FfxClassifierContext</i></c> structure.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxClassifierReflectionDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxClassifier
FFX_API FfxErrorCode ffxClassifierContextReflectionDispatch(FfxClassifierContext* pContext, const FfxClassifierReflectionDispatchDescription* pDispatchDescription);
/// Destroy the FidelityFX Classifier context.
///
/// @param [out] pContext A pointer to a <c><i>FfxClassifierContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxClassifier
FFX_API FfxErrorCode ffxClassifierContextDestroy(FfxClassifierContext* pContext);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxClassifier
FFX_API FfxVersionNumber ffxClassifierGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,266 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 the interface for the backend of the Denoiser API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup FfxDenoiser FidelityFX Denoiser
/// FidelityFX Denoiser runtime library
///
/// @ingroup SDKComponents
/// FidelityFX Denoiser major version.
///
/// @ingroup FfxDenoiser
#define FFX_DENOISER_VERSION_MAJOR (1)
/// FidelityFX Denoiser minor version.
///
/// @ingroup FfxDenoiser
#define FFX_DENOISER_VERSION_MINOR (3)
/// FidelityFX Denoiser patch version.
///
/// @ingroup FfxDenoiser
#define FFX_DENOISER_VERSION_PATCH (0)
/// FidelityFX denoiser context count
///
/// Defines the number of internal effect contexts required by the denoiser
///
/// @ingroup FfxDenoiser
#define FFX_DENOISER_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup Denoiser
#define FFX_DENOISER_CONTEXT_SIZE (73098)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of the pass which constitutes the Denoiser algorithm.
///
/// @ingroup Denoiser
typedef enum FfxDenoiserPass
{
FFX_DENOISER_PASS_PREPARE_SHADOW_MASK = 0,
FFX_DENOISER_PASS_SHADOWS_TILE_CLASSIFICATION = 1,
FFX_DENOISER_PASS_FILTER_SOFT_SHADOWS_0 = 2,
FFX_DENOISER_PASS_FILTER_SOFT_SHADOWS_1 = 3,
FFX_DENOISER_PASS_FILTER_SOFT_SHADOWS_2 = 4,
FFX_DENOISER_PASS_REPROJECT_REFLECTIONS = 5, ///< A pass which reprojects and estimates the variance.
FFX_DENOISER_PASS_PREFILTER_REFLECTIONS = 6, ///< A pass which spatially filters the reflections.
FFX_DENOISER_PASS_RESOLVE_TEMPORAL_REFLECTIONS = 7, ///< A pass which temporally filters the reflections.
FFX_DENOISER_PASS_COUNT ///< The number of passes in Denoiser
} FfxDenoiserPass;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxDenoiserContext</i></c>. See <c><i>FfxDenoiserContextDescription</i></c>.
///
/// @ingroup FfxDenoiser
typedef enum FfxDenoiserInitializationFlagBits {
FFX_DENOISER_SHADOWS = (1 << 0), ///< A bit indicating that the denoiser is used for denoising shadows
FFX_DENOISER_REFLECTIONS = (1 << 1), ///< A bit indicating that the denoiser is used for denoising reflections
FFX_DENOISER_ENABLE_DEPTH_INVERTED = (1 << 2), ///< A bit indicating that the input depth buffer data provided is inverted [1..0].
} FfxDenoiserInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize FidelityFX Denoiser
///
/// @ingroup FfxDenoiser
typedef struct FfxDenoiserContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxDenoiserInitializationFlagBits</i></c>
FfxDimensions2D windowSize; ///< The resolution that was used for rendering the input resource.
FfxSurfaceFormat normalsHistoryBufferFormat; ///< The format used by the reflections denoiser to store the normals buffer history
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX.
} FfxDenoiserContextDescription;
/// A structure encapsulating the parameters for dispatching
/// of FidelityFX Denoiser
///
/// @ingroup FfxDenoiser
typedef struct FfxDenoiserShadowsDispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record Denoiser rendering commands into.
FfxResource hitMaskResults; ///< A <c><i>FfxResource</i></c> containing the raytracing results where every pixel represents a 8x4 tile.
FfxResource depth; ///< A <c><i>FfxResource</i></c> containing 32bit depth values for the current frame.
FfxResource velocity; ///< A <c><i>FfxResource</i></c> containing 2-dimensional motion vectors.
FfxResource normal; ///< A <c><i>FfxResource</i></c> containing the normals.
FfxResource shadowMaskOutput; ///< A <c><i>FfxResource</i></c> which is used to store the fullscreen raytracing output.
FfxFloat32x2 motionVectorScale; ///< A multiply factor to transform the motion vectors to the space expected by the shadow denoiser.
FfxFloat32 normalsUnpackMul; ///< A multiply factor to transform the normal to the space expected by the shadow denoiser.
FfxFloat32 normalsUnpackAdd; ///< An offset to transform the normal to the space expected by the shadow denoiser.
FfxFloat32x3 eye; ///< The camera position
uint32_t frameIndex; ///< The current frame index
FfxFloat32 projectionInverse[16]; ///< The inverse of the camera projection matrix
FfxFloat32 reprojectionMatrix[16]; ///< The result of multiplying the projection matrix of the current frame by the result of the multiplication between the camera previous's frame view matrix by the inverse of the view-projection matrix
FfxFloat32 viewProjectionInverse[16]; ///< The inverse of the camera view-projection matrix
FfxFloat32 depthSimilaritySigma; ///< A constant factor used in the denoising filters, defaults to 1.0f
} FfxDenoiserShadowsDispatchDescription;
/// A structure encapsulating the parameters for dispatching
/// of FidelityFX Denoiser
///
/// @ingroup FfxDenoiser
typedef struct FfxDenoiserReflectionsDispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record Denoiser rendering commands into.
FfxResource depthHierarchy; ///< A <c><i>FfxResource</i></c> containing the depth buffer with full mip maps for the current frame.
FfxResource motionVectors; ///< A <c><i>FfxResource</i></c> containing the motion vectors buffer for the current frame.
FfxResource normal; ///< A <c><i>FfxResource</i></c> containing the normal buffer for the current frame.
FfxResource radianceA; ///< A <c><i>FfxResource</i></c> containing the ping-pong radiance buffers to filter.
FfxResource radianceB; ///< A <c><i>FfxResource</i></c> containing the ping-pong radiance buffers to filter.
FfxResource varianceA; ///< A <c><i>FfxResource</i></c> containing the ping-pong variance buffers used to filter and guide reflections.
FfxResource varianceB; ///< A <c><i>FfxResource</i></c> containing the ping-pong variance buffers used to filter and guide reflections.
FfxResource extractedRoughness; ///< A <c><i>FfxResource</i></c> containing the roughness of the current frame.
FfxResource denoiserTileList; ///< A <c><i>FfxResource</i></c> containing the tiles to be denoised.
FfxResource indirectArgumentsBuffer; ///< A <c><i>FfxResource</i></c> containing the indirect arguments used by the indirect dispatch calls tha compose the denoiser.
FfxResource output; ///< A <c><i>FfxResource</i></c> to store the denoised reflections.
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
FfxFloatCoords2D motionVectorScale; ///< The scale factor to apply to motion vectors.
float invProjection[16]; ///< An array containing the inverse of the projection matrix in column major layout.
float invView[16]; ///< An array containing the inverse of the view matrix in column major layout.
float prevViewProjection[16]; ///< An array containing the view projection matrix of the previous frame in column major layout.
float normalsUnpackMul; ///< A multiply factor to transform the normal to the space expected by SSSR.
float normalsUnpackAdd; ///< An offset to transform the normal to the space expected by SSSR.
bool isRoughnessPerceptual; ///< A boolean to describe the space used to store roughness in the materialParameters texture. If false, we assume roughness squared was stored in the Gbuffer.
uint32_t roughnessChannel; ///< The channel to read the roughness from the materialParameters texture
float temporalStabilityFactor; ///< A boolean to describe the space used to store roughness in the materialParameters texture. If false, we assume roughness squared was stored in the Gbuffer.
float roughnessThreshold; ///< Regions with a roughness value greater than this threshold won't spawn rays.
uint32_t frameIndex; ///< The index of the current frame.
bool reset;
} FfxDenoiserReflectionsDispatchDescription;
/// A structure encapsulating the FidelityFX denoiser context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by Denoiser.
///
/// The <c><i>FfxDenoiserContext</i></c> object should have a lifetime matching
/// your use of Denoiser. Before destroying the Denoiser context care should be taken
/// to ensure the GPU is not accessing the resources created or used by Denoiser.
/// It is therefore recommended that the GPU is idle before destroying the
/// Denoiser context.
///
/// @ingroup FfxDenoiser
typedef struct FfxDenoiserContext {
uint32_t data[FFX_DENOISER_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxDenoiserContext;
/// Create a FidelityFX Denoiser context from the parameters
/// programmed to the <c><i>FfxDenoiserContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the
/// Denoiser API, and is responsible for the management of the internal resources
/// used by the Denoiser algorithm. When this API is called, multiple calls
/// will be made via the pointers contained in the <c><i>backendInterface</i></c>
/// structure. This backend will attempt to retrieve the device capabilities,
/// and create the internal resources, and pipelines required by Denoiser to function.
/// Depending on the precise configuration used when
/// creating the <c><i>FfxDenoiserContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The <c><i>FfxDenoiserContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or shadow
/// denoising is disabled by a user. To destroy the Denoiser context you
/// should call <c><i>ffxDenoiserContextDestroy</i></c>.
///
/// @param [out] context A pointer to a <c><i>FfxDenoiserContext</i></c> structure to populate.
/// @param [in] contextDescription A pointer to a <c><i>FfxDenoiserContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxDenoiserContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxDenoiser
FFX_API FfxErrorCode ffxDenoiserContextCreate(FfxDenoiserContext* pContext, const FfxDenoiserContextDescription* pContextDescription);
/// Dispatches work to the FidelityFX Denoiser context
///
/// @param [out] context A pointer to a <c><i>FfxDenoiserContext</i></c> structure to populate.
/// @param [in] dispatchDescription A pointer to a <c><i>FfxDenoiserShadowsDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxDenoiser
FFX_API FfxErrorCode ffxDenoiserContextDispatchShadows(FfxDenoiserContext* context, const FfxDenoiserShadowsDispatchDescription* dispatchDescription);
/// Dispatches work to the FidelityFX Denoiser context
///
/// @param [out] context A pointer to a <c><i>FfxDenoiserContext</i></c> structure to populate.
/// @param [in] dispatchDescription A pointer to a <c><i>FfxDenoiserReflectionsDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxDenoiser
FFX_API FfxErrorCode ffxDenoiserContextDispatchReflections(FfxDenoiserContext* context, const FfxDenoiserReflectionsDispatchDescription* dispatchDescription);
/// Destroy the FidelityFX Denoiser context.
///
/// @param [out] context A pointer to a <c><i>FfxDenoiserContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FfxDenoiser
FFX_API FfxErrorCode ffxDenoiserContextDestroy(FfxDenoiserContext* context);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup FfxDenoiser
FFX_API FfxVersionNumber ffxDenoiserGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,263 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
// @defgroup DOF
#pragma once
// Include the interface for the backend of the FSR2 API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup ffxDof FidelityFX DoF
/// FidelityFX Depth of Field runtime library
///
/// @ingroup SDKComponents
/// FidelityFX DOF major version.
///
/// @ingroup ffxDof
#define FFX_DOF_VERSION_MAJOR (1)
/// FidelityFX DOF minor version.
///
/// @ingroup ffxDof
#define FFX_DOF_VERSION_MINOR (1)
/// FidelityFX DOF patch version.
///
/// @ingroup ffxDof
#define FFX_DOF_VERSION_PATCH (0)
/// FidelityFX DOF context count
///
/// Defines the number of internal effect contexts required by DOF
///
/// @ingroup ffxDof
#define FFX_DOF_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup ffxDof
#define FFX_DOF_CONTEXT_SIZE (45674)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of the passes which constitute the DoF algorithm.
///
/// DOF is implemented as a composite of several compute passes each
/// computing a key part of the final result. Each call to the
/// <c><i>FfxDofScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single pass included in <c><i>FfxDofPass</i></c>. For a
/// more comprehensive description of each pass, please refer to the DoF
/// reference documentation.
///
/// @ingroup ffxDof
typedef enum FfxDofPass {
FFX_DOF_PASS_DOWNSAMPLE_DEPTH = 0, ///< A pass which downsamples the depth buffer
FFX_DOF_PASS_DOWNSAMPLE_COLOR = 1, ///< A pass which downsamples the color buffer
FFX_DOF_PASS_DILATE = 2, ///< A pass which dilates the depth tile buffer
FFX_DOF_PASS_BLUR = 3, ///< A pass which performs the depth of field blur
FFX_DOF_PASS_COMPOSITE = 4, ///< A pass which combines the blurred images with the sharp input
FFX_DOF_PASS_COUNT ///< The number of passes in DOF
} FfxDofPass;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxDofContext</i></c>. See <c><i>FfxDofContextDescription</i></c>.
/// Curently, no flags exist.
///
/// @ingroup ffxDof
typedef enum FfxDofInitializationFlagBits {
FFX_DOF_REVERSE_DEPTH = (1 << 0), ///< A bit indicating whether input depth is reversed (1 is closest)
FFX_DOF_OUTPUT_PRE_INIT = (1 << 1), ///< A bit indicating whether the output is pre-initialized with the input color (e.g. it is the same texture)
FFX_DOF_DISABLE_RING_MERGE = (1 << 2), ///< A bit indicating whether to disable merging kernel rings
} FfxDofInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Depth of Field.
///
/// @ingroup ffxDof
typedef struct FfxDofContextDescription {
uint32_t flags; ///< A collection of @ref FfxDofInitializationFlagBits
uint32_t quality; ///< The number of rings to be used in the DoF blur kernel
FfxDimensions2D resolution; ///< Resolution of the input and output textures
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX
float cocLimitFactor; ///< The limit to apply to circle of confusion size as a factor for resolution height
} FfxDofContextDescription;
/// A structure encapsulating the parameters for dispatching
/// of FidelityFX Depth of Field
///
/// @ingroup ffxDof
typedef struct FfxDofDispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record DoF rendering commands into.
FfxResource color; ///< The <c><i>FfxResource</i></c> containing color information
FfxResource depth; ///< The <c><i>FfxResource</i></c> containing depth information
FfxResource output; ///< The <c><i>FfxResource</i></c> to output into. Can be the same as the color input.
float cocScale; ///< The factor converting depth to circle of confusion size. Can be calculated using ffxDofCalculateCocScale.
float cocBias; ///< The bias to apply to circle of confusion size. Can be calculated using ffxDofCalculateCocBias.
} FfxDofDispatchDescription;
/// A structure encapsulating the FidelityFX Depth of Field context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by DoF.
///
/// The <c><i>FfxDofContext</i></c> object should have a lifetime matching
/// your use of DoF. Before destroying the DoF context care should be taken
/// to ensure the GPU is not accessing the resources created or used by DoF.
/// It is therefore recommended that the GPU is idle before destroying the
/// DoF context.
///
/// @ingroup ffxDof
typedef struct FfxDofContext {
uint32_t data[FFX_DOF_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxDofContext;
/// Create a FidelityFX Depth of Field context from the parameters
/// programmed to the <c><i>FfxDofContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the Depth of
/// Field API, and is responsible for the management of the internal resources
/// used by the DoF algorithm. When this API is called, multiple calls
/// will be made via the pointers contained in the <c><i>backendInterface</i></c>
/// structure. This backend will attempt to retrieve the device capabilities,
/// and create the internal resources, and pipelines required by DoF to function.
/// Depending on the precise configuration used when
/// creating the <c><i>FfxDofContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The <c><i>FfxDofContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or DoF
/// is disabled by a user. To destroy the DoF context you
/// should call <c><i>ffxDofContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxDofContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxDofContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxDofContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxDof
FFX_API FfxErrorCode ffxDofContextCreate(FfxDofContext* pContext, const FfxDofContextDescription* pContextDescription);
/// Dispatches work to the FidelityFX DoF context
///
/// @param [in] pContext A pointer to a <c><i>FfxDofContext</i></c> structure.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxDofDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxDof
FFX_API FfxErrorCode ffxDofContextDispatch(FfxDofContext* pContext, const FfxDofDispatchDescription* pDispatchDescription);
/// Destroy the FidelityFX DoF context.
///
/// @param [out] pContext A pointer to a <c><i>FfxDofContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxDof
FFX_API FfxErrorCode ffxDofContextDestroy(FfxDofContext* pContext);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxDof
FFX_API FfxVersionNumber ffxDofGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
/// Calculates the scale parameter in the thin lens model according to lens and projection parameters.
/// @param aperture Aperture radius in view space units
/// @param focus Distance to focus plane in view space units
/// @param focalLength Lens focal length in view space units
/// @param conversion Conversion factor for view units to pixels (i.e. image width in pixels / sensor size)
/// @param proj33 Element (3,3) of the projection matrix (z range scale)
/// @param proj34 Element (3,4) of the projection matrix (z range offset)
/// @param proj43 Element (4,3) of the projection matrix (typically 1 or -1)
///
/// @ingroup ffxDof
static inline float ffxDofCalculateCocScale(float aperture, float focus, float focalLength, float conversion,
float proj33, float proj34, float proj43)
{
(void)proj33;
// z = (vd * proj33 + proj34) / (vd * proj43) = proj33/proj43 + proj34/(vd*proj43)
// => view depth = proj34 / (z*proj43 - proj33)
// C = (A * L * (F - D)) / (D * (F - L))
// = AL/(F-L) * (F/D - 1)
// = AL/(F-L) * (F(z*p43-p33)/p34 - 1) ignore non-factor terms
// = AL/(F-L) * (F(z*p43-.)/p34 - .)
// = AL/(F-L) * (F(z*p43-.)/p34 - .)
// = AL/(F-L) * F*z*p43/p34 + .
// = z * AL/(F-L) * F*p43/p34 + .
float absFocus = focus < 0 ? -focus : focus;
float commonFactor = conversion * aperture * focalLength / (absFocus - focalLength);
return commonFactor * focus * (proj43 / proj34);
}
/// Calculates the bias parameter in the thin lens model according to lens and projection parameters.
/// @param aperture Aperture radius in view space units
/// @param focus Distance to focus plane in view space units
/// @param focalLength Lens focal length in view space units
/// @param conversion Conversion factor for view units to pixels (i.e. image width in pixels / sensor size)
/// @param proj33 Element (3,3) of the projection matrix (a.k.a. z range scale)
/// @param proj34 Element (3,4) of the projection matrix (a.k.a. z range offset)
/// @param proj43 Element (4,3) of the projection matrix (typically 1 or -1)
///
/// @ingroup ffxDof
static inline float ffxDofCalculateCocBias(float aperture, float focus, float focalLength, float conversion,
float proj33, float proj34, float proj43)
{
(void)proj43;
// z = (D * proj33 + proj34) / (D * proj43) = proj33/proj43 + proj34/(D*proj43)
// => view depth D = proj34 / (z*proj43 - proj33)
// C = (A * L * (F - D)) / (D * (F - L))
// = AL/(F-L) * (F/D - 1)
// = AL/(F-L) * (F(z*p43-p33)/p34 - 1) ignore factor terms
// = AL/(F-L) * (F(0*p43-p33)/p34 - 1)
// = AL/(F-L) * (-F*p33/p34 - 1)
float absFocus = focus < 0 ? -focus : focus;
float commonFactor = conversion * aperture * focalLength / (absFocus - focalLength);
return commonFactor * (-focus * (proj33 / proj34) - 1);
}
@@ -0,0 +1,79 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 <FidelityFX/host/ffx_types.h>
/// @defgroup Errors Error Codes
/// Error codes returned from FidelityFX SDK functions
///
/// @ingroup ffxHost
/// Typedef for error codes returned from functions in the FidelityFX SDK.
///
/// @ingroup Errors
typedef int32_t FfxErrorCode;
/// Error codes and their meaning
///
/// @ingroup Errors
typedef enum FfxErrorCodes {
FFX_OK = 0, ///< The operation completed successfully.
FFX_ERROR_INVALID_POINTER = 0x80000000, ///< The operation failed due to an invalid pointer.
FFX_ERROR_INVALID_ALIGNMENT = 0x80000001, ///< The operation failed due to an invalid alignment.
FFX_ERROR_INVALID_SIZE = 0x80000002, ///< The operation failed due to an invalid size.
FFX_EOF = 0x80000003, ///< The end of the file was encountered.
FFX_ERROR_INVALID_PATH = 0x80000004, ///< The operation failed because the specified path was invalid.
FFX_ERROR_EOF = 0x80000005, ///< The operation failed because end of file was reached.
FFX_ERROR_MALFORMED_DATA = 0x80000006, ///< The operation failed because of some malformed data.
FFX_ERROR_OUT_OF_MEMORY = 0x80000007, ///< The operation failed because it ran out memory.
FFX_ERROR_INCOMPLETE_INTERFACE = 0x80000008, ///< The operation failed because the interface was not fully configured.
FFX_ERROR_INVALID_ENUM = 0x80000009, ///< The operation failed because of an invalid enumeration value.
FFX_ERROR_INVALID_ARGUMENT = 0x8000000a, ///< The operation failed because an argument was invalid.
FFX_ERROR_OUT_OF_RANGE = 0x8000000b, ///< The operation failed because a value was out of range.
FFX_ERROR_NULL_DEVICE = 0x8000000c, ///< The operation failed because a device was null.
FFX_ERROR_BACKEND_API_ERROR = 0x8000000d, ///< The operation failed because the backend API returned an error code.
FFX_ERROR_INSUFFICIENT_MEMORY = 0x8000000e, ///< The operation failed because there was not enough memory.
FFX_ERROR_INVALID_VERSION = 0x8000000f, ///< The operation failed because the wrong backend was linked.
FFX_ERROR_ACCESS_DENIED = 0x80000010, ///< The operation failed because access to the resource was denied.
}FfxErrorCodes;
/// Helper macro to return error code y from a function when a specific condition, x, is not met.
///
/// @ingroup Errors
#define FFX_RETURN_ON_ERROR(x, y) \
if (!(x)) \
{ \
return (y); \
}
/// Helper macro to return error code x from a function when it is not FFX_OK.
///
/// @ingroup Errors
#define FFX_VALIDATE(x) \
{ \
FfxErrorCode ret = x; \
FFX_RETURN_ON_ERROR(ret == FFX_OK, ret); \
}
@@ -0,0 +1,316 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
// @defgroup FRAMEINTERPOLATION
#pragma once
// Include the interface for the backend of the Frameinterpolation API.
#include <FidelityFX/host/ffx_interface.h>
/// FidelityFX Frameinterpolation major version.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
#define FFX_FRAMEINTERPOLATION_VERSION_MAJOR (1)
/// FidelityFX Frameinterpolation minor version.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
#define FFX_FRAMEINTERPOLATION_VERSION_MINOR (1)
/// FidelityFX Frameinterpolation patch version.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
#define FFX_FRAMEINTERPOLATION_VERSION_PATCH (3)
/// FidelityFX Frame Interpolation context count
///
/// Defines the number of internal effect contexts required by Frame Interpolation
///
/// @ingroup ffxFrameInterpolation
#define FFX_FRAMEINTERPOLATION_CONTEXT_COUNT (1)
/// The size of the context specified in 32bit values.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
#define FFX_FRAMEINTERPOLATION_CONTEXT_SIZE (FFX_SDK_DEFAULT_CONTEXT_SIZE)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of all the passes which constitute the FSR3 algorithm.
///
/// FSR3 is implemented as a composite of several compute passes each
/// computing a key part of the final result. Each call to the
/// <c><i>FfxFsr3ScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single pass included in <c><i>FfxFsr3Pass</i></c>. For a
/// more comprehensive description of each pass, please refer to the FSR3
/// reference documentation.
///
/// Please note in some cases e.g.: <c><i>FFX_FSR3_PASS_ACCUMULATE</i></c>
/// and <c><i>FFX_FSR3_PASS_ACCUMULATE_SHARPEN</i></c> either one pass or the
/// other will be used (they are mutually exclusive). The choice of which will
/// depend on the way the <c><i>FfxFsr3Context</i></c> is created and the
/// precise contents of <c><i>FfxFsr3DispatchParamters</i></c> each time a call
/// is made to <c><i>ffxFsr3ContextDispatch</i></c>.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
typedef enum FfxFrameInterpolationPass
{
FFX_FRAMEINTERPOLATION_PASS_RECONSTRUCT_AND_DILATE,
FFX_FRAMEINTERPOLATION_PASS_SETUP,
FFX_FRAMEINTERPOLATION_PASS_RECONSTRUCT_PREV_DEPTH,
FFX_FRAMEINTERPOLATION_PASS_GAME_MOTION_VECTOR_FIELD,
FFX_FRAMEINTERPOLATION_PASS_OPTICAL_FLOW_VECTOR_FIELD,
FFX_FRAMEINTERPOLATION_PASS_DISOCCLUSION_MASK,
FFX_FRAMEINTERPOLATION_PASS_INTERPOLATION,
FFX_FRAMEINTERPOLATION_PASS_INPAINTING_PYRAMID,
FFX_FRAMEINTERPOLATION_PASS_INPAINTING,
FFX_FRAMEINTERPOLATION_PASS_GAME_VECTOR_FIELD_INPAINTING_PYRAMID,
FFX_FRAMEINTERPOLATION_PASS_DEBUG_VIEW,
FFX_FRAMEINTERPOLATION_PASS_COUNT ///< The number of passes performed by FrameInterpolation.
} FfxFrameInterpolationPass;
// forward declarations
struct FfxFrameInterpolationContext;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxFrameInterpolationContext</i></c>. See <c><i>FfxFrameInterpolationContextDescription</i></c>.
///
/// @ingroup FRAMEINTERPOLATIONFRAMEINTERPOLATION
typedef enum FfxFrameInterpolationInitializationFlagBits {
FFX_FRAMEINTERPOLATION_ENABLE_DEPTH_INVERTED = (1<<0), ///< A bit indicating that the input depth buffer data provided is inverted [1..0].
FFX_FRAMEINTERPOLATION_ENABLE_DEPTH_INFINITE = (1<<1), ///< A bit indicating that the input depth buffer data provided is using an infinite far plane.
FFX_FRAMEINTERPOLATION_ENABLE_TEXTURE1D_USAGE = (1<<2), ///< A bit indicating that the backend should use 1D textures.
FFX_FRAMEINTERPOLATION_ENABLE_HDR_COLOR_INPUT = (1<<3), ///< A bit indicating that HDR values are present in the imaging pipeline.
FFX_FRAMEINTERPOLATION_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS = (1<<4), ///< A bit indicating if the motion vectors are rendered at display resolution.
FFX_FRAMEINTERPOLATION_ENABLE_JITTER_MOTION_VECTORS = (1<<5),
FFX_FRAMEINTERPOLATION_ENABLE_ASYNC_SUPPORT = (1<<6),
FFX_FRAMEINTERPOLATION_ENABLE_DEBUG_CHECKING = (1<<7), ///< A bit indicating that the runtime should check some API values and report issues.
} FfxFrameInterpolationInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize
/// FidelityFX Frameinterpolation.
///
/// @ingroup FRAMEINTERPOLATION
typedef struct FfxFrameInterpolationContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxFrameInterpolationInitializationFlagBits</i></c>.
FfxDimensions2D maxRenderSize; ///< The maximum size that rendering will be performed at.
FfxDimensions2D displaySize; ///< The size of the presentation resolution
FfxSurfaceFormat backBufferFormat; ///< the format of the backbuffer
FfxSurfaceFormat previousInterpolationSourceFormat; ///< the format of the texture that will store the interpolation source for the next frame. Can be different than the backbuffer one, especially when using hudless
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX SDK
} FfxFrameInterpolationContextDescription;
/// A structure encapsulating the resource descriptions for shared resources for this effect.
///
/// @ingroup FRAMEINTERPOLATION
typedef struct FfxFrameInterpolationSharedResourceDescriptions
{
FfxCreateResourceDescription reconstructedPrevNearestDepth; ///< The <c><i>FfxCreateResourceDescription</i></c> for allocating the <c><i>reconstructedPrevNearestDepth</i></c> shared resource.
FfxCreateResourceDescription dilatedDepth; ///< The <c><i>FfxCreateResourceDescription</i></c> for allocating the <c><i>dilatedDepth</i></c> shared resource.
FfxCreateResourceDescription dilatedMotionVectors; ///< The <c><i>FfxCreateResourceDescription</i></c> for allocating the <c><i>dilatedMotionVectors</i></c> shared resource.
} FfxFrameInterpolationSharedResourceDescriptions;
/// A structure encapsulating the FidelityFX Super Resolution 2 context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by FSR3.
///
/// The <c><i>FfxFsr3Context</i></c> object should have a lifetime matching
/// your use of FSR3. Before destroying the FSR3 context care should be taken
/// to ensure the GPU is not accessing the resources created or used by FSR3.
/// It is therefore recommended that the GPU is idle before destroying the
/// FSR3 context.
///
/// @ingroup FRAMEINTERPOLATION
typedef struct FfxFrameInterpolationContext
{
uint32_t data[FFX_FRAMEINTERPOLATION_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxFrameInterpolationContext;
/// Create a FidelityFX Super Resolution 2 context from the parameters
/// programmed to the <c><i>FfxFsr3CreateParams</i></c> structure.
///
/// The context structure is the main object used to interact with the FSR3
/// API, and is responsible for the management of the internal resources used
/// by the FSR3 algorithm. When this API is called, multiple calls will be
/// made via the pointers contained in the <c><i>callbacks</i></c> structure.
/// These callbacks will attempt to retreive the device capabilities, and
/// create the internal resources, and pipelines required by FSR3's
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxFsr3Context</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The flags included in the <c><i>flags</i></c> field of
/// <c><i>FfxFsr3Context</i></c> how match the configuration of your
/// application as well as the intended use of FSR3. It is important that these
/// flags are set correctly (as well as a correct programmed
/// <c><i>FfxFsr3DispatchDescription</i></c>) to ensure correct operation. It is
/// recommended to consult the overview documentation for further details on
/// how FSR3 should be integerated into an application.
///
/// When the <c><i>FfxFsr3Context</i></c> is created, you should use the
/// <c><i>ffxFsr3ContextDispatch</i></c> function each frame where FSR3
/// upscaling should be applied. See the documentation of
/// <c><i>ffxFsr3ContextDispatch</i></c> for more details.
///
/// The <c><i>FfxFsr3Context</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or FSR3 upscaling is
/// disabled by a user. To destroy the FSR3 context you should call
/// <c><i>ffxFsr3ContextDestroy</i></c>.
///
/// @param [out] context A pointer to a <c><i>FfxFsr3Context</i></c> structure to populate.
/// @param [in] contextDescription A pointer to a <c><i>FfxFsr3ContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxFsr3ContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FRAMEINTERPOLATION
FFX_API FfxErrorCode ffxFrameInterpolationContextCreate(FfxFrameInterpolationContext* context, FfxFrameInterpolationContextDescription* contextDescription);
FFX_API FfxErrorCode ffxFrameInterpolationContextGetGpuMemoryUsage(FfxFrameInterpolationContext* pContext, FfxEffectMemoryUsage* vramUsage);
FFX_API FfxErrorCode ffxFrameInterpolationGetSharedResourceDescriptions(FfxFrameInterpolationContext* pContext, FfxFrameInterpolationSharedResourceDescriptions* SharedResources);
FFX_API FfxErrorCode ffxSharedContextGetGpuMemoryUsage(FfxInterface* backendInterfaceShared, FfxEffectMemoryUsage* vramUsage);
typedef struct FfxFrameInterpolationPrepareDescription
{
uint32_t flags; ///< combination of FfxFrameInterpolationDispatchFlags
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record frame interpolation commands into.
FfxDimensions2D renderSize; ///< The dimensions used to render game content, dilatedDepth, dilatedMotionVectors are expected to be of ths size.
FfxFloatCoords2D jitterOffset; ///< The subpixel jitter offset applied to the camera. jitter;
FfxFloatCoords2D motionVectorScale; ///< The scale factor to apply to motion vectors. motionVectorScale;
float frameTimeDelta;
float cameraNear;
float cameraFar;
float viewSpaceToMetersFactor;
float cameraFovAngleVertical;
FfxResource depth; ///< The depth buffer data
FfxResource motionVectors; ///< The motion vector data
uint64_t frameID;
FfxResource dilatedDepth; ///< The dilated depth buffer data
FfxResource dilatedMotionVectors; ///< The dilated motion vector data
FfxResource reconstructedPrevDepth; ///< The reconstructed depth buffer data
FfxFloat32x3 cameraPosition; ///< The camera position in world space
FfxFloat32x3 cameraUp; ///< The camera up normalized vector in world space.
FfxFloat32x3 cameraRight; ///< The camera right normalized vector in world space.
FfxFloat32x3 cameraForward; ///< The camera forward normalized vector in world space.
} FfxFrameInterpolationPrepareDescription;
FFX_API FfxErrorCode ffxFrameInterpolationPrepare(FfxFrameInterpolationContext* context, const FfxFrameInterpolationPrepareDescription* params);
typedef enum FfxFrameInterpolationDispatchFlags
{
FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_TEAR_LINES = (1 << 0), ///< A bit indicating that the debug tear lines will be drawn to the interpolated output.
FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_RESET_INDICATORS = (1 << 1), ///< A bit indicating that the debug reset indicators will be drawn to the generated output.
FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_VIEW = (1 << 2), ///< A bit indicating that the interpolated output resource will contain debug views with relevant information.
FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_PACING_LINES = (1 << 3), ///< A bit indicating that the debug pacing lines will be drawn to the generated output.
FFX_FRAMEINTERPOLATION_DISPATCH_RESERVED_1 = (1 << 4),
FFX_FRAMEINTERPOLATION_DISPATCH_RESERVED_2 = (1 << 5),
} FfxFrameInterpolationDispatchFlags;
typedef struct FfxFrameInterpolationDispatchDescription {
uint32_t flags; ///< combination of FfxFrameInterpolationDispatchFlags
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record frame interpolation commands into.
FfxDimensions2D displaySize; ///< The destination output dimensions
FfxDimensions2D renderSize; ///< The dimensions used to render game content, dilatedDepth, dilatedMotionVectors are expected to be of ths size.
FfxResource currentBackBuffer; ///< The current presentation color, if currentBackBuffer_HUDLess is not used, this will be used as interpolation source data.
FfxResource currentBackBuffer_HUDLess; ///< The current presentation color without HUD content, when use it will be used as interpolation source data.
FfxResource output; ///< The output resource where to store the interpolated result.
FfxRect2D interpolationRect; ///< The area of the backbuffer that should be used for interpolation in case only a part of the screen is used e.g. due to movie bars
FfxResource opticalFlowVector; ///< The optical flow motion vectors (see example computation in the FfxOpticalFlow effect)
FfxResource opticalFlowSceneChangeDetection; ///< The optical flow scene change detection data
FfxDimensions2D opticalFlowBufferSize; ///< The optical flow motion vector resource dimensions
FfxFloatCoords2D opticalFlowScale; ///< The optical flow motion vector scale factor, used to scale resoure values into [0.0,1.0] range.
int opticalFlowBlockSize; ///< The optical flow block dimension size
float cameraNear; ///< The distance to the near plane of the camera.
float cameraFar; ///< The distance to the far plane of the camera. This is used only used in case of non infinite depth.
float cameraFovAngleVertical; ///< The camera angle field of view in the vertical direction (expressed in radians).
float viewSpaceToMetersFactor; ///< The unit to scale view space coordinates to meters.
float frameTimeDelta; ///< The time elapsed since the last frame (expressed in milliseconds).
bool reset; ///< A boolean value which when set to true, indicates the camera has moved discontinuously.
FfxBackbufferTransferFunction backBufferTransferFunction; ///< The transfer function use to convert interpolation source color data to linear RGB.
float minMaxLuminance[2]; ///< Min and max luminance values, used when converting HDR colors to linear RGB
uint64_t frameID; ///< Identifier used to select internal resources when async support is enabled. Must increment by exactly one (1) for each frame. Any non-exactly-one difference will reset the frame generation logic.
FfxResource dilatedDepth; ///< The dilated depth buffer data
FfxResource dilatedMotionVectors; ///< The dilated motion vector data
FfxResource reconstructedPrevDepth; ///< The reconstructed depth buffer data
FfxResource distortionField; ///< A resource containing distortion offset data used when distortion post effects are enabled.
} FfxFrameInterpolationDispatchDescription;
FFX_API FfxErrorCode ffxFrameInterpolationDispatch(FfxFrameInterpolationContext* context, const FfxFrameInterpolationDispatchDescription* params);
/// Destroy the FidelityFX Super Resolution context.
///
/// @param [out] context A pointer to a <c><i>FfxFsr3Context</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FRAMEINTERPOLATION
FFX_API FfxErrorCode ffxFrameInterpolationContextDestroy(FfxFrameInterpolationContext* context);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup FRAMEINTERPOLATION
FFX_API FfxVersionNumber ffxFrameInterpolationGetEffectVersion();
/// Set global debug message settings
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup FRAMEINTERPOLATION
FFX_API FfxErrorCode ffxFrameInterpolationSetGlobalDebugMessage(ffxMessageCallback fpMessage, uint32_t debugLevel);
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,297 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
/// @defgroup ffxFsr1 FidelityFX FSR1
/// FidelityFX Super Resolution 1 runtime library
///
/// @ingroup SDKComponents
#pragma once
/// Include the interface for the backend of the FSR 1.0 API.
///
/// @ingroup ffxFsr1
#include <FidelityFX/host/ffx_interface.h>
/// FidelityFX Super Resolution 1.0 major version.
///
/// @ingroup ffxFsr1
#define FFX_FSR1_VERSION_MAJOR (1)
/// FidelityFX Super Resolution 1.0 minor version.
///
/// @ingroup ffxFsr1
#define FFX_FSR1_VERSION_MINOR (2)
/// FidelityFX Super Resolution 1.0 patch version.
///
/// @ingroup ffxFsr1
#define FFX_FSR1_VERSION_PATCH (0)
/// FidelityFX Super Resolution 1.0 context count
///
/// Defines the number of internal effect contexts required by FSR1
///
/// @ingroup ffxFsr1
#define FFX_FSR1_CONTEXT_COUNT 2
/// The size of the context specified in 32bit values.
///
/// @ingroup ffxFsr1
#define FFX_FSR1_CONTEXT_SIZE (27448)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of all the passes which constitute the FSR1 algorithm.
///
/// FSR1 is implemented as a composite of several compute passes each
/// computing a key part of the final result. Each call to the
/// <c><i>FfxFsr1ScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single pass included in <c><i>FfxFsr1Pass</i></c>. For a
/// more comprehensive description of each pass, please refer to the FSR1
/// reference documentation.
///
/// @ingroup ffxFsr1
typedef enum FfxFsr1Pass
{
FFX_FSR1_PASS_EASU = 0, ///< A pass which upscales the color buffer using easu.
FFX_FSR1_PASS_EASU_RCAS = 1, ///< A pass which upscales the color buffer in preparation for rcas
FFX_FSR1_PASS_RCAS = 2, ///< A pass which performs rcas sharpening on the upscaled image.
FFX_FSR1_PASS_COUNT ///< The number of passes performed by FSR2.
} FfxFsr1Pass;
/// An enumeration of all the quality modes supported by FidelityFX Super
/// Resolution 1 upscaling.
///
/// In order to provide a consistent user experience across multiple
/// applications which implement FSR1. It is strongly recommended that the
/// following preset scaling factors are made available through your
/// application's user interface.
///
/// If your application does not expose the notion of preset scaling factors
/// for upscaling algorithms (perhaps instead implementing a fixed ratio which
/// is immutable) or implementing a more dynamic scaling scheme (such as
/// dynamic resolution scaling), then there is no need to use these presets.
///
/// @ingroup ffxFsr1
typedef enum FfxFsr1QualityMode {
FFX_FSR1_QUALITY_MODE_ULTRA_QUALITY = 0, ///< Perform upscaling with a per-dimension upscaling ratio of 1.3x.
FFX_FSR1_QUALITY_MODE_QUALITY = 1, ///< Perform upscaling with a per-dimension upscaling ratio of 1.5x.
FFX_FSR1_QUALITY_MODE_BALANCED = 2, ///< Perform upscaling with a per-dimension upscaling ratio of 1.7x.
FFX_FSR1_QUALITY_MODE_PERFORMANCE = 3 ///< Perform upscaling with a per-dimension upscaling ratio of 2.0x.
} FfxFsr1QualityMode;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxFsr1Context</i></c>. See <c><i>FfxFsr1ContextDescription</i></c>.
///
/// @ingroup ffxFsr1
typedef enum FfxFsr1InitializationFlagBits {
FFX_FSR1_ENABLE_RCAS = (1 << 0), ///< A bit indicating if we should use rcas.
FFX_FSR1_RCAS_PASSTHROUGH_ALPHA = (1 << 1), ///< A bit indicating if we should use passthrough alpha during rcas.
FFX_FSR1_RCAS_DENOISE = (1 << 2), ///< A bit indicating if denoising is invoked during rcas.
FFX_FSR1_ENABLE_HIGH_DYNAMIC_RANGE = (1 << 3), ///< A bit indicating if the input color data provided is using a high-dynamic range.
FFX_FSR1_ENABLE_SRGB_CONVERSIONS = (1 << 4), ///< A bit indicating that input/output resources require gamma conversions
} FfxFsr1InitializationFlagBits;
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Super Resolution 1.0
///
/// @ingroup ffxFsr1
typedef struct FfxFsr1ContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxFsr1InitializationFlagBits</i></c>.
FfxSurfaceFormat outputFormat; ///< Format of the output target used for creation of the internal upscale resource
FfxDimensions2D maxRenderSize; ///< The maximum size that rendering will be performed at.
FfxDimensions2D displaySize; ///< The size of the presentation resolution targeted by the upscaling process.
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FSR1.
} FfxFsr1ContextDescription;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX Super Resolution 1.0
///
/// @ingroup ffxFsr1
typedef struct FfxFsr1DispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR1 rendering commands into.
FfxResource color; ///< A <c><i>FfxResource</i></c> containing the color buffer for the current frame (at render resolution).
FfxResource output; ///< A <c><i>FfxResource</i></c> containing the output color buffer for the current frame (at presentation resolution).
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resource.
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.
} FfxFsr1DispatchDescription;
/// A structure encapsulating the FidelityFX Super Resolution 1.0 context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by FSR1.
///
/// The <c><i>FfxFsr1Context</i></c> object should have a lifetime matching
/// your use of FSR1. Before destroying the FSR1 context care should be taken
/// to ensure the GPU is not accessing the resources created or used by FSR1.
/// It is therefore recommended that the GPU is idle before destroying the
/// FSR1 context.
///
/// @ingroup ffxFsr1
typedef struct FfxFsr1Context {
uint32_t data[FFX_FSR1_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxFsr1Context;
/// Create a FidelityFX Super Resolution 1.0 context from the parameters
/// programmed to the <c><i>FfxFsr1ContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the Super
/// Resoution 1.0 API, and is responsible for the management of the internal resources
/// used by the FSR1 algorithm. When this API is called, multiple calls
/// will be made via the pointers contained in the <c><i>callbacks</i></c>
/// structure. These callbacks will attempt to retreive the device capabilities,
/// and create the internal resources, and pipelines required by FSR1
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxFsr1Context</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The <c><i>FfxParallelSortContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or FSR1
/// upscaling is disabled by a user. To destroy the FSR1 context you
/// should call <c><i>ffxFsr1ContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxFsr1Context</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxFsr1ContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxFsr1ContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxFsr1
FFX_API FfxErrorCode ffxFsr1ContextCreate(FfxFsr1Context* pContext, const FfxFsr1ContextDescription* pContextDescription);
/// Get GPU memory usage of the FidelityFX Super Resolution context.
///
/// @param [in] pContext A pointer to a <c><i>FfxFsr1Context</i></c> structure.
/// @param [out] pVramUsage A pointer to a <c><i>FfxEffectMemoryUsage</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>vramUsage</i></c> were <c><i>NULL</i></c>.
///
/// @ingroup ffxFsr1
FFX_API FfxErrorCode ffxFsr1ContextGetGpuMemoryUsage(FfxFsr1Context* pContext, FfxEffectMemoryUsage* pVramUsage);
/// @param [out] pContext A pointer to a <c><i>FfxFsr1Context</i></c> structure to populate.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxFsr1DispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxFsr1
FFX_API FfxErrorCode ffxFsr1ContextDispatch(FfxFsr1Context* pContext, const FfxFsr1DispatchDescription* pDispatchDescription);
/// Destroy the FidelityFX FSR 1 context.
///
/// @param [out] pContext A pointer to a <c><i>FfxFsr1Context</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxFsr1
FFX_API FfxErrorCode ffxFsr1ContextDestroy(FfxFsr1Context* pContext);
/// Get the upscale ratio from the quality mode.
///
/// The following table enumerates the mapping of the quality modes to
/// per-dimension scaling ratios.
///
/// Quality preset | Scale factor
/// ----------------------------------------------------- | -------------
/// <c><i>FFX_FSR1_QUALITY_MODE_ULTRA_QUALITY</i></c> | 1.3x
/// <c><i>FFX_FSR1_QUALITY_MODE_QUALITY</i></c> | 1.5x
/// <c><i>FFX_FSR1_QUALITY_MODE_BALANCED</i></c> | 1.7x
/// <c><i>FFX_FSR1_QUALITY_MODE_PERFORMANCE</i></c> | 2.0x
///
/// Passing an invalid <c><i>qualityMode</i></c> will return 0.0f.
///
/// @param [in] qualityMode The quality mode preset.
///
/// @returns
/// The upscaling the per-dimension upscaling ratio for
/// <c><i>qualityMode</i></c> according to the table above.
///
/// @ingroup ffxFsr1
FFX_API float ffxFsr1GetUpscaleRatioFromQualityMode(FfxFsr1QualityMode qualityMode);
/// A helper function to calculate the rendering resolution from a target
/// resolution and desired quality level.
///
/// This function applies the scaling factor returned by
/// <c><i>ffxFsr1GetUpscaleRatioFromQualityMode</i></c> to each dimension.
///
/// @param [out] pRenderWidth A pointer to a <c>uint32_t</c> which will hold the calculated render resolution width.
/// @param [out] pRenderHeight A pointer to a <c>uint32_t</c> which will hold the calculated render resolution height.
/// @param [in] displayWidth The target display resolution width.
/// @param [in] displayHeight The target display resolution height.
/// @param [in] qualityMode The desired quality mode for FSR1 upscaling.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>renderWidth</i></c> or <c><i>renderHeight</i></c> was <c>NULL</c>.
/// @retval
/// FFX_ERROR_INVALID_ENUM An invalid quality mode was specified.
///
/// @ingroup ffxFsr1
FFX_API FfxErrorCode ffxFsr1GetRenderResolutionFromQualityMode(
uint32_t* pRenderWidth,
uint32_t* pRenderHeight,
uint32_t displayWidth,
uint32_t displayHeight,
FfxFsr1QualityMode qualityMode);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxFsr1
FFX_API FfxVersionNumber ffxFsr1GetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,539 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 the interface for the backend of the FSR2 API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup ffxFsr2 FidelityFX FSR2
/// FidelityFX Super Resolution 2 runtime library
///
/// @ingroup SDKComponents
/// FidelityFX Super Resolution 2 major version.
///
/// @ingroup ffxFsr2
#define FFX_FSR2_VERSION_MAJOR (2)
/// FidelityFX Super Resolution 2 minor version.
///
/// @ingroup ffxFsr2
#define FFX_FSR2_VERSION_MINOR (3)
/// FidelityFX Super Resolution 2 patch version.
///
/// @ingroup ffxFsr2
#define FFX_FSR2_VERSION_PATCH (3)
/// FidelityFX Super Resolution 2 context count
///
/// Defines the number of internal effect contexts required by FSR2
///
/// @ingroup ffxFsr2
#define FFX_FSR2_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup ffxFsr2
#define FFX_FSR2_CONTEXT_SIZE (FFX_SDK_DEFAULT_CONTEXT_SIZE)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of all the passes which constitute the FSR2 algorithm.
///
/// FSR2 is implemented as a composite of several compute passes each
/// computing a key part of the final result. Each call to the
/// <c><i>FfxFsr2ScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single pass included in <c><i>FfxFsr2Pass</i></c>. For a
/// more comprehensive description of each pass, please refer to the FSR2
/// reference documentation.
///
/// Please note in some cases e.g.: <c><i>FFX_FSR2_PASS_ACCUMULATE</i></c>
/// and <c><i>FFX_FSR2_PASS_ACCUMULATE_SHARPEN</i></c> either one pass or the
/// other will be used (they are mutually exclusive). The choice of which will
/// depend on the way the <c><i>FfxFsr2Context</i></c> is created and the
/// precise contents of <c><i>FfxFsr2DispatchParamters</i></c> each time a call
/// is made to <c><i>ffxFsr2ContextDispatch</i></c>.
///
/// @ingroup ffxFsr2
typedef enum FfxFsr2Pass
{
FFX_FSR2_PASS_DEPTH_CLIP = 0, ///< A pass which performs depth clipping.
FFX_FSR2_PASS_RECONSTRUCT_PREVIOUS_DEPTH = 1, ///< A pass which performs reconstruction of previous frame's depth.
FFX_FSR2_PASS_LOCK = 2, ///< A pass which calculates pixel locks.
FFX_FSR2_PASS_ACCUMULATE = 3, ///< A pass which performs upscaling.
FFX_FSR2_PASS_ACCUMULATE_SHARPEN = 4, ///< A pass which performs upscaling when sharpening is used.
FFX_FSR2_PASS_RCAS = 5, ///< A pass which performs sharpening.
FFX_FSR2_PASS_COMPUTE_LUMINANCE_PYRAMID = 6, ///< A pass which generates the luminance mipmap chain for the current frame.
FFX_FSR2_PASS_GENERATE_REACTIVE = 7, ///< An optional pass to generate a reactive mask.
FFX_FSR2_PASS_TCR_AUTOGENERATE = 8, ///< An optional pass to automatically generate transparency/composition and reactive masks.
FFX_FSR2_PASS_COUNT ///< The number of passes performed by FSR2.
} FfxFsr2Pass;
/// An enumeration of all the quality modes supported by FidelityFX Super
/// Resolution 2 upscaling.
///
/// In order to provide a consistent user experience across multiple
/// applications which implement FSR2. It is strongly recommended that the
/// following preset scaling factors are made available through your
/// application's user interface.
///
/// If your application does not expose the notion of preset scaling factors
/// for upscaling algorithms (perhaps instead implementing a fixed ratio which
/// is immutable) or implementing a more dynamic scaling scheme (such as
/// dynamic resolution scaling), then there is no need to use these presets.
///
/// Please note that <c><i>FFX_FSR2_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> is
/// an optional mode which may introduce significant quality degradation in the
/// final image. As such it is recommended that you evaluate the final results
/// of using this scaling mode before deciding if you should include it in your
/// application.
///
/// @ingroup ffxFsr2
typedef enum FfxFsr2QualityMode {
FFX_FSR2_QUALITY_MODE_QUALITY = 1, ///< Perform upscaling with a per-dimension upscaling ratio of 1.5x.
FFX_FSR2_QUALITY_MODE_BALANCED = 2, ///< Perform upscaling with a per-dimension upscaling ratio of 1.7x.
FFX_FSR2_QUALITY_MODE_PERFORMANCE = 3, ///< Perform upscaling with a per-dimension upscaling ratio of 2.0x.
FFX_FSR2_QUALITY_MODE_ULTRA_PERFORMANCE = 4 ///< Perform upscaling with a per-dimension upscaling ratio of 3.0x.
} FfxFsr2QualityMode;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxFsr2Context</i></c>. See <c><i>FfxFsr2ContextDescription</i></c>.
///
/// @ingroup ffxFsr2
typedef enum FfxFsr2InitializationFlagBits {
FFX_FSR2_ENABLE_HIGH_DYNAMIC_RANGE = (1<<0), ///< A bit indicating if the input color data provided is using a high-dynamic range.
FFX_FSR2_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS = (1<<1), ///< A bit indicating if the motion vectors are rendered at display resolution.
FFX_FSR2_ENABLE_MOTION_VECTORS_JITTER_CANCELLATION = (1<<2), ///< A bit indicating that the motion vectors have the jittering pattern applied to them.
FFX_FSR2_ENABLE_DEPTH_INVERTED = (1<<3), ///< A bit indicating that the input depth buffer data provided is inverted [1..0].
FFX_FSR2_ENABLE_DEPTH_INFINITE = (1<<4), ///< A bit indicating that the input depth buffer data provided is using an infinite far plane.
FFX_FSR2_ENABLE_AUTO_EXPOSURE = (1<<5), ///< A bit indicating if automatic exposure should be applied to input color data.
FFX_FSR2_ENABLE_DYNAMIC_RESOLUTION = (1<<6), ///< A bit indicating that the application uses dynamic resolution scaling.
FFX_FSR2_ENABLE_TEXTURE1D_USAGE = (1<<7), ///< A bit indicating that the backend should use 1D textures.
FFX_FSR2_ENABLE_DEBUG_CHECKING = (1<<8), ///< A bit indicating that the runtime should check some API values and report issues.
} FfxFsr2InitializationFlagBits;
/// Pass a string message
///
/// Used for debug messages.
///
/// @param [in] type The type of message.
/// @param [in] message A string message to pass.
///
///
/// @ingroup ffxFsr2
typedef void(*FfxFsr2Message)(
FfxMsgType type,
const wchar_t* message);
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Super Resolution 2 upscaling.
///
/// @ingroup ffxFsr2
typedef struct FfxFsr2ContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxFsr2InitializationFlagBits</i></c>.
FfxDimensions2D maxRenderSize; ///< The maximum size that rendering will be performed at.
FfxDimensions2D displaySize; ///< The size of the presentation resolution targeted by the upscaling process.
FfxFsr2Message fpMessage; ///< A pointer to a function that can receive messages from the runtime.
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX SDK
} FfxFsr2ContextDescription;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX Super Resolution 2.
///
/// @ingroup ffxFsr2
typedef struct FfxFsr2DispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR2 rendering commands into.
FfxResource color; ///< A <c><i>FfxResource</i></c> containing the color buffer for the current frame (at render resolution).
FfxResource depth; ///< A <c><i>FfxResource</i></c> containing 32bit depth values for the current frame (at render resolution).
FfxResource motionVectors; ///< A <c><i>FfxResource</i></c> containing 2-dimensional motion vectors (at render resolution if <c><i>FFX_FSR2_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS</i></c> is not set).
FfxResource exposure; ///< A optional <c><i>FfxResource</i></c> containing a 1x1 exposure value.
FfxResource reactive; ///< A optional <c><i>FfxResource</i></c> containing alpha value of reactive objects in the scene.
FfxResource transparencyAndComposition; ///< A optional <c><i>FfxResource</i></c> containing alpha value of special objects in the scene.
FfxResource output; ///< A <c><i>FfxResource</i></c> containing the output color buffer for the current frame (at presentation resolution).
FfxFloatCoords2D jitterOffset; ///< The subpixel jitter offset applied to the camera.
FfxFloatCoords2D motionVectorScale; ///< The scale factor to apply to motion vectors.
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
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
// EXPERIMENTAL reactive mask generation parameters
bool enableAutoReactive; ///< A boolean value to indicate internal reactive autogeneration should be used
FfxResource colorOpaqueOnly; ///< A <c><i>FfxResource</i></c> containing the opaque only color buffer for the current frame (at render resolution).
float autoTcThreshold; ///< Cutoff value for TC
float autoTcScale; ///< A value to scale the transparency and composition mask
float autoReactiveScale; ///< A value to scale the reactive mask
float autoReactiveMax; ///< A value to clamp the reactive mask
} FfxFsr2DispatchDescription;
/// A structure encapsulating the parameters for automatic generation of a reactive mask
///
/// @ingroup ffxFsr2
typedef struct FfxFsr2GenerateReactiveDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR2 rendering commands into.
FfxResource colorOpaqueOnly; ///< A <c><i>FfxResource</i></c> containing the opaque only color buffer for the current frame (at render resolution).
FfxResource colorPreUpscale; ///< A <c><i>FfxResource</i></c> containing the opaque+translucent color buffer for the current frame (at render resolution).
FfxResource outReactive; ///< A <c><i>FfxResource</i></c> containing the surface to generate the reactive mask into.
FfxDimensions2D 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
} FfxFsr2GenerateReactiveDescription;
/// A structure encapsulating the FidelityFX Super Resolution 2 context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by FSR2.
///
/// The <c><i>FfxFsr2Context</i></c> object should have a lifetime matching
/// your use of FSR2. Before destroying the FSR2 context care should be taken
/// to ensure the GPU is not accessing the resources created or used by FSR2.
/// It is therefore recommended that the GPU is idle before destroying the
/// FSR2 context.
///
/// @ingroup ffxFsr2
typedef struct FfxFsr2Context
{
uint32_t data[FFX_FSR2_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxFsr2Context;
/// Create a FidelityFX Super Resolution 2 context from the parameters
/// programmed to the <c><i>FfxFsr2CreateParams</i></c> structure.
///
/// The context structure is the main object used to interact with the FSR2
/// API, and is responsible for the management of the internal resources used
/// by the FSR2 algorithm. When this API is called, multiple calls will be
/// made via the pointers contained in the <c><i>callbacks</i></c> structure.
/// These callbacks will attempt to retreive the device capabilities, and
/// create the internal resources, and pipelines required by FSR2's
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxFsr2Context</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The flags included in the <c><i>flags</i></c> field of
/// <c><i>FfxFsr2Context</i></c> how match the configuration of your
/// application as well as the intended use of FSR2. It is important that these
/// flags are set correctly (as well as a correct programmed
/// <c><i>FfxFsr2DispatchDescription</i></c>) to ensure correct operation. It is
/// recommended to consult the overview documentation for further details on
/// how FSR2 should be integerated into an application.
///
/// When the <c><i>FfxFsr2Context</i></c> is created, you should use the
/// <c><i>ffxFsr2ContextDispatch</i></c> function each frame where FSR2
/// upscaling should be applied. See the documentation of
/// <c><i>ffxFsr2ContextDispatch</i></c> for more details.
///
/// The <c><i>FfxFsr2Context</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or FSR2 upscaling is
/// disabled by a user. To destroy the FSR2 context you should call
/// <c><i>ffxFsr2ContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxFsr2Context</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxFsr2ContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxFsr2ContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxFsr2
FFX_API FfxErrorCode ffxFsr2ContextCreate(FfxFsr2Context* pContext, const FfxFsr2ContextDescription* pContextDescription);
/// Get GPU memory usage of the FidelityFX Super Resolution context.
///
/// @param [in] pContext A pointer to a <c><i>FfxFsr2Context</i></c> structure.
/// @param [out] pVramUsage A pointer to a <c><i>FfxEffectMemoryUsage</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>vramUsage</i></c> were <c><i>NULL</i></c>.
///
/// @ingroup ffxFsr2
FFX_API FfxErrorCode ffxFsr2ContextGetGpuMemoryUsage(FfxFsr2Context* pContext, FfxEffectMemoryUsage* pVramUsage);
/// Dispatch the various passes that constitute FidelityFX Super Resolution 2.
///
/// FSR2 is a composite effect, meaning that it is compromised of multiple
/// constituent passes (implemented as one or more clears, copies and compute
/// dispatches). The <c><i>ffxFsr2ContextDispatch</i></c> function is the
/// function which (via the use of the functions contained in the
/// <c><i>callbacks</i></c> field of the <c><i>FfxFsr2Context</i></c>
/// structure) utlimately generates the sequence of graphics API calls required
/// each frame.
///
/// As with the creation of the <c><i>FfxFsr2Context</i></c> correctly
/// programming the <c><i>FfxFsr2DispatchDescription</i></c> is key to ensuring
/// the correct operation of FSR2. It is particularly important to ensure that
/// camera jitter is correctly applied to your application's projection matrix
/// (or camera origin for raytraced applications). FSR2 provides the
/// <c><i>ffxFsr2GetJitterPhaseCount</i></c> and
/// <c><i>ffxFsr2GetJitterOffset</i></c> entry points to help applications
/// correctly compute the camera jitter. Whatever jitter pattern is used by the
/// application it should be correctly programmed to the
/// <c><i>jitterOffset</i></c> field of the <c><i>dispatchDescription</i></c>
/// structure. For more guidance on camera jitter please consult the
/// documentation for <c><i>ffxFsr2GetJitterOffset</i></c> as well as the
/// accompanying overview documentation for FSR2.
///
/// @param [in] pContext A pointer to a <c><i>FfxFsr2Context</i></c> structure.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxFsr2DispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_OUT_OF_RANGE The operation failed because <c><i>dispatchDescription.renderSize</i></c> was larger than the maximum render resolution.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the device inside the context was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxFsr2
FFX_API FfxErrorCode ffxFsr2ContextDispatch(FfxFsr2Context* pContext, const FfxFsr2DispatchDescription* pDispatchDescription);
/// A helper function generate a Reactive mask from an opaque only texure and one containing translucent objects.
///
/// @param [in] pContext A pointer to a <c><i>FfxFsr2Context</i></c> structure.
/// @param [in] pParams A pointer to a <c><i>FfxFsr2GenerateReactiveDescription</i></c> structure
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxFsr2
FFX_API FfxErrorCode ffxFsr2ContextGenerateReactiveMask(FfxFsr2Context* pContext, const FfxFsr2GenerateReactiveDescription* pParams);
/// Destroy the FidelityFX Super Resolution context.
///
/// @param [out] pContext A pointer to a <c><i>FfxFsr2Context</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxFsr2
FFX_API FfxErrorCode ffxFsr2ContextDestroy(FfxFsr2Context* pContext);
/// Get the upscale ratio from the quality mode.
///
/// The following table enumerates the mapping of the quality modes to
/// per-dimension scaling ratios.
///
/// Quality preset | Scale factor
/// ----------------------------------------------------- | -------------
/// <c><i>FFX_FSR2_QUALITY_MODE_QUALITY</i></c> | 1.5x
/// <c><i>FFX_FSR2_QUALITY_MODE_BALANCED</i></c> | 1.7x
/// <c><i>FFX_FSR2_QUALITY_MODE_PERFORMANCE</i></c> | 2.0x
/// <c><i>FFX_FSR2_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> | 3.0x
///
/// Passing an invalid <c><i>qualityMode</i></c> will return 0.0f.
///
/// @param [in] qualityMode The quality mode preset.
///
/// @returns
/// The upscaling the per-dimension upscaling ratio for
/// <c><i>qualityMode</i></c> according to the table above.
///
/// @ingroup ffxFsr2
FFX_API float ffxFsr2GetUpscaleRatioFromQualityMode(FfxFsr2QualityMode qualityMode);
/// A helper function to calculate the rendering resolution from a target
/// resolution and desired quality level.
///
/// This function applies the scaling factor returned by
/// <c><i>ffxFsr2GetUpscaleRatioFromQualityMode</i></c> to each dimension.
///
/// @param [out] pRenderWidth A pointer to a <c>uint32_t</c> which will hold the calculated render resolution width.
/// @param [out] pRenderHeight A pointer to a <c>uint32_t</c> which will hold the calculated render resolution height.
/// @param [in] displayWidth The target display resolution width.
/// @param [in] displayHeight The target display resolution height.
/// @param [in] qualityMode The desired quality mode for FSR 2 upscaling.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>renderWidth</i></c> or <c><i>renderHeight</i></c> was <c>NULL</c>.
/// @retval
/// FFX_ERROR_INVALID_ENUM An invalid quality mode was specified.
///
/// @ingroup ffxFsr2
FFX_API FfxErrorCode ffxFsr2GetRenderResolutionFromQualityMode(
uint32_t* pRenderWidth,
uint32_t* pRenderHeight,
uint32_t displayWidth,
uint32_t displayHeight,
FfxFsr2QualityMode qualityMode);
/// A helper function to calculate the jitter phase count from display
/// resolution.
///
/// For more detailed information about the application of camera jitter to
/// your application's rendering please refer to the
/// <c><i>ffxFsr2GetJitterOffset</i></c> function.
///
/// The table below shows the jitter phase count which this function
/// would return for each of the quality presets.
///
/// Quality preset | Scale factor | Phase count
/// ----------------------------------------------------- | ------------- | ---------------
/// <c><i>FFX_FSR2_QUALITY_MODE_QUALITY</i></c> | 1.5x | 18
/// <c><i>FFX_FSR2_QUALITY_MODE_BALANCED</i></c> | 1.7x | 23
/// <c><i>FFX_FSR2_QUALITY_MODE_PERFORMANCE</i></c> | 2.0x | 32
/// <c><i>FFX_FSR2_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> | 3.0x | 72
/// Custom | [1..n]x | ceil(8*n^2)
///
/// @param [in] renderWidth The render resolution width.
/// @param [in] displayWidth The display resolution width.
///
/// @returns
/// The jitter phase count for the scaling factor between <c><i>renderWidth</i></c> and <c><i>displayWidth</i></c>.
///
/// @ingroup ffxFsr2
FFX_API int32_t ffxFsr2GetJitterPhaseCount(int32_t renderWidth, int32_t displayWidth);
/// A helper function to calculate the subpixel jitter offset.
///
/// FSR2 relies on the application to apply sub-pixel jittering while rendering.
/// This is typically included in the projection matrix of the camera. To make
/// the application of camera jitter simple, the FSR2 API provides a small set
/// of utility function which computes the sub-pixel jitter offset for a
/// particular frame within a sequence of separate jitter offsets. To begin, the
/// index within the jitter phase must be computed. To calculate the
/// sequence's length, you can call the <c><i>ffxFsr2GetJitterPhaseCount</i></c>
/// function. The index should be a value which is incremented each frame modulo
/// the length of the sequence computed by <c><i>ffxFsr2GetJitterPhaseCount</i></c>.
/// The index within the jitter phase is passed to
/// <c><i>ffxFsr2GetJitterOffset</i></c> via the <c><i>index</i></c> parameter.
///
/// This function uses a Halton(2,3) sequence to compute the jitter offset.
/// The ultimate index used for the sequence is <c><i>index</i></c> %
/// <c><i>phaseCount</i></c>.
///
/// It is important to understand that the values returned from the
/// <c><i>ffxFsr2GetJitterOffset</i></c> function are in unit pixel space, and
/// in order to composite this correctly into a projection matrix we must
/// convert them into projection offsets. This is done as per the pseudo code
/// listing which is shown below.
///
/// const int32_t jitterPhaseCount = ffxFsr2GetJitterPhaseCount(renderWidth, displayWidth);
///
/// float jitterX = 0;
/// float jitterY = 0;
/// ffxFsr2GetJitterOffset(&jitterX, &jitterY, index, jitterPhaseCount);
///
/// const float jitterX = 2.0f * jitterX / (float)renderWidth;
/// const float jitterY = -2.0f * jitterY / (float)renderHeight;
/// const Matrix4 jitterTranslationMatrix = translateMatrix(Matrix3::identity, Vector3(jitterX, jitterY, 0));
/// const Matrix4 jitteredProjectionMatrix = jitterTranslationMatrix * projectionMatrix;
///
/// Jitter should be applied to all rendering. This includes opaque, alpha
/// transparent, and raytraced objects. For rasterized objects, the sub-pixel
/// jittering values calculated by the <c><i>iffxFsr2GetJitterOffset</i></c>
/// function can be applied to the camera projection matrix which is ultimately
/// used to perform transformations during vertex shading. For raytraced
/// rendering, the sub-pixel jitter should be applied to the ray's origin,
/// often the camera's position.
///
/// Whether you elect to use the <c><i>ffxFsr2GetJitterOffset</i></c> function
/// or your own sequence generator, you must program the
/// <c><i>jitterOffset</i></c> field of the
/// <c><i>FfxFsr2DispatchParameters</i></c> structure in order to inform FSR2
/// of the jitter offset that has been applied in order to render each frame.
///
/// If not using the recommended <c><i>ffxFsr2GetJitterOffset</i></c> function,
/// care should be taken that your jitter sequence never generates a null vector;
/// that is value of 0 in both the X and Y dimensions.
///
/// @param [out] pOutX A pointer to a <c>float</c> which will contain the subpixel jitter offset for the x dimension.
/// @param [out] pOutY A pointer to a <c>float</c> which will contain the subpixel jitter offset for the y dimension.
/// @param [in] index The index within the jitter sequence.
/// @param [in] phaseCount The length of jitter phase. See <c><i>ffxFsr2GetJitterPhaseCount</i></c>.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>outX</i></c> or <c><i>outY</i></c> was <c>NULL</c>.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT Argument <c><i>phaseCount</i></c> must be greater than 0.
///
/// @ingroup ffxFsr2
FFX_API FfxErrorCode ffxFsr2GetJitterOffset(float* pOutX, float* pOutY, int32_t index, int32_t phaseCount);
/// A helper function to check if a resource is
/// <c><i>FFX_FSR2_RESOURCE_IDENTIFIER_NULL</i></c>.
///
/// @param [in] resource A <c><i>FfxResource</i></c>.
///
/// @returns
/// true The <c><i>resource</i></c> was not <c><i>FFX_FSR2_RESOURCE_IDENTIFIER_NULL</i></c>.
/// @returns
/// false The <c><i>resource</i></c> was <c><i>FFX_FSR2_RESOURCE_IDENTIFIER_NULL</i></c>.
///
/// @ingroup ffxFsr2
FFX_API bool ffxFsr2ResourceIsNull(FfxResource resource);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxFsr2
FFX_API FfxVersionNumber ffxFsr2GetEffectVersion();
/// Set global debug message settings
///
/// @param [in] fpMessage A <c><i>ffxMessageCallback</i></ci>
/// @param [in] debugLevel An unsigned integer. Unimplemented.
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup FRAMEINTERPOLATION
FFX_API FfxErrorCode ffxFsr2SetGlobalDebugMessage(ffxMessageCallback fpMessage, uint32_t debugLevel);
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,540 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
// @defgroup FSR3
#pragma once
// Include the interface for the backend of the FSR3 API.
#include <FidelityFX/host/ffx_interface.h>
#include <FidelityFX/host/ffx_fsr3upscaler.h>
#include <FidelityFX/host/ffx_frameinterpolation.h>
#include <FidelityFX/host/ffx_opticalflow.h>
/// FidelityFX Super Resolution 3 major version.
///
/// @ingroup FSR3
#define FFX_FSR3_VERSION_MAJOR (3)
/// FidelityFX Super Resolution 3 minor version.
///
/// @ingroup FSR3
#define FFX_FSR3_VERSION_MINOR (1)
/// FidelityFX Super Resolution 3 patch version.
///
/// @ingroup FSR3
#define FFX_FSR3_VERSION_PATCH (4)
/// FidelityFX Super Resolution 3 context count
///
/// Defines the number of internal effect contexts required by FSR3 (+1 for proxy swapchain)
///
/// @ingroup ffxFsr3
#define FFX_FSR3_CONTEXT_COUNT (FFX_FSR3UPSCALER_CONTEXT_COUNT + FFX_OPTICALFLOW_CONTEXT_COUNT + FFX_FRAMEINTERPOLATION_CONTEXT_COUNT + 1)
/// The size of the context specified in 32bit values.
///
/// @ingroup FSR3
#define FFX_FSR3_CONTEXT_SIZE (FFX_FSR3UPSCALER_CONTEXT_SIZE + FFX_OPTICALFLOW_CONTEXT_SIZE + FFX_FRAMEINTERPOLATION_CONTEXT_SIZE + FFX_SDK_DEFAULT_CONTEXT_SIZE)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
///// An enumeration of all the passes which constitute the FSR3 algorithm.
/////
///// FSR3 is implemented as a composite of several compute passes each
///// computing a key part of the final result. Each call to the
///// <c><i>FfxFsr3ScheduleGpuJobFunc</i></c> callback function will
///// correspond to a single pass included in <c><i>FfxFsr3Pass</i></c>. For a
///// more comprehensive description of each pass, please refer to the FSR3
///// reference documentation.
/////
///// Please note in some cases e.g.: <c><i>FFX_FSR3_PASS_ACCUMULATE</i></c>
///// and <c><i>FFX_FSR3_PASS_ACCUMULATE_SHARPEN</i></c> either one pass or the
///// other will be used (they are mutually exclusive). The choice of which will
///// depend on the way the <c><i>FfxFsr3Context</i></c> is created and the
///// precise contents of <c><i>FfxFsr3DispatchParamters</i></c> each time a call
///// is made to <c><i>ffxFsr3ContextDispatch</i></c>.
/////
///// @ingroup FSR3
//typedef enum FfxFsr3Pass
//{
// // no special FSR3 pipelines
//
// FFX_FSR3_PASS_COUNT ///< The number of passes performed by FSR3.
//} FfxFsr3Pass;
/// An enumeration of all the quality modes supported by FidelityFX Super
/// Resolution 2 upscaling.
///
/// In order to provide a consistent user experience across multiple
/// applications which implement FSR3. It is strongly recommended that the
/// following preset scaling factors are made available through your
/// application's user interface.
///
/// If your application does not expose the notion of preset scaling factors
/// for upscaling algorithms (perhaps instead implementing a fixed ratio which
/// is immutable) or implementing a more dynamic scaling scheme (such as
/// dynamic resolution scaling), then there is no need to use these presets.
///
/// Please note that <c><i>FFX_FSR3_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> is
/// an optional mode which may introduce significant quality degradation in the
/// final image. As such it is recommended that you evaluate the final results
/// of using this scaling mode before deciding if you should include it in your
/// application.
///
/// @ingroup FSR3
typedef enum FfxFsr3QualityMode {
FFX_FSR3_QUALITY_MODE_QUALITY = 1, ///< Perform upscaling with a per-dimension upscaling ratio of 1.5x.
FFX_FSR3_QUALITY_MODE_BALANCED = 2, ///< Perform upscaling with a per-dimension upscaling ratio of 1.7x.
FFX_FSR3_QUALITY_MODE_PERFORMANCE = 3, ///< Perform upscaling with a per-dimension upscaling ratio of 2.0x.
FFX_FSR3_QUALITY_MODE_ULTRA_PERFORMANCE = 4 ///< Perform upscaling with a per-dimension upscaling ratio of 3.0x.
} FfxFsr3QualityMode;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxFsr3Context</i></c>. See <c><i>FfxFsr3ContextDescription</i></c>.
///
/// @ingroup FSR3
typedef enum FfxFsr3InitializationFlagBits {
FFX_FSR3_ENABLE_HIGH_DYNAMIC_RANGE = (1<<0), ///< A bit indicating if the input color data provided to all inputs is using a high-dynamic range.
FFX_FSR3_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS = (1<<1), ///< A bit indicating if the motion vectors are rendered at display resolution.
FFX_FSR3_ENABLE_MOTION_VECTORS_JITTER_CANCELLATION = (1<<2), ///< A bit indicating that the motion vectors have the jittering pattern applied to them.
FFX_FSR3_ENABLE_DEPTH_INVERTED = (1<<3), ///< A bit indicating that the input depth buffer data provided is inverted [1..0].
FFX_FSR3_ENABLE_DEPTH_INFINITE = (1<<4), ///< A bit indicating that the input depth buffer data provided is using an infinite far plane.
FFX_FSR3_ENABLE_AUTO_EXPOSURE = (1<<5), ///< A bit indicating if automatic exposure should be applied to input color data.
FFX_FSR3_ENABLE_DYNAMIC_RESOLUTION = (1<<6), ///< A bit indicating that the application uses dynamic resolution scaling.
FFX_FSR3_ENABLE_TEXTURE1D_USAGE = (1<<7), ///< This value is deprecated, but remains in order to aid upgrading from older versions of FSR3.
FFX_FSR3_ENABLE_DEBUG_CHECKING = (1<<8), ///< A bit indicating that the runtime should check some API values and report issues.
FFX_FSR3_ENABLE_UPSCALING_ONLY = (1<<9), ///, A bit indicating that the context will only be used for upscaling
FFX_FSR3_ENABLE_HDR_UPSCALE_SDR_FINALOUTPUT = (1<<10), ///, A bit indicating if the input color data provided to UPSCALE is using a high-dynamic range, final output SDR.
FFX_FSR3_ENABLE_SDR_UPSCALE_HDR_FINALOUTPUT = (1<<11), ///, A bit indicating if the input color data provided to UPSCALE is using SDR, final output is high-dynamic range.
FFX_FSR3_ENABLE_ASYNC_WORKLOAD_SUPPORT = (1<<12),
FFX_FSR3_ENABLE_INTERPOLATION_ONLY = (1<<13),
} FfxFsr3InitializationFlagBits;
typedef enum FfxFsr3FrameGenerationFlags
{
FFX_FSR3_FRAME_GENERATION_FLAG_DRAW_DEBUG_TEAR_LINES = FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_TEAR_LINES, ///< A bit indicating that the debug tear lines will be drawn to the interpolated output.
FFX_FSR3_FRAME_GENERATION_FLAG_DRAW_DEBUG_VIEW = FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_VIEW, ///< A bit indicating that the interpolated output resource will contain debug views with relevant information.
FFX_FSR3_FRAME_GENERATION_FLAG_DRAW_DEBUG_PACING_LINES = FFX_FRAMEINTERPOLATION_DISPATCH_DRAW_DEBUG_PACING_LINES ///< A bit indicating that the debug pacing lines will be drawn to the generated output.
} FfxFsr3FrameGenerationFlags;
typedef enum FfxFsr3UpscalingFlags
{
FFX_FSR3_UPSCALER_FLAG_DRAW_DEBUG_VIEW = FFX_FSR3UPSCALER_DISPATCH_DRAW_DEBUG_VIEW, ///< A bit indicating that the upscaled output resource will contain debug views with relevant information.
} FfxFsr3UpscalingFlags;
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Super Resolution 3 upscaling.
///
/// @ingroup FSR3
typedef struct FfxFsr3ContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxFsr3InitializationFlagBits</i></c>.
FfxDimensions2D maxRenderSize; ///< The maximum size that rendering will be performed at.
FfxDimensions2D maxUpscaleSize; ///< The size of the presentation resolution targeted by the upscaling process.
FfxDimensions2D displaySize; ///< The size of the presentation resolution targeted by the frame interpolation process.
FfxInterface backendInterfaceSharedResources; ///< A set of pointers to the backend implementation for FidelityFX SDK
FfxInterface backendInterfaceUpscaling; ///< A set of pointers to the backend implementation for FidelityFX SDK
FfxInterface backendInterfaceFrameInterpolation; ///< A set of pointers to the backend implementation for FidelityFX SDK
FfxFsr3UpscalerMessage fpMessage; ///< A pointer to a function that can receive messages from the runtime.
FfxSurfaceFormat backBufferFormat; ///< The format of the swapchain surface
} FfxFsr3ContextDescription;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX Super Resolution 3.
///
/// @ingroup FSR3
typedef struct FfxFsr3DispatchUpscaleDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR2 rendering commands into.
FfxResource color; ///< A <c><i>FfxResource</i></c> containing the color buffer for the current frame (at render resolution).
FfxResource depth; ///< A <c><i>FfxResource</i></c> containing 32bit depth values for the current frame (at render resolution).
FfxResource motionVectors; ///< A <c><i>FfxResource</i></c> containing 2-dimensional motion vectors (at render resolution if <c><i>FFX_FSR2_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS</i></c> is not set).
FfxResource exposure; ///< A optional <c><i>FfxResource</i></c> containing a 1x1 exposure value.
FfxResource reactive; ///< A optional <c><i>FfxResource</i></c> containing alpha value of reactive objects in the scene.
FfxResource transparencyAndComposition; ///< A optional <c><i>FfxResource</i></c> containing alpha value of special objects in the scene.
FfxResource upscaleOutput; ///< A <c><i>FfxResource</i></c> containing the output color buffer for the current frame (at presentation resolution).
FfxFloatCoords2D jitterOffset; ///< The subpixel jitter offset applied to the camera.
FfxFloatCoords2D motionVectorScale; ///< The scale factor to apply to motion vectors.
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
FfxDimensions2D upscaleSize; ///< The resolution that the upscaler will output.
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. This is used only used in case of non infinite depth.
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; ///< combination of FfxFsr3UpscalingFlags
uint64_t frameID;
} FfxFsr3DispatchUpscaleDescription;
typedef struct FfxFsr3DispatchFrameGenerationPrepareDescription
{
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR2 rendering commands into.
FfxResource depth; ///< A <c><i>FfxResource</i></c> containing 32bit depth values for the current frame (at render resolution).
FfxResource motionVectors; ///< A <c><i>FfxResource</i></c> containing 2-dimensional motion vectors (at render resolution if <c><i>FFX_FSR2_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS</i></c> is not set).
FfxFloatCoords2D jitterOffset; ///< The subpixel jitter offset applied to the camera.
FfxFloatCoords2D motionVectorScale; ///< The scale factor to apply to motion vectors.
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
float frameTimeDelta;
float cameraNear;
float cameraFar;
float viewSpaceToMetersFactor;
float cameraFovAngleVertical;
uint64_t frameID;
} FfxFsr3DispatchFrameGenerationPrepareDescription;
FFX_API FfxErrorCode ffxFsr3DispatchFrameGeneration(const FfxFrameGenerationDispatchDescription* desc);
/// A structure encapsulating the parameters for automatic generation of a reactive mask
///
/// @ingroup FSR3
typedef struct FfxFsr3GenerateReactiveDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR3 rendering commands into.
FfxResource colorOpaqueOnly; ///< A <c><i>FfxResource</i></c> containing the opaque only color buffer for the current frame (at render resolution).
FfxResource colorPreUpscale; ///< A <c><i>FfxResource</i></c> containing the opaque+translucent color buffer for the current frame (at render resolution).
FfxResource outReactive; ///< A <c><i>FfxResource</i></c> containing the surface to generate the reactive mask into.
FfxDimensions2D 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;
uint32_t flags; ///< Flags to determine how to generate the reactive mask
} FfxFsr3GenerateReactiveDescription;
/// A structure encapsulating the FidelityFX Super Resolution 3 context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by FSR3.
///
/// The <c><i>FfxFsr3Context</i></c> object should have a lifetime matching
/// your use of FSR3. Before destroying the FSR3 context care should be taken
/// to ensure the GPU is not accessing the resources created or used by FSR3.
/// It is therefore recommended that the GPU is idle before destroying the
/// FSR3 context.
///
/// @ingroup FSR3
typedef struct FfxFsr3Context
{
uint32_t data[FFX_FSR3_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxFsr3Context;
/// Create a FidelityFX Super Resolution 3 context from the parameters
/// programmed to the <c><i>FfxFsr3CreateParams</i></c> structure.
///
/// The context structure is the main object used to interact with the FSR3
/// API, and is responsible for the management of the internal resources used
/// by the FSR3 algorithm. When this API is called, multiple calls will be
/// made via the pointers contained in the <c><i>callbacks</i></c> structure.
/// These callbacks will attempt to retreive the device capabilities, and
/// create the internal resources, and pipelines required by FSR3's
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxFsr3Context</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The flags included in the <c><i>flags</i></c> field of
/// <c><i>FfxFsr3Context</i></c> how match the configuration of your
/// application as well as the intended use of FSR3. It is important that these
/// flags are set correctly (as well as a correct programmed
/// <c><i>FfxFsr3DispatchDescription</i></c>) to ensure correct operation. It is
/// recommended to consult the overview documentation for further details on
/// how FSR3 should be integerated into an application.
///
/// When the <c><i>FfxFsr3Context</i></c> is created, you should use the
/// <c><i>ffxFsr3ContextDispatch</i></c> function each frame where FSR3
/// upscaling should be applied. See the documentation of
/// <c><i>ffxFsr3ContextDispatch</i></c> for more details.
///
/// The <c><i>FfxFsr3Context</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or FSR3 upscaling is
/// disabled by a user. To destroy the FSR3 context you should call
/// <c><i>ffxFsr3ContextDestroy</i></c>.
///
/// @param [out] context A pointer to a <c><i>FfxFsr3Context</i></c> structure to populate.
/// @param [in] contextDescription A pointer to a <c><i>FfxFsr3ContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxFsr3ContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3ContextCreate(FfxFsr3Context* context, FfxFsr3ContextDescription* contextDescription);
FFX_API FfxErrorCode ffxFsr3ContextGetGpuMemoryUsage(FfxFsr3Context* pContext,
FfxEffectMemoryUsage* pUpscalerUsage,
FfxEffectMemoryUsage* pOpticalFlowUsage,
FfxEffectMemoryUsage* pFrameGenerationUsage);
/// Dispatch the various passes that constitute FidelityFX Super Resolution 3 Upscaling.
///
/// FSR3 is a composite effect, meaning that it is compromised of multiple
/// constituent passes (implemented as one or more clears, copies and compute
/// dispatches). The <c><i>ffxFsr3ContextDispatchUpscale</i></c> function is the
/// function which (via the use of the functions contained in the
/// <c><i>callbacks</i></c> field of the <c><i>FfxFsr3Context</i></c>
/// structure) utlimately generates the sequence of graphics API calls required
/// each frame.
///
/// As with the creation of the <c><i>FfxFsr3Context</i></c> correctly
/// programming the <c><i>dispatchParams</i></c> is key to ensuring
/// the correct operation of FSR3. It is particularly important to ensure that
/// camera jitter is correctly applied to your application's projection matrix
/// (or camera origin for raytraced applications). FSR3 provides the
/// <c><i>ffxFsr3GetJitterPhaseCount</i></c> and
/// <c><i>ffxFsr3GetJitterOffset</i></c> entry points to help applications
/// correctly compute the camera jitter. Whatever jitter pattern is used by the
/// application it should be correctly programmed to the
/// <c><i>jitterOffset</i></c> field of the <c><i>dispatchParams</i></c>
/// structure. For more guidance on camera jitter please consult the
/// documentation for <c><i>ffxFsr3GetJitterOffset</i></c> as well as the
/// accompanying overview documentation for FSR3.
///
/// @param [in] context A pointer to a <c><i>FfxFsr3Context</i></c> structure.
/// @param [in] dispatchParams A pointer to a <c><i>FfxFsr3DispatchUpscaleDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchParams</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_OUT_OF_RANGE The operation failed because <c><i>dispatchParams.renderSize</i></c> was larger than the maximum render resolution.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the device inside the context was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3ContextDispatchUpscale(FfxFsr3Context* context, const FfxFsr3DispatchUpscaleDescription* dispatchParams);
FFX_API FfxErrorCode ffxFsr3ContextDispatchFrameGenerationPrepare(FfxFsr3Context* context, const FfxFsr3DispatchFrameGenerationPrepareDescription* dispatchParams);
FFX_API FfxErrorCode ffxFsr3SkipPresent(FfxFsr3Context* context);
/// A helper function generate a Reactive mask from an opaque only texure and one containing translucent objects.
///
/// @param [in] context A pointer to a <c><i>FfxFsr3Context</i></c> structure.
/// @param [in] params A pointer to a <c><i>FfxFsr3GenerateReactiveDescription</i></c> structure
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3ContextGenerateReactiveMask(FfxFsr3Context* context, const FfxFsr3GenerateReactiveDescription* params);
FFX_API FfxErrorCode ffxFsr3ConfigureFrameGeneration(FfxFsr3Context* context, const FfxFrameGenerationConfig* config);
/// Destroy the FidelityFX Super Resolution context.
///
/// @param [out] context A pointer to a <c><i>FfxFsr3Context</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3ContextDestroy(FfxFsr3Context* context);
/// Get the upscale ratio from the quality mode.
///
/// The following table enumerates the mapping of the quality modes to
/// per-dimension scaling ratios.
///
/// Quality preset | Scale factor
/// ----------------------------------------------------- | -------------
/// <c><i>FFX_FSR3_QUALITY_MODE_NATIVEAA</i></c> | 1.0x
/// <c><i>FFX_FSR3_QUALITY_MODE_QUALITY</i></c> | 1.5x
/// <c><i>FFX_FSR3_QUALITY_MODE_BALANCED</i></c> | 1.7x
/// <c><i>FFX_FSR3_QUALITY_MODE_PERFORMANCE</i></c> | 2.0x
/// <c><i>FFX_FSR3_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> | 3.0x
///
/// Passing an invalid <c><i>qualityMode</i></c> will return 0.0f.
///
/// @param [in] qualityMode The quality mode preset.
///
/// @returns
/// The upscaling the per-dimension upscaling ratio for
/// <c><i>qualityMode</i></c> according to the table above.
///
/// @ingroup FSR3
FFX_API float ffxFsr3GetUpscaleRatioFromQualityMode(FfxFsr3QualityMode qualityMode);
/// A helper function to calculate the rendering resolution from a target
/// resolution and desired quality level.
///
/// This function applies the scaling factor returned by
/// <c><i>ffxFsr3GetUpscaleRatioFromQualityMode</i></c> to each dimension.
///
/// @param [out] renderWidth A pointer to a <c>uint32_t</c> which will hold the calculated render resolution width.
/// @param [out] renderHeight A pointer to a <c>uint32_t</c> which will hold the calculated render resolution height.
/// @param [in] displayWidth The target display resolution width.
/// @param [in] displayHeight The target display resolution height.
/// @param [in] qualityMode The desired quality mode for FSR 2 upscaling.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>renderWidth</i></c> or <c><i>renderHeight</i></c> was <c>NULL</c>.
/// @retval
/// FFX_ERROR_INVALID_ENUM An invalid quality mode was specified.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3GetRenderResolutionFromQualityMode(
uint32_t* renderWidth,
uint32_t* renderHeight,
uint32_t displayWidth,
uint32_t displayHeight,
FfxFsr3QualityMode qualityMode);
/// A helper function to calculate the jitter phase count from display
/// resolution.
///
/// For more detailed information about the application of camera jitter to
/// your application's rendering please refer to the
/// <c><i>ffxFsr3GetJitterOffset</i></c> function.
///
/// The table below shows the jitter phase count which this function
/// would return for each of the quality presets.
///
/// Quality preset | Scale factor | Phase count
/// ----------------------------------------------------- | ------------- | ---------------
/// <c><i>FFX_FSR3_QUALITY_MODE_QUALITY</i></c> | 1.5x | 18
/// <c><i>FFX_FSR3_QUALITY_MODE_BALANCED</i></c> | 1.7x | 23
/// <c><i>FFX_FSR3_QUALITY_MODE_PERFORMANCE</i></c> | 2.0x | 32
/// <c><i>FFX_FSR3_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> | 3.0x | 72
/// Custom | [1..n]x | ceil(8*n^2)
///
/// @param [in] renderWidth The render resolution width.
/// @param [in] displayWidth The display resolution width.
///
/// @returns
/// The jitter phase count for the scaling factor between <c><i>renderWidth</i></c> and <c><i>displayWidth</i></c>.
///
/// @ingroup FSR3
FFX_API int32_t ffxFsr3GetJitterPhaseCount(int32_t renderWidth, int32_t displayWidth);
/// A helper function to calculate the subpixel jitter offset.
///
/// FSR3 relies on the application to apply sub-pixel jittering while rendering.
/// This is typically included in the projection matrix of the camera. To make
/// the application of camera jitter simple, the FSR3 API provides a small set
/// of utility function which computes the sub-pixel jitter offset for a
/// particular frame within a sequence of separate jitter offsets. To begin, the
/// index within the jitter phase must be computed. To calculate the
/// sequence's length, you can call the <c><i>ffxFsr3GetJitterPhaseCount</i></c>
/// function. The index should be a value which is incremented each frame modulo
/// the length of the sequence computed by <c><i>ffxFsr3GetJitterPhaseCount</i></c>.
/// The index within the jitter phase is passed to
/// <c><i>ffxFsr3GetJitterOffset</i></c> via the <c><i>index</i></c> parameter.
///
/// This function uses a Halton(2,3) sequence to compute the jitter offset.
/// The ultimate index used for the sequence is <c><i>index</i></c> %
/// <c><i>phaseCount</i></c>.
///
/// It is important to understand that the values returned from the
/// <c><i>ffxFsr3GetJitterOffset</i></c> function are in unit pixel space, and
/// in order to composite this correctly into a projection matrix we must
/// convert them into projection offsets. This is done as per the pseudo code
/// listing which is shown below.
///
/// const int32_t jitterPhaseCount = ffxFsr3GetJitterPhaseCount(renderWidth, displayWidth);
///
/// float jitterX = 0;
/// float jitterY = 0;
/// ffxFsr3GetJitterOffset(&jitterX, &jitterY, index, jitterPhaseCount);
///
/// const float jitterX = 2.0f * jitterX / (float)renderWidth;
/// const float jitterY = -2.0f * jitterY / (float)renderHeight;
/// const Matrix4 jitterTranslationMatrix = translateMatrix(Matrix3::identity, Vector3(jitterX, jitterY, 0));
/// const Matrix4 jitteredProjectionMatrix = jitterTranslationMatrix * projectionMatrix;
///
/// Jitter should be applied to all rendering. This includes opaque, alpha
/// transparent, and raytraced objects. For rasterized objects, the sub-pixel
/// jittering values calculated by the <c><i>iffxFsr3GetJitterOffset</i></c>
/// function can be applied to the camera projection matrix which is ultimately
/// used to perform transformations during vertex shading. For raytraced
/// rendering, the sub-pixel jitter should be applied to the ray's origin,
/// often the camera's position.
///
/// Whether you elect to use the <c><i>ffxFsr3GetJitterOffset</i></c> function
/// or your own sequence generator, you must program the
/// <c><i>jitterOffset</i></c> field of the
/// <c><i>FfxFsr3DispatchParameters</i></c> structure in order to inform FSR3
/// of the jitter offset that has been applied in order to render each frame.
///
/// If not using the recommended <c><i>ffxFsr3GetJitterOffset</i></c> function,
/// care should be taken that your jitter sequence never generates a null vector;
/// that is value of 0 in both the X and Y dimensions.
///
/// @param [out] outX A pointer to a <c>float</c> which will contain the subpixel jitter offset for the x dimension.
/// @param [out] outY A pointer to a <c>float</c> which will contain the subpixel jitter offset for the y dimension.
/// @param [in] index The index within the jitter sequence.
/// @param [in] phaseCount The length of jitter phase. See <c><i>ffxFsr3GetJitterPhaseCount</i></c>.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>outX</i></c> or <c><i>outY</i></c> was <c>NULL</c>.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT Argument <c><i>phaseCount</i></c> must be greater than 0.
///
/// @ingroup FSR3
FFX_API FfxErrorCode ffxFsr3GetJitterOffset(float* outX, float* outY, int32_t index, int32_t phaseCount);
/// A helper function to check if a resource is
/// <c><i>FFX_FSR3_RESOURCE_IDENTIFIER_NULL</i></c>.
///
/// @param [in] resource A <c><i>FfxResource</i></c>.
///
/// @returns
/// true The <c><i>resource</i></c> was not <c><i>FFX_FSR3_RESOURCE_IDENTIFIER_NULL</i></c>.
/// @returns
/// false The <c><i>resource</i></c> was <c><i>FFX_FSR3_RESOURCE_IDENTIFIER_NULL</i></c>.
///
/// @ingroup FSR3
FFX_API bool ffxFsr3ResourceIsNull(FfxResource resource);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup FSR3
FFX_API FfxVersionNumber ffxFsr3GetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,592 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 the interface for the backend of the FSR3 API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup ffxFsr3Upscaler FidelityFX FSR3
/// FidelityFX Super Resolution 3 runtime library
///
/// @ingroup SDKComponents
/// FidelityFX Super Resolution 3 major version.
///
/// @ingroup ffxFsr3Upscaler
#define FFX_FSR3UPSCALER_VERSION_MAJOR (3)
/// FidelityFX Super Resolution 3 minor version.
///
/// @ingroup ffxFsr3Upscaler
#define FFX_FSR3UPSCALER_VERSION_MINOR (1)
/// FidelityFX Super Resolution 3 patch version.
///
/// @ingroup ffxFsr3Upscaler
#define FFX_FSR3UPSCALER_VERSION_PATCH (4)
/// FidelityFX Super Resolution 3 context count
///
/// Defines the number of internal effect contexts required by FSR3
///
/// @ingroup ffxFsr3Upscaler
#define FFX_FSR3UPSCALER_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup ffxFsr3Upscaler
#define FFX_FSR3UPSCALER_CONTEXT_SIZE (FFX_SDK_DEFAULT_CONTEXT_SIZE)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of all the passes which constitute the FSR3 algorithm.
///
/// FSR3 is implemented as a composite of several compute passes each
/// computing a key part of the final result. Each call to the
/// <c><i>FfxFsr3UpscalerScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single pass included in <c><i>FfxFsr3UpscalerPass</i></c>. For a
/// more comprehensive description of each pass, please refer to the FSR3
/// reference documentation.
///
/// Please note in some cases e.g.: <c><i>FFX_FSR3UPSCALER_PASS_ACCUMULATE</i></c>
/// and <c><i>FFX_FSR3UPSCALER_PASS_ACCUMULATE_SHARPEN</i></c> either one pass or the
/// other will be used (they are mutually exclusive). The choice of which will
/// depend on the way the <c><i>FfxFsr3UpscalerContext</i></c> is created and the
/// precise contents of <c><i>FfxFsr3UpscalerDispatchParamters</i></c> each time a call
/// is made to <c><i>ffxFsr3UpscalerContextDispatch</i></c>.
///
/// @ingroup ffxFsr3Upscaler
typedef enum FfxFsr3UpscalerPass
{
FFX_FSR3UPSCALER_PASS_PREPARE_INPUTS, ///< A pass which prepares game inputs for later passes
FFX_FSR3UPSCALER_PASS_LUMA_PYRAMID, ///< A pass which generates the luminance mipmap chain for the current frame.
FFX_FSR3UPSCALER_PASS_SHADING_CHANGE_PYRAMID, ///< A pass which generates the shading change detection mipmap chain for the current frame.
FFX_FSR3UPSCALER_PASS_SHADING_CHANGE, ///< A pass which estimates shading changes for the current frame
FFX_FSR3UPSCALER_PASS_PREPARE_REACTIVITY, ///< A pass which prepares accumulation relevant information
FFX_FSR3UPSCALER_PASS_LUMA_INSTABILITY, ///< A pass which estimates temporal instability of the luminance changes.
FFX_FSR3UPSCALER_PASS_ACCUMULATE, ///< A pass which performs upscaling.
FFX_FSR3UPSCALER_PASS_ACCUMULATE_SHARPEN, ///< A pass which performs upscaling when sharpening is used.
FFX_FSR3UPSCALER_PASS_RCAS, ///< A pass which performs sharpening.
FFX_FSR3UPSCALER_PASS_DEBUG_VIEW, ///< A pass which draws some internal resources, for debugging purposes
FFX_FSR3UPSCALER_PASS_GENERATE_REACTIVE, ///< An optional pass to generate a reactive mask.
FFX_FSR3UPSCALER_PASS_TCR_AUTOGENERATE, ///< DEPRECATED - NO LONGER SUPPORTED
FFX_FSR3UPSCALER_PASS_COUNT ///< The number of passes performed by FSR3.
} FfxFsr3UpscalerPass;
/// An enumeration of all the quality modes supported by FidelityFX Super
/// Resolution 3 upscaling.
///
/// In order to provide a consistent user experience across multiple
/// applications which implement FSR3. It is strongly recommended that the
/// following preset scaling factors are made available through your
/// application's user interface.
///
/// If your application does not expose the notion of preset scaling factors
/// for upscaling algorithms (perhaps instead implementing a fixed ratio which
/// is immutable) or implementing a more dynamic scaling scheme (such as
/// dynamic resolution scaling), then there is no need to use these presets.
///
/// Please note that <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> is
/// an optional mode which may introduce significant quality degradation in the
/// final image. As such it is recommended that you evaluate the final results
/// of using this scaling mode before deciding if you should include it in your
/// application.
///
/// @ingroup ffxFsr3Upscaler
typedef enum FfxFsr3UpscalerQualityMode {
FFX_FSR3UPSCALER_QUALITY_MODE_NATIVEAA = 0, ///< Perform upscaling with a per-dimension upscaling ratio of 1.0x.
FFX_FSR3UPSCALER_QUALITY_MODE_QUALITY = 1, ///< Perform upscaling with a per-dimension upscaling ratio of 1.5x.
FFX_FSR3UPSCALER_QUALITY_MODE_BALANCED = 2, ///< Perform upscaling with a per-dimension upscaling ratio of 1.7x.
FFX_FSR3UPSCALER_QUALITY_MODE_PERFORMANCE = 3, ///< Perform upscaling with a per-dimension upscaling ratio of 2.0x.
FFX_FSR3UPSCALER_QUALITY_MODE_ULTRA_PERFORMANCE = 4 ///< Perform upscaling with a per-dimension upscaling ratio of 3.0x.
} FfxFsr3UpscalerQualityMode;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxFsr3UpscalerContext</i></c>. See <c><i>FfxFsr3UpscalerContextDescription</i></c>.
///
/// @ingroup ffxFsr3Upscaler
typedef enum FfxFsr3UpscalerInitializationFlagBits {
FFX_FSR3UPSCALER_ENABLE_HIGH_DYNAMIC_RANGE = (1<<0), ///< A bit indicating if the input color data provided is using a high-dynamic range.
FFX_FSR3UPSCALER_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS = (1<<1), ///< A bit indicating if the motion vectors are rendered at display resolution.
FFX_FSR3UPSCALER_ENABLE_MOTION_VECTORS_JITTER_CANCELLATION = (1<<2), ///< A bit indicating that the motion vectors have the jittering pattern applied to them.
FFX_FSR3UPSCALER_ENABLE_DEPTH_INVERTED = (1<<3), ///< A bit indicating that the input depth buffer data provided is inverted [1..0].
FFX_FSR3UPSCALER_ENABLE_DEPTH_INFINITE = (1<<4), ///< A bit indicating that the input depth buffer data provided is using an infinite far plane.
FFX_FSR3UPSCALER_ENABLE_AUTO_EXPOSURE = (1<<5), ///< A bit indicating if automatic exposure should be applied to input color data.
FFX_FSR3UPSCALER_ENABLE_DYNAMIC_RESOLUTION = (1<<6), ///< A bit indicating that the application uses dynamic resolution scaling.
FFX_FSR3UPSCALER_ENABLE_TEXTURE1D_USAGE = (1<<7), ///< This value is deprecated, but remains in order to aid upgrading from older versions of FSR3.
FFX_FSR3UPSCALER_ENABLE_DEBUG_CHECKING = (1<<8), ///< A bit indicating that the runtime should check some API values and report issues.
} FfxFsr3UpscalerInitializationFlagBits;
/// Pass a string message
///
/// Used for debug messages.
///
/// @param [in] type The type of message.
/// @param [in] message A string message to pass.
///
///
/// @ingroup ffxFsr3Upscaler
typedef void(*FfxFsr3UpscalerMessage)(
FfxMsgType type,
const wchar_t* message);
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Super Resolution 3 upscaling.
///
/// @ingroup ffxFsr3Upscaler
typedef struct FfxFsr3UpscalerContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxFsr3UpscalerInitializationFlagBits</i></c>.
FfxDimensions2D maxRenderSize; ///< The maximum size that rendering will be performed at.
FfxDimensions2D maxUpscaleSize; ///< The size of the output resolution targeted by the upscaling process.
FfxFsr3UpscalerMessage fpMessage; ///< A pointer to a function that can receive messages from the runtime.
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX SDK
} FfxFsr3UpscalerContextDescription;
typedef enum FfxFsr3UpscalerDispatchFlags
{
FFX_FSR3UPSCALER_DISPATCH_DRAW_DEBUG_VIEW = (1 << 0), ///< A bit indicating that the interpolated output resource will contain debug views with relevant information.
} FfxFsr3UpscalerDispatchFlags;
typedef enum FfxFsr3UpscalerConfigureKey
{
FFX_FSR3UPSCALER_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_FSR3UPSCALER_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_FSR3UPSCALER_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_FSR3UPSCALER_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_FSR3UPSCALER_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. Default value is -0.333. 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].
} FfxFsr3UpscalerConfigureKey;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX Super Resolution 3.
///
/// @ingroup ffxFsr3Upscaler
typedef struct FfxFsr3UpscalerDispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR3 rendering commands into.
FfxResource color; ///< A <c><i>FfxResource</i></c> containing the color buffer for the current frame (at render resolution).
FfxResource depth; ///< A <c><i>FfxResource</i></c> containing 32bit depth values for the current frame (at render resolution).
FfxResource motionVectors; ///< A <c><i>FfxResource</i></c> containing 2-dimensional motion vectors (at render resolution if <c><i>FFX_FSR3UPSCALER_ENABLE_DISPLAY_RESOLUTION_MOTION_VECTORS</i></c> is not set).
FfxResource exposure; ///< A optional <c><i>FfxResource</i></c> containing a 1x1 exposure value.
FfxResource reactive; ///< A optional <c><i>FfxResource</i></c> containing alpha value of reactive objects in the scene.
FfxResource transparencyAndComposition; ///< A optional <c><i>FfxResource</i></c> containing alpha value of special objects in the scene.
FfxResource dilatedDepth; ///< A <c><i>FfxResource</i></c> allocated as described in <c><i>FfxFsr3UpscalerSharedResourceDescriptions</i></c> that is used to emit dilated depth and share with following effects.
FfxResource dilatedMotionVectors; ///< A <c><i>FfxResource</i></c> allocated as described in <c><i>FfxFsr3UpscalerSharedResourceDescriptions</i></c> that is used to emit dilated motion vectors and share with following effects.
FfxResource reconstructedPrevNearestDepth; ///< A <c><i>FfxResource</i></c> allocated as described in <c><i>FfxFsr3UpscalerSharedResourceDescriptions</i></c> that is used to emit reconstructed previous nearest depth and share with following effects.
FfxResource output; ///< A <c><i>FfxResource</i></c> containing the output color buffer for the current frame (at presentation resolution).
FfxFloatCoords2D jitterOffset; ///< The subpixel jitter offset applied to the camera.
FfxFloatCoords2D motionVectorScale; ///< The scale factor to apply to motion vectors.
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
FfxDimensions2D upscaleSize; ///< The resolution that the upscaler will output.
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; ///< combination of FfxFsr3UpscalerDispatchFlags
} FfxFsr3UpscalerDispatchDescription;
/// A structure encapsulating the parameters for automatic generation of a reactive mask
///
/// @ingroup ffxFsr3Upscaler
typedef struct FfxFsr3UpscalerGenerateReactiveDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record FSR3 rendering commands into.
FfxResource colorOpaqueOnly; ///< A <c><i>FfxResource</i></c> containing the opaque only color buffer for the current frame (at render resolution).
FfxResource colorPreUpscale; ///< A <c><i>FfxResource</i></c> containing the opaque+translucent color buffer for the current frame (at render resolution).
FfxResource outReactive; ///< A <c><i>FfxResource</i></c> containing the surface to generate the reactive mask into.
FfxDimensions2D 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
} FfxFsr3UpscalerGenerateReactiveDescription;
/// A structure encapsulating the resource descriptions for shared resources for this effect.
///
/// @ingroup ffxFsr3Upscaler
typedef struct FfxFsr3UpscalerSharedResourceDescriptions {
FfxCreateResourceDescription reconstructedPrevNearestDepth; ///< The <c><i>FfxCreateResourceDescription</i></c> for allocating the <c><i>reconstructedPrevNearestDepth</i></c> shared resource.
FfxCreateResourceDescription dilatedDepth; ///< The <c><i>FfxCreateResourceDescription</i></c> for allocating the <c><i>dilatedDepth</i></c> shared resource.
FfxCreateResourceDescription dilatedMotionVectors; ///< The <c><i>FfxCreateResourceDescription</i></c> for allocating the <c><i>dilatedMotionVectors</i></c> shared resource.
} FfxFsr3UpscalerSharedResourceDescriptions;
/// A structure encapsulating the FidelityFX Super Resolution 3 context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by FSR3.
///
/// The <c><i>FfxFsr3UpscalerContext</i></c> object should have a lifetime matching
/// your use of FSR3. Before destroying the FSR3 context care should be taken
/// to ensure the GPU is not accessing the resources created or used by FSR3.
/// It is therefore recommended that the GPU is idle before destroying the
/// FSR3 context.
///
/// @ingroup ffxFsr3Upscaler
typedef struct FfxFsr3UpscalerContext
{
uint32_t data[FFX_FSR3UPSCALER_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxFsr3UpscalerContext;
/// Create a FidelityFX Super Resolution 3 context from the parameters
/// programmed to the <c><i>FfxFsr3UpscalerCreateParams</i></c> structure.
///
/// The context structure is the main object used to interact with the FSR3
/// API, and is responsible for the management of the internal resources used
/// by the FSR3 algorithm. When this API is called, multiple calls will be
/// made via the pointers contained in the <c><i>callbacks</i></c> structure.
/// These callbacks will attempt to retreive the device capabilities, and
/// create the internal resources, and pipelines required by FSR3's
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxFsr3UpscalerContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The flags included in the <c><i>flags</i></c> field of
/// <c><i>FfxFsr3UpscalerContext</i></c> how match the configuration of your
/// application as well as the intended use of FSR3. It is important that these
/// flags are set correctly (as well as a correct programmed
/// <c><i>FfxFsr3UpscalerDispatchDescription</i></c>) to ensure correct operation. It is
/// recommended to consult the overview documentation for further details on
/// how FSR3 should be integerated into an application.
///
/// When the <c><i>FfxFsr3UpscalerContext</i></c> is created, you should use the
/// <c><i>ffxFsr3UpscalerContextDispatch</i></c> function each frame where FSR3
/// upscaling should be applied. See the documentation of
/// <c><i>ffxFsr3UpscalerContextDispatch</i></c> for more details.
///
/// The <c><i>FfxFsr3UpscalerContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or FSR3 upscaling is
/// disabled by a user. To destroy the FSR3 context you should call
/// <c><i>ffxFsr3UpscalerContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxFsr3UpscalerContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxFsr3UpscalerContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerContextCreate(FfxFsr3UpscalerContext* pContext, const FfxFsr3UpscalerContextDescription* pContextDescription);
/// Provides the descriptions for shared resources that must be allocated for this effect.
///
/// @param [in] context A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure.
/// @param [out] SharedResources A pointer to a <c><i>FfxFsr3UpscalerSharedResourceDescriptions</i></c> to populate.
///
/// @returns
/// FFX_OK The operation completed successfully.
/// @returns
/// Anything else The operation failed.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerGetSharedResourceDescriptions(FfxFsr3UpscalerContext* context, FfxFsr3UpscalerSharedResourceDescriptions* SharedResources);
/// Get GPU memory usage of the FidelityFX Super Resolution context.
///
/// @param [in] pContext A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure.
/// @param [out] pVramUsage A pointer to a <c><i>FfxEffectMemoryUsage</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>vramUsage</i></c> were <c><i>NULL</i></c>.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerContextGetGpuMemoryUsage(FfxFsr3UpscalerContext* pContext, FfxEffectMemoryUsage* pVramUsage);
/// Dispatch the various passes that constitute FidelityFX Super Resolution 3.
///
/// FSR3 is a composite effect, meaning that it is compromised of multiple
/// constituent passes (implemented as one or more clears, copies and compute
/// dispatches). The <c><i>ffxFsr3UpscalerContextDispatch</i></c> function is the
/// function which (via the use of the functions contained in the
/// <c><i>callbacks</i></c> field of the <c><i>FfxFsr3UpscalerContext</i></c>
/// structure) utlimately generates the sequence of graphics API calls required
/// each frame.
///
/// As with the creation of the <c><i>FfxFsr3UpscalerContext</i></c> correctly
/// programming the <c><i>FfxFsr3UpscalerDispatchDescription</i></c> is key to ensuring
/// the correct operation of FSR3. It is particularly important to ensure that
/// camera jitter is correctly applied to your application's projection matrix
/// (or camera origin for raytraced applications). FSR3 provides the
/// <c><i>ffxFsr3UpscalerGetJitterPhaseCount</i></c> and
/// <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> entry points to help applications
/// correctly compute the camera jitter. Whatever jitter pattern is used by the
/// application it should be correctly programmed to the
/// <c><i>jitterOffset</i></c> field of the <c><i>dispatchDescription</i></c>
/// structure. For more guidance on camera jitter please consult the
/// documentation for <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> as well as the
/// accompanying overview documentation for FSR3.
///
/// @param [in] pContext A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxFsr3UpscalerDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_OUT_OF_RANGE The operation failed because <c><i>dispatchDescription.renderSize</i></c> was larger than the maximum render resolution.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the device inside the context was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerContextDispatch(FfxFsr3UpscalerContext* pContext, const FfxFsr3UpscalerDispatchDescription* pDispatchDescription);
/// A helper function generate a Reactive mask from an opaque only texure and one containing translucent objects.
///
/// @param [in] pContext A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure.
/// @param [in] pParams A pointer to a <c><i>FfxFsr3UpscalerGenerateReactiveDescription</i></c> structure
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerContextGenerateReactiveMask(FfxFsr3UpscalerContext* pContext, const FfxFsr3UpscalerGenerateReactiveDescription* pParams);
/// Destroy the FidelityFX Super Resolution context.
///
/// @param [out] pContext A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerContextDestroy(FfxFsr3UpscalerContext* pContext);
/// Get the upscale ratio from the quality mode.
///
/// The following table enumerates the mapping of the quality modes to
/// per-dimension scaling ratios.
///
/// Quality preset | Scale factor
/// ----------------------------------------------------- | -------------
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_QUALITY</i></c> | 1.5x
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_BALANCED</i></c> | 1.7x
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_PERFORMANCE</i></c> | 2.0x
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> | 3.0x
///
/// Passing an invalid <c><i>qualityMode</i></c> will return 0.0f.
///
/// @param [in] qualityMode The quality mode preset.
///
/// @returns
/// The upscaling the per-dimension upscaling ratio for
/// <c><i>qualityMode</i></c> according to the table above.
///
/// @ingroup ffxFsr3Upscaler
FFX_API float ffxFsr3UpscalerGetUpscaleRatioFromQualityMode(FfxFsr3UpscalerQualityMode qualityMode);
/// A helper function to calculate the rendering resolution from a target
/// resolution and desired quality level.
///
/// This function applies the scaling factor returned by
/// <c><i>ffxFsr3UpscalerGetUpscaleRatioFromQualityMode</i></c> to each dimension.
///
/// @param [out] pRenderWidth A pointer to a <c>uint32_t</c> which will hold the calculated render resolution width.
/// @param [out] pRenderHeight A pointer to a <c>uint32_t</c> which will hold the calculated render resolution height.
/// @param [in] displayWidth The target display resolution width.
/// @param [in] displayHeight The target display resolution height.
/// @param [in] qualityMode The desired quality mode for FSR 2 upscaling.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>renderWidth</i></c> or <c><i>renderHeight</i></c> was <c>NULL</c>.
/// @retval
/// FFX_ERROR_INVALID_ENUM An invalid quality mode was specified.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerGetRenderResolutionFromQualityMode(
uint32_t* pRenderWidth,
uint32_t* pRenderHeight,
uint32_t displayWidth,
uint32_t displayHeight,
FfxFsr3UpscalerQualityMode qualityMode);
/// A helper function to calculate the jitter phase count from display
/// resolution.
///
/// For more detailed information about the application of camera jitter to
/// your application's rendering please refer to the
/// <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> function.
///
/// The table below shows the jitter phase count which this function
/// would return for each of the quality presets.
///
/// Quality preset | Scale factor | Phase count
/// ----------------------------------------------------- | ------------- | ---------------
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_QUALITY</i></c> | 1.5x | 18
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_BALANCED</i></c> | 1.7x | 23
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_PERFORMANCE</i></c> | 2.0x | 32
/// <c><i>FFX_FSR3UPSCALER_QUALITY_MODE_ULTRA_PERFORMANCE</i></c> | 3.0x | 72
/// Custom | [1..n]x | ceil(8*n^2)
///
/// @param [in] renderWidth The render resolution width.
/// @param [in] displayWidth The display resolution width.
///
/// @returns
/// The jitter phase count for the scaling factor between <c><i>renderWidth</i></c> and <c><i>displayWidth</i></c>.
///
/// @ingroup ffxFsr3Upscaler
FFX_API int32_t ffxFsr3UpscalerGetJitterPhaseCount(int32_t renderWidth, int32_t displayWidth);
/// A helper function to calculate the subpixel jitter offset.
///
/// FSR3 relies on the application to apply sub-pixel jittering while rendering.
/// This is typically included in the projection matrix of the camera. To make
/// the application of camera jitter simple, the FSR3 API provides a small set
/// of utility function which computes the sub-pixel jitter offset for a
/// particular frame within a sequence of separate jitter offsets. To begin, the
/// index within the jitter phase must be computed. To calculate the
/// sequence's length, you can call the <c><i>ffxFsr3UpscalerGetJitterPhaseCount</i></c>
/// function. The index should be a value which is incremented each frame modulo
/// the length of the sequence computed by <c><i>ffxFsr3UpscalerGetJitterPhaseCount</i></c>.
/// The index within the jitter phase is passed to
/// <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> via the <c><i>index</i></c> parameter.
///
/// This function uses a Halton(2,3) sequence to compute the jitter offset.
/// The ultimate index used for the sequence is <c><i>index</i></c> %
/// <c><i>phaseCount</i></c>.
///
/// It is important to understand that the values returned from the
/// <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> function are in unit pixel space, and
/// in order to composite this correctly into a projection matrix we must
/// convert them into projection offsets. This is done as per the pseudo code
/// listing which is shown below.
///
/// const int32_t jitterPhaseCount = ffxFsr3UpscalerGetJitterPhaseCount(renderWidth, displayWidth);
///
/// float jitterX = 0;
/// float jitterY = 0;
/// ffxFsr3UpscalerGetJitterOffset(&jitterX, &jitterY, index, jitterPhaseCount);
///
/// const float jitterX = 2.0f * jitterX / (float)renderWidth;
/// const float jitterY = -2.0f * jitterY / (float)renderHeight;
/// const Matrix4 jitterTranslationMatrix = translateMatrix(Matrix3::identity, Vector3(jitterX, jitterY, 0));
/// const Matrix4 jitteredProjectionMatrix = jitterTranslationMatrix * projectionMatrix;
///
/// Jitter should be applied to all rendering. This includes opaque, alpha
/// transparent, and raytraced objects. For rasterized objects, the sub-pixel
/// jittering values calculated by the <c><i>iffxFsr3UpscalerGetJitterOffset</i></c>
/// function can be applied to the camera projection matrix which is ultimately
/// used to perform transformations during vertex shading. For raytraced
/// rendering, the sub-pixel jitter should be applied to the ray's origin,
/// often the camera's position.
///
/// Whether you elect to use the <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> function
/// or your own sequence generator, you must program the
/// <c><i>jitterOffset</i></c> field of the
/// <c><i>FfxFsr3UpscalerDispatchParameters</i></c> structure in order to inform FSR3
/// of the jitter offset that has been applied in order to render each frame.
///
/// If not using the recommended <c><i>ffxFsr3UpscalerGetJitterOffset</i></c> function,
/// care should be taken that your jitter sequence never generates a null vector;
/// that is value of 0 in both the X and Y dimensions.
///
/// @param [out] pOutX A pointer to a <c>float</c> which will contain the subpixel jitter offset for the x dimension.
/// @param [out] pOutY A pointer to a <c>float</c> which will contain the subpixel jitter offset for the y dimension.
/// @param [in] index The index within the jitter sequence.
/// @param [in] phaseCount The length of jitter phase. See <c><i>ffxFsr3UpscalerGetJitterPhaseCount</i></c>.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>outX</i></c> or <c><i>outY</i></c> was <c>NULL</c>.
/// @retval
/// FFX_ERROR_INVALID_ARGUMENT Argument <c><i>phaseCount</i></c> must be greater than 0.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerGetJitterOffset(float* pOutX, float* pOutY, int32_t index, int32_t phaseCount);
/// A helper function to check if a resource is
/// <c><i>FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_NULL</i></c>.
///
/// @param [in] resource A <c><i>FfxResource</i></c>.
///
/// @returns
/// true The <c><i>resource</i></c> was not <c><i>FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_NULL</i></c>.
/// @returns
/// false The <c><i>resource</i></c> was <c><i>FFX_FSR3UPSCALER_RESOURCE_IDENTIFIER_NULL</i></c>.
///
/// @ingroup ffxFsr3Upscaler
FFX_API bool ffxFsr3UpscalerResourceIsNull(FfxResource resource);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxVersionNumber ffxFsr3UpscalerGetEffectVersion();
/// Override upscaler constant buffer value after upscaler context creation.
///
/// @param [in] context A pointer to a <c><i>FfxFsr3UpscalerContext</i></c> structure.
/// @param [in] key A key from <c><i>FfxFsr3UpscalerConfigureKey</i></c> enum
/// @param [in] valuePtr A pointer to value to pass to shader in Constant Buffer. See Fsr3UpscalerConstants
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_ENUM An invalid FfxFsr3UpscalerConfigureKey was specified.
/// @retval
/// FFX_ERROR_INVALID_POINTER <c><i>pContext</c></i> was NULL.
///
/// @ingroup ffxFsr3Upscaler
FFX_API FfxErrorCode ffxFsr3UpscalerSetConstant(FfxFsr3UpscalerContext* context, FfxFsr3UpscalerConfigureKey key, void* valuePtr);
/// Set global debug message settings
///
/// @param [in] fpMessage A <c><i>ffxMessageCallback</i></ci>
/// @param [in] debugLevel An unsigned integer. Unimplemented.
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup FRAMEINTERPOLATION
FFX_API FfxErrorCode ffxFsr3UpscalerSetGlobalDebugMessage(ffxMessageCallback fpMessage, uint32_t debugLevel);
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,44 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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
/// @defgroup SDKComponents Effect Components
/// Runtime FidelityFX Effect Components that compile and link to calling effect libraries
///
/// @ingroup ffxSDK
#include <FidelityFX/host/ffx_fsr3.h>
#include <FidelityFX/host/ffx_fsr3upscaler.h>
#include <FidelityFX/host/ffx_frameinterpolation.h>
#include <FidelityFX/host/ffx_opticalflow.h>
#include <FidelityFX/host/ffx_fsr2.h>
#include <FidelityFX/host/ffx_fsr1.h>
#include <FidelityFX/host/ffx_spd.h>
#include <FidelityFX/host/ffx_lpm.h>
#include <FidelityFX/host/ffx_vrs.h>
#include <FidelityFX/host/ffx_dof.h>
#include <FidelityFX/host/ffx_blur.h>
#include <FidelityFX/host/ffx_cas.h>
#include <FidelityFX/host/ffx_lens.h>
#include <FidelityFX/host/ffx_denoiser.h>
#include <FidelityFX/host/ffx_sssr.h>
#include <FidelityFX/host/ffx_breadcrumbs.h>
@@ -0,0 +1,664 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 <FidelityFX/host/ffx_assert.h>
#include <FidelityFX/host/ffx_types.h>
#include <FidelityFX/host/ffx_error.h>
#include <FidelityFX/host/ffx_message.h>
#if defined(__cplusplus)
#define FFX_CPU
extern "C" {
#endif // #if defined(__cplusplus)
/// @defgroup Backends Backends
/// Core interface declarations and natively supported backends
///
/// @ingroup ffxSDK
/// @defgroup FfxInterface FfxInterface
/// FidelityFX SDK function signatures and core defines requiring
/// overrides for backend implementation.
///
/// @ingroup Backends
FFX_FORWARD_DECLARE(FfxInterface);
/// FidelityFX SDK major version.
///
/// @ingroup FfxInterface
#define FFX_SDK_VERSION_MAJOR (1)
/// FidelityFX SDK minor version.
///
/// @ingroup FfxInterface
#define FFX_SDK_VERSION_MINOR (1)
/// FidelityFX SDK patch version.
///
/// @ingroup FfxInterface
#define FFX_SDK_VERSION_PATCH (4)
/// Macro to pack a FidelityFX SDK version id together.
///
/// @ingroup FfxInterface
#define FFX_SDK_MAKE_VERSION( major, minor, patch ) ( ( major << 22 ) | ( minor << 12 ) | patch )
/// Stand in type for FfxPass
///
/// These will be defined for each effect individually (i.e. FfxFsr2Pass).
/// They are used to fetch the proper blob index to build effect shaders
///
/// @ingroup FfxInterface
typedef uint32_t FfxPass;
/// Get the SDK version of the backend context.
///
/// @param [in] backendInterface A pointer to the backend interface.
///
/// @returns
/// The SDK version a backend was built with.
///
/// @ingroup FfxInterface
typedef FfxVersionNumber(*FfxGetSDKVersionFunc)(
FfxInterface* backendInterface);
/// Get effect VRAM usage.
///
/// Newer effects may require support that legacy versions of the SDK will not be
/// able to provide. A version query is thus required to ensure an effect component
/// will always be paired with a backend which will support all needed functionality.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] effectContextId The context space to be used for the effect in question.
/// @param [out] outVramUsage The effect memory usage structure to fill out.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxGetEffectGpuMemoryUsageFunc)(FfxInterface* backendInterface, FfxUInt32 effectContextId, FfxEffectMemoryUsage* outVramUsage);
/// Create and initialize the backend context.
///
/// The callback function sets up the backend context for rendering.
/// It will create or reference the device and create required internal data structures.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] effect The effect the context is being created for
/// @param [in] bindlessConfig A pointer to the bindless configuration, if required by the effect.
/// @param [out] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxCreateBackendContextFunc)(
FfxInterface* backendInterface,
FfxEffect effect,
FfxEffectBindlessConfig* bindlessConfig,
FfxUInt32* effectContextId);
/// Get a list of capabilities of the device.
///
/// When creating an <c><i>FfxEffectContext</i></c> it is desirable for the FFX
/// core implementation to be aware of certain characteristics of the platform
/// that is being targetted. This is because some optimizations which FFX SDK
/// attempts to perform are more effective on certain classes of hardware than
/// others, or are not supported by older hardware. In order to avoid cases
/// where optimizations actually have the effect of decreasing performance, or
/// reduce the breadth of support provided by FFX SDK, the FFX interface queries the
/// capabilities of the device to make such decisions.
///
/// For target platforms with fixed hardware support you need not implement
/// this callback function by querying the device, but instead may hardcore
/// what features are available on the platform.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [out] outDeviceCapabilities The device capabilities structure to fill out.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode(*FfxGetDeviceCapabilitiesFunc)(
FfxInterface* backendInterface,
FfxDeviceCapabilities* outDeviceCapabilities);
/// Destroy the backend context and dereference the device.
///
/// This function is called when the <c><i>FfxEffectContext</i></c> is destroyed.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode(*FfxDestroyBackendContextFunc)(
FfxInterface* backendInterface,
FfxUInt32 effectContextId);
/// Create a resource.
///
/// This callback is intended for the backend to create internal resources.
///
/// Please note: It is also possible that the creation of resources might
/// itself cause additional resources to be created by simply calling the
/// <c><i>FfxCreateResourceFunc</i></c> function pointer again. This is
/// useful when handling the initial creation of resources which must be
/// initialized. The flow in such a case would be an initial call to create the
/// CPU-side resource, another to create the GPU-side resource, and then a call
/// to schedule a copy render job to move the data between the two. Typically
/// this type of function call flow is only seen during the creation of an
/// <c><i>FfxEffectContext</i></c>.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] createResourceDescription A pointer to a <c><i>FfxCreateResourceDescription</i></c>.
/// @param [in] effectContextId The context space to be used for the effect in question.
/// @param [out] outResource A pointer to a <c><i>FfxResource</i></c> object.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxCreateResourceFunc)(
FfxInterface* backendInterface,
const FfxCreateResourceDescription* createResourceDescription,
FfxUInt32 effectContextId,
FfxResourceInternal* outResource);
/// Register a resource in the backend for the current frame.
///
/// Since the FfxInterface and the backends are not aware how many different
/// resources will get passed in over time, it's not safe
/// to register all resources simultaneously in the backend.
/// Also passed resources may not be valid after the dispatch call.
/// As a result it's safest to register them as FfxResourceInternal
/// and clear them at the end of the dispatch call.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] inResource A pointer to a <c><i>FfxResource</i></c>.
/// @param [in] effectContextId The context space to be used for the effect in question.
/// @param [out] outResource A pointer to a <c><i>FfxResourceInternal</i></c> object.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode(*FfxRegisterResourceFunc)(
FfxInterface* backendInterface,
const FfxResource* inResource,
FfxUInt32 effectContextId,
FfxResourceInternal* outResource);
/// Get an FfxResource from an FfxResourceInternal resource.
///
/// At times it is necessary to create an FfxResource representation
/// of an internally created resource in order to register it with a
/// child effect context. This function sets up the FfxResource needed
/// to register.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] resource The <c><i>FfxResourceInternal</i></c> for which to setup an FfxResource.
///
/// @returns
/// An FfxResource built from the internal resource
///
/// @ingroup FfxInterface
typedef FfxResource(*FfxGetResourceFunc)(
FfxInterface* backendInterface,
FfxResourceInternal resource);
/// Unregister all temporary FfxResourceInternal from the backend.
///
/// Unregister FfxResourceInternal referencing resources passed to
/// a function as a parameter.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] commandList A pointer to a <c><i>FfxCommandList</i></c> structure.
/// @param [in] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode(*FfxUnregisterResourcesFunc)(
FfxInterface* backendInterface,
FfxCommandList commandList,
FfxUInt32 effectContextId);
/// Register a resource in the static bindless table of the backend.
///
/// A static resource will persist in their respective bindless table until it is
/// overwritten by a different resource at the same index.
/// The calling code must take care not to immediately register a new resource at an index
/// that might be in use by an in-flight frame.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] desc A pointer to an <c><i>FfxStaticResourceDescription</i></c>.
/// @param [in] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxRegisterStaticResourceFunc)(FfxInterface* backendInterface,
const FfxStaticResourceDescription* desc,
FfxUInt32 effectContextId);
/// Retrieve a <c><i>FfxResourceDescription</i></c> matching a
/// <c><i>FfxResource</i></c> structure.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] resource A pointer to a <c><i>FfxResource</i></c> object.
///
/// @returns
/// A description of the resource.
///
/// @ingroup FfxInterface
typedef FfxResourceDescription (*FfxGetResourceDescriptionFunc)(
FfxInterface* backendInterface,
FfxResourceInternal resource);
/// Destroy a resource
///
/// This callback is intended for the backend to release an internal resource.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] resource A pointer to a <c><i>FfxResource</i></c> object.
/// @param [in] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxDestroyResourceFunc)(
FfxInterface* backendInterface,
FfxResourceInternal resource,
FfxUInt32 effectContextId);
/// Map resource memory
///
/// Maps the memory of the resource to a pointer and returns it.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] resource A pointer to a <c><i>FfxResource</i></c> object.
/// @param [out] ptr A pointer to the mapped memory.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxMapResourceFunc)(FfxInterface* backendInterface, FfxResourceInternal resource, void** ptr);
/// Unmap resource memory
///
/// Unmaps previously mapped memory of a resource.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] resource A pointer to a <c><i>FfxResource</i></c> object.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxUnmapResourceFunc)(FfxInterface* backendInterface, FfxResourceInternal resource);
/// Destroy a resource
///
/// This callback is intended for the backend to release an internal resource.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] resource A pointer to a <c><i>FfxResource</i></c> object.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxStageConstantBufferDataFunc)(
FfxInterface* backendInterface,
void* data,
FfxUInt32 size,
FfxConstantBuffer* constantBuffer);
/// Create a render pipeline.
///
/// A rendering pipeline contains the shader as well as resource bindpoints
/// and samplers.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] pass The identifier for the pass.
/// @param [in] pipelineDescription A pointer to a <c><i>FfxPipelineDescription</i></c> describing the pipeline to be created.
/// @param [in] effectContextId The context space to be used for the effect in question.
/// @param [out] outPipeline A pointer to a <c><i>FfxPipelineState</i></c> structure which should be populated.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxCreatePipelineFunc)(
FfxInterface* backendInterface,
FfxEffect effect,
FfxPass pass,
uint32_t permutationOptions,
const FfxPipelineDescription* pipelineDescription,
FfxUInt32 effectContextId,
FfxPipelineState* outPipeline);
typedef FfxErrorCode(*FfxGetPermutationBlobByIndexFunc)(FfxEffect effectId,
FfxPass passId,
FfxBindStage bindStage,
uint32_t permutationOptions,
FfxShaderBlob* outBlob);
/// Destroy a render pipeline.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] effectContextId The context space to be used for the effect in question.
/// @param [out] pipeline A pointer to a <c><i>FfxPipelineState</i></c> structure which should be released.
/// @param [in] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxDestroyPipelineFunc)(
FfxInterface* backendInterface,
FfxPipelineState* pipeline,
FfxUInt32 effectContextId);
/// Schedule a render job to be executed on the next call of
/// <c><i>FfxExecuteGpuJobsFunc</i></c>.
///
/// Render jobs can perform one of three different tasks: clear, copy or
/// compute dispatches.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] job A pointer to a <c><i>FfxGpuJobDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxScheduleGpuJobFunc)(
FfxInterface* backendInterface,
const FfxGpuJobDescription* job);
/// Execute scheduled render jobs on the <c><i>comandList</i></c> provided.
///
/// The recording of the graphics API commands should take place in this
/// callback function, the render jobs which were previously enqueued (via
/// callbacks made to <c><i>FfxScheduleGpuJobFunc</i></c>) should be
/// processed in the order they were received. Advanced users might choose to
/// reorder the rendering jobs, but should do so with care to respect the
/// resource dependencies.
///
/// Depending on the precise contents of <c><i>FfxDispatchDescription</i></c> a
/// different number of render jobs might have previously been enqueued (for
/// example if sharpening is toggled on and off).
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] commandList A pointer to a <c><i>FfxCommandList</i></c> structure.
/// @param [in] effectContextId The context space to be used for the effect in question.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxExecuteGpuJobsFunc)(
FfxInterface* backendInterface,
FfxCommandList commandList,
FfxUInt32 effectContextId);
typedef enum FfxUiCompositionFlags
{
FFX_UI_COMPOSITION_FLAG_USE_PREMUL_ALPHA = (1 << 0), ///< A bit indicating that we use premultiplied alpha for UI composition
FFX_UI_COMPOSITION_FLAG_ENABLE_INTERNAL_UI_DOUBLE_BUFFERING = (1 << 1), ///< A bit indicating that the swapchain should doublebuffer the UI resource
} FfxUiCompositionFlags;
typedef FfxErrorCode(*FfxPresentCallbackFunc)(const FfxPresentCallbackDescription* params, void*);
typedef FfxErrorCode(*FfxFrameGenerationDispatchFunc)(const FfxFrameGenerationDispatchDescription* params, void*);
typedef FfxErrorCode(*FfxWaitCallbackFunc)(wchar_t* fenceName, uint64_t fenceValueToWaitFor);
/// A structure representing the configuration options to pass to FrameInterpolationSwapChain
///
/// @ingroup FfxInterface
typedef struct FfxFrameGenerationConfig
{
FfxSwapchain swapChain; ///< The <c><i>FfxSwapchain</i></c> to use with frame interpolation
FfxPresentCallbackFunc presentCallback; ///< A UI composition callback to call when finalizing the frame image
void* presentCallbackContext; ///< A pointer to be passed to the UI composition callback
FfxFrameGenerationDispatchFunc frameGenerationCallback; ///< The frame generation callback to use to generate the interpolated frame
void* frameGenerationCallbackContext; ///< A pointer to be passed to the frame generation callback
bool frameGenerationEnabled; ///< Sets the state of frame generation. Set to false to disable frame generation
bool allowAsyncWorkloads; ///< Sets the state of async workloads. Set to true to enable interpolation work on async compute
bool allowAsyncPresent; ///< Sets the state of async presentation (console only). Set to true to enable present from async command queue
FfxResource HUDLessColor; ///< The hudless back buffer image to use for UI extraction from backbuffer resource
FfxUInt32 flags; ///< Flags
bool onlyPresentInterpolated; ///< Set to true to only present interpolated frame
FfxRect2D interpolationRect; ///< Set the area in the backbuffer that will be interpolated
uint64_t frameID; ///< A frame identifier used to synchronize resource usage in workloads
bool drawDebugPacingLines; ///< Sets the state of pacing debug lines. Set to true to display debug lines
} FfxFrameGenerationConfig;
typedef FfxErrorCode (*FfxSwapChainConfigureFrameGenerationFunc)(FfxFrameGenerationConfig const* config);
/// Allocate AMD FidelityFX Breadcrumbs Library markers buffer.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] blockBytes Size in bytes of the buffer to be allocated.
/// @param [out] blockData Output information about allocated AMD FidelityFX Breadcrumbs Library buffer. Filled only on success of operation.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// Anything else The operation failed.
///
/// @ingroup FfxInterface
typedef FfxErrorCode (*FfxBreadcrumbsAllocBlockFunc)(
FfxInterface* backendInterface,
uint64_t blockBytes,
FfxBreadcrumbsBlockData* blockData
);
/// Deallocate AMD FidelityFX Breadcrumbs Library markers buffer.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [out] blockData Information about buffer to be freed. All resource handles are cleared after this operation.
///
/// @ingroup FfxInterface
typedef void (*FfxBreadcrumbsFreeBlockFunc)(
FfxInterface* backendInterface,
FfxBreadcrumbsBlockData* blockData
);
/// Write marker to AMD FidelityFX Breadcrumbs Library buffer on the <c><i>comandList</i></c> provided.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] commandList GPU command list to record marker writing command.
/// @param [in] value Marker value to be written.
/// @param [in] gpuLocation GPU destination address where marker will be written.
/// @param [in] gpuBuffer Destination AMD FidelityFX Breadcrumbs Library buffer.
/// @param [in] isBegin <c><i>true</i></c> for writing opening marker and <c><i>false</i></c> for ending marker.
///
/// @ingroup FfxInterface
typedef void (*FfxBreadcrumbsWriteFunc)(
FfxInterface* backendInterface,
FfxCommandList commandList,
uint32_t value,
uint64_t gpuLocation,
void* gpuBuffer,
bool isBegin
);
/// Printing GPU specific info to the AMD FidelityFX Breadcrumbs Library status buffer.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] allocs A pointer to the allocation callbacks.
/// @param [in] extendedInfo <c><i>true</i></c> if should print more verbose device info and <c><i>false</i></c> for standard output.
/// @param [out] printBuffer String buffer for writing GPU info.
/// @param [out] printSize Size of string buffer for writing GPU info.
///
/// @ingroup FfxInterface
typedef void (*FfxBreadcrumbsPrintDeviceInfoFunc)(
FfxInterface* backendInterface,
FfxAllocationCallbacks* allocs,
bool extendedInfo,
char** printBuffer,
size_t* printSize
);
/// Register a <b>Thread Safe</b> constant buffer allocator to be used by the backend.
///
/// @param [in] backendInterface A pointer to the backend interface.
/// @param [in] constantAllocator An <c><i>FfxConstantBufferAllocator</i></c> callback to be used by the backend.
///
/// @ingroup FfxInterface
typedef void(*FfxRegisterConstantBufferAllocatorFunc)(FfxInterface* backendInterface,
FfxConstantBufferAllocator constantAllocator);
/// A structure encapsulating the interface between the core implementation of
/// the FfxInterface and any graphics API that it should ultimately call.
///
/// This set of functions serves as an abstraction layer between FfxInterfae and the
/// API used to implement it. While the FidelityFX SDK ships with backends for DirectX12 and
/// Vulkan, it is possible to implement your own backend for other platforms
/// which sit on top of your engine's own abstraction layer. For details on the
/// expectations of what each function should do you should refer the
/// description of the following function pointer types:
/// - <c><i>FfxCreateDeviceFunc</i></c>
/// - <c><i>FfxGetDeviceCapabilitiesFunc</i></c>
/// - <c><i>FfxDestroyDeviceFunc</i></c>
/// - <c><i>FfxCreateResourceFunc</i></c>
/// - <c><i>FfxRegisterResourceFunc</i></c>
/// - <c><i>FfxGetResourceFunc</i></c>
/// - <c><i>FfxUnregisterResourcesFunc</i></c>
/// - <c><i>FfxGetResourceDescriptionFunc</i></c>
/// - <c><i>FfxDestroyResourceFunc</i></c>
/// - <c><i>FfxCreatePipelineFunc</i></c>
/// - <c><i>FfxDestroyPipelineFunc</i></c>
/// - <c><i>FfxScheduleGpuJobFunc</i></c>
/// - <c><i>FfxExecuteGpuJobsFunc</i></c>
/// - <c><i>FfxBeginMarkerFunc</i></c>
/// - <c><i>FfxEndMarkerFunc</i></c>
/// - <c><i>FfxRegisterConstantBufferAllocatorFunc</i></c>
///
/// Depending on the graphics API that is abstracted by the backend, it may be
/// required that the backend is to some extent stateful. To ensure that
/// applications retain full control to manage the memory used by the FidelityFX SDK, the
/// <c><i>scratchBuffer</i></c> and <c><i>scratchBufferSize</i></c> fields are
/// provided. A backend should provide a means of specifying how much scratch
/// memory is required for its internal implementation (e.g: via a function
/// or constant value). The application is then responsible for allocating that
/// memory and providing it when setting up the SDK backend. Backends provided
/// with the FidelityFX SDK do not perform dynamic memory allocations, and instead
/// sub-allocate all memory from the scratch buffers provided.
///
/// The <c><i>scratchBuffer</i></c> and <c><i>scratchBufferSize</i></c> fields
/// should be populated according to the requirements of each backend. For
/// example, if using the DirectX 12 backend you should call the
/// <c><i>ffxGetScratchMemorySizeDX12</i></c> function. It is not required
/// that custom backend implementations use a scratch buffer.
///
/// Any functional addition to this interface mandates a version
/// bump to ensure full functionality across effects and backends.
///
/// @ingroup FfxInterface
typedef struct FfxInterface {
// FidelityFX SDK 1.0 callback handles
FfxGetSDKVersionFunc fpGetSDKVersion; ///< A callback function to query the SDK version.
FfxGetEffectGpuMemoryUsageFunc fpGetEffectGpuMemoryUsage; ///< A callback function to query effect Gpu memory usage
FfxCreateBackendContextFunc fpCreateBackendContext; ///< A callback function to create and initialize the backend context.
FfxGetDeviceCapabilitiesFunc fpGetDeviceCapabilities; ///< A callback function to query device capabilites.
FfxDestroyBackendContextFunc fpDestroyBackendContext; ///< A callback function to destroy the backendcontext. This also dereferences the device.
FfxCreateResourceFunc fpCreateResource; ///< A callback function to create a resource.
FfxRegisterResourceFunc fpRegisterResource; ///< A callback function to register an external resource.
FfxGetResourceFunc fpGetResource; ///< A callback function to convert an internal resource to external resource type
FfxUnregisterResourcesFunc fpUnregisterResources; ///< A callback function to unregister external resource.
FfxRegisterStaticResourceFunc fpRegisterStaticResource; ///< A callback function to register a static resource.
FfxGetResourceDescriptionFunc fpGetResourceDescription; ///< A callback function to retrieve a resource description.
FfxDestroyResourceFunc fpDestroyResource; ///< A callback function to destroy a resource.
FfxMapResourceFunc fpMapResource; ///< A callback function to map a resource.
FfxUnmapResourceFunc fpUnmapResource; ///< A callback function to unmap a resource.
FfxStageConstantBufferDataFunc fpStageConstantBufferDataFunc; ///< A callback function to copy constant buffer data into staging memory.
FfxCreatePipelineFunc fpCreatePipeline; ///< A callback function to create a render or compute pipeline.
FfxDestroyPipelineFunc fpDestroyPipeline; ///< A callback function to destroy a render or compute pipeline.
FfxScheduleGpuJobFunc fpScheduleGpuJob; ///< A callback function to schedule a render job.
FfxExecuteGpuJobsFunc fpExecuteGpuJobs; ///< A callback function to execute all queued render jobs.
// FidelityFX SDK 1.1 callback handles
FfxBreadcrumbsAllocBlockFunc fpBreadcrumbsAllocBlock; ///< A callback function to allocate block of memory for AMD FidelityFX Breadcrumbs Library buffer.
FfxBreadcrumbsFreeBlockFunc fpBreadcrumbsFreeBlock; ///< A callback function to free AMD FidelityFX Breadcrumbs Library buffer.
FfxBreadcrumbsWriteFunc fpBreadcrumbsWrite; ///< A callback function to write marker into AMD FidelityFX Breadcrumbs Library.
FfxBreadcrumbsPrintDeviceInfoFunc fpBreadcrumbsPrintDeviceInfo; ///< A callback function to print active GPU info for AMD FidelityFX Breadcrumbs Library log.
FfxGetPermutationBlobByIndexFunc fpGetPermutationBlobByIndex;
FfxSwapChainConfigureFrameGenerationFunc fpSwapChainConfigureFrameGeneration; ///< A callback function to configure swap chain present callback.
FfxRegisterConstantBufferAllocatorFunc fpRegisterConstantBufferAllocator; ///< A callback function to register a custom <b>Thread Safe</b> constant buffer allocator.
void* scratchBuffer; ///< A preallocated buffer for memory utilized internally by the backend.
size_t scratchBufferSize; ///< Size of the buffer pointed to by <c><i>scratchBuffer</i></c>.
FfxDevice device; ///< A backend specific device
} FfxInterface;
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,216 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
// @defgroup Lens
#pragma once
// Include the interface for the backend of the Lens API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup FfxLens FidelityFX Lens
/// FidelityFX Lens runtime library
///
/// @ingroup SDKComponents
/// FidelityFX Lens major version.
///
/// @ingroup FfxLens
#define FFX_LENS_VERSION_MAJOR (1)
/// FidelityFX Lens minor version.
///
/// @ingroup FfxLens
#define FFX_LENS_VERSION_MINOR (1)
/// FidelityFX Lens patch version.
///
/// @ingroup FfxLens
#define FFX_LENS_VERSION_PATCH (0)
/// FidelityFX Lens context count
///
/// Defines the number of internal effect contexts required by Lens
///
/// @ingroup FfxLens
#define FFX_LENS_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup FfxLens
#define FFX_LENS_CONTEXT_SIZE (9200)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of the pass which constitutes the Lens algorithm.
///
/// Lens is implemented as a single pass algorithm. Each call to the
/// <c><i>FfxLensScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single lens effect compute job. For a
/// more comprehensive description of Lens's inner workings, please
/// refer to the Lens reference documentation.
///
/// @ingroup FfxLens
typedef enum FfxLensPass
{
FFX_LENS_PASS_MAIN_PASS = 0, ///< A pass which which applies the lens effect
FFX_LENS_PASS_COUNT ///< The number of passes in Lens
} FfxLensPass;
typedef enum FfxLensFloatPrecision
{
FFX_LENS_FLOAT_PRECISION_32BIT = 0,
FFX_LENS_FLOAT_PRECISION_16BIT = 1,
FFX_LENS_FLOAT_PRECISION_COUNT = 2
} FfxLensFloatPrecision;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxLensContext</i></c>. See <c><i>FfxLensContextDescription</i></c>.
///
/// @ingroup FfxLens
typedef enum FfxLensInitializationFlagBits {
FFX_LENS_MATH_NONPACKED = (1 << 0), ///< A bit indicating if we should use floating point math
FFX_LENS_MATH_PACKED = (1 << 1) ///< A bit indicating if we should use 16-bit half precision floating point math (favored)
} FfxLensInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Lens.
///
/// @ingroup FfxLens
typedef struct FfxLensContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxLensInitializationFlagBits</i></c>
FfxSurfaceFormat outputFormat; ///< Format of the output target used for creation of output resource.
FfxLensFloatPrecision floatPrecision; ///< A flag indicating the desired floating point precision for use in ffxBlurContextDispatch
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX.
} FfxLensContextDescription;
/// A structure encapsulating the parameters for dispatching
/// of FidelityFX Lens
///
/// @ingroup FfxLens
typedef struct FfxLensDispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record Lens rendering commands into.
FfxResource resource; ///< The <c><i>FfxResource</i></c> to run Lens on.
FfxResource resourceOutput; ///< The <c><i>FfxResource</i></c> to write Lens output to.
FfxDimensions2D renderSize; ///< The resolution used for rendering the scene.
float grainScale; ///< Artistic tweaking constant for grain scale..
float grainAmount; ///< Artistic tweaking constant for how intense the grain is.
uint32_t grainSeed; ///< The seed for grain RNG.
float chromAb; ///< Artistic tweaking constant for chromatic aberration intensity.
float vignette; ///< Artistic tweaking constant for vignette intensity.
} FfxLensDispatchDescription;
/// A structure encapsulating the FidelityFX Lens context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by Lens.
///
/// The <c><i>FfxLensContext</i></c> object should have a lifetime matching
/// your use of Lens. Before destroying the Lens context care should be taken
/// to ensure the GPU is not accessing the resources created or used by Lens.
/// It is therefore recommended that the GPU is idle before destroying the
/// Lens context.
///
/// @ingroup FfxLens
typedef struct FfxLensContext {
uint32_t data[FFX_LENS_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxLensContext;
/// Create a FidelityFX Lens Downsampler context from the parameters
/// programmed to the <c><i>FfxLensContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the Lens
/// API, and is responsible for the management of the internal resources
/// used by the Lens algorithm. When this API is called, multiple calls
/// will be made via the pointers contained in the <c><i>backendInterface</i></c>
/// structure. This backend will attempt to retrieve the device capabilities,
/// and create the internal resources, and pipelines required by Lens to function.
/// Depending on the precise configuration used when
/// creating the <c><i>FfxLensContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The <c><i>FfxLensContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or Lens
/// upscaling is disabled by a user. To destroy the Lens context you
/// should call <c><i>ffxLensContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxLensContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxLensContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxLensContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxLens
FFX_API FfxErrorCode ffxLensContextCreate(FfxLensContext* pContext, const FfxLensContextDescription* pContextDescription);
/// Dispatches work to the FidelityFX Lens context
///
/// @param [out] pContext A pointer to a <c><i>FfxLensContext</i></c> structure to populate.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxLensDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxLens
FFX_API FfxErrorCode ffxLensContextDispatch(FfxLensContext* pContext, const FfxLensDispatchDescription* pDispatchDescription);
/// Destroy the FidelityFX Lens context.
///
/// @param [out] pContext A pointer to a <c><i>FfxLensContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FfxLens
FFX_API FfxErrorCode ffxLensContextDestroy(FfxLensContext* pContext);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup FfxLens
FFX_API FfxVersionNumber ffxLensGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,273 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
// @defgroup LPM
#pragma once
// Include the interface for the backend of the LPM 1.0 API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup FfxLpm FidelityFX LPM
/// FidelityFX Luma Preserving Mapper runtime library
///
/// @ingroup SDKComponents
/// FidelityFX Luma Preserving Mapper 1.3 major version.
///
/// @ingroup FfxLpm
#define FFX_LPM_VERSION_MAJOR (1)
/// FidelityFX Luma Preserving Mapper 1.3 minor version.
///
/// @ingroup FfxLpm
#define FFX_LPM_VERSION_MINOR (4)
/// FidelityFX Luma Preserving Mapper 1.3 patch version.
///
/// @ingroup FfxLpm
#define FFX_LPM_VERSION_PATCH (0)
/// FidelityFX Luma Preserving Mapper context count
///
/// Defines the number of internal effect contexts required by LPM
///
/// @ingroup FfxLpm
#define FFX_LPM_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup FfxLpm
#define FFX_LPM_CONTEXT_SIZE (9300)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of all the passes which constitute the LPM algorithm.
///
/// LPM is implemented as a composite of several compute passes each
/// computing a key part of the final result. Each call to the
/// <c><i>FfxLPMScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single pass included in <c><i>FfxLPMPass</i></c>. For a
/// more comprehensive description of each pass, please refer to the LPM
/// reference documentation.
///
/// @ingroup FfxLpm
typedef enum FfxLpmPass
{
FFX_LPM_PASS_FILTER = 0, ///< A pass which filters the color buffer using LPM's tone and gamut mapping solution.
FFX_LPM_PASS_COUNT ///< The number of passes performed by LPM.
} FfxLpmPass;
/// An enumeration of monitor display modes supported by LPM
/// FFX_LPM_DISPLAYMODE_LDR tagets low or standard dynamic range monitor using 8bit back buffer
/// FFX_LPM_DISPLAYMODE_HDR10_2084 targets HDR10 perceptual quantizer (PQ) transfer function using 10bit backbuffer
/// FFX_LPM_DISPLAYMODE_HDR10_SCRGB targets HDR10 linear output with no transfer function using 16bit backbuffer
/// FFX_LPM_DISPLAYMODE_FSHDR_2084 targets freesync premium pro hdr thorugh PQ transfer function using 10bit backbuffer
/// FFX_LPM_DISPLAYMODE_FSHDR_SCRGB targets linear output with no transfer function using 16bit backbuffer
/// @ingroup LPM
typedef enum class FfxLpmDisplayMode
{
FFX_LPM_DISPLAYMODE_LDR = 0,
FFX_LPM_DISPLAYMODE_HDR10_2084 = 1,
FFX_LPM_DISPLAYMODE_HDR10_SCRGB = 2,
FFX_LPM_DISPLAYMODE_FSHDR_2084 = 3,
FFX_LPM_DISPLAYMODE_FSHDR_SCRGB = 4
} FfxLpmDisplayMode;
/// An enumeration of colourspaces supported by LPM
/// FFX_LPM_ColorSpace_REC709 uses rec709 colour primaries used for FFX_LPM_DISPLAYMODE_LDR, FFX_LPM_DISPLAYMODE_HDR10_SCRGB and FFX_LPM_DISPLAYMODE_FSHDR_SCRGB modes
/// FFX_LPM_ColorSpace_P3 uses P3 colour primaries
/// FFX_LPM_ColorSpace_REC2020 uses rec2020 colour primaries used for FFX_LPM_DISPLAYMODE_HDR10_2084 and FFX_LPM_DISPLAYMODE_FSHDR_2084 modes
/// FFX_LPM_ColorSapce_Display uses custom primaries queried from display
/// @ingroup LPM
typedef enum class FfxLpmColorSpace
{
FFX_LPM_ColorSpace_REC709 = 0,
FFX_LPM_ColorSpace_P3 = 1,
FFX_LPM_ColorSpace_REC2020 = 2,
FFX_LPM_ColorSapce_Display = 3,
} FfxLpmColorSpace;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxLpmContext</i></c>. See <c><i>FfxLpmContextDescription</i></c>.
///
/// @ingroup FfxLpm
typedef enum FfxLpmInitializationFlagBits
{
} FfxLpmInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Luma Preserving Mapper
///
/// @ingroup FfxLpm
typedef struct FfxLpmContextDescription
{
uint32_t flags;
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for LPM.
} FfxLpmContextDescription;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX Luma Preserving Mapper 1.0
///
/// @ingroup FfxLpm
typedef struct FfxLpmDispatchDescription
{
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record LPM rendering commands into.
FfxResource inputColor; ///< A <c><i>FfxResource</i></c> containing the color buffer for the current frame.
FfxResource outputColor; ///< A <c><i>FfxResource</i></c> containing the tone and gamut mapped output color buffer for the current frame.
bool shoulder;
float softGap;
float hdrMax;
float lpmExposure;
float contrast;
float shoulderContrast;
float saturation[3];
float crosstalk[3];
FfxLpmColorSpace colorSpace;
FfxLpmDisplayMode displayMode;
float displayRedPrimary[2];
float displayGreenPrimary[2];
float displayBluePrimary[2];
float displayWhitePoint[2];
float displayMinLuminance;
float displayMaxLuminance;
} FfxLpmDispatchDescription;
/// A structure encapsulating the FidelityFX Luma Preserving 1.0 context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by LPM.
///
/// The <c><i>FfxLpmContext</i></c> object should have a lifetime matching
/// your use of LPM. Before destroying the LPM context care should be taken
/// to ensure the GPU is not accessing the resources created or used by LPM.
/// It is therefore recommended that the GPU is idle before destroying the
/// LPM context.
///
/// @ingroup FfxLpm
typedef struct FfxLpmContext
{
uint32_t data[FFX_LPM_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxLpmContext;
/// Create a FidelityFX Luma Preserving 1.0 context from the parameters
/// programmed to the <c><i>FfxLpmContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the Luma Preserving
/// Mapper 1.0 API, and is responsible for the management of the internal resources
/// used by the LPM algorithm. When this API is called, multiple calls
/// will be made via the pointers contained in the <c><i>callbacks</i></c>
/// structure. These callbacks will attempt to retreive the device capabilities,
/// and create the internal resources, and pipelines required by LPM
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxLpmContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The <c><i>FfxLpmContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or LPM
/// tone and gamut mapping is disabled by a user. To destroy the LPM context you
/// should call <c><i>ffxLpmContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxLpmContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxLpmContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxLpmContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxLpm
FFX_API FfxErrorCode ffxLpmContextCreate(FfxLpmContext* pContext, const FfxLpmContextDescription* pContextDescription);
/// Dispatches work to the FidelityFX LPM context
/// @param [out] pContext A pointer to a <c><i>FfxLpmContext</i></c> structure to populate.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxLpmDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxLpm
FFX_API FfxErrorCode ffxLpmContextDispatch(FfxLpmContext* pContext, const FfxLpmDispatchDescription* pDispatchDescription);
/// Destroy the FidelityFX LPM context.
///
/// @param [out] pContext A pointer to a <c><i>FfxLpmContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FfxLpm
FFX_API FfxErrorCode ffxLpmContextDestroy(FfxLpmContext* pContext);
/// Sets up the constant buffer data necessary for LPM compute
///
/// @param [in] incon
/// @param [in] insoft
/// @param [in] incon2
/// @param [in] inclip
/// @param [in] inscaleOnly
/// @param [out] outcon
/// @param [out] outsoft
/// @param [out] outcon2
/// @param [out] outclip
/// @param [out] outscaleOnly
///
/// @retval
/// FFX_OK The operation completed successfully.
///
/// @ingroup FfxLpm
FFX_API FfxErrorCode FfxPopulateLpmConsts(bool incon,
bool insoft,
bool incon2,
bool inclip,
bool inscaleOnly,
uint32_t& outcon,
uint32_t& outsoft,
uint32_t& outcon2,
uint32_t& outclip,
uint32_t& outscaleOnly);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup FfxLpm
FFX_API FfxVersionNumber ffxLpmGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,63 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 <FidelityFX/host/ffx_types.h>
#ifdef __cplusplus
extern "C" {
#endif // #ifdef __cplusplus
/// @defgroup Messages Messages
/// Messages used by FidelityFX SDK functions
///
/// @ingroup ffxHost
/// Provides the ability to set a callback for print messages.
///
/// @param [in] callback The callback function that will receive assert messages.
///
/// @ingroup Messages
FFX_API void ffxSetPrintMessageCallback(ffxMessageCallback callback, uint32_t debugLevel);
/// Function to print a message.
///
/// @param [in] type See FfxMsgType
/// @param [in] message The message to print.
///
/// @ingroup Messages
FFX_API void ffxPrintMessage(uint32_t type, const wchar_t* message);
/// Macro to print message
/// by calling application registered callback,
/// otherwise to debugger's TTY
///
/// @ingroup Messages
#define FFX_PRINT_MESSAGE( type, msg) \
do \
{ \
ffxPrintMessage( type, msg); \
} while (0)
#ifdef __cplusplus
}
#endif // #ifdef __cplusplus
@@ -0,0 +1,212 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
// @defgroup OpticalFlow
#pragma once
// Include the interface for the backend of the OpticalFlow API.
#include <FidelityFX/host/ffx_interface.h>
/// FidelityFX OpticalFlow major version.
///
/// @ingroup ffxOpticalflow
#define FFX_OPTICALFLOW_VERSION_MAJOR (1)
/// FidelityFX OpticalFlow minor version.
///
/// @ingroup ffxOpticalflow
#define FFX_OPTICALFLOW_VERSION_MINOR (1)
/// FidelityFX OpticalFlow patch version.
///
/// @ingroup ffxOpticalflow
#define FFX_OPTICALFLOW_VERSION_PATCH (2)
/// FidelityFX Optical Flow context count
///
/// Defines the number of internal effect contexts required by Optical Flow
///
/// @ingroup ffxOpticalFlow
#define FFX_OPTICALFLOW_CONTEXT_COUNT (1)
/// The size of the context specified in 32bit size units.
///
/// @ingroup ffxOpticalflow
#define FFX_OPTICALFLOW_CONTEXT_SIZE (FFX_SDK_DEFAULT_CONTEXT_SIZE)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of all the passes which constitute the OpticalFlow algorithm.
///
/// @ingroup ffxOpticalflow
typedef enum FfxOpticalflowPass
{
FFX_OPTICALFLOW_PASS_PREPARE_LUMA = 0,
FFX_OPTICALFLOW_PASS_GENERATE_OPTICAL_FLOW_INPUT_PYRAMID,
FFX_OPTICALFLOW_PASS_GENERATE_SCD_HISTOGRAM,
FFX_OPTICALFLOW_PASS_COMPUTE_SCD_DIVERGENCE,
FFX_OPTICALFLOW_PASS_COMPUTE_OPTICAL_FLOW_ADVANCED_V5,
FFX_OPTICALFLOW_PASS_FILTER_OPTICAL_FLOW_V5,
FFX_OPTICALFLOW_PASS_SCALE_OPTICAL_FLOW_ADVANCED_V5,
FFX_OPTICALFLOW_PASS_COUNT
} FfxOpticalflowPass;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxOpticalflowContext</i></c>. See <c><i>FfxOpticalflowDispatchDescription</i></c>.
///
/// @ingroup ffxOpticalflow
typedef enum FfxOpticalflowInitializationFlagBits
{
FFX_OPTICALFLOW_ENABLE_TEXTURE1D_USAGE = (1 << 0),
} FfxOpticalflowInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize
/// FidelityFX OpticalFlow.
///
/// @ingroup ffxOpticalflow
typedef struct FfxOpticalflowContextDescription {
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX SDK
uint32_t flags; ///< A collection of <c><i>FfxOpticalflowInitializationFlagBits</i></c>.
FfxDimensions2D resolution;
} FfxOpticalflowContextDescription;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX Opticalflow.
///
/// @ingroup ffxOpticalflow
typedef struct FfxOpticalflowDispatchDescription
{
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record rendering commands into.
FfxResource color; ///< A <c><i>FfxResource</i></c> containing the input color buffer
FfxResource opticalFlowVector; ///< A <c><i>FfxResource</i></c> containing the output motion buffer
FfxResource opticalFlowSCD; ///< A <c><i>FfxResource</i></c> containing the output scene change detection buffer
bool reset; ///< A boolean value which when set to true, indicates the camera has moved discontinuously.
int backbufferTransferFunction;
FfxFloatCoords2D minMaxLuminance;
} FfxOpticalflowDispatchDescription;
typedef struct FfxOpticalflowSharedResourceDescriptions {
FfxCreateResourceDescription opticalFlowVector;
FfxCreateResourceDescription opticalFlowSCD;
} FfxOpticalflowSharedResourceDescriptions;
/// A structure encapsulating the FidelityFX OpticalFlow context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by OpticalFlow.
///
/// The <c><i>FfxOpticalflowContext</i></c> object should have a lifetime matching
/// your use of OpticalFlow. Before destroying the OpticalFlow context care should be taken
/// to ensure the GPU is not accessing the resources created or used by OpticalFlow.
/// It is therefore recommended that the GPU is idle before destroying OpticalFlow
/// OpticalFlow context.
///
/// @ingroup ffxOpticalflow
typedef struct FfxOpticalflowContext
{
uint32_t data[FFX_OPTICALFLOW_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxOpticalflowContext;
/// Create a FidelityFX OpticalFlow context from the parameters
/// programmed to the <c><i>FfxOpticalflowContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the OpticalFlow
/// API, and is responsible for the management of the internal resources used
/// by the OpticalFlow algorithm. When this API is called, multiple calls will be
/// made via the pointers contained in the <c><i>callbacks</i></c> structure.
/// These callbacks will attempt to retreive the device capabilities, and
/// create the internal resources, and pipelines required by OpticalFlow's
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxOpticalflowContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The flags included in the <c><i>flags</i></c> field of
/// <c><i>FfxOpticalflowContext</i></c> how match the configuration of your
/// application as well as the intended use of OpticalFlow. It is important that these
/// flags are set correctly (as well as a correct programmed
/// <c><i>FfxOpticalflowContextDescription</i></c>) to ensure correct operation. It is
/// recommended to consult the overview documentation for further details on
/// how OpticalFlow should be integerated into an application.
///
/// When the <c><i>FfxOpticalflowContext</i></c> is created, you should use the
/// <c><i>ffxOpticalflowContextDispatch</i></c> function each frame where FSR3
/// upscaling should be applied. See the documentation of
/// <c><i>ffxOpticalflowContextDispatch</i></c> for more details.
///
/// The <c><i>FfxOpticalflowContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or OpticalFlow is
/// disabled by a user. To destroy the OpticalFlow context you should call
/// <c><i>ffxOpticalflowContextDestroy</i></c>.
///
/// @param [out] context A pointer to a <c><i>FfxOpticalflowContext</i></c> structure to populate.
/// @param [in] contextDescription A pointer to a <c><i>FfxOpticalflowContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxOpticalflowContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxOpticalflow
FFX_API FfxErrorCode ffxOpticalflowContextCreate(FfxOpticalflowContext* context, FfxOpticalflowContextDescription* contextDescription);
FFX_API FfxErrorCode ffxOpticalflowContextGetGpuMemoryUsage(FfxOpticalflowContext* pContext, FfxEffectMemoryUsage* vramUsage);
FFX_API FfxErrorCode ffxOpticalflowGetSharedResourceDescriptions(FfxOpticalflowContext* context, FfxOpticalflowSharedResourceDescriptions* SharedResources);
FFX_API FfxErrorCode ffxOpticalflowContextDispatch(FfxOpticalflowContext* context, const FfxOpticalflowDispatchDescription* dispatchDescription);
/// Destroy the FidelityFX OpticalFlow context.
///
/// @param [out] context A pointer to a <c><i>FfxOpticalflowContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxOpticalflow
FFX_API FfxErrorCode ffxOpticalflowContextDestroy(FfxOpticalflowContext* context);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxOpticalflow
FFX_API FfxVersionNumber ffxOpticalflowGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,210 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
// @defgroup PARALLEL_SORT
#pragma once
// Include the interface for the backend of the FSR2 API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup FfxParallelSort FidelityFX Parallel Sort
/// FidelityFX Single Pass Downsampler runtime library
///
/// @ingroup SDKComponents
/// FidelityFX Parallel Sort major version.
///
/// @ingroup FfxParallelSort
#define FFX_PARALLELSORT_VERSION_MAJOR (1)
/// FidelityFX Parallel Sort minor version.
///
/// @ingroup FfxParallelSort
#define FFX_PARALLELSORT_VERSION_MINOR (3)
/// FidelityFX Parallel Sort patch version.
///
/// @ingroup FfxParallelSort
#define FFX_PARALLELSORT_VERSION_PATCH (0)
/// FidelityFX SPD context count
///
/// Defines the number of internal effect contexts required by SPD
///
/// @ingroup FfxParallelSort
#define FFX_PARALLELSORT_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup FfxParallelSort
#define FFX_PARALLELSORT_CONTEXT_SIZE (373794)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of the passes which constitute the Parallel Sort algorithm.
///
/// Parallel Sort is implemented as a multi-pass algorithm that is invoked over
/// a number of successive iterations until all bits in the key are sorted.
/// For a more comprehensive description of Parallel Sort's inner workings, please
/// refer to the Parallel Sort reference documentation.
///
/// @ingroup FfxParallelSort
typedef enum FfxParallelSortPass
{
FFX_PARALLELSORT_PASS_SETUP_INDIRECT_ARGS = 0, ///< A pass which sets up indirect params to invoke sorting when <c><i>FFX_PARALLEL_SORT_INDIRECT</i></c> flag bit is set.
FFX_PARALLELSORT_PASS_SUM, ///< A pass which counts the number of occurrences of each value in the data set.
FFX_PARALLELSORT_PASS_REDUCE, ///< A pass which further reduces the counts across thread groups for faster offset calculations in large data sets.
FFX_PARALLELSORT_PASS_SCAN, ///< A pass which prefixes the count totals into global offsets.
FFX_PARALLELSORT_PASS_SCAN_ADD, ///< A pass which does a second prefix add the global offsets to each local thread group offset.
FFX_PARALLELSORT_PASS_SCATTER, ///< A pass which performs a local sort of all values in the thread group and outputs to new global offset
FFX_PARALLELSORT_PASS_COUNT ///< The number of passes in Parallel Sort
} FfxParallelSortPass;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxParallelSortContextDescription</i></c>. See <c><i>FfxParallelSortContextDescription</i></c>.
///
/// @ingroup FfxParallelSort
typedef enum FfxParallelSortInitializationFlagBits {
FFX_PARALLELSORT_INDIRECT_SORT = (1 << 0), ///< A bit indicating if we should use indirect version of sort algorithm
FFX_PARALLELSORT_PAYLOAD_SORT = (1 << 1), ///< A bit indicating if we should sort a payload buffer
} FfxParallelSortInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Parallel Sort.
///
/// @ingroup FfxParallelSort
typedef struct FfxParallelSortContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxParallelSortInitializationFlagBits</i></c>.
uint32_t maxEntries; ///< Maximum number of entries to sort
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX.
} FfxParallelSortContextDescription;
/// A structure encapsulating the parameters needed to sort
/// the buffer(s) provided
///
/// @ingroup FfxParallelSort
typedef struct FfxParallelSortDispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record parallel sort compute commands into.
FfxResource keyBuffer; ///< The buffer resource containing the keys to sort
FfxResource payloadBuffer; ///< The (optional) payload buffer to sort (requires <c><i>FFX_PARALLELSORT_PAYLOAD_SORT</i></c> be set)
uint32_t numKeysToSort; ///< The number of keys in the buffer requiring sorting
} FfxParallelSortDispatchDescription;
/// A structure encapsulating the FidelityFX Parallel Sort context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by parallel sort.
///
/// The <c><i>FfxParallelSortContext</i></c> object should have a lifetime matching
/// your use of parallel sort. Before destroying the parallel sort context care
/// should be taken to ensure the GPU is not accessing the resources created or
/// used by parallel sort. It is therefore recommended that the GPU is idle
/// before destroying the parallel sort context.
///
/// @ingroup FfxParallelSort
typedef struct FfxParallelSortContext {
uint32_t data[FFX_PARALLELSORT_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxParallelSortContext;
/// Create a FidelityFX Parallel Sort context from the parameters
/// programmed to the <c><i>FfxParallelSortContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the parallel
/// sort API, and is responsible for the management of the internal resources
/// used by the parallel sort algorithm. When this API is called, multiple calls
/// will be made via the pointers contained in the <c><i>callbacks</i></c>
/// structure. These callbacks will attempt to retreive the device capabilities,
/// and create the internal resources, and pipelines required by parallel sorts'
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxParallelSortContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The <c><i>FfxParallelSortContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or parallel sort
/// upscaling is disabled by a user. To destroy the parallel sort context you
/// should call <c><i>ffxParallelSortContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxParallelSortContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxParallelSortContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxFsr2ContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxParallelSort
FFX_API FfxErrorCode ffxParallelSortContextCreate(FfxParallelSortContext* pContext, const FfxParallelSortContextDescription* pContextDescription);
/// Execute a FidelityFX Parallel Sort context to sort the provided data
/// according to the passed in dispatch description.
///
/// @param [out] pContext A pointer to a <c><i>FfxParallelSortContext</i></c> structure to populate.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxParallelSortDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>sortDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxParallelSort
FFX_API FfxErrorCode ffxParallelSortContextDispatch(FfxParallelSortContext* pContext, const FfxParallelSortDispatchDescription* pDispatchDescription);
/// Destroy the FidelityFX Parallel Sort context.
///
/// @param [out] pContext A pointer to a <c><i>FfxParallelSortContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FfxParallelSort
FFX_API FfxErrorCode ffxParallelSortContextDestroy(FfxParallelSortContext* pContext);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup FfxParallelSort
FFX_API FfxVersionNumber ffxParallelSortGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,222 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
// @defgroup FSR2
#pragma once
// Include the interface for the backend of the FSR2 API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup FfxSpd FidelityFX SPD
/// FidelityFX Single Pass Downsampler runtime library
///
/// @ingroup SDKComponents
/// FidelityFX SPD major version.
///
/// @ingroup FfxSpd
#define FFX_SPD_VERSION_MAJOR (2)
/// FidelityFX SPD minor version.
///
/// @ingroup FfxSpd
#define FFX_SPD_VERSION_MINOR (2)
/// FidelityFX SPD patch version.
///
/// @ingroup FfxSpd
#define FFX_SPD_VERSION_PATCH (0)
/// FidelityFX SPD context count
///
/// Defines the number of internal effect contexts required by SPD
///
/// @ingroup FfxSpd
#define FFX_SPD_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup FfxSpd
#define FFX_SPD_CONTEXT_SIZE (9300)
/// If this ever changes, need to also reflect a change in number
/// of resources in ffx_spd_resources.h
///
/// @ingroup FfxSpd
#define SPD_MAX_MIP_LEVELS 12
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of the pass which constitutes the SPD algorithm.
///
/// SPD is implemented as a single pass algorithm. Each call to the
/// <c><i>FfxSPDScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single downsample job. For a
/// more comprehensive description of SPD's inner workings, please
/// refer to the SPD reference documentation.
///
/// @ingroup FfxSpd
typedef enum FfxSpdPass
{
FFX_SPD_PASS_DOWNSAMPLE = 0, ///< A pass which which downsamples all mips
FFX_SPD_PASS_COUNT ///< The number of passes in SPD
} FfxSpdPass;
typedef enum FfxSpdDownsampleFilter
{
FFX_SPD_DOWNSAMPLE_FILTER_MEAN = 0,
FFX_SPD_DOWNSAMPLE_FILTER_MIN,
FFX_SPD_DOWNSAMPLE_FILTER_MAX,
FFX_SPD_DOWNSAMPLE_FILTER_COUNT
} FfxSpdDownsampleFilter;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxSpdContext</i></c>. See <c><i>FfxSpdContextDescription</i></c>.
///
/// @ingroup FfxSpd
typedef enum FfxSpdInitializationFlagBits {
FFX_SPD_SAMPLER_LOAD = (1 << 0), ///< A bit indicating if we should use resource loads (favor loads over sampler)
FFX_SPD_SAMPLER_LINEAR = (1 << 1), ///< A bit indicating if we should use sampler to load resources.
FFX_SPD_WAVE_INTEROP_LDS = (1 << 2), ///< A bit indicating if we should use LDS
FFX_SPD_WAVE_INTEROP_WAVE_OPS = (1 << 3), ///< A bit indicating if we should use WAVE OPS (favor wave ops over LDS)
FFX_SPD_MATH_NONPACKED = (1 << 4), ///< A bit indicating if we should use floating point math
FFX_SPD_MATH_PACKED = (1 << 5) ///< A bit indicating if we should use 16-bit half precision floating point math (favored)
} FfxSpdInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Single Pass Downsampler.
///
/// @ingroup FfxSpd
typedef struct FfxSpdContextDescription {
uint32_t flags; ///< A collection of <c><i>FfxSpdInitializationFlagBits</i></c>
FfxSpdDownsampleFilter downsampleFilter;
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX.
} FfxSpdContextDescription;
/// A structure encapsulating the parameters for dispatching
/// of FidelityFX Single Pass Downsampler
///
/// @ingroup FfxSpd
typedef struct FfxSpdDispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record rendering commands into.
FfxResource resource; ///< The <c><i>FfxResource</i></c> to downsample
} FfxSpdDispatchDescription;
/// A structure encapsulating the FidelityFX single pass downsampler context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by SPD.
///
/// The <c><i>FfxSpdContext</i></c> object should have a lifetime matching
/// your use of FSR1. Before destroying the SPD context care should be taken
/// to ensure the GPU is not accessing the resources created or used by SPD.
/// It is therefore recommended that the GPU is idle before destroying the
/// SPD context.
///
/// @ingroup FfxSpd
typedef struct FfxSpdContext {
uint32_t data[FFX_SPD_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxSpdContext;
/// Create a FidelityFX Single Pass Downsampler context from the parameters
/// programmed to the <c><i>FfxSpdContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the Single
/// Pass Downsampler API, and is responsible for the management of the internal resources
/// used by the SPD algorithm. When this API is called, multiple calls
/// will be made via the pointers contained in the <c><i>backendInterface</i></c>
/// structure. This backend will attempt to retrieve the device capabilities,
/// and create the internal resources, and pipelines required by SPD to function.
/// Depending on the precise configuration used when
/// creating the <c><i>FfxSpdContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The <c><i>FfxSpdContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or SPD
/// upscaling is disabled by a user. To destroy the SPD context you
/// should call <c><i>ffxSpdContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxSpdContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxSpdContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxSpdContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxSpd
FFX_API FfxErrorCode ffxSpdContextCreate(FfxSpdContext* pContext, const FfxSpdContextDescription* pContextDescription);
/// Dispatches work to the FidelityFX SPD context
///
/// @param [out] pContext A pointer to a <c><i>FfxSpdContext</i></c> structure to populate.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxSpdDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxSpd
FFX_API FfxErrorCode ffxSpdContextDispatch(FfxSpdContext* pContext, const FfxSpdDispatchDescription* pDispatchDescription);
/// Destroy the FidelityFX SPD context.
///
/// @param [out] pContext A pointer to a <c><i>FfxSpdContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FfxSpd
FFX_API FfxErrorCode ffxSpdContextDestroy(FfxSpdContext* pContext);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup FfxSpd
FFX_API FfxVersionNumber ffxSpdGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,260 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 the interface for the backend of the SSSR API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup FfxSssr FidelityFX SSSR
/// FidelityFX Stochastic Screen Space Reflections runtime library
///
/// @ingroup SDKComponents
/// FidelityFX Stochastic Screen Space Reflections major version.
///
/// @ingroup FfxSssr
#define FFX_SSSR_VERSION_MAJOR (1)
/// FidelityFX Stochastic Screen Space Reflections minor version.
///
/// @ingroup FfxSssr
#define FFX_SSSR_VERSION_MINOR (5)
/// FidelityFX Stochastic Screen Space Reflections patch version.
///
/// @ingroup FfxSssr
#define FFX_SSSR_VERSION_PATCH (0)
/// FidelityFX SSSR context count
///
/// Defines the number of internal effect contexts required by SSSR
/// We need 2, one for the SSSR context and one for the FidelityFX Denoiser
///
/// @ingroup FfxSssr
#define FFX_SSSR_CONTEXT_COUNT 2
/// The size of the context specified in 32bit values.
///
/// @ingroup FfxSssr
#define FFX_SSSR_CONTEXT_SIZE (118914)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of all the passes which constitute the SSSR algorithm.
///
/// SSSR is implemented as a composite of several compute passes each
/// computing a key part of the final result. Each call to the
/// <c><i>FfxSssrScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single pass included in <c><i>FfxSssrPass</i></c>. For a
/// more comprehensive description of each pass, please refer to the SSSR
/// reference documentation.
///
/// @ingroup FfxSssr
typedef enum FfxSssrPass
{
FFX_SSSR_PASS_DEPTH_DOWNSAMPLE = 0, ///< A pass which performs the hierarchical depth buffer generation
FFX_SSSR_PASS_CLASSIFY_TILES = 1, ///< A pass which classifies which pixels require screen space ray marching
FFX_SSSR_PASS_PREPARE_BLUE_NOISE_TEXTURE = 2, ///< A pass which generates an optimized blue noise texture
FFX_SSSR_PASS_PREPARE_INDIRECT_ARGS = 3, ///< A pass which generates the indirect arguments for the intersection pass.
FFX_SSSR_PASS_INTERSECTION = 4, ///< A pass which performs the actual hierarchical depth ray marching.
FFX_SSSR_PASS_COUNT
} FfxSssrPass;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxSssrContext</i></c>. See <c><i>FfxSssrContextDescription</i></c>.
///
/// @ingroup FfxSssr
typedef enum FfxSssrInitializationFlagBits {
FFX_SSSR_ENABLE_DEPTH_INVERTED = (1 << 0) ///< A bit indicating that the input depth buffer data provided is inverted [1..0].
} FfxSssrInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Stochastic Screen Space Reflections.
///
/// @ingroup ffxSssr
typedef struct FfxSssrContextDescription
{
uint32_t flags; ///< A collection of <c><i>FfxSssrInitializationFlagBits</i></c>.
FfxDimensions2D renderSize; ///< The resolution we are currently rendering at
FfxSurfaceFormat normalsHistoryBufferFormat; ///< The format used by the reflections denoiser to store the normals buffer history
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX SDK
} FfxSssrContextDescription;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX Stochastic Screen Space Reflections.
///
/// @ingroup ffxSssr
typedef struct FfxSssrDispatchDescription {
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record SSSR rendering commands into.
FfxResource color; ///< A <c><i>FfxResource</i></c> containing the color buffer for the current frame.
FfxResource depth; ///< A <c><i>FfxResource</i></c> containing the depth buffer for the current frame.
FfxResource motionVectors; ///< A <c><i>FfxResource</i></c> containing the motion vectors buffer for the current frame.
FfxResource normal; ///< A <c><i>FfxResource</i></c> containing the normal buffer for the current frame.
FfxResource materialParameters; ///< A <c><i>FfxResource</i></c> containing the roughness buffer for the current frame.
FfxResource environmentMap; ///< A <c><i>FfxResource</i></c> containing the environment map to fallback to when screenspace data is not sufficient.
FfxResource brdfTexture; ///< A <c><i>FfxResource</i></c> containing the precomputed brdf LUT.
FfxResource output; ///< A <c><i>FfxResource</i></c> to store the result of the SSSR algorithm into.
float invViewProjection[16]; ///< An array containing the inverse of the view projection matrix in column major layout.
float projection[16]; ///< An array containing the projection matrix in column major layout.
float invProjection[16]; ///< An array containing the inverse of the projection matrix in column major layout.
float view[16]; ///< An array containing the view matrix in column major layout.
float invView[16]; ///< An array containing the inverse of the view matrix in column major layout.
float prevViewProjection[16]; ///< An array containing the previous frame's view projection matrix in column major layout.
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resources.
FfxFloatCoords2D motionVectorScale; ///< The scale factor to apply to motion vectors.
float iblFactor; ///< A factor to control the intensity of the image based lighting. Set to 1 for an HDR probe.
float normalUnPackMul; ///< A multiply factor to transform the normal to the space expected by SSSR.
float normalUnPackAdd; ///< An offset to transform the normal to the space expected by SSSR.
uint32_t roughnessChannel; ///< The channel to read the roughness from the materialParameters texture
bool isRoughnessPerceptual; ///< A boolean to describe the space used to store roughness in the materialParameters texture. If false, we assume roughness squared was stored in the Gbuffer.
float temporalStabilityFactor; ///< A factor to control the accmulation of history values. Higher values reduce noise, but are more likely to exhibit ghosting artefacts.
float depthBufferThickness; ///< A bias for accepting hits. Larger values can cause streaks, lower values can cause holes.
float roughnessThreshold; ///< Regions with a roughness value greater than this threshold won't spawn rays.
float varianceThreshold; ///< Luminance differences between history results will trigger an additional ray if they are greater than this threshold value.
uint32_t maxTraversalIntersections; ///< Caps the maximum number of lookups that are performed from the depth buffer hierarchy. Most rays should terminate after approximately 20 lookups.
uint32_t minTraversalOccupancy; ///< Exit the core loop early if less than this number of threads are running.
uint32_t mostDetailedMip; ///< The most detailed MIP map level in the depth hierarchy. Perfect mirrors always use 0 as the most detailed level.
uint32_t samplesPerQuad; ///< The minimum number of rays per quad. Variance guided tracing can increase this up to a maximum of 4.
uint32_t temporalVarianceGuidedTracingEnabled; ///< A boolean controlling whether a ray should be spawned on pixels where a temporal variance is detected or not.
} FfxSssrDispatchDescription;
/// A structure encapsulating the FidelityFX Stochastic Screen Space Reflections context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by SSSR.
///
/// The <c><i>FfxSssrContext</i></c> object should have a lifetime matching
/// your use of SSSR. Before destroying the SSSR context care should be taken
/// to ensure the GPU is not accessing the resources created or used by SSSR.
/// It is therefore recommended that the GPU is idle before destroying the
/// SSSR context.
///
/// @ingroup ffxSssr
typedef struct FfxSssrContext
{
uint32_t data[FFX_SSSR_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxSssrContext;
/// Create a FidelityFX Stochastic Screen Space Reflections context from the parameters
/// programmed to the <c><i>FfxSssrCreateParams</i></c> structure.
///
/// The context structure is the main object used to interact with the SSSR
/// API, and is responsible for the management of the internal resources used
/// by the SSSR algorithm. When this API is called, multiple calls will be
/// made via the pointers contained in the <c><i>callbacks</i></c> structure.
/// These callbacks will attempt to retreive the device capabilities, and
/// create the internal resources, and pipelines required by SSSR's
/// frame-to-frame function. Depending on the precise configuration used when
/// creating the <c><i>FfxSssrContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The flags included in the <c><i>flags</i></c> field of
/// <c><i>FfxSssrContext</i></c> how match the configuration of your
/// application as well as the intended use of SSSR. It is important that these
/// flags are set correctly (as well as a correct programmed
/// <c><i>FfxSssrDispatchDescription</i></c>) to ensure correct operation. It is
/// recommended to consult the overview documentation for further details on
/// how SSSR should be integerated into an application.
///
/// When the <c><i>FfxSssrContext</i></c> is created, you should use the
/// <c><i>ffxSssrContextDispatch</i></c> function each frame where SSSR
/// algorithm should be applied. See the documentation of
/// <c><i>ffxSssrContextDispatch</i></c> for more details.
///
/// The <c><i>FfxSssrContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or SSSR upscaling is
/// disabled by a user. To destroy the SSSR context you should call
/// <c><i>ffxSssrContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxSssrContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxSssrContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxSssrContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxSssr
FFX_API FfxErrorCode ffxSssrContextCreate(FfxSssrContext* context, const FfxSssrContextDescription* contextDescription);
/// Dispatch the various passes that constitute the FidelityFX Stochastic Screen Space Reflections.
///
/// SSSR is a composite effect, meaning that it is compromised of multiple
/// constituent passes (implemented as one or more clears, copies and compute
/// dispatches). The <c><i>ffxSssrContextDispatch</i></c> function is the
/// function which (via the use of the functions contained in the
/// <c><i>callbacks</i></c> field of the <c><i>FfxSssrContext</i></c>
/// structure) utlimately generates the sequence of graphics API calls required
/// each frame.
///
/// As with the creation of the <c><i>FfxSssrContext</i></c> correctly
/// programming the <c><i>FfxSssrDispatchDescription</i></c> is key to ensuring
/// the correct operation of SSSR.
///
/// @param [in] pContext A pointer to a <c><i>FfxSssrContext</i></c> structure.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxSssrDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_NULL_DEVICE The operation failed because the device inside the context was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup ffxSssr
FFX_API FfxErrorCode ffxSssrContextDispatch(FfxSssrContext* context, const FfxSssrDispatchDescription* dispatchDescription);
/// Destroy the FidelityFX Stochastic Screen Space Reflections context.
///
/// @param [out] pContext A pointer to a <c><i>FfxSssrContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup ffxSssr
FFX_API FfxErrorCode ffxSssrContextDestroy(FfxSssrContext* context);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup ffxSssr
FFX_API FfxVersionNumber ffxSssrGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,190 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 <FidelityFX/host/ffx_types.h>
/// @defgroup Utils Utilities
/// Utility Macros used by the FidelityFX SDK
///
/// @ingroup ffxHost
/// The value of Pi.
///
/// @ingroup Utils
const float FFX_PI = 3.141592653589793f;
/// An epsilon value for floating point numbers.
///
/// @ingroup Utils
const float FFX_EPSILON = 1e-06f;
/// Helper macro to create the version number.
///
/// @ingroup Utils
#define FFX_MAKE_VERSION(major, minor, patch) ((major << 22) | (minor << 12) | patch)
///< Use this to specify no version.
///
/// @ingroup Utils
#define FFX_UNSPECIFIED_VERSION 0xFFFFAD00
/// Helper macro to avoid warnings about unused variables.
///
/// @ingroup Utils
#define FFX_UNUSED(x) ((void)(x))
/// Helper macro to align an integer to the specified power of 2 boundary
///
/// @ingroup Utils
#define FFX_ALIGN_UP(x, y) (((x) + ((y)-1)) & ~((y)-1))
/// Helper macro to check if a value is aligned.
///
/// @ingroup Utils
#define FFX_IS_ALIGNED(x) (((x) != 0) && ((x) & ((x)-1)))
/// Helper macro to compute the rounded-up integer division of two unsigned integers
///
/// @ingroup Utils
#define FFX_DIVIDE_ROUNDING_UP(x, y) ((x + y - 1) / y)
/// Helper macro to stringify a value.
///
/// @ingroup Utils
#define FFX_STR(s) FFX_XSTR(s)
#define FFX_XSTR(s) #s
/// Helper macro to forward declare a structure.
///
/// @ingroup Utils
#define FFX_FORWARD_DECLARE(x) typedef struct x x
/// Helper macro to return the maximum of two values.
///
/// @ingroup Utils
#define FFX_MAXIMUM(x, y) (((x) > (y)) ? (x) : (y))
/// Helper macro to return the minimum of two values.
///
/// @ingroup Utils
#define FFX_MINIMUM(x, y) (((x) < (y)) ? (x) : (y))
/// Helper macro to do safe free on a pointer.
///
/// @ingroup Utils
#define FFX_SAFE_FREE(x, freeFunc) \
do { \
if (x) \
{ \
freeFunc(x); \
x = nullptr; \
} \
} while (false)
/// Helper macro to return the abs of an integer value.
///
/// @ingroup Utils
#define FFX_ABSOLUTE(x) (((x) < 0) ? (-(x)) : (x))
/// Helper macro to return sign of a value.
///
/// @ingroup Utils
#define FFX_SIGN(x) (((x) < 0) ? -1 : 1)
/// Helper macro to work out the number of elements in an array.
///
/// @ingroup Utils
#define FFX_ARRAY_ELEMENTS(x) (int32_t)((sizeof(x) / sizeof(0 [x])) / ((size_t)(!(sizeof(x) % sizeof(0 [x])))))
/// The maximum length of a path that can be specified to the FidelityFX API.
///
/// @ingroup Utils
#define FFX_MAXIMUM_PATH (260)
/// Helper macro to check if the specified key is set in a bitfield.
///
/// @ingroup Utils
#define FFX_CONTAINS_FLAG(options, key) (((options) & key) == key)
#if defined(FFX_MUTEX_IMPL_SHARED)
/// Lock mutex exclusively.
///
/// @ingroup Utils
#define FFX_MUTEX_LOCK(x) x.lock()
/// Lock mutex for shared access.
///
/// @ingroup Utils
#define FFX_MUTEX_LOCK_SHARED(x) x.lock_shared()
/// Unlock exclusive mutex lock.
///
/// @ingroup Utils
#define FFX_MUTEX_UNLOCK(x) x.unlock()
/// Unlock shared mutex lock.
///
/// @ingroup Utils
#define FFX_MUTEX_UNLOCK_SHARED(x) x.unlock_shared()
#elif defined(FFX_MUTEX_IMPL_STANDARD)
/// Lock mutex exclusively.
///
/// @ingroup Utils
#define FFX_MUTEX_LOCK(x) x.lock()
/// Lock mutex for shared access.
///
/// @ingroup Utils
#define FFX_MUTEX_LOCK_SHARED(x) FFX_MUTEX_LOCK(x)
/// Unlock exclusive mutex lock.
///
/// @ingroup Utils
#define FFX_MUTEX_UNLOCK(x) x.unlock()
/// Unlock shared mutex lock.
///
/// @ingroup Utils
#define FFX_MUTEX_UNLOCK_SHARED(x) FFX_MUTEX_UNLOCK(x)
#elif !defined(FFX_MUTEX_LOCK) || !defined(FFX_MUTEX_LOCK_SHARED) || !defined(FFX_MUTEX_UNLOCK) || !defined(FFX_MUTEX_UNLOCK_SHARED)
#error When using custom mutex you have to provide all following operations too: FFX_MUTEX_LOCK, FFX_MUTEX_LOCK_SHARED, FFX_MUTEX_UNLOCK, FFX_MUTEX_UNLOCK_SHARED!
#endif // #if defined(FFX_MUTEX_IMPL_SHARED)
/// Computes the number of bits set to 1 in a integer.
///
/// @param [in] val Integer mask.
///
/// @return Number of bits set to 1 in provided val.
///
/// @ingroup Utils
inline uint8_t ffxCountBitsSet(uint32_t val) noexcept
{
#if __cplusplus >= 202002L
return static_cast<uint8_t>(std::popcount(val));
#elif defined(_MSVC_LANG)
return static_cast<uint8_t>(__popcnt(val));
#elif defined(__GNUC__) || defined(__clang__)
return static_cast<uint8_t>(__builtin_popcount(val));
#else
uint32_t c = val - ((val >> 1) & 0x55555555);
c = ((c >> 2) & 0x33333333) + (c & 0x33333333);
c = ((c >> 4) + c) & 0x0F0F0F0F;
c = ((c >> 8) + c) & 0x00FF00FF;
return static_cast<uint8_t>(((c >> 16) + c) & 0x0000FFFF);
#endif
}
@@ -0,0 +1,224 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
// @defgroup VRS
#pragma once
// Include the interface for the backend of the FSR 2.0 API.
#include <FidelityFX/host/ffx_interface.h>
/// @defgroup FfxVrs FidelityFX VRS
/// FidelityFX Variable Rate Shading runtime library
///
/// @ingroup SDKComponents
/// FidelityFX VRS major version.
///
/// @ingroup FfxVrs
#define FFX_VRS_VERSION_MAJOR (1)
/// FidelityFX VRS minor version.
///
/// @ingroup FfxVrs
#define FFX_VRS_VERSION_MINOR (2)
/// FidelityFX VRS patch version.
///
/// @ingroup FfxVrs
#define FFX_VRS_VERSION_PATCH (0)
/// FidelityFX VRS context count
///
/// Defines the number of internal effect contexts required by VRS
///
/// @ingroup FfxVrs
#define FFX_VRS_CONTEXT_COUNT 1
/// The size of the context specified in 32bit values.
///
/// @ingroup FfxVrs
#define FFX_VRS_CONTEXT_SIZE (16536)
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
/// An enumeration of the pass which constitutes the ShadingRateImage
/// generation algorithm.
///
/// VRS is implemented as a single pass algorithm. Each call to the
/// <c><i>FfxScheduleGpuJobFunc</i></c> callback function will
/// correspond to a single image generation job. For a
/// more comprehensive description of VRS's inner workings, please
/// refer to the VRS reference documentation.
///
/// @ingroup FfxVrs
typedef enum FfxVrsPass
{
FFX_VRS_PASS_IMAGEGEN = 0, ///< A pass which generates a ShadingRateImage.
FFX_VRS_PASS_COUNT ///< The number of passes performed by VRS.
} FfxVrsPass;
/// An enumeration of bit flags used when creating a
/// <c><i>FfxVrsContext</i></c>. See <c><i>FfxVrsContextDescription</i></c>.
///
/// @ingroup FfxVrs
typedef enum FfxVrsInitializationFlagBits
{
FFX_VRS_ALLOW_ADDITIONAL_SHADING_RATES = (1 << 0), ///< A bit indicating if we should enable additional shading rates.
} FfxVrsInitializationFlagBits;
/// A structure encapsulating the parameters required to initialize FidelityFX
/// Variable Shading
///
/// @ingroup FfxVrs
typedef struct FfxVrsContextDescription
{
uint32_t flags; ///< A collection of <c><i>FfxVrsInitializationFlagBits</i></c>
uint32_t shadingRateImageTileSize; ///< ShadingRateImage tile size.
FfxInterface backendInterface; ///< A set of pointers to the backend implementation for FidelityFX.
} FfxVrsContextDescription;
/// A structure encapsulating the parameters for dispatching the various passes
/// of FidelityFX Variable Shading
///
/// @ingroup FfxVrs
typedef struct FfxVrsDispatchDescription
{
FfxCommandList commandList; ///< The <c><i>FfxCommandList</i></c> to record VRS rendering commands into.
FfxResource historyColor; ///< A <c><i>FfxResource</i></c> containing the color buffer for the previous frame (at presentation resolution).
FfxResource motionVectors; ///< A <c><i>FfxResource</i></c> containing the velocity buffer for the current frame (at presentation resolution).
FfxResource output; ///< A <c><i>FfxResource</i></c> containing the ShadingRateImage buffer for the current frame.
FfxDimensions2D renderSize; ///< The resolution that was used for rendering the input resource.
float varianceCutoff; ///< This value specifies how much variance in luminance is acceptable to reduce shading rate.
float motionFactor; ///< The lower this value, the faster a pixel has to move to get the shading rate reduced.
uint32_t tileSize; ///< ShadingRateImage tile size.
FfxFloatCoords2D motionVectorScale; ///< Scale motion vectors to different format
} FfxVrsDispatchDescription;
/// A structure encapsulating the FidelityFX Variable Shading context.
///
/// This sets up an object which contains all persistent internal data and
/// resources that are required by VRS.
///
/// The <c><i>FfxVrsContext</i></c> object should have a lifetime matching
/// your use of VRS. Before destroying the VRS context care should be taken
/// to ensure the GPU is not accessing the resources created or used by VRS.
/// It is therefore recommended that the GPU is idle before destroying the
/// VRS context.
///
/// @ingroup FfxVrs
typedef struct FfxVrsContext
{
uint32_t data[FFX_VRS_CONTEXT_SIZE]; ///< An opaque set of <c>uint32_t</c> which contain the data for the context.
} FfxVrsContext;
/// Create a FidelityFX Variable Shading context from the parameters
/// programmed to the <c><i>FfxVrsContextDescription</i></c> structure.
///
/// The context structure is the main object used to interact with the Variable
/// Shading API, and is responsible for the management of the internal resources
/// used by the VRS algorithm. When this API is called, multiple calls
/// will be made via the pointers contained in the <c><i>backendInterface</i></c>
/// structure. This backend will attempt to retrieve the device capabilities,
/// and create the internal resources, and pipelines required by VRS to function.
/// Depending on the precise configuration used when
/// creating the <c><i>FfxVrsContext</i></c> a different set of resources and
/// pipelines might be requested via the callback functions.
///
/// The <c><i>FfxVrsContext</i></c> should be destroyed when use of it is
/// completed, typically when an application is unloaded or Variable
/// Shading is disabled by a user. To destroy the VRS context you
/// should call <c><i>ffxVrsContextDestroy</i></c>.
///
/// @param [out] pContext A pointer to a <c><i>FfxVrsContext</i></c> structure to populate.
/// @param [in] pContextDescription A pointer to a <c><i>FfxVrsContextDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>contextDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_INCOMPLETE_INTERFACE The operation failed because the <c><i>FfxVrsContextDescription.callbacks</i></c> was not fully specified.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxVrs
FFX_API FfxErrorCode ffxVrsContextCreate(FfxVrsContext* pContext, const FfxVrsContextDescription* pContextDescription);
/// Dispatches work to the FidelityFX VRS context
///
/// @param [in] pContext A pointer to a <c><i>FfxVrsContext</i></c> structure to populate.
/// @param [in] pDispatchDescription A pointer to a <c><i>FfxVrsDispatchDescription</i></c> structure.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> or <c><i>dispatchDescription</i></c> was <c><i>NULL</i></c>.
/// @retval
/// FFX_ERROR_BACKEND_API_ERROR The operation failed because of an error returned from the backend.
///
/// @ingroup FfxVrs
FFX_API FfxErrorCode ffxVrsContextDispatch(FfxVrsContext* pContext, const FfxVrsDispatchDescription* pDispatchDescription);
/// Destroy the FidelityFX VRS context.
///
/// @param [in] pContext A pointer to a <c><i>FfxVrsContext</i></c> structure to destroy.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_CODE_NULL_POINTER The operation failed because either <c><i>context</i></c> was <c><i>NULL</i></c>.
///
/// @ingroup FfxVrs
FFX_API FfxErrorCode ffxVrsContextDestroy(FfxVrsContext* pContext);
/// A helper function to calculate the ShadingRateImage size from a target
/// resolution.
///
///
/// @param [out] pImageWidth A pointer to a <c>uint32_t</c> which will hold the calculated image width.
/// @param [out] pImageHeight A pointer to a <c>uint32_t</c> which will hold the calculated image height.
/// @param [in] renderWidth The render resolution width.
/// @param [in] renderHeight The render resolution height.
/// @param [in] shadingRateImageTileSize The ShadingRateImage tile size.
///
/// @retval
/// FFX_OK The operation completed successfully.
/// @retval
/// FFX_ERROR_INVALID_POINTER Either <c><i>imageWidth</i></c> or <c><i>imageHeight</i></c> was <c>NULL</c>.
///
/// @ingroup FfxVrs
FFX_API FfxErrorCode ffxVrsGetImageSizeFromeRenderResolution(uint32_t* pImageWidth, uint32_t* pImageHeight, uint32_t renderWidth, uint32_t renderHeight, uint32_t shadingRateImageTileSize);
/// Queries the effect version number.
///
/// @returns
/// The SDK version the effect was built with.
///
/// @ingroup FfxVrs
FFX_API FfxVersionNumber ffxVrsGetEffectVersion();
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
@@ -0,0 +1,46 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 <FidelityFX/host/ffx_interface.h>
#if defined(__cplusplus)
extern "C" {
#endif // #if defined(__cplusplus)
struct FfxShaderBlob;
// Get a shader blob for the specified effect, pass, and permutation index.
FfxErrorCode ffxGetPermutationBlobByIndex(FfxEffect effectId,
FfxPass passId,
FfxBindStage bindStage,
uint32_t permutationOptions,
FfxShaderBlob* outBlob);
// Check is Wave64 is requested on this permutation
FfxErrorCode ffxIsWave64(FfxEffect effectId, uint32_t permutationOptions, bool& isWave64);
#if defined(__cplusplus)
}
#endif // #if defined(__cplusplus)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,75 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_X 0
#define FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_Y 1
#define FFX_FRAMEINTERPOLATION_BIND_UAV_COUNTERS 2
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_0 3
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_1 4
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_2 5
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_3 6
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_4 7
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_5 8
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_6 9
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_7 10
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_8 11
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_9 12
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_10 13
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_11 14
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_12 15
#define FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION 16
#define FFX_FRAMEINTERPOLATION_BIND_CB_INPAINTING_PYRAMID 17
#ifdef FFX_HALF
#undef FFX_HALF
#define FFX_HALF 0
#endif
#include "frameinterpolation/ffx_frameinterpolation_callbacks_glsl.h"
#include "frameinterpolation/ffx_frameinterpolation_common.h"
#include "frameinterpolation/ffx_frameinterpolation_compute_game_vector_field_inpainting_pyramid.h"
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH 256
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
#define FFX_FRAMEINTERPOLATION_NUM_THREADS layout (local_size_x = FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH, local_size_y = FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT, local_size_z = FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
FFX_FRAMEINTERPOLATION_NUM_THREADS
void main()
{
computeFrameinterpolationGameVectorFieldInpaintingPyramid(FfxInt32x3(gl_WorkGroupID), FfxInt32(gl_LocalInvocationIndex));
}
@@ -0,0 +1,74 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_FRAMEINTERPOLATION_BIND_SRV_OUTPUT 0
#define FFX_FRAMEINTERPOLATION_BIND_UAV_COUNTERS 1
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_0 2
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_1 3
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_2 4
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_3 5
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_4 6
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_5 7
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_6 8
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_7 9
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_8 10
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_9 11
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_10 12
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_11 13
#define FFX_FRAMEINTERPOLATION_BIND_UAV_INPAINTING_PYRAMID_MIPMAP_12 14
#define FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION 15
#define FFX_FRAMEINTERPOLATION_BIND_CB_INPAINTING_PYRAMID 16
#ifdef FFX_HALF
#undef FFX_HALF
#define FFX_HALF 0
#endif
#include "frameinterpolation/ffx_frameinterpolation_callbacks_glsl.h"
#include "frameinterpolation/ffx_frameinterpolation_common.h"
#include "frameinterpolation/ffx_frameinterpolation_compute_inpainting_pyramid.h"
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH 256
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
#define FFX_FRAMEINTERPOLATION_NUM_THREADS layout (local_size_x = FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH, local_size_y = FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT, local_size_z = FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
FFX_FRAMEINTERPOLATION_NUM_THREADS
void main()
{
computeFrameinterpolationInpaintingPyramid(FfxInt32x3(gl_WorkGroupID), FfxInt32(gl_LocalInvocationIndex));
}
@@ -0,0 +1,65 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
// Needed for rw_output declaration
#extension GL_EXT_shader_image_load_formatted : require
#define FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_X 0
#define FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_Y 1
#define FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X 2
#define FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y 3
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DISOCCLUSION_MASK 4
#define FFX_FRAMEINTERPOLATION_BIND_SRV_PRESENT_BACKBUFFER 5
#define FFX_FRAMEINTERPOLATION_BIND_SRV_INPAINTING_PYRAMID 6
#define FFX_FRAMEINTERPOLATION_BIND_SRV_CURRENT_INTERPOLATION_SOURCE 7
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DISTORTION_FIELD 8
#define FFX_FRAMEINTERPOLATION_BIND_UAV_OUTPUT 9
#define FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION 10
#include "frameinterpolation/ffx_frameinterpolation_callbacks_glsl.h"
#include "frameinterpolation/ffx_frameinterpolation_common.h"
#include "frameinterpolation/ffx_frameinterpolation_debug_view.h"
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
#define FFX_FRAMEINTERPOLATION_NUM_THREADS layout (local_size_x = FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH, local_size_y = FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT, local_size_z = FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
FFX_FRAMEINTERPOLATION_NUM_THREADS
void main()
{
computeDebugView(FfxInt32x2(gl_GlobalInvocationID.xy));
}
@@ -0,0 +1,61 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_X 0
#define FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_Y 1
#define FFX_FRAMEINTERPOLATION_BIND_SRV_RECONSTRUCTED_DEPTH_PREVIOUS_FRAME 2
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_DEPTH 3
#define FFX_FRAMEINTERPOLATION_BIND_SRV_RECONSTRUCTED_DEPTH_INTERPOLATED_FRAME 4
#define FFX_FRAMEINTERPOLATION_BIND_SRV_INPAINTING_PYRAMID 5
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DISTORTION_FIELD 6
#define FFX_FRAMEINTERPOLATION_BIND_UAV_DISOCCLUSION_MASK 7
#define FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION 8
#include "frameinterpolation/ffx_frameinterpolation_callbacks_glsl.h"
#include "frameinterpolation/ffx_frameinterpolation_common.h"
#include "frameinterpolation/ffx_frameinterpolation_disocclusion_mask.h"
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
#define FFX_FRAMEINTERPOLATION_NUM_THREADS layout (local_size_x = FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH, local_size_y = FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT, local_size_z = FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
FFX_FRAMEINTERPOLATION_NUM_THREADS
void main()
{
computeDisocclusionMask(FfxInt32x2(gl_GlobalInvocationID.xy));
}
@@ -0,0 +1,60 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_MOTION_VECTORS 0
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_DEPTH 1
#define FFX_FRAMEINTERPOLATION_BIND_SRV_PREVIOUS_INTERPOLATION_SOURCE 2
#define FFX_FRAMEINTERPOLATION_BIND_SRV_CURRENT_INTERPOLATION_SOURCE 3
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DISTORTION_FIELD 4
#define FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_X 5
#define FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_Y 6
#define FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION 7
#include "frameinterpolation/ffx_frameinterpolation_callbacks_glsl.h"
#include "frameinterpolation/ffx_frameinterpolation_common.h"
#include "frameinterpolation/ffx_frameinterpolation_game_motion_vector_field.h"
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
#define FFX_FRAMEINTERPOLATION_NUM_THREADS layout (local_size_x = FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH, local_size_y = FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT, local_size_z = FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
FFX_FRAMEINTERPOLATION_NUM_THREADS
void main()
{
computeGameFieldMvs(FfxInt32x2(gl_GlobalInvocationID.xy));
}
@@ -0,0 +1,60 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
// Needed for rw_output declaration
#extension GL_EXT_shader_image_load_formatted : require
#define FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_SCENE_CHANGE_DETECTION 0
#define FFX_FRAMEINTERPOLATION_BIND_SRV_INPAINTING_PYRAMID 1
#define FFX_FRAMEINTERPOLATION_BIND_SRV_PRESENT_BACKBUFFER 2
#define FFX_FRAMEINTERPOLATION_BIND_SRV_CURRENT_INTERPOLATION_SOURCE 3
#define FFX_FRAMEINTERPOLATION_BIND_UAV_OUTPUT 7
#define FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION 8
#include "frameinterpolation/ffx_frameinterpolation_callbacks_glsl.h"
#include "frameinterpolation/ffx_frameinterpolation_common.h"
#include "frameinterpolation/ffx_frameinterpolation_inpainting.h"
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
#define FFX_FRAMEINTERPOLATION_NUM_THREADS layout (local_size_x = FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH, local_size_y = FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT, local_size_z = FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
FFX_FRAMEINTERPOLATION_NUM_THREADS
void main()
{
computeInpainting(FfxInt32x2(gl_GlobalInvocationID.xy));
}
@@ -0,0 +1,60 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW 0
#define FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_CONFIDENCE 1
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_DEPTH 2
#define FFX_FRAMEINTERPOLATION_BIND_SRV_PREVIOUS_INTERPOLATION_SOURCE 3
#define FFX_FRAMEINTERPOLATION_BIND_SRV_CURRENT_INTERPOLATION_SOURCE 4
#define FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X 6
#define FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y 7
#define FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION 8
#include "frameinterpolation/ffx_frameinterpolation_callbacks_glsl.h"
#include "frameinterpolation/ffx_frameinterpolation_common.h"
#include "frameinterpolation/ffx_frameinterpolation_optical_flow_vector_field.h"
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
#define FFX_FRAMEINTERPOLATION_NUM_THREADS layout (local_size_x = FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH, local_size_y = FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT, local_size_z = FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
FFX_FRAMEINTERPOLATION_NUM_THREADS
void main()
{
computeOpticalFlowVectorField(FfxInt32x2(gl_GlobalInvocationID.xy));
}
@@ -0,0 +1,65 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
// Needed for rw_output declaration
#extension GL_EXT_shader_image_load_formatted : require
#define FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_X 0
#define FFX_FRAMEINTERPOLATION_BIND_SRV_GAME_MOTION_VECTOR_FIELD_Y 1
#define FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X 2
#define FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y 3
#define FFX_FRAMEINTERPOLATION_BIND_SRV_PREVIOUS_INTERPOLATION_SOURCE 4
#define FFX_FRAMEINTERPOLATION_BIND_SRV_CURRENT_INTERPOLATION_SOURCE 5
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DISOCCLUSION_MASK 6
#define FFX_FRAMEINTERPOLATION_BIND_SRV_INPAINTING_PYRAMID 7
#define FFX_FRAMEINTERPOLATION_BIND_SRV_COUNTERS 8
#define FFX_FRAMEINTERPOLATION_BIND_UAV_OUTPUT 9
#define FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION 10
#include "frameinterpolation/ffx_frameinterpolation_callbacks_glsl.h"
#include "frameinterpolation/ffx_frameinterpolation_common.h"
#include "frameinterpolation/ffx_frameinterpolation.h"
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
#define FFX_FRAMEINTERPOLATION_NUM_THREADS layout (local_size_x = FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH, local_size_y = FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT, local_size_z = FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
FFX_FRAMEINTERPOLATION_NUM_THREADS
void main()
{
computeFrameinterpolation(ivec2(gl_GlobalInvocationID.xy));
}
@@ -0,0 +1,58 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_FRAMEINTERPOLATION_BIND_SRV_INPUT_MOTION_VECTORS 0
#define FFX_FRAMEINTERPOLATION_BIND_SRV_INPUT_DEPTH 1
#define FFX_FRAMEINTERPOLATION_BIND_UAV_RECONSTRUCTED_DEPTH_PREVIOUS_FRAME 2
#define FFX_FRAMEINTERPOLATION_BIND_UAV_DILATED_MOTION_VECTORS 3
#define FFX_FRAMEINTERPOLATION_BIND_UAV_DILATED_DEPTH 4
#define FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION 5
#include "frameinterpolation/ffx_frameinterpolation_callbacks_glsl.h"
#include "frameinterpolation/ffx_frameinterpolation_common.h"
#include "frameinterpolation/ffx_frameinterpolation_reconstruct_dilated_velocity_and_previous_depth.h"
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH 8
#endif // #ifndef FFX_FSR3UPSCALER_THREAD_GROUP_WIDTH
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT 8
#endif // #ifndef FFX_FSR3UPSCALER_THREAD_GROUP_HEIGHT
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_FSR3UPSCALER_THREAD_GROUP_DEPTH
#ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
#define FFX_FRAMEINTERPOLATION_NUM_THREADS layout (local_size_x = FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH, local_size_y = FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT, local_size_z = FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_FSR3UPSCALER_NUM_THREADS
FFX_FRAMEINTERPOLATION_NUM_THREADS
void main()
{
ReconstructAndDilate(FfxInt32x2(gl_GlobalInvocationID.xy));
}
@@ -0,0 +1,58 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_MOTION_VECTORS 0
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DILATED_DEPTH 1
#define FFX_FRAMEINTERPOLATION_BIND_SRV_CURRENT_INTERPOLATION_SOURCE 2
#define FFX_FRAMEINTERPOLATION_BIND_SRV_DISTORTION_FIELD 3
#define FFX_FRAMEINTERPOLATION_BIND_UAV_RECONSTRUCTED_DEPTH_INTERPOLATED_FRAME 4
#define FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION 5
#include "frameinterpolation/ffx_frameinterpolation_callbacks_glsl.h"
#include "frameinterpolation/ffx_frameinterpolation_common.h"
#include "frameinterpolation/ffx_frameinterpolation_reconstruct_previous_depth.h"
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
#define FFX_FRAMEINTERPOLATION_NUM_THREADS layout (local_size_x = FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH, local_size_y = FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT, local_size_z = FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
FFX_FRAMEINTERPOLATION_NUM_THREADS
void main()
{
reconstructPreviousDepth(FfxInt32x2(gl_GlobalInvocationID.xy));
}
@@ -0,0 +1,60 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_FRAMEINTERPOLATION_BIND_SRV_OPTICAL_FLOW_SCENE_CHANGE_DETECTION 0
#define FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_X 1
#define FFX_FRAMEINTERPOLATION_BIND_UAV_GAME_MOTION_VECTOR_FIELD_Y 2
#define FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_X 3
#define FFX_FRAMEINTERPOLATION_BIND_UAV_OPTICAL_FLOW_MOTION_VECTOR_FIELD_Y 4
#define FFX_FRAMEINTERPOLATION_BIND_UAV_DISOCCLUSION_MASK 5
#define FFX_FRAMEINTERPOLATION_BIND_UAV_COUNTERS 6
#define FFX_FRAMEINTERPOLATION_BIND_CB_FRAMEINTERPOLATION 7
#include "frameinterpolation/ffx_frameinterpolation_callbacks_glsl.h"
#include "frameinterpolation/ffx_frameinterpolation_common.h"
#include "frameinterpolation/ffx_frameinterpolation_setup.h"
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT 8
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT
#ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#define FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH
#ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
#define FFX_FRAMEINTERPOLATION_NUM_THREADS layout (local_size_x = FFX_FRAMEINTERPOLATION_THREAD_GROUP_WIDTH, local_size_y = FFX_FRAMEINTERPOLATION_THREAD_GROUP_HEIGHT, local_size_z = FFX_FRAMEINTERPOLATION_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_FRAMEINTERPOLATION_NUM_THREADS
FFX_FRAMEINTERPOLATION_NUM_THREADS
void main()
{
setupFrameinterpolationResources(FfxInt32x2(gl_GlobalInvocationID.xy));
}
@@ -0,0 +1,60 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT 0
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_1 1
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_2 2
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_3 3
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_4 4
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_5 5
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT_LEVEL_6 6
#define FFX_OPTICALFLOW_BIND_CB_COMMON 7
#define FFX_OPTICALFLOW_BIND_CB_SPD 8
#include "opticalflow/ffx_opticalflow_callbacks_glsl.h"
#include "opticalflow/ffx_opticalflow_common.h"
#include "opticalflow/ffx_opticalflow_compute_luminance_pyramid.h"
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#define FFX_OPTICALFLOW_THREAD_GROUP_WIDTH 256
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#define FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT 1
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#define FFX_OPTICALFLOW_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#ifndef FFX_OPTICALFLOW_NUM_THREADS
#define FFX_OPTICALFLOW_NUM_THREADS layout (local_size_x = FFX_OPTICALFLOW_THREAD_GROUP_WIDTH, local_size_y = FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT, local_size_z = FFX_OPTICALFLOW_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_OPTICALFLOW_NUM_THREADS
FFX_OPTICALFLOW_NUM_THREADS
void main()
{
ComputeOpticalFlowInputPyramid(FfxInt32x2(gl_WorkGroupID.xy), FfxInt32(gl_LocalInvocationIndex));
}
@@ -0,0 +1,66 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_WAVE 1
#extension GL_KHR_shader_subgroup_basic : require
#define FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_INPUT 0
#define FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS_INPUT 1
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW 2
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT 3
#define FFX_OPTICALFLOW_BIND_CB_COMMON 4
#include "opticalflow/ffx_opticalflow_callbacks_glsl.h"
#include "opticalflow/ffx_opticalflow_common.h"
#ifndef FFX_OPTICALFLOW_BLOCK_SIZE
#define FFX_OPTICALFLOW_BLOCK_SIZE 8
#endif // #ifndef FFX_OPTICALFLOW_BLOCK_SIZE
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#define FFX_OPTICALFLOW_THREAD_GROUP_WIDTH 64
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#define FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT 1
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#define FFX_OPTICALFLOW_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#include "opticalflow/ffx_opticalflow_compute_optical_flow_v5.h"
#ifndef FFX_OPTICALFLOW_NUM_THREADS
#define FFX_OPTICALFLOW_NUM_THREADS layout (local_size_x = FFX_OPTICALFLOW_THREAD_GROUP_WIDTH, local_size_y = FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT, local_size_z = FFX_OPTICALFLOW_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_OPTICALFLOW_NUM_THREADS
FFX_OPTICALFLOW_NUM_THREADS
void main()
{
ComputeOpticalFlowAdvanced(FfxInt32x2(gl_GlobalInvocationID.xy), FfxInt32x2(gl_LocalInvocationID.xy), FfxInt32x2(gl_WorkGroupID.xy), FfxInt32(gl_LocalInvocationIndex));
}
@@ -0,0 +1,57 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM 0
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM 1
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_TEMP 2
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT 3
#define FFX_OPTICALFLOW_BIND_CB_COMMON 4
#include "opticalflow/ffx_opticalflow_callbacks_glsl.h"
#include "opticalflow/ffx_opticalflow_common.h"
#include "opticalflow/ffx_opticalflow_compute_scd_divergence.h"
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#define FFX_OPTICALFLOW_THREAD_GROUP_WIDTH 256
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#define FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT 1
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#define FFX_OPTICALFLOW_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#ifndef FFX_OPTICALFLOW_NUM_THREADS
#define FFX_OPTICALFLOW_NUM_THREADS layout (local_size_x = FFX_OPTICALFLOW_THREAD_GROUP_WIDTH, local_size_y = FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT, local_size_z = FFX_OPTICALFLOW_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_OPTICALFLOW_NUM_THREADS
FFX_OPTICALFLOW_NUM_THREADS
void main()
{
FfxInt32x2 iGroupSize = FfxInt32x2(FFX_OPTICALFLOW_THREAD_GROUP_WIDTH, FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT);
ComputeSCDHistogramsDivergence(FfxInt32x3(gl_GlobalInvocationID.xyz), FfxInt32x2(gl_LocalInvocationID.xy), FfxInt32(gl_LocalInvocationIndex), FfxInt32x2(gl_WorkGroupID.xy), iGroupSize);
}
@@ -0,0 +1,57 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS 0
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW 1
#define FFX_OPTICALFLOW_BIND_CB_COMMON 2
#include "opticalflow/ffx_opticalflow_callbacks_glsl.h"
#include "opticalflow/ffx_opticalflow_common.h"
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#define FFX_OPTICALFLOW_THREAD_GROUP_WIDTH 16
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#define FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT 4
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#define FFX_OPTICALFLOW_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#include "opticalflow/ffx_opticalflow_filter_optical_flow_v5.h"
#ifndef FFX_OPTICALFLOW_NUM_THREADS
#define FFX_OPTICALFLOW_NUM_THREADS layout (local_size_x = FFX_OPTICALFLOW_THREAD_GROUP_WIDTH, local_size_y = FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT, local_size_z = FFX_OPTICALFLOW_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_OPTICALFLOW_NUM_THREADS
FFX_OPTICALFLOW_NUM_THREADS
void main()
{
FilterOpticalFlow(FfxInt32x2(gl_GlobalInvocationID.xy), FfxInt32x2(gl_LocalInvocationID.xy), FfxInt32x2(gl_WorkGroupID.xy), FfxInt32(gl_LocalInvocationIndex));
}
@@ -0,0 +1,55 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_INPUT 0
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_HISTOGRAM 1
#define FFX_OPTICALFLOW_BIND_CB_COMMON 2
#include "opticalflow/ffx_opticalflow_callbacks_glsl.h"
#include "opticalflow/ffx_opticalflow_common.h"
#include "opticalflow/ffx_opticalflow_generate_scd_histogram.h"
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#define FFX_OPTICALFLOW_THREAD_GROUP_WIDTH 32
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#define FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT 8
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#define FFX_OPTICALFLOW_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#ifndef FFX_OPTICALFLOW_NUM_THREADS
#define FFX_OPTICALFLOW_NUM_THREADS layout (local_size_x = FFX_OPTICALFLOW_THREAD_GROUP_WIDTH, local_size_y = FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT, local_size_z = FFX_OPTICALFLOW_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_OPTICALFLOW_NUM_THREADS
FFX_OPTICALFLOW_NUM_THREADS
void main()
{
FfxInt32x2 iGroupSize = FfxInt32x2(FFX_OPTICALFLOW_THREAD_GROUP_WIDTH, FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT);
GenerateSceneChangeDetectionHistogram(FfxInt32x3(gl_GlobalInvocationID.xyz), FfxInt32x2(gl_LocalInvocationID.xy), FfxInt32(gl_LocalInvocationIndex), FfxInt32x2(gl_WorkGroupID.xy), iGroupSize);
}
@@ -0,0 +1,55 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_OPTICALFLOW_BIND_SRV_INPUT_COLOR 0
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_INPUT 1
#define FFX_OPTICALFLOW_BIND_CB_COMMON 2
#include "opticalflow/ffx_opticalflow_callbacks_glsl.h"
#include "opticalflow/ffx_opticalflow_common.h"
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#define FFX_OPTICALFLOW_THREAD_GROUP_WIDTH 16
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#define FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT 16
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#define FFX_OPTICALFLOW_THREAD_GROUP_DEPTH 1
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#ifndef FFX_OPTICALFLOW_NUM_THREADS
#define FFX_OPTICALFLOW_NUM_THREADS layout (local_size_x = FFX_OPTICALFLOW_THREAD_GROUP_WIDTH, local_size_y = FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT, local_size_z = FFX_OPTICALFLOW_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_OPTICALFLOW_NUM_THREADS
#include "opticalflow/ffx_opticalflow_prepare_luma.h"
FFX_OPTICALFLOW_NUM_THREADS
void main()
{
PrepareLuma(FfxInt32x2(gl_GlobalInvocationID.xy), FfxInt32(gl_LocalInvocationIndex));
}
@@ -0,0 +1,66 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#version 450
#extension GL_GOOGLE_include_directive : require
#extension GL_EXT_samplerless_texture_functions : require
#define FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_INPUT 0
#define FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW_PREVIOUS_INPUT 1
#define FFX_OPTICALFLOW_BIND_SRV_OPTICAL_FLOW 2
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_NEXT_LEVEL 3
#define FFX_OPTICALFLOW_BIND_UAV_OPTICAL_FLOW_SCD_OUTPUT 4
#define FFX_OPTICALFLOW_BIND_CB_COMMON 5
#include "opticalflow/ffx_opticalflow_callbacks_glsl.h"
#include "opticalflow/ffx_opticalflow_common.h"
#ifndef FFX_OPTICALFLOW_BLOCK_SIZE
#define FFX_OPTICALFLOW_BLOCK_SIZE 8
#endif // #ifndef FFX_OPTICALFLOW_BLOCK_SIZE
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#define FFX_OPTICALFLOW_THREAD_GROUP_WIDTH 4
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_WIDTH
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#define FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT 4
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT
#ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#define FFX_OPTICALFLOW_THREAD_GROUP_DEPTH 4
#endif // #ifndef FFX_OPTICALFLOW_THREAD_GROUP_DEPTH
#include "opticalflow/ffx_opticalflow_scale_optical_flow_advanced_v5.h"
#ifndef FFX_OPTICALFLOW_NUM_THREADS
#define FFX_OPTICALFLOW_NUM_THREADS layout (local_size_x = FFX_OPTICALFLOW_THREAD_GROUP_WIDTH, local_size_y = FFX_OPTICALFLOW_THREAD_GROUP_HEIGHT, local_size_z = FFX_OPTICALFLOW_THREAD_GROUP_DEPTH) in;
#endif // #ifndef FFX_OPTICALFLOW_NUM_THREADS
FFX_OPTICALFLOW_NUM_THREADS
void main()
{
ScaleOpticalFlowAdvanced(FfxInt32x3(gl_GlobalInvocationID.xyz), FfxInt32x3(gl_LocalInvocationID.xyz));
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,147 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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 <FidelityFX/gpu/frameinterpolation/ffx_frameinterpolation_resources.h>
/// An enumeration of all the permutations that can be passed to the FSR3 algorithm.
///
/// FSR3 features are organized through a set of pre-defined compile
/// permutation options that need to be specified. Which shader blob
/// is returned for pipeline creation will be determined by what combination
/// of shader permutations are enabled.
///
/// @ingroup FRAMEINTERPOLATION
typedef enum FrameInterpolationShaderPermutationOptions
{
FRAMEINTERPOLATION_SHADER_PERMUTATION_LOW_RES_MOTION_VECTORS = (1 << 0),
FRAMEINTERPOLATION_SHADER_PERMUTATION_JITTER_MOTION_VECTORS = (1 << 1),
FRAMEINTERPOLATION_SHADER_PERMUTATION_DEPTH_INVERTED = (1 << 2), ///< Indicates input resources were generated with inverted depth
FRAMEINTERPOLATION_SHADER_PERMUTATION_FORCE_WAVE64 = (1 << 3), ///< doesn't map to a define, selects different table
FRAMEINTERPOLATION_SHADER_PERMUTATION_ALLOW_FP16 = (1 << 4), ///< Enables fast math computations where possible
} FrameInterpolationShaderPermutationOptions;
typedef struct FrameInterpolationConstants
{
int32_t renderSize[2];
int32_t displaySize[2];
float displaySizeRcp[2];
float cameraNear;
float cameraFar;
int32_t upscalerTargetSize[2]; // how is that different from display size?
int Mode;
int Reset;
float deviceToViewDepth[4];
float deltaTime;
int HUDLessAttachedFactor;
int32_t distortionFieldSize[2];
float opticalFlowScale[2];
int32_t opticalFlowBlockSize;
uint32_t dispatchFlags;
int32_t maxRenderSize[2];
int opticalFlowHalfResMode;
int numInstances;
int32_t interpolationRectBase[2];
int32_t interpolationRectSize[2];
float debugBarColor[3];
uint32_t backBufferTransferFunction;
float minMaxLuminance[2];
float fTanHalfFOV;
float _pad1;
float jitter[2];
float motionVectorScale[2];
} FrameInterpolationConstants;
typedef struct InpaintingPyramidConstants {
uint32_t mips;
uint32_t numworkGroups;
uint32_t workGroupOffset[2];
} InpaintingPyramidConstants;
struct FfxDeviceCapabilities;
struct FfxPipelineState;
struct FfxResource;
typedef struct FfxFrameInterpolationRenderDescription
{
FfxDimensions2D renderSize;
FfxDimensions2D upscaleSize;
float cameraNear;
float cameraFar;
float cameraFovAngleVertical;
float viewSpaceToMetersFactor;
FfxFloatCoords2D motionVectorScale; ///< The scale factor to apply to motion vectors.
} FfxFrameInterpolationRenderDescription;
// FfxFsr3Context_Private
// The private implementation of the FSR3 context.
typedef struct FfxFrameInterpolationContext_Private {
FfxFrameInterpolationContextDescription contextDescription;
FfxUInt32 effectContextId;
FfxFrameInterpolationRenderDescription renderDescription;
FrameInterpolationConstants constants;
InpaintingPyramidConstants inpaintingPyramidContants;
FfxDevice device;
FfxDeviceCapabilities deviceCapabilities;
// FrameInterpolation Pipelines
FfxPipelineState pipelineFiReconstructAndDilate;
FfxPipelineState pipelineFiSetup;
FfxPipelineState pipelineFiReconstructPreviousDepth;
FfxPipelineState pipelineFiGameMotionVectorField;
FfxPipelineState pipelineFiOpticalFlowVectorField;
FfxPipelineState pipelineFiDisocclusionMask;
FfxPipelineState pipelineFiScfi;
FfxPipelineState pipelineInpaintingPyramid;
FfxPipelineState pipelineInpainting;
FfxPipelineState pipelineGameVectorFieldInpaintingPyramid;
FfxPipelineState pipelineDebugView;
FfxConstantBuffer constantBuffers[FFX_FRAMEINTERPOLATION_CONSTANTBUFFER_COUNT];
// 2 arrays of resources, as e.g. FFX_FSR3_RESOURCE_IDENTIFIER_LOCK_STATUS will use different resources when bound as SRV vs when bound as UAV
FfxResourceInternal srvResources[FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_COUNT];
FfxResourceInternal uavResources[FFX_FRAMEINTERPOLATION_RESOURCE_IDENTIFIER_COUNT];
bool firstExecution;
bool refreshPipelineStates;
bool asyncSupported;
uint64_t previousFrameID;
uint64_t dispatchCount;
} FfxFrameInterpolationContext_Private;
@@ -0,0 +1,987 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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.
#include <algorithm> // for max used inside SPD CPU code.
#include <cmath> // for fabs, abs, sinf, sqrt, etc.
#include <string> // for memset
#include <cfloat> // for FLT_EPSILON
#include "FidelityFX/host/ffx_opticalflow.h"
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wsign-compare"
#endif
#define FFX_CPU
#include <FidelityFX/gpu/ffx_core.h>
#include <FidelityFX/gpu/spd/ffx_spd.h>
#include <FidelityFX/gpu/opticalflow/ffx_opticalflow_callbacks_hlsl.h>
#include <ffx_object_management.h>
#define FFX_OPTICALFLOW_MAX_QUEUED_FRAMES 16
#include "ffx_opticalflow_private.h"
typedef struct Binding
{
uint32_t index;
wchar_t name[64];
}Binding;
static const Binding srvBindingNames[] =
{
{FFX_OF_BINDING_IDENTIFIER_INPUT_COLOR, L"r_input_color"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT, L"r_optical_flow_input"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_PREVIOUS_INPUT, L"r_optical_flow_previous_input"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW, L"r_optical_flow"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_PREVIOUS, L"r_optical_flow_previous"},
};
static const Binding uavBindingNames[] =
{
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT, L"rw_optical_flow_input"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_1, L"rw_optical_flow_input_level_1"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_2, L"rw_optical_flow_input_level_2"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_3, L"rw_optical_flow_input_level_3"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_4, L"rw_optical_flow_input_level_4"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_5, L"rw_optical_flow_input_level_5"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_6, L"rw_optical_flow_input_level_6"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW, L"rw_optical_flow"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_NEXT_LEVEL, L"rw_optical_flow_next_level"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_HISTOGRAM, L"rw_optical_flow_scd_histogram"}, // scene change detection histogram
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM, L"rw_optical_flow_scd_previous_histogram"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_TEMP, L"rw_optical_flow_scd_temp"},
{FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_OUTPUT, L"rw_optical_flow_scd_output"},
};
static const Binding cbBindingNames[] =
{
{FFX_OPTICALFLOW_CONSTANTBUFFER_IDENTIFIER, L"cbOF"},
{FFX_OPTICALFLOW_CONSTANTBUFFER_IDENTIFIER_SPD, L"cbOF_SPD"}
};
// Broad structure of the root signature.
typedef enum OpticalFlowRootSignatureLayout {
OPTICALFLOW_ROOT_SIGNATURE_LAYOUT_UAVS,
OPTICALFLOW_ROOT_SIGNATURE_LAYOUT_SRVS,
OPTICALFLOW_ROOT_SIGNATURE_LAYOUT_CONSTANTS,
OPTICALFLOW_ROOT_SIGNATURE_LAYOUT_CONSTANTS_REGISTER_1,
OPTICALFLOW_ROOT_SIGNATURE_LAYOUT_PARAMETER_COUNT
} OpticalFlowRootSignatureLayout;
typedef struct OpticalFlowSpdConstants
{
uint32_t mips;
uint32_t numworkGroups;
uint32_t workGroupOffset[2];
uint32_t numworkGroupsOpticalFlowInputPyramid;
uint32_t pad0_;
uint32_t pad1_;
uint32_t pad2_;
} OpticalFlowSpdConstants;
static FfxErrorCode patchResourceBindings(FfxPipelineState* inoutPipeline)
{
for (uint32_t srvIndex = 0; srvIndex < inoutPipeline->srvTextureCount; ++srvIndex)
{
int32_t mapIndex = 0;
for (mapIndex = 0; mapIndex < _countof(srvBindingNames); ++mapIndex)
{
if (0 == wcscmp(srvBindingNames[mapIndex].name, inoutPipeline->srvTextureBindings[srvIndex].name))
break;
}
FFX_ASSERT(mapIndex < _countof(srvBindingNames));
if (mapIndex == _countof(srvBindingNames))
return FFX_ERROR_INVALID_ARGUMENT;
inoutPipeline->srvTextureBindings[srvIndex].resourceIdentifier = srvBindingNames[mapIndex].index;
}
for (uint32_t uavIndex = 0; uavIndex < inoutPipeline->uavTextureCount; ++uavIndex)
{
int32_t mapIndex = 0;
for (mapIndex = 0; mapIndex < _countof(uavBindingNames); ++mapIndex)
{
if (0 == wcscmp(uavBindingNames[mapIndex].name, inoutPipeline->uavTextureBindings[uavIndex].name))
break;
}
FFX_ASSERT(mapIndex < _countof(uavBindingNames));
if (mapIndex == _countof(uavBindingNames))
return FFX_ERROR_INVALID_ARGUMENT;
inoutPipeline->uavTextureBindings[uavIndex].resourceIdentifier = uavBindingNames[mapIndex].index;
}
for (uint32_t cbIndex = 0; cbIndex < inoutPipeline->constCount; ++cbIndex)
{
int32_t mapIndex = 0;
for (mapIndex = 0; mapIndex < _countof(cbBindingNames); ++mapIndex)
{
if (0 == wcscmp(cbBindingNames[mapIndex].name, inoutPipeline->constantBufferBindings[cbIndex].name))
break;
}
FFX_ASSERT(mapIndex < _countof(cbBindingNames));
if (mapIndex == _countof(cbBindingNames))
return FFX_ERROR_INVALID_ARGUMENT;
inoutPipeline->constantBufferBindings[cbIndex].resourceIdentifier = cbBindingNames[mapIndex].index;
}
return FFX_OK;
}
static uint32_t getPipelinePermutationFlags(uint32_t, FfxPass, bool fp16, bool force64, bool)
{
uint32_t flags = 0;
flags |= (force64) ? OPTICALFLOW_SHADER_PERMUTATION_FORCE_WAVE64 : 0;
flags |= (fp16) ? OPTICALFLOW_SHADER_PERMUTATION_ALLOW_FP16 : 0;
return flags;
}
static FfxErrorCode createPipelineStates(FfxOpticalflowContext_Private* context)
{
FFX_ASSERT(context);
constexpr size_t samplerCount = 2;
FfxSamplerDescription samplerDescs[samplerCount] = {
{FFX_FILTER_TYPE_MINMAGMIP_POINT, FFX_ADDRESS_MODE_CLAMP, FFX_ADDRESS_MODE_CLAMP, FFX_ADDRESS_MODE_CLAMP, FFX_BIND_COMPUTE_SHADER_STAGE},
{FFX_FILTER_TYPE_MINMAGMIP_LINEAR, FFX_ADDRESS_MODE_CLAMP, FFX_ADDRESS_MODE_CLAMP, FFX_ADDRESS_MODE_CLAMP, FFX_BIND_COMPUTE_SHADER_STAGE} };
const size_t rootConstantCount = 2;
FfxRootConstantDescription rootConstantDescs[2] = { {sizeof(OpticalflowConstants) / sizeof(uint32_t), FFX_BIND_COMPUTE_SHADER_STAGE},
{sizeof(OpticalFlowSpdConstants) / sizeof(uint32_t), FFX_BIND_COMPUTE_SHADER_STAGE} };
FfxPipelineDescription pipelineDescription = {};
pipelineDescription.stage = FFX_BIND_COMPUTE_SHADER_STAGE;
pipelineDescription.contextFlags = context->contextDescription.flags;
pipelineDescription.samplerCount = samplerCount;
pipelineDescription.samplers = samplerDescs;
pipelineDescription.rootConstantBufferCount = rootConstantCount;
pipelineDescription.rootConstants = rootConstantDescs;
FfxDeviceCapabilities capabilities;
context->contextDescription.backendInterface.fpGetDeviceCapabilities(&context->contextDescription.backendInterface, &capabilities);
bool haveShaderModel66 = capabilities.maximumSupportedShaderModel >= FFX_SHADER_MODEL_6_6;
bool supportedFP16 = capabilities.fp16Supported;
bool canForceWave64 = false;
bool useLut = false;
const uint32_t waveLaneCountMin = capabilities.waveLaneCountMin;
const uint32_t waveLaneCountMax = capabilities.waveLaneCountMax;
if (waveLaneCountMin == 32 && waveLaneCountMax == 64)
{
useLut = true;
canForceWave64 = haveShaderModel66;
}
else
canForceWave64 = false;
uint32_t contextFlags = context->contextDescription.flags;
auto CreateComputePipeline = [&](FfxPass pass, const wchar_t* name, FfxPipelineState* pipeline) -> FfxErrorCode {
ffxSafeReleasePipeline(&context->contextDescription.backendInterface, pipeline, context->effectContextId);
wcscpy_s(pipelineDescription.name, name);
FFX_VALIDATE(context->contextDescription.backendInterface.fpCreatePipeline(
&context->contextDescription.backendInterface,
FFX_EFFECT_OPTICALFLOW,
pass,
getPipelinePermutationFlags(contextFlags, pass, supportedFP16, canForceWave64, useLut),
&pipelineDescription,
context->effectContextId,
pipeline));
patchResourceBindings(pipeline);
return FFX_OK;
};
CreateComputePipeline(FFX_OPTICALFLOW_PASS_GENERATE_OPTICAL_FLOW_INPUT_PYRAMID, L"Opticalflow_InputPyramid", & context->pipelineGenerateOpticalFlowInputPyramid);
pipelineDescription.rootConstantBufferCount = 1;
CreateComputePipeline(FFX_OPTICALFLOW_PASS_PREPARE_LUMA, L"Opticalflow_Luma", &context->pipelinePrepareLuma);
CreateComputePipeline(FFX_OPTICALFLOW_PASS_GENERATE_SCD_HISTOGRAM, L"Opticalflow_SCD_Histogram", &context->pipelineGenerateSCDHistogram);
CreateComputePipeline(FFX_OPTICALFLOW_PASS_COMPUTE_SCD_DIVERGENCE, L"Opticalflow_SCD_Divergence", &context->pipelineComputeSCDDivergence);
CreateComputePipeline(FFX_OPTICALFLOW_PASS_COMPUTE_OPTICAL_FLOW_ADVANCED_V5, L"Opticalflow_Search", &context->pipelineComputeOpticalFlowAdvancedV5);
CreateComputePipeline(FFX_OPTICALFLOW_PASS_FILTER_OPTICAL_FLOW_V5, L"Opticalflow_Filter", &context->pipelineFilterOpticalFlowV5);
CreateComputePipeline(FFX_OPTICALFLOW_PASS_SCALE_OPTICAL_FLOW_ADVANCED_V5, L"Opticalflow_Upscale", &context->pipelineScaleOpticalFlowAdvancedV5);
return FFX_OK;
}
constexpr uint32_t OpticalFlowMaxPyramidLevels = 7;
constexpr uint32_t HistogramBins = 256;
constexpr uint32_t HistogramsPerDim = 3;
constexpr uint32_t HistogramShifts = 3;
static FfxDimensions2D GetOpticalFlowTextureSize(const FfxDimensions2D& displaySize, const uint32_t opticalFlowBlockSize)
{
uint32_t width = (displaySize.width + opticalFlowBlockSize - 1) / opticalFlowBlockSize;
uint32_t height = (displaySize.height + opticalFlowBlockSize - 1) / opticalFlowBlockSize;
return { width, height };
}
static FfxDimensions2D GetOpticalFlowHistogramSize(int level)
{
const uint32_t searchRadius = 8;
uint32_t maxVelocity = searchRadius * (1 << (OpticalFlowMaxPyramidLevels - 1 - level));
uint32_t binsPerDimension = 2 * maxVelocity + 1;
return { binsPerDimension, binsPerDimension };
}
static FfxDimensions2D GetGlobalMotionSearchDispatchSize(int level)
{
const uint32_t threadGroupSizeX = 16;
const uint32_t threadGroupSizeY = 16;
const FfxDimensions2D opticalFlowHistogramSize = GetOpticalFlowHistogramSize(level);
const uint32_t additionalElementsDueToShiftsX = opticalFlowHistogramSize.width / threadGroupSizeX;
const uint32_t additionalElementsDueToShiftsY = opticalFlowHistogramSize.height / threadGroupSizeY;
const uint32_t dispatchX = (opticalFlowHistogramSize.width + additionalElementsDueToShiftsX + threadGroupSizeX - 1) / threadGroupSizeX;
const uint32_t dispatchY = (opticalFlowHistogramSize.height + additionalElementsDueToShiftsY + threadGroupSizeY - 1) / threadGroupSizeY;
return { dispatchX, dispatchY };
}
static uint32_t GetSCDHistogramTextureWidth()
{
return HistogramBins * (HistogramsPerDim * HistogramsPerDim);
}
static FfxErrorCode opticalflowCreate(FfxOpticalflowContext_Private* context, const FfxOpticalflowContextDescription* contextDescription)
{
FFX_ASSERT(context);
FFX_ASSERT(contextDescription);
FfxErrorCode errorCode = FFX_OK;
memset(context, 0, sizeof(FfxOpticalflowContext_Private));
context->device = contextDescription->backendInterface.device;
memcpy(&context->contextDescription, contextDescription, sizeof(FfxOpticalflowContextDescription));
// Check version info - make sure we are linked with the right backend version
FfxVersionNumber version = context->contextDescription.backendInterface.fpGetSDKVersion(&context->contextDescription.backendInterface);
FFX_RETURN_ON_ERROR(version == FFX_SDK_MAKE_VERSION(1, 1, 4), FFX_ERROR_INVALID_VERSION);
errorCode = context->contextDescription.backendInterface.fpCreateBackendContext(&context->contextDescription.backendInterface, FFX_EFFECT_OPTICALFLOW, nullptr, &context->effectContextId);
FFX_RETURN_ON_ERROR(errorCode == FFX_OK, errorCode);
errorCode = context->contextDescription.backendInterface.fpGetDeviceCapabilities(&context->contextDescription.backendInterface, &context->deviceCapabilities);
FFX_RETURN_ON_ERROR(errorCode == FFX_OK, errorCode);
context->firstExecution = true;
context->resourceFrameIndex = 0;
context->constants.inputLumaResolution[0] = context->contextDescription.resolution.width;
context->constants.inputLumaResolution[1] = context->contextDescription.resolution.height;
FfxDimensions2D opticalFlowInputTextureSize = context->contextDescription.resolution;
const FfxResourceType texture1dResourceType = (context->contextDescription.flags & FFX_OPTICALFLOW_ENABLE_TEXTURE1D_USAGE) ? FFX_RESOURCE_TYPE_TEXTURE1D : FFX_RESOURCE_TYPE_TEXTURE2D;
uint32_t minBlockSize = 8;
const FfxDimensions2D opticalFlowTextureSize = GetOpticalFlowTextureSize(contextDescription->resolution, minBlockSize);
const FfxDimensions2D opticalFlowLevel1TextureSize = { FFX_ALIGN_UP(opticalFlowTextureSize.width, 2) / 2, FFX_ALIGN_UP(opticalFlowTextureSize.height, 2) / 2 };
const FfxDimensions2D opticalFlowLevel2TextureSize = { FFX_ALIGN_UP(opticalFlowLevel1TextureSize.width, 2) / 2, FFX_ALIGN_UP(opticalFlowLevel1TextureSize.height, 2) / 2 };
const FfxDimensions2D opticalFlowLevel3TextureSize = { FFX_ALIGN_UP(opticalFlowLevel2TextureSize.width, 2) / 2, FFX_ALIGN_UP(opticalFlowLevel2TextureSize.height, 2) / 2 };
const FfxDimensions2D opticalFlowLevel4TextureSize = { FFX_ALIGN_UP(opticalFlowLevel3TextureSize.width, 2) / 2, FFX_ALIGN_UP(opticalFlowLevel3TextureSize.height, 2) / 2 };
const FfxDimensions2D opticalFlowLevel5TextureSize = { FFX_ALIGN_UP(opticalFlowLevel4TextureSize.width, 2) / 2, FFX_ALIGN_UP(opticalFlowLevel4TextureSize.height, 2) / 2 };
const FfxDimensions2D opticalFlowLevel6TextureSize = { FFX_ALIGN_UP(opticalFlowLevel5TextureSize.width, 2) / 2, FFX_ALIGN_UP(opticalFlowLevel5TextureSize.height, 2) / 2 };
const FfxDimensions2D opticalFlowLevel7TextureSize = { FFX_ALIGN_UP(opticalFlowLevel6TextureSize.width, 2) / 2, FFX_ALIGN_UP(opticalFlowLevel6TextureSize.height, 2) / 2 };
const FfxDimensions2D opticalFlowHistogramTextureSize = GetOpticalFlowHistogramSize(0);
const FfxDimensions2D globalMotionSearchMaxDispatchSize = GetGlobalMotionSearchDispatchSize(0);
const uint32_t globalMotionSearchTextureWidth = 4 + (globalMotionSearchMaxDispatchSize.width * globalMotionSearchMaxDispatchSize.height);
const FfxInternalResourceDescription internalSurfaceDesc[] = {
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1, L"OPTICALFLOW_OpticalFlowInput1", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width, opticalFlowInputTextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_1, L"OPTICALFLOW_OpticalFlowInput1Level1", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 1, opticalFlowInputTextureSize.height >> 1, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_2, L"OPTICALFLOW_OpticalFlowInput1Level2", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 2, opticalFlowInputTextureSize.height >> 2, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_3, L"OPTICALFLOW_OpticalFlowInput1Level3", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 3, opticalFlowInputTextureSize.height >> 3, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_4, L"OPTICALFLOW_OpticalFlowInput1Level4", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 4, opticalFlowInputTextureSize.height >> 4, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_5, L"OPTICALFLOW_OpticalFlowInput1Level5", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 5, opticalFlowInputTextureSize.height >> 5, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_6, L"OPTICALFLOW_OpticalFlowInput1Level6", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 6, opticalFlowInputTextureSize.height >> 6, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2, L"OPTICALFLOW_OpticalFlowInput2", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width, opticalFlowInputTextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_1, L"OPTICALFLOW_OpticalFlowInput2Level1", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 1, opticalFlowInputTextureSize.height >> 1, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_2, L"OPTICALFLOW_OpticalFlowInput2Level2", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 2, opticalFlowInputTextureSize.height >> 2, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_3, L"OPTICALFLOW_OpticalFlowInput2Level3", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 3, opticalFlowInputTextureSize.height >> 3, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_4, L"OPTICALFLOW_OpticalFlowInput2Level4", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 4, opticalFlowInputTextureSize.height >> 4, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_5, L"OPTICALFLOW_OpticalFlowInput2Level5", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 5, opticalFlowInputTextureSize.height >> 5, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_6, L"OPTICALFLOW_OpticalFlowInput2Level6", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R8_UINT, opticalFlowInputTextureSize.width >> 6, opticalFlowInputTextureSize.height >> 6, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1, L"OPTICALFLOW_OpticalFlow1", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowTextureSize.width, opticalFlowTextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_1, L"OPTICALFLOW_OpticalFlow1Level1", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel1TextureSize.width, opticalFlowLevel1TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_2, L"OPTICALFLOW_OpticalFlow1Level2", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel2TextureSize.width, opticalFlowLevel2TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_3, L"OPTICALFLOW_OpticalFlow1Level3", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel3TextureSize.width, opticalFlowLevel3TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_4, L"OPTICALFLOW_OpticalFlow1Level4", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel4TextureSize.width, opticalFlowLevel4TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_5, L"OPTICALFLOW_OpticalFlow1Level5", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel5TextureSize.width, opticalFlowLevel5TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1_LEVEL_6, L"OPTICALFLOW_OpticalFlow1Level6", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel6TextureSize.width, opticalFlowLevel6TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2, L"OPTICALFLOW_OpticalFlow2", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowTextureSize.width, opticalFlowTextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_1, L"OPTICALFLOW_OpticalFlow2Level1", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel1TextureSize.width, opticalFlowLevel1TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_2, L"OPTICALFLOW_OpticalFlow2Level2", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel2TextureSize.width, opticalFlowLevel2TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_3, L"OPTICALFLOW_OpticalFlow2Level3", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel3TextureSize.width, opticalFlowLevel3TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_4, L"OPTICALFLOW_OpticalFlow2Level4", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel4TextureSize.width, opticalFlowLevel4TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_5, L"OPTICALFLOW_OpticalFlow2Level5", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel5TextureSize.width, opticalFlowLevel5TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2_LEVEL_6, L"OPTICALFLOW_OpticalFlow2Level6", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowLevel6TextureSize.width, opticalFlowLevel6TextureSize.height, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_HISTOGRAM, L"OPTICALFLOW_OpticalFlowSCDHistogram", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R32_UINT, GetSCDHistogramTextureWidth(), 1, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM, L"OPTICALFLOW_OpticalFlowSCDPreviousHistogram", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R32_FLOAT, GetSCDHistogramTextureWidth(), 1, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
{ FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_TEMP, L"OPTICALFLOW_OpticalFlowSCDTemp", FFX_RESOURCE_TYPE_TEXTURE2D, FFX_RESOURCE_USAGE_UAV,
FFX_SURFACE_FORMAT_R32_UINT, 3, 1, 1, FFX_RESOURCE_FLAGS_NONE, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} },
};
memset(context->resources, 0, sizeof(context->resources));
for (int32_t currentSurfaceIndex = 0; currentSurfaceIndex < FFX_ARRAY_ELEMENTS(internalSurfaceDesc); ++currentSurfaceIndex) {
const FfxInternalResourceDescription* currentSurfaceDescription = &internalSurfaceDesc[currentSurfaceIndex];
const FfxResourceType resourceType = currentSurfaceDescription->height > 1 ? FFX_RESOURCE_TYPE_TEXTURE2D : texture1dResourceType;
const FfxResourceDescription resourceDescription = {
resourceType, currentSurfaceDescription->format,
currentSurfaceDescription->width, currentSurfaceDescription->height, 1,
currentSurfaceDescription->mipCount, FFX_RESOURCE_FLAGS_NONE, currentSurfaceDescription->usage };
const FfxResourceStates initialState = FFX_RESOURCE_STATE_UNORDERED_ACCESS;
const FfxCreateResourceDescription createResourceDescription = {
FFX_HEAP_TYPE_DEFAULT, resourceDescription, initialState, currentSurfaceDescription->name, currentSurfaceDescription->id, currentSurfaceDescription->initData };
FFX_VALIDATE(context->contextDescription.backendInterface.fpCreateResource(
&context->contextDescription.backendInterface,
&createResourceDescription,
context->effectContextId,
&context->resources[currentSurfaceDescription->id]));
}
memset(context->srvBindings, 0, sizeof(context->srvBindings));
memset(context->uavBindings, 0, sizeof(context->uavBindings));
{
context->refreshPipelineStates = false;
errorCode = createPipelineStates(context);
FFX_RETURN_ON_ERROR(errorCode == FFX_OK, errorCode);
}
return FFX_OK;
}
static FfxErrorCode opticalflowRelease(FfxOpticalflowContext_Private* context)
{
FFX_ASSERT(context);
ffxSafeReleasePipeline(&context->contextDescription.backendInterface, &context->pipelinePrepareLuma, context->effectContextId);
ffxSafeReleasePipeline(&context->contextDescription.backendInterface, &context->pipelineGenerateOpticalFlowInputPyramid, context->effectContextId);
ffxSafeReleasePipeline(&context->contextDescription.backendInterface, &context->pipelineGenerateSCDHistogram, context->effectContextId);
ffxSafeReleasePipeline(&context->contextDescription.backendInterface, &context->pipelineComputeSCDDivergence, context->effectContextId);
ffxSafeReleasePipeline(&context->contextDescription.backendInterface, &context->pipelineComputeOpticalFlowAdvancedV5, context->effectContextId);
ffxSafeReleasePipeline(&context->contextDescription.backendInterface, &context->pipelineFilterOpticalFlowV5, context->effectContextId);
ffxSafeReleasePipeline(&context->contextDescription.backendInterface, &context->pipelineScaleOpticalFlowAdvancedV5, context->effectContextId);
for (int32_t currentResourceIndex = 0; currentResourceIndex < FFX_OF_RESOURCE_IDENTIFIER_COUNT; ++currentResourceIndex) {
ffxSafeReleaseResource(&context->contextDescription.backendInterface, context->resources[currentResourceIndex], context->effectContextId);
}
context->contextDescription.backendInterface.fpDestroyBackendContext(&context->contextDescription.backendInterface, context->effectContextId);
return FFX_OK;
}
static void scheduleDispatch(FfxOpticalflowContext_Private* context, const FfxPipelineState* pipeline, const wchar_t* pipelineName, uint32_t dispatchX, uint32_t dispatchY, uint32_t dispatchZ = 1)
{
FfxComputeJobDescription jobDescriptor = {};
for (uint32_t currentShaderResourceViewIndex = 0; currentShaderResourceViewIndex < pipeline->srvTextureCount; ++currentShaderResourceViewIndex) {
const uint32_t bindingIdentifier = pipeline->srvTextureBindings[currentShaderResourceViewIndex].resourceIdentifier;
const FfxResourceInternal currentResource = context->srvBindings[bindingIdentifier];
jobDescriptor.srvTextures[currentShaderResourceViewIndex].resource = currentResource;
#ifdef FFX_DEBUG
wcscpy_s(jobDescriptor.srvTextures[currentShaderResourceViewIndex].name, pipeline->srvTextureBindings[currentShaderResourceViewIndex].name);
#endif
FFX_ASSERT(bindingIdentifier != FFX_OF_BINDING_IDENTIFIER_NULL);
FFX_ASSERT(bindingIdentifier < FFX_OF_BINDING_IDENTIFIER_COUNT);
}
for (uint32_t currentUnorderedAccessViewIndex = 0; currentUnorderedAccessViewIndex < pipeline->uavTextureCount; ++currentUnorderedAccessViewIndex) {
const uint32_t bindingIdentifier = pipeline->uavTextureBindings[currentUnorderedAccessViewIndex].resourceIdentifier;
const FfxResourceInternal currentResource = context->uavBindings[bindingIdentifier];
jobDescriptor.uavTextures[currentUnorderedAccessViewIndex].resource = currentResource;
jobDescriptor.uavTextures[currentUnorderedAccessViewIndex].mip = 0;
#ifdef FFX_DEBUG
wcscpy_s(jobDescriptor.uavTextures[currentUnorderedAccessViewIndex].name, pipeline->uavTextureBindings[currentUnorderedAccessViewIndex].name);
#endif
FFX_ASSERT(bindingIdentifier != FFX_OF_BINDING_IDENTIFIER_NULL);
FFX_ASSERT(bindingIdentifier < FFX_OF_BINDING_IDENTIFIER_COUNT);
}
jobDescriptor.dimensions[0] = dispatchX;
jobDescriptor.dimensions[1] = dispatchY;
jobDescriptor.dimensions[2] = dispatchZ;
jobDescriptor.pipeline = *pipeline;
for (uint32_t currentRootConstantIndex = 0; currentRootConstantIndex < pipeline->constCount; ++currentRootConstantIndex) {
#ifdef FFX_DEBUG
wcscpy_s(jobDescriptor.cbNames[currentRootConstantIndex], pipeline->constantBufferBindings[currentRootConstantIndex].name);
#endif
jobDescriptor.cbs[currentRootConstantIndex] = context->constantBuffers[pipeline->constantBufferBindings[currentRootConstantIndex].resourceIdentifier];
}
FfxGpuJobDescription dispatchJob = { FFX_GPU_JOB_COMPUTE };
wcscpy_s(dispatchJob.jobLabel, pipelineName);
dispatchJob.computeJobDescriptor = jobDescriptor;
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &dispatchJob);
}
static FfxErrorCode dispatch(FfxOpticalflowContext_Private* context, const FfxOpticalflowDispatchDescription* params)
{
context->contextDescription.backendInterface.fpRegisterResource(
&context->contextDescription.backendInterface,
&params->opticalFlowVector,
context->effectContextId,
&context->uavBindings[FFX_OF_BINDING_IDENTIFIER_SHARED_OPTICAL_FLOW_VECTOR]);
context->contextDescription.backendInterface.fpRegisterResource(
&context->contextDescription.backendInterface,
&params->opticalFlowSCD,
context->effectContextId,
&context->uavBindings[FFX_OF_BINDING_IDENTIFIER_SHARED_OPTICAL_FLOW_SCD_OUTPUT]);
context->contextDescription.backendInterface.fpRegisterResource(
&context->contextDescription.backendInterface,
&params->color,
context->effectContextId,
&context->srvBindings[FFX_OF_BINDING_IDENTIFIER_INPUT_COLOR]);
FfxCommandList commandList = params->commandList;
int advancedAlgorithmIterations = 7;
uint32_t opticalFlowBlockSize = 8;
if (context->refreshPipelineStates) {
context->refreshPipelineStates = false;
const FfxErrorCode errorCode = createPipelineStates(context);
FFX_RETURN_ON_ERROR(errorCode == FFX_OK, errorCode);
}
const FfxResourceDescription resourceDescInputColor = context->contextDescription.backendInterface.fpGetResourceDescription(
&context->contextDescription.backendInterface,
context->srvBindings[FFX_OF_BINDING_IDENTIFIER_INPUT_COLOR]);
FFX_ASSERT(resourceDescInputColor.type == FFX_RESOURCE_TYPE_TEXTURE2D);
context->constants.backbufferTransferFunction = params->backbufferTransferFunction;
context->constants.minMaxLuminance[0] = params->minMaxLuminance.x;
context->constants.minMaxLuminance[1] = params->minMaxLuminance.y;
const bool resetAccumulation = params->reset || context->firstExecution;
context->firstExecution = false;
if (resetAccumulation) {
context->constants.frameIndex = 0;
}
else {
context->constants.frameIndex++;
}
if (resetAccumulation)
{
const float clearValuesToZeroFloat[]{ 0.f, 0.f, 0.f, 0.f };
FfxGpuJobDescription clearJob = { FFX_GPU_JOB_CLEAR_FLOAT };
memcpy(clearJob.clearJobDescriptor.color, clearValuesToZeroFloat, 4 * sizeof(float));
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow SCD Temp");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_TEMP];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
clearJob.clearJobDescriptor.target = context->uavBindings[FFX_OF_BINDING_IDENTIFIER_SHARED_OPTICAL_FLOW_SCD_OUTPUT];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow SCD Histogram");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_HISTOGRAM];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow SCD Previous histogram");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 1");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 1 Level 1");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_1];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 1 Level 2");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_2];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 1 Level 3");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_3];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 1 Level 4");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_4];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 1 Level 5");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_5];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 1 Level 6");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_6];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 2");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 2 Level 1");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_1];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 2 Level 2");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_2];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 2 Level 3");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_3];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 2 Level 4");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_4];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 2 Level 5");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_5];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
wcscpy_s(clearJob.jobLabel, L"Clear Optical Flow Input 2 Level 6");
clearJob.clearJobDescriptor.target = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_6];
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &clearJob);
}
uint32_t resolutionMultiplier = 1;
FfxUInt32x2 threadGroupSizeOpticalFlowInputPyramid;
FfxUInt32x2 workGroupOffset;
FfxUInt32x2 numWorkGroupsAndMips;
FfxUInt32x4 rectInfo = { 0, 0,
context->contextDescription.resolution.width * resolutionMultiplier,
context->contextDescription.resolution.height * resolutionMultiplier };
ffxSpdSetup(threadGroupSizeOpticalFlowInputPyramid, workGroupOffset, numWorkGroupsAndMips, rectInfo, 4);
OpticalFlowSpdConstants luminancePyramidConstants;
luminancePyramidConstants.numworkGroups = numWorkGroupsAndMips[0];
luminancePyramidConstants.mips = numWorkGroupsAndMips[1];
luminancePyramidConstants.workGroupOffset[0] = workGroupOffset[0];
luminancePyramidConstants.workGroupOffset[1] = workGroupOffset[1];
luminancePyramidConstants.numworkGroupsOpticalFlowInputPyramid = numWorkGroupsAndMips[0];
context->contextDescription.backendInterface.fpStageConstantBufferDataFunc(&context->contextDescription.backendInterface, &context->constants, sizeof(context->constants), &context->constantBuffers[FFX_OPTICALFLOW_CONSTANTBUFFER_IDENTIFIER]);
context->contextDescription.backendInterface.fpStageConstantBufferDataFunc(&context->contextDescription.backendInterface, &luminancePyramidConstants, sizeof(luminancePyramidConstants), &context->constantBuffers[FFX_OPTICALFLOW_CONSTANTBUFFER_IDENTIFIER_SPD]);
{
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_HISTOGRAM] = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_HISTOGRAM];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM] = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_TEMP] = context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_SCD_TEMP];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_OUTPUT] = context->uavBindings[FFX_OF_BINDING_IDENTIFIER_SHARED_OPTICAL_FLOW_SCD_OUTPUT];
const bool isOddFrame = !!(context->resourceFrameIndex & 1);
uint32_t opticalFlowInputResourceIndex = isOddFrame ? FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2 : FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1;
uint32_t opticalFlowPreviousInputResourceIndex = isOddFrame ? FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1 : FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2;
uint32_t opticalFlowResourceIndex = isOddFrame ? FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2 : FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1;
uint32_t opticalFlowPreviousResourceIndex = isOddFrame ? FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1 : FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2;
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT] = context->resources[opticalFlowInputResourceIndex];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_1] = context->resources[opticalFlowInputResourceIndex + 1];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_2] = context->resources[opticalFlowInputResourceIndex + 2];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_3] = context->resources[opticalFlowInputResourceIndex + 3];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_4] = context->resources[opticalFlowInputResourceIndex + 4];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_5] = context->resources[opticalFlowInputResourceIndex + 5];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_6] = context->resources[opticalFlowInputResourceIndex + 6];
context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT] = context->resources[opticalFlowInputResourceIndex];
context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_PREVIOUS_INPUT] = context->resources[opticalFlowPreviousInputResourceIndex];
context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW] = context->resources[opticalFlowResourceIndex];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW] = context->resources[opticalFlowResourceIndex];
context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_PREVIOUS] = context->resources[opticalFlowPreviousResourceIndex];
{
int32_t threadGroupSizeX = 16;
int32_t threadGroupSizeY = 16;
uint32_t threadPixelsX = 2;
uint32_t threadPixelsY = 2;
int32_t dispatchX = ((context->contextDescription.resolution.width + (threadPixelsX - 1)) / threadPixelsX + (threadGroupSizeX - 1)) / threadGroupSizeX;
int32_t dispatchY = ((context->contextDescription.resolution.height + (threadPixelsY - 1)) / threadPixelsY + (threadGroupSizeY - 1)) / threadGroupSizeY;
scheduleDispatch(context, &context->pipelinePrepareLuma, L"OF PrepareLuma", dispatchX, dispatchY);
}
{
{
scheduleDispatch(context,
&context->pipelineGenerateOpticalFlowInputPyramid,
L"OF GenerateOpticalFlowInputPyramid",
threadGroupSizeOpticalFlowInputPyramid[0],
threadGroupSizeOpticalFlowInputPyramid[1]
);
}
{
{
const uint32_t threadGroupSizeX = 32;
const uint32_t threadGroupSizeY = 8;
const uint32_t strataWidth = (context->contextDescription.resolution.width / 4) / HistogramsPerDim;
const uint32_t strataHeight = context->contextDescription.resolution.height / HistogramsPerDim;
const uint32_t dispatchX = (strataWidth + threadGroupSizeX - 1) / threadGroupSizeX;
const uint32_t dispatchY = 16;
const uint32_t dispatchZ = HistogramsPerDim * HistogramsPerDim;
scheduleDispatch(context, &context->pipelineGenerateSCDHistogram, L"OF GenerateSCDHistogram", dispatchX, dispatchY, dispatchZ);
}
{
const uint32_t dispatchX = HistogramsPerDim * HistogramsPerDim;
const uint32_t dispatchY = HistogramShifts;
scheduleDispatch(context, &context->pipelineComputeSCDDivergence, L"OF ComputeSCDDivergence", dispatchX, dispatchY);
}
}
FfxDimensions2D opticalFlowTextureSizes[OpticalFlowMaxPyramidLevels];
const int pyramidMaxIterations = advancedAlgorithmIterations;
FFX_ASSERT(pyramidMaxIterations <= OpticalFlowMaxPyramidLevels);
opticalFlowTextureSizes[0] = GetOpticalFlowTextureSize(context->contextDescription.resolution, opticalFlowBlockSize);
for (int i = 1; i < pyramidMaxIterations; i++)
{
opticalFlowTextureSizes[i] = {
(opticalFlowTextureSizes[i - 1].width + 1) / 2,
(opticalFlowTextureSizes[i - 1].height + 1) / 2
};
}
for (int level = pyramidMaxIterations - 1; level >= 0; level--)
{
bool isOddLevel = !!(level & 1);
uint32_t opticalFlowInputResourceIndexA = isOddFrame ? FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2 : FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1;
uint32_t opticalFlowInputResourceIndexB = isOddFrame ? FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1 : FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2;
uint32_t opticalFlowResourceIndexA = (isOddFrame != isOddLevel) ? FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2 : FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1;
uint32_t opticalFlowResourceIndexB = (isOddFrame != isOddLevel) ? FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_1 : FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_2;
context->constants.opticalFlowPyramidLevel = level;
context->constants.opticalFlowPyramidLevelCount = pyramidMaxIterations;
context->contextDescription.backendInterface.fpStageConstantBufferDataFunc(&context->contextDescription.backendInterface, &context->constants, sizeof(context->constants), &context->constantBuffers[FFX_OPTICALFLOW_CONSTANTBUFFER_IDENTIFIER]);
context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT] = context->resources[opticalFlowInputResourceIndexA + level];
context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_PREVIOUS_INPUT] = context->resources[opticalFlowInputResourceIndexB + level];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW] = context->resources[opticalFlowResourceIndexA + level];
context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_PREVIOUS] = context->resources[opticalFlowResourceIndexB + level];
{
const FfxUInt32 inputLumaWidth = ffxMax(context->contextDescription.resolution.width >> level, 1);
const FfxUInt32 inputLumaHeight = ffxMax(context->contextDescription.resolution.height >> level, 1);
std::wstring pipelineName = L"OF " + std::to_wstring(level) + L" Search";
{
uint32_t threadPixels = 4;
FFX_ASSERT(opticalFlowBlockSize >= threadPixels);
uint32_t threadGroupSizeY = 16;
uint32_t threadGroupSize = 64;
uint32_t dispatchX = ((inputLumaWidth + threadPixels - 1) / threadPixels * threadGroupSizeY + (threadGroupSize - 1)) / threadGroupSize;
uint32_t dispatchY = (inputLumaHeight + (threadGroupSizeY - 1)) / threadGroupSizeY;
scheduleDispatch(context, &context->pipelineComputeOpticalFlowAdvancedV5, pipelineName.c_str(), dispatchX, dispatchY);
}
}
{
context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_PREVIOUS] = context->resources[opticalFlowResourceIndexA + level];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW] = context->resources[opticalFlowResourceIndexB + level];
}
{
if (level == 0)
{
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW] = context->uavBindings[FFX_OF_BINDING_IDENTIFIER_SHARED_OPTICAL_FLOW_VECTOR];
}
const uint32_t levelWidth = opticalFlowTextureSizes[level].width;
const uint32_t levelHeight = opticalFlowTextureSizes[level].height;
const uint32_t threadGroupSizeX = 16;
const uint32_t threadGroupSizeY = 4;
const uint32_t dispatchX = (levelWidth + threadGroupSizeX - 1) / threadGroupSizeX;
const uint32_t dispatchY = (levelHeight + threadGroupSizeY - 1) / threadGroupSizeY;
std::wstring pipelineName = L"OF " + std::to_wstring(level) + L" Filter";
{
scheduleDispatch(context, &context->pipelineFilterOpticalFlowV5, pipelineName.c_str(), dispatchX, dispatchY);
}
}
if (level > 0)
{
context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_ALIAS_LEVEL_1 + level - 1] = context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW];
}
if (level > 0)
{
{
context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW] = context->resources[opticalFlowResourceIndexB + level];
context->uavBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_NEXT_LEVEL] = level > 0 ? context->resources[opticalFlowResourceIndexB + level - 1] : FfxResourceInternal{ FFX_OF_RESOURCE_IDENTIFIER_NULL };
}
FFX_ASSERT(opticalFlowBlockSize >= 2);
const uint32_t nextLevelWidth = opticalFlowTextureSizes[level - 1].width;
const uint32_t nextLevelHeight = opticalFlowTextureSizes[level - 1].height;
const uint32_t threadGroupSizeX = opticalFlowBlockSize / 2;
const uint32_t threadGroupSizeY = opticalFlowBlockSize / 2;
const uint32_t threadGroupSizeZ = 4;
const uint32_t dispatchX = (nextLevelWidth + threadGroupSizeX - 1) / threadGroupSizeX;
const uint32_t dispatchY = (nextLevelHeight + threadGroupSizeY - 1) / threadGroupSizeY;
const uint32_t dispatchZ = 1;
std::wstring pipelineName = L"OF " + std::to_wstring(level) + L" Scale";
{
const uint32_t dispatchX = (nextLevelWidth + 3) / 4;
const uint32_t dispatchY = (nextLevelHeight + 3) / 4;
scheduleDispatch(context, &context->pipelineScaleOpticalFlowAdvancedV5, pipelineName.c_str(), dispatchX, dispatchY, dispatchZ);
}
{
FfxGpuJobDescription barrierJob = {FFX_GPU_JOB_BARRIER};
barrierJob.barrierDescriptor = { context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
}
}
{
FfxGpuJobDescription barrierJob = {FFX_GPU_JOB_BARRIER};
barrierJob.barrierDescriptor = { context->srvBindings[FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_PREVIOUS], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
}
}
}
}
{
FfxGpuJobDescription barrierJob = {FFX_GPU_JOB_BARRIER};
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 1");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 1 Level 1");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_1], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 1 Level 2");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_2], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 1 Level 3");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_3], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 1 Level 4");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_4], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 1 Level 5");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_5], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 1 Level 6");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_1_LEVEL_6], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 2");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 2 Level 1");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_1], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 2 Level 2");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_2], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 2 Level 3");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_3], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 2 Level 4");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_4], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 2 Level 5");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_5], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
wcscpy_s(barrierJob.jobLabel, L"Transition Optical Flow Input 2 Level 6");
barrierJob.barrierDescriptor = { context->resources[FFX_OF_RESOURCE_IDENTIFIER_OPTICAL_FLOW_INPUT_2_LEVEL_6], FFX_BARRIER_TYPE_TRANSITION, FFX_RESOURCE_STATE_COMPUTE_READ, FFX_RESOURCE_STATE_UNORDERED_ACCESS, 0};
context->contextDescription.backendInterface.fpScheduleGpuJob(&context->contextDescription.backendInterface, &barrierJob);
}
context->resourceFrameIndex = (context->resourceFrameIndex + 1) % FFX_OPTICALFLOW_MAX_QUEUED_FRAMES;
FFX_VALIDATE(context->contextDescription.backendInterface.fpExecuteGpuJobs(&context->contextDescription.backendInterface, commandList, context->effectContextId));
context->contextDescription.backendInterface.fpUnregisterResources(&context->contextDescription.backendInterface, commandList, context->effectContextId);
return FFX_OK;
}
FfxErrorCode ffxOpticalflowContextCreate(FfxOpticalflowContext* context, FfxOpticalflowContextDescription* contextDescription)
{
FFX_RETURN_ON_ERROR(context, FFX_ERROR_INVALID_POINTER);
FFX_RETURN_ON_ERROR(contextDescription, FFX_ERROR_INVALID_POINTER);
FFX_RETURN_ON_ERROR(contextDescription->backendInterface.fpGetSDKVersion, FFX_ERROR_INCOMPLETE_INTERFACE);
FFX_RETURN_ON_ERROR(contextDescription->backendInterface.fpGetDeviceCapabilities, FFX_ERROR_INCOMPLETE_INTERFACE);
FFX_RETURN_ON_ERROR(contextDescription->backendInterface.fpCreateBackendContext, FFX_ERROR_INCOMPLETE_INTERFACE);
FFX_RETURN_ON_ERROR(contextDescription->backendInterface.fpDestroyBackendContext, FFX_ERROR_INCOMPLETE_INTERFACE);
if (contextDescription->backendInterface.scratchBuffer) {
FFX_RETURN_ON_ERROR(contextDescription->backendInterface.scratchBufferSize, FFX_ERROR_INCOMPLETE_INTERFACE);
}
FFX_STATIC_ASSERT(sizeof(FfxOpticalflowContext) >= sizeof(FfxOpticalflowContext_Private));
FfxOpticalflowContext_Private* contextPrivate = (FfxOpticalflowContext_Private*)(context);
FfxErrorCode errorCode = opticalflowCreate(contextPrivate, contextDescription);
return errorCode;
}
FFX_API FfxErrorCode ffxOpticalflowContextGetGpuMemoryUsage(FfxOpticalflowContext* context, FfxEffectMemoryUsage* vramUsage)
{
FFX_RETURN_ON_ERROR(context, FFX_ERROR_INVALID_POINTER);
FFX_RETURN_ON_ERROR(vramUsage, FFX_ERROR_INVALID_POINTER);
FfxOpticalflowContext_Private* contextPrivate = (FfxOpticalflowContext_Private*)(context);
FFX_RETURN_ON_ERROR(contextPrivate->device, FFX_ERROR_NULL_DEVICE);
FfxErrorCode errorCode = contextPrivate->contextDescription.backendInterface.fpGetEffectGpuMemoryUsage(
&contextPrivate->contextDescription.backendInterface, contextPrivate->effectContextId, vramUsage);
FFX_RETURN_ON_ERROR(errorCode == FFX_OK, errorCode);
return FFX_OK;
}
FfxErrorCode ffxOpticalflowContextDestroy(FfxOpticalflowContext* context)
{
FFX_RETURN_ON_ERROR(context, FFX_ERROR_INVALID_POINTER);
FfxOpticalflowContext_Private* contextPrivate = (FfxOpticalflowContext_Private*)(context);
const FfxErrorCode errorCode = opticalflowRelease(contextPrivate);
return errorCode;
}
FFX_API bool ffxOpticalflowResourceIsNull(FfxResource resource)
{
return resource.resource == NULL;
}
FFX_API FfxErrorCode ffxOpticalflowGetSharedResourceDescriptions(FfxOpticalflowContext* context, FfxOpticalflowSharedResourceDescriptions* SharedResources)
{
FFX_RETURN_ON_ERROR(context, FFX_ERROR_INVALID_POINTER);
FFX_RETURN_ON_ERROR(SharedResources, FFX_ERROR_INVALID_POINTER);
FfxOpticalflowContext_Private* contextPrivate = (FfxOpticalflowContext_Private*)(context);
const FfxDimensions2D opticalFlowTextureSize = GetOpticalFlowTextureSize(contextPrivate->contextDescription.resolution, 8);
const FfxDimensions2D globalMotionSearchMaxDispatchSize = GetGlobalMotionSearchDispatchSize(0);
const uint32_t globalMotionSearchTextureWidth = 4 /* predefined slots */ + (globalMotionSearchMaxDispatchSize.width * globalMotionSearchMaxDispatchSize.height);
SharedResources->opticalFlowVector = {
FFX_HEAP_TYPE_DEFAULT,
{ FFX_RESOURCE_TYPE_TEXTURE2D, FFX_SURFACE_FORMAT_R16G16_SINT, opticalFlowTextureSize.width, opticalFlowTextureSize.height, 1, 1, FFX_RESOURCE_FLAGS_NONE, FFX_RESOURCE_USAGE_UAV },
FFX_RESOURCE_STATE_UNORDERED_ACCESS, L"OPTICALFLOW_Result", 0, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} };
SharedResources->opticalFlowSCD = {
FFX_HEAP_TYPE_DEFAULT,
{ FFX_RESOURCE_TYPE_TEXTURE2D, FFX_SURFACE_FORMAT_R32_UINT, 3, 1, 1, 1, FFX_RESOURCE_FLAGS_NONE, FFX_RESOURCE_USAGE_UAV },
FFX_RESOURCE_STATE_UNORDERED_ACCESS, L"OPTICALFLOW_SCDOutput", 0, {FFX_RESOURCE_INIT_DATA_TYPE_UNINITIALIZED} };
return FFX_OK;
}
FfxErrorCode ffxOpticalflowContextDispatch(FfxOpticalflowContext* context, const FfxOpticalflowDispatchDescription* dispatchParams)
{
FFX_RETURN_ON_ERROR(context, FFX_ERROR_INVALID_POINTER);
FFX_RETURN_ON_ERROR(dispatchParams, FFX_ERROR_INVALID_POINTER);
FFX_RETURN_ON_ERROR(dispatchParams->commandList, FFX_ERROR_INVALID_POINTER);
FFX_RETURN_ON_ERROR(!ffxOpticalflowResourceIsNull(dispatchParams->color), FFX_ERROR_INVALID_POINTER);
FFX_RETURN_ON_ERROR(dispatchParams->color.description.type == FFX_RESOURCE_TYPE_TEXTURE2D, FFX_ERROR_INVALID_ARGUMENT);
FFX_RETURN_ON_ERROR(!ffxOpticalflowResourceIsNull(dispatchParams->opticalFlowVector), FFX_ERROR_INVALID_POINTER);
FFX_RETURN_ON_ERROR(!ffxOpticalflowResourceIsNull(dispatchParams->opticalFlowSCD), FFX_ERROR_INVALID_POINTER);
FfxOpticalflowContext_Private* contextPrivate = (FfxOpticalflowContext_Private*)(context);
FFX_RETURN_ON_ERROR(contextPrivate->device, FFX_ERROR_NULL_DEVICE);
FFX_RETURN_ON_ERROR(dispatchParams->color.description.width <= contextPrivate->contextDescription.resolution.width, FFX_ERROR_INVALID_ARGUMENT);
FFX_RETURN_ON_ERROR(dispatchParams->color.description.height <= contextPrivate->contextDescription.resolution.height, FFX_ERROR_INVALID_ARGUMENT);
const FfxErrorCode errorCode = dispatch(contextPrivate, dispatchParams);
return errorCode;
}
FFX_API FfxVersionNumber ffxOpticalflowGetEffectVersion()
{
return FFX_SDK_MAKE_VERSION(FFX_OPTICALFLOW_VERSION_MAJOR, FFX_OPTICALFLOW_VERSION_MINOR, FFX_OPTICALFLOW_VERSION_PATCH);
}
@@ -0,0 +1,108 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 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
#define FFX_CPU
#include <FidelityFX/gpu/opticalflow/ffx_opticalflow_resources.h>
typedef enum OpticalFlowBindingIdentifiers
{
FFX_OF_BINDING_IDENTIFIER_NULL = 0,
FFX_OF_BINDING_IDENTIFIER_INPUT_COLOR,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_1,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_2,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_3,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_4,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_5,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_INPUT_LEVEL_6,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_PREVIOUS_INPUT,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_HISTOGRAM,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_PREVIOUS_HISTOGRAM,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_TEMP,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_SCD_OUTPUT,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_NEXT_LEVEL,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_PREVIOUS,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_ALIAS_LEVEL_1,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_ALIAS_LEVEL_2,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_ALIAS_LEVEL_3,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_ALIAS_LEVEL_4,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_ALIAS_LEVEL_5,
FFX_OF_BINDING_IDENTIFIER_OPTICAL_FLOW_ALIAS_LEVEL_6,
FFX_OF_BINDING_IDENTIFIER_SHARED_OPTICAL_FLOW_VECTOR,
FFX_OF_BINDING_IDENTIFIER_SHARED_OPTICAL_FLOW_SCD_OUTPUT,
FFX_OF_BINDING_IDENTIFIER_COUNT
} OpticalFlowBindingIdentifiers;
typedef enum OpticalflowShaderPermutationOptions
{
OPTICALFLOW_SHADER_PERMUTATION_FORCE_WAVE64 = (1 << 0), ///< doesn't map to a define, selects different table
OPTICALFLOW_SHADER_PERMUTATION_ALLOW_FP16 = (1 << 1), ///< Enables fast math computations where possible
OPTICALFLOW_HDR_COLOR_INPUT = (1 << 2),
} OpticalflowShaderPermutationOptions;
typedef struct OpticalflowConstants
{
int32_t inputLumaResolution[2];
uint32_t opticalFlowPyramidLevel;
uint32_t opticalFlowPyramidLevelCount;
int32_t frameIndex;
uint32_t backbufferTransferFunction;
float minMaxLuminance[2];
} OpticalflowConstants;
typedef struct FfxOpticalflowContext_Private
{
FfxOpticalflowContextDescription contextDescription;
FfxUInt32 effectContextId;
OpticalflowConstants constants;
FfxDevice device;
FfxDeviceCapabilities deviceCapabilities;
FfxPipelineState pipelinePrepareLuma;
FfxPipelineState pipelineGenerateOpticalFlowInputPyramid;
FfxPipelineState pipelineGenerateSCDHistogram;
FfxPipelineState pipelineComputeSCDDivergence;
FfxPipelineState pipelineComputeOpticalFlowAdvancedV5;
FfxPipelineState pipelineFilterOpticalFlowV5;
FfxPipelineState pipelineScaleOpticalFlowAdvancedV5;
FfxResourceInternal resources[FFX_OF_RESOURCE_IDENTIFIER_COUNT];
FfxResourceInternal srvBindings[FFX_OF_BINDING_IDENTIFIER_COUNT];
FfxResourceInternal uavBindings[FFX_OF_BINDING_IDENTIFIER_COUNT];
FfxConstantBuffer constantBuffers[FFX_OPTICALFLOW_CONSTANTBUFFER_COUNT];
bool firstExecution;
bool refreshPipelineStates;
uint32_t resourceFrameIndex;
} FfxOpticalflowContext_Private;
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more