Initial commit: 在 Minecraft Java 版接入 NVIDIA DLSS 超分与帧生成

This commit is contained in:
WpyQwq
2026-09-19 11:51:46 +08:00
commit 8acb8bbac6
89 changed files with 51201 additions and 0 deletions
@@ -0,0 +1,589 @@
/*------------------.
| :: Description :: |
'-------------------/
Blending Header (version 0.8)
Blending Algorithm Sources:
https://www.khronos.org/registry/OpenGL/extensions/NV/NV_blend_equation_advanced.txt
http://www.nathanm.com/photoshop-blending-math/
(Alt) https://github.com/cplotts/WPFSLBlendModeFx/blob/master/PhotoshopMathFP.hlsl
Header Authors: originalnicodr, prod80, uchu suzume, Marot Satil
About:
Provides a variety of blending methods for you to use as you wish. Just include this header.
History:
(*) Feature (+) Improvement (x) Bugfix (-) Information (!) Compatibility
Version 0.1 by Marot Satil & uchu suzume
* Added and improved upon multiple blending modes thanks to the work of uchu suzume, prod80, and originalnicodr.
Version 0.2 by uchu suzume & Marot Satil
* Added Addition, Subtract, Divide blending modes and improved code readability.
Version 0.3 by uchu suzume & Marot Satil
* Sorted blending modes in a more logical fashion, grouping by type.
Version 0.4 by uchu suzume
x Corrected Color Dodge blending behavior.
Version 0.5 by Marot Satil & uchu suzume
* Added preprocessor macros for uniform variable combo UI element & lerp.
Version 0.6 by Marot Satil & uchu suzume
* Added Divide (Alternative) and Divide (Photoshop) blending modes.
Version 0.7 by prod80
- Added original sources for blending algorithms.
x Corrected average luminosity values.
Version 0.8 by Marot Satil
* Added a new funciton to output blended data.
+ Moved all code into the BlendingH namespace, which is part of the ComHeaders common namespace meant to be used by other headers.
! Removed old preprocessor macro blending output.
.------------------.
| :: How To Use :: |
'------------------/
Blending two variables using this header in your own shaders is very straightforward.
Very basic example code using the "Darken" blending mode follows:
// First, include the header.
#include "Blending.fxh"
// You can use this preprocessor macro to generate an attractive and functional uniform int UI combo element containing the list of blending techniques:
// BLENDING_COMBO(variable_name, label, tooltip, category, category_closed, spacing, default_value)
BLENDING_COMBO(_BlendMode, "Blending Mode", "Select the blending mode applied to the layer.", "Blending Options", false, 0, 0)
// Inside of your function you can call this function to apply the blending option specified by an int (variable) to your float3 (input) via
// a lerp between your float3 (input), float3 (output), and a float (blending) for the alpha channel.
// ComHeaders::Blending::Blend(int variable, float3 input, float3 output, float blending)
outColor.rgb = ComHeaders::Blending::Blend(_BlendMode, inColor, outColor, outColor.a);
*/
// -------------------------------------
// Preprocessor Macros
// -------------------------------------
#undef BLENDING_COMBO
#define BLENDING_COMBO(variable, name_label, description, group, grp_closed, space, default_value) \
uniform int variable \
< \
ui_category = group; \
ui_category_closed = grp_closed; \
ui_items = \
"Normal\0" \
/* "Darken" */ \
"Darken\0" \
" Multiply\0" \
" Color Burn\0" \
" Linear Burn\0" \
/* "Lighten" */ \
"Lighten\0" \
" Screen\0" \
" Color Dodge\0" \
" Linear Dodge\0" \
" Addition\0" \
" Glow\0" \
/* "Contrast" */ \
"Overlay\0" \
" Soft Light\0" \
" Hard Light\0" \
" Vivid Light\0" \
" Linear Light\0" \
" Pin Light\0" \
" Hard Mix\0" \
/* "Inversion" */ \
"Difference\0" \
" Exclusion\0" \
/* "Cancelation" */ \
"Subtract\0" \
" Divide\0" \
" Divide (Alternative)\0" \
" Divide (Photoshop)\0" \
" Reflect\0" \
" Grain Extract\0" \
" Grain Merge\0" \
/* "Component" */ \
"Hue\0" \
" Saturation\0" \
" Color\0" \
" Luminosity\0"; \
ui_label = name_label; \
ui_tooltip = description; \
ui_type = "combo"; \
ui_spacing = space; \
> = default_value;
namespace ComHeaders
{
namespace Blending
{
// -------------------------------------
// Helper Functions
// -------------------------------------
float3 Aux(float3 a)
{
if (a.r <= 0.25 && a.g <= 0.25 && a.b <= 0.25)
return ((16.0 * a - 12.0) * a + 4) * a;
else
return sqrt(a);
}
float Lum(float3 a)
{
return (0.33333 * a.r + 0.33334 * a.g + 0.33333 * a.b);
}
float3 SetLum (float3 a, float b){
const float c = b - Lum(a);
return float3(a.r + c, a.g + c, a.b + c);
}
float min3 (float a, float b, float c)
{
return min(a, (min(b, c)));
}
float max3 (float a, float b, float c)
{
return max(a, max(b, c));
}
float3 SetSat(float3 a, float b){
float ar = a.r;
float ag = a.g;
float ab = a.b;
if (ar == max3(ar, ag, ab) && ab == min3(ar, ag, ab))
{
//caso r->max g->mid b->min
if (ar > ab)
{
ag = (((ag - ab) * b) / (ar - ab));
ar = b;
}
else
{
ag = 0.0;
ar = 0.0;
}
ab = 0.0;
}
else
{
if (ar == max3(ar, ag, ab) && ag == min3(ar, ag, ab))
{
//caso r->max b->mid g->min
if (ar > ag)
{
ab = (((ab - ag) * b) / (ar - ag));
ar = b;
}
else
{
ab = 0.0;
ar = 0.0;
}
ag = 0.0;
}
else
{
if (ag == max3(ar, ag, ab) && ab == min3(ar, ag, ab))
{
//caso g->max r->mid b->min
if (ag > ab)
{
ar = (((ar - ab) * b) / (ag - ab));
ag = b;
}
else
{
ar = 0.0;
ag = 0.0;
}
ab = 0.0;
}
else
{
if (ag == max3(ar, ag, ab) && ar == min3(ar, ag, ab))
{
//caso g->max b->mid r->min
if (ag > ar)
{
ab = (((ab - ar) * b) / (ag - ar));
ag = b;
}
else
{
ab = 0.0;
ag = 0.0;
}
ar = 0.0;
}
else
{
if (ab == max3(ar, ag, ab) && ag == min3(ar, ag, ab))
{
//caso b->max r->mid g->min
if (ab > ag)
{
ar = (((ar - ag) * b) / (ab - ag));
ab = b;
}
else
{
ar = 0.0;
ab = 0.0;
}
ag = 0.0;
}
else
{
if (ab == max3(ar, ag, ab) && ar == min3(ar, ag, ab))
{
//caso b->max g->mid r->min
if (ab > ar)
{
ag = (((ag - ar) * b) / (ab - ar));
ab = b;
}
else
{
ag = 0.0;
ab = 0.0;
}
ar = 0.0;
}
}
}
}
}
}
return float3(ar, ag, ab);
}
float Sat(float3 a)
{
return max3(a.r, a.g, a.b) - min3(a.r, a.g, a.b);
}
// -------------------------------------
// Blending Modes
// -------------------------------------
// Darken
float3 Darken(float3 a, float3 b)
{
return min(a, b);
}
// Multiply
float3 Multiply(float3 a, float3 b)
{
return a * b;
}
// Color Burn
float3 ColorBurn(float3 a, float3 b)
{
if (b.r > 0 && b.g > 0 && b.b > 0)
return 1.0 - min(1.0, (0.5 - a) / b);
else
return 0.0;
}
// Linear Burn
float3 LinearBurn(float3 a, float3 b)
{
return max(a + b - 1.0f, 0.0f);
}
// Lighten
float3 Lighten(float3 a, float3 b)
{
return max(a, b);
}
// Screen
float3 Screen(float3 a, float3 b)
{
return 1.0 - (1.0 - a) * (1.0 - b);
}
// Color Dodge
float3 ColorDodge(float3 a, float3 b)
{
if (b.r < 1 && b.g < 1 && b.b < 1)
return min(1.0, a / (1.0 - b));
else
return 1.0;
}
// Linear Dodge
float3 LinearDodge(float3 a, float3 b)
{
return min(a + b, 1.0f);
}
// Addition
float3 Addition(float3 a, float3 b)
{
return min((a + b), 1);
}
// Reflect
float3 Reflect(float3 a, float3 b)
{
if (b.r >= 0.999999 || b.g >= 0.999999 || b.b >= 0.999999)
return b;
else
return saturate(a * a / (1.0f - b));
}
// Glow
float3 Glow(float3 a, float3 b)
{
return Reflect(b, a);
}
// Overlay
float3 Overlay(float3 a, float3 b)
{
return lerp(2 * a * b, 1.0 - 2 * (1.0 - a) * (1.0 - b), step(0.5, a));
}
// Soft Light
float3 SoftLight(float3 a, float3 b)
{
if (b.r <= 0.5 && b.g <= 0.5 && b.b <= 0.5)
return clamp(a - (1.0 - 2 * b) * a * (1 - a), 0,1);
else
return clamp(a + (2 * b - 1.0) * (Aux(a) - a), 0, 1);
}
// Hard Light
float3 HardLight(float3 a, float3 b)
{
return lerp(2 * a * b, 1.0 - 2 * (1.0 - b) * (1.0 - a), step(0.5, b));
}
// Vivid Light
float3 VividLight(float3 a, float3 b)
{
return lerp(2 * a * b, b / (2 * (1.01 - a)), step(0.50, a));
}
// Linear Light
float3 LinearLight(float3 a, float3 b)
{
if (b.r < 0.5 || b.g < 0.5 || b.b < 0.5)
return LinearBurn(a, (2.0 * b));
else
return LinearDodge(a, (2.0 * (b - 0.5)));
}
// Pin Light
float3 PinLight(float3 a, float3 b)
{
if (b.r < 0.5 || b.g < 0.5 || b.b < 0.5)
return Darken(a, (2.0 * b));
else
return Lighten(a, (2.0 * (b - 0.5)));
}
// Hard Mix
float3 HardMix(float3 a, float3 b)
{
const float3 vl = VividLight(a, b);
if (vl.r < 0.5 || vl.g < 0.5 || vl.b < 0.5)
return 0.0;
else
return 1.0;
}
// Difference
float3 Difference(float3 a, float3 b)
{
return max(a - b, b - a);
}
// Exclusion
float3 Exclusion(float3 a, float3 b)
{
return a + b - 2 * a * b;
}
// Subtract
float3 Subtract(float3 a, float3 b)
{
return max((a - b), 0);
}
// Divide
float3 Divide(float3 a, float3 b)
{
return (saturate(a / (b + 0.01)));
}
// Divide (Alternative)
float3 DivideAlt(float3 a, float3 b)
{
return (saturate(1.0 / (a / b)));
}
// Divide (Photoshop)
float3 DividePS(float3 a, float3 b)
{
return (saturate(a / b));
}
// Grain Merge
float3 GrainMerge(float3 a, float3 b)
{
return saturate(b + a - 0.5);
}
// Grain Extract
float3 GrainExtract(float3 a, float3 b)
{
return saturate(a - b + 0.5);
}
// Hue
float3 Hue(float3 a, float3 b)
{
return SetLum(SetSat(b, Sat(a)), Lum(a));
}
// Saturation
float3 Saturation(float3 a, float3 b)
{
return SetLum(SetSat(a, Sat(b)), Lum(a));
}
// Color
float3 ColorB(float3 a, float3 b)
{
return SetLum(b, Lum(a));
}
// Luminousity
float3 Luminosity(float3 a, float3 b)
{
return SetLum(a, Lum(b));
}
// -------------------------------------
// Output Functions
// -------------------------------------
float3 Blend(int mode, float3 input, float3 output, float blending)
{
switch (mode)
{
// Normal
default:
return lerp(input.rgb, output.rgb, blending);
// Darken
case 1:
return lerp(input.rgb, Darken(input.rgb, output.rgb), blending);
// Multiply
case 2:
return lerp(input.rgb, Multiply(input.rgb, output.rgb), blending);
// Color Burn
case 3:
return lerp(input.rgb, ColorBurn(input.rgb, output.rgb), blending);
// Linear Burn
case 4:
return lerp(input.rgb, LinearBurn(input.rgb, output.rgb), blending);
// Lighten
case 5:
return lerp(input.rgb, Lighten(input.rgb, output.rgb), blending);
// Screen
case 6:
return lerp(input.rgb, Screen(input.rgb, output.rgb), blending);
// Color Dodge
case 7:
return lerp(input.rgb, ColorDodge(input.rgb, output.rgb), blending);
// Linear Dodge
case 8:
return lerp(input.rgb, LinearDodge(input.rgb, output.rgb), blending);
// Addition
case 9:
return lerp(input.rgb, Addition(input.rgb, output.rgb), blending);
// Glow
case 10:
return lerp(input.rgb, Glow(input.rgb, output.rgb), blending);
// Overlay
case 11:
return lerp(input.rgb, Overlay(input.rgb, output.rgb), blending);
// Soft Light
case 12:
return lerp(input.rgb, SoftLight(input.rgb, output.rgb), blending);
// Hard Light
case 13:
return lerp(input.rgb, HardLight(input.rgb, output.rgb), blending);
// Vivid Light
case 14:
return lerp(input.rgb, VividLight(input.rgb, output.rgb), blending);
// Linear Light
case 15:
return lerp(input.rgb, LinearLight(input.rgb, output.rgb), blending);
// Pin Light
case 16:
return lerp(input.rgb, PinLight(input.rgb, output.rgb), blending);
// Hard Mix
case 17:
return lerp(input.rgb, HardMix(input.rgb, output.rgb), blending);
// Difference
case 18:
return lerp(input.rgb, Difference(input.rgb, output.rgb), blending);
// Exclusion
case 19:
return lerp(input.rgb, Exclusion(input.rgb, output.rgb), blending);
// Subtract
case 20:
return lerp(input.rgb, Subtract(input.rgb, output.rgb), blending);
// Divide
case 21:
return lerp(input.rgb, Divide(input.rgb, output.rgb), blending);
// Divide (Alternative)
case 22:
return lerp(input.rgb, DivideAlt(input.rgb, output.rgb), blending);
// Divide (Photoshop)
case 23:
return lerp(input.rgb, DividePS(input.rgb, output.rgb), blending);
// Reflect
case 24:
return lerp(input.rgb, Reflect(input.rgb, output.rgb), blending);
// Grain Merge
case 25:
return lerp(input.rgb, GrainMerge(input.rgb, output.rgb), blending);
// Grain Extract
case 26:
return lerp(input.rgb, GrainExtract(input.rgb, output.rgb), blending);
// Hue
case 27:
return lerp(input.rgb, Hue(input.rgb, output.rgb), blending);
// Saturation
case 28:
return lerp(input.rgb, Saturation(input.rgb, output.rgb), blending);
// Color
case 29:
return lerp(input.rgb, ColorB(input.rgb, output.rgb), blending);
// Luminosity
case 30:
return lerp(input.rgb, Luminosity(input.rgb, output.rgb), blending);
}
}
}
}
@@ -0,0 +1,893 @@
/*
DLSS5_Feed.fx - companion effect for the "DLSS 5 Feed" ReShade add-on (dlss5-feed.addon64/32).
It turns what ReShade already has into the guide textures DLSS needs, in the exact layout
the add-on expects:
DLSS5_MV RG16F motion vectors in PIXELS, pointing from the current pixel to where it was
in the previous frame (DLSS convention). Vectors that fail validation
(below) are zeroed.
DLSS5_Depth R32F the game's raw hardware depth (not linearised), sampled at backbuffer size,
with ReShade's RESHADE_DEPTH_INPUT_* orientation fixes applied.
DLSS5_Mask R8 "bias current colour" mask for DLSS: 1 where the motion vector could not
be trusted, so DLSS leans on the current frame there instead of warping
history in. Optional -- an add-on that does not know it ignores it.
MOTION VECTOR PROVIDER -- set the DLSS5_MV_PROVIDER preprocessor definition (ReShade overlay:
this effect's "Preprocessor definitions", or the global list) and enable that provider's
technique ABOVE this one in the effect list:
0 texMotionVectors the community-standard shared texture: qUINT_motionvectors,
dh_uber_motion, ReshadeMotionEstimation (DRME -- NOTE: DRME does not
compile on ReShade 6.8, "cannot sample from texture that is also used
as render target"; it then silently writes nothing) [default]
1 Launchpad iMMERSE Launchpad (MartysMods_LAUNCHPAD.fx): Deferred::MotionVectorsTex.
Launchpad only runs its optical flow when asked to, so this mode also
files that per-frame request (Launchpad's IPC buffer, see below).
2 VORT vort_Motion.fx (MIT): MotVectTexVort -- the recommended provider
3 LumeniteFX Kernel lumenite_Kernel.fx ("LUMENITE: Kernel"): Kernel::tFlow -- pyramidal
optical flow with per-level median + a-trous filtering and previous-
frame seeding. 1/8 resolution, upsampled here. Needs no depth buffer.
4 LumeniteFX QuantMotion
lumenite_QuantMotion.fx: QuantMotion::tFlow -- the light cut of 3.
This is the same mechanism dh_uber_rt (USE_MARTY_LAUNCHPAD_MOTION / USE_VORT_MOTION) and
vort (V_MV_MODE) use: the selected provider's OUTPUT texture is declared here exactly as the
provider declares it, so ReShade binds the same resource, and only that one is allocated.
Every provider above hands out delta UV with prev_uv = uv + mv. Nothing of any provider is
included or bundled: this file contains no third-party code and includes no third-party
files beyond ReShade's own headers.
VALIDATION -- why it exists. A game's motion vectors are geometric: a static wall under a
flickering light has vectors of exactly zero. Every provider above is OPTICAL FLOW: it
matches pixels, so a lighting change (flicker, flames, particles) is answered with a vector
that points at whatever happened to match -- confidently wrong, and DLSS then warps its
history in from there. That is the "warping around flames" and the "bad dither when the
light flickers". The fix is the one every production TAA uses: reproject and CHECK.
For each pixel, three tests against the previous frame at uv + mv:
- luma: the previous luma must fall inside the current 3x3 neighbourhood's range
(flicker moves the whole range, so a stale match falls outside);
- depth: the previous linear depth must match the current one (disocclusions);
- consistency: the previous frame's vector at that spot must resemble this one
(real motion is smooth frame to frame; flow on fire is erratic).
A vector failing any test is zeroed (the surface is treated as static -- the right answer
for a lit wall) and the pixel is flagged in DLSS5_Mask so DLSS trusts the current frame there.
The add-on runs DLSS + DLSS 5 neural rendering right after the "DLSS5_Feed" technique has
rendered, so anything placed below it in the list is applied on top of the neural output.
*/
#include "ReShade.fxh"
// D3D9 is not a target. The add-on attaches to D3D10/11/12, OpenGL and Vulkan runtimes only,
// so if ReShade is on its DirectX 9 backend the effect could never be fed anyway -- and the
// geometric-fit solver below cannot compile there (SM3 has no tex2Dfetch and must unroll the
// [loop]s over dynamically indexed arrays, which is the "error X3531: can't unroll loops
// marked with loop attribute" of issue #56). Say which of those two facts the user is looking
// at, because the compiler error alone sends people hunting through their shader list.
#if __RENDERER__ < 0xA000
#error "DLSS5_Feed needs D3D10 or newer, and ReShade has loaded its DirectX 9 backend. For a D3D9 game the dgVoodoo2 wrapper must be in effect first (check DisableAndPassThru=false in dgVoodoo.conf); see the README's 'Install for a DirectX 9 game' section. A 64-bit D3D9 game does not need this add-on at all -- renodx-dlss handles those on its own."
#endif
// Expose ReShade's completed frame to the add-on as an SRV. The 64-bit D3D11 path
// uses this only when its work-resolution control is below 100%; no extra pass or
// copy is introduced by this declaration.
texture DLSS5_ColorInput : COLOR;
sampler sDLSS5_ColorInput { Texture = DLSS5_ColorInput; AddressU = Clamp; AddressV = Clamp; MipFilter = Point; MinFilter = Point; MagFilter = Point; };
#ifndef DLSS5_MV_PROVIDER
#define DLSS5_MV_PROVIDER 0
#endif
// ---------------------------------------------------------------------------------------------
// The selected provider's output, declared byte for byte like the provider itself does.
// ---------------------------------------------------------------------------------------------
#if DLSS5_MV_PROVIDER == 1
// iMMERSE Launchpad (MartysMods/mmx_deferred.fxh)
namespace Deferred {
texture MotionVectorsTex { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RG16F; };
// Launchpad's request buffer. Launchpad only computes optical flow when a consumer asked
// for it during the previous frame (it reads this 1x1 RGBA8 at the top of its technique
// and clears it at the bottom; bit 4 = optical flow, written through the render-target
// write mask). Being below Launchpad in the list, our request lands for the next frame.
// Declared like Launchpad declares it; the two shaders that write it below are ours.
namespace IPC {
texture2D PredicationBuffer { Format = RGBA8; };
}
}
sampler sDLSS5_ProviderMV { Texture = Deferred::MotionVectorsTex; AddressU = Clamp; AddressV = Clamp; MipFilter = Point; MinFilter = Point; MagFilter = Point; };
float4 DLSS5_IpcRequestVS(in uint id : SV_VertexID) : SV_Position { return float4(0.0, 0.0, 0.0, 1.0); }
float4 DLSS5_IpcRequestPS(in float4 vpos : SV_Position) : SV_Target0 { return 1.0; }
#define DLSS5_MV_PROVIDER_NAME "Launchpad (Deferred::MotionVectorsTex)"
#define DLSS5_MV_REQUEST_PASS pass IpcRequestOpticalFlow { PrimitiveTopology = POINTLIST; VertexCount = 1; VertexShader = DLSS5_IpcRequestVS; PixelShader = DLSS5_IpcRequestPS; RenderTarget = Deferred::IPC::PredicationBuffer; RenderTargetWriteMask = 4; }
#elif DLSS5_MV_PROVIDER == 2
// VORT (Includes/vort_MotionUtils.fxh, V_MV_MODE 1)
texture2D MotVectTexVort { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RG16F; };
sampler sDLSS5_ProviderMV { Texture = MotVectTexVort; AddressU = Clamp; AddressV = Clamp; MipFilter = Point; MinFilter = Point; MagFilter = Point; };
#define DLSS5_MV_PROVIDER_NAME "VORT (MotVectTexVort)"
#elif DLSS5_MV_PROVIDER == 3
// LumeniteFX Kernel (lumenite_Kernel.fx), as lumenite_RTAO/TRAA re-declare it. 1/8 resolution.
namespace Kernel {
texture2D tFlow { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
texture2D tConfidence { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
}
sampler sDLSS5_ProviderMV { Texture = Kernel::tFlow; AddressU = Clamp; AddressV = Clamp; MipFilter = Point; MinFilter = Linear; MagFilter = Linear; };
sampler sDLSS5_ProviderMVPoint { Texture = Kernel::tFlow; AddressU = Clamp; AddressV = Clamp; MipFilter = Point; MinFilter = Point; MagFilter = Point; };
sampler sDLSS5_ProviderConfidence{ Texture = Kernel::tConfidence; AddressU = Clamp; AddressV = Clamp; };
#define DLSS5_MV_PROVIDER_NAME "LumeniteFX Kernel (Kernel::tFlow, 1/8 res)"
#define DLSS5_MV_LOWRES 1
#elif DLSS5_MV_PROVIDER == 4
// LumeniteFX QuantMotion (lumenite_QuantMotion.fx), as lumenite_QuantAO re-declares it. 1/8 resolution.
namespace QuantMotion {
texture2D tFlow { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
texture2D tConfidence { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
}
sampler sDLSS5_ProviderMV { Texture = QuantMotion::tFlow; AddressU = Clamp; AddressV = Clamp; MipFilter = Point; MinFilter = Linear; MagFilter = Linear; };
sampler sDLSS5_ProviderMVPoint { Texture = QuantMotion::tFlow; AddressU = Clamp; AddressV = Clamp; MipFilter = Point; MinFilter = Point; MagFilter = Point; };
sampler sDLSS5_ProviderConfidence{ Texture = QuantMotion::tConfidence; AddressU = Clamp; AddressV = Clamp; };
#define DLSS5_MV_PROVIDER_NAME "LumeniteFX QuantMotion (QuantMotion::tFlow, 1/8 res)"
#define DLSS5_MV_LOWRES 1
#else
// The community-standard shared texture (ReshadeMotionEstimation, qUINT, dh_uber_motion, ...)
texture texMotionVectors < pooled = false; > { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RG16F; };
sampler sDLSS5_ProviderMV { Texture = texMotionVectors; AddressU = Clamp; AddressV = Clamp; MipFilter = Point; MinFilter = Point; MagFilter = Point; };
#define DLSS5_MV_PROVIDER_NAME "texMotionVectors (DRME, qUINT, dh_uber_motion, ...)"
#endif
#ifndef DLSS5_MV_LOWRES
#define DLSS5_MV_LOWRES 0
#endif
#ifndef DLSS5_MV_REQUEST_PASS
#define DLSS5_MV_REQUEST_PASS
#endif
// ---------------------------------------------------------------------------------------------
uniform int MV_PROVIDER_INFO <
ui_type = "radio";
ui_label = " ";
ui_text = "Motion vector provider: " DLSS5_MV_PROVIDER_NAME "\n"
"Change it with the DLSS5_MV_PROVIDER preprocessor definition:\n"
" 0 texMotionVectors (DRME, qUINT, dh_uber_motion) 1 Launchpad 2 VORT\n"
" 3 LumeniteFX Kernel 4 LumeniteFX QuantMotion\n"
"Enable that provider's technique ABOVE DLSS 5 Feed.";
>;
#if DLSS5_MV_LOWRES
uniform int MV_LOWRES_FILTER <
ui_type = "combo";
ui_items = "Bilinear\0Point (nearest)\0";
ui_label = "Low-res provider filter";
ui_tooltip = "How the provider's 1/8-resolution flow is brought up to full resolution.\n"
"Bilinear smooths across flow cells; point keeps each 8x8 cell's vector as-is.";
> = 0;
#endif
// ---------------------------------------------------------------------------------------------
// Geometry vectors. A game's motion vectors for static geometry come from camera motion and
// depth, not from pixels. We have depth; the camera motion is fitted each frame from the
// provider's flow over a sparse grid (robust two-pass least squares on a 9-term screen-space
// model: affine + quadratic rotation terms + inverse-depth parallax terms), and every pixel
// then gets the vector that model predicts from its depth -- correct under flicker, correct
// while moving. The provider's flow is only used where it disagrees with the model AND wins a
// structure test: a genuinely moving object. Flames and flicker lose that test and keep the
// geometric vector, so nothing warps.
// ---------------------------------------------------------------------------------------------
uniform bool GEOM_ENABLE <
ui_category = "Geometry vectors (camera model + depth) -- EXPERIMENTAL";
ui_label = "Use geometry vectors (experimental, off by default)";
ui_tooltip = "Fit the camera motion from the provider's flow + depth each frame and derive every static\n"
"pixel's vector from it. The provider is then only consulted for moving objects.\n"
"EXPERIMENTAL: the per-frame fit is still noisy, and anything not part of the 3D world\n"
"(the HUD) gets camera vectors it should not have -- expect jitter there.\n"
"Off = the per-pixel validation below is applied to the provider's flow directly.";
> = false;
uniform float GEOM_PARALLAX <
ui_category = "Geometry vectors (camera model + depth)";
ui_type = "drag"; ui_min = 0.001; ui_max = 0.5; ui_step = 0.001;
ui_label = "Parallax depth scale";
ui_tooltip = "The model's inverse-depth term is s / (depth + s) with linear depth in 0..1. Smaller = more\n"
"parallax resolution near the camera. Usually fine as is.";
> = 0.02;
uniform float GEOM_OUTLIER_PX <
ui_category = "Geometry vectors (camera model + depth)";
ui_type = "drag"; ui_min = 0.5; ui_max = 32.0; ui_step = 0.5;
ui_label = "Fit: outlier rejection (px)";
ui_tooltip = "Second fitting pass ignores samples whose flow is further than this from the first pass's\n"
"prediction -- moving objects, flames, the first-person weapon.";
> = 4.0;
uniform float GEOM_AGREE_PX <
ui_category = "Geometry vectors (camera model + depth)";
ui_type = "drag"; ui_min = 0.0; ui_max = 16.0; ui_step = 0.1;
ui_label = "Agreement (px)";
ui_tooltip = "If the provider's flow is within this many pixels (+10% of the vector) of the model, the\n"
"model's vector is used as-is. Beyond it, the structure test decides moving object vs junk.";
> = 1.5;
uniform float GEOM_DYNAMIC_MARGIN <
ui_category = "Geometry vectors (camera model + depth)";
ui_type = "drag"; ui_min = 0.0; ui_max = 0.9; ui_step = 0.01;
ui_label = "Moving-object margin";
ui_tooltip = "For the provider's flow to override the model on a disagreeing pixel, its reprojection must\n"
"explain the pixel's structure at least this much (relative) better than the model's does.\n"
"Higher = more conservative (fewer things count as moving objects).";
> = 0.25;
uniform float GEOM_MASK_REJECTED <
ui_category = "Geometry vectors (camera model + depth)";
ui_type = "drag"; ui_min = 0.0; ui_max = 1.0; ui_step = 0.05;
ui_label = "Mask strength on rejected flow";
ui_tooltip = "Where the provider disagreed with the model but did not win the structure test (fire, smoke,\n"
"flicker), the geometric vector is used; this is how strongly DLSS is additionally asked to\n"
"favour the current frame there. 0 = pure history (smoothest), 1 = mostly current frame.\n\n"
"Also used by the static test's first frame when hysteresis holds its vector back.";
> = 0.35;
uniform bool MV_VALIDATE <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_label = "Validate motion vectors against the previous frame";
ui_tooltip = "Optical-flow providers answer a lighting change (flicker, flames) with a vector that\n"
"points at whatever happened to match. Reprojecting and checking catches those:\n"
"the vector is zeroed and DLSS is told to trust the current frame there (DLSS5_Mask).";
> = true;
uniform bool VALIDATE_STATIC <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_label = "Static-hypothesis test (zeroes the vector, keeps history)";
ui_tooltip = "For each pixel, asks which explains it better: 'did not move' or the provider's vector.\n"
"Both are scored on illumination-normalised 3x3 structure (local mean removed), so a\n"
"flickering light does not count as motion. When 'did not move' wins, the vector is zeroed\n"
"and the pixel is NOT masked -- a static wall wants its full history, which is what smooths\n"
"the flicker. This is the test for the flickering-wall case.";
> = true;
uniform bool STATIC_HYSTERESIS <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_label = "Static test: require two frames in a row";
ui_tooltip = "The static test has no memory: on a low-contrast surface under a slow pan it can win on\n"
"one frame and lose on the next, so the vector alternates between the provider's and zero\n"
"and DLSS alternately reprojects and does not -- a flicker/judder that comes and goes.\n"
"With this on, the vector is only zeroed where the test won on this frame AND the last;\n"
"on the first frame the provider's vector is kept and the pixel is masked instead, so\n"
"DLSS leans on the current frame rather than reprojecting from nowhere.\n"
"Turn it off to compare against the old (per-frame) behaviour.";
> = true;
uniform float STATIC_BIAS <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_type = "drag"; ui_min = 0.0; ui_max = 1.0; ui_step = 0.01;
ui_label = "Static bias";
ui_tooltip = "How much worse (relative) the static explanation may score than the vector's and still win.\n"
"0 = the vector must strictly beat 'did not move'. Higher favours zero vectors.";
> = 0.15;
uniform float STATIC_MIN_CONTRAST <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_type = "drag"; ui_min = 0.0; ui_max = 0.1; ui_step = 0.001;
ui_label = "Static test: minimum patch contrast";
ui_tooltip = "Below this 3x3 contrast (mean absolute deviation of luma) a patch has no structure to judge\n"
"motion by, and the test abstains -- the provider's vector stands. Raise it if flat surfaces\n"
"trail while moving (yellow on plain motion in the debug view); lower it if the\n"
"flickering wall stops being caught.";
> = 0.012;
uniform bool VALIDATE_LUMA <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_label = "Luma test (mask only)";
ui_tooltip = "The reprojected previous luma must fall inside the current 3x3 neighbourhood's luma range.\n"
"A failure only raises the mask (DLSS leans on the current frame); it never zeroes the vector,\n"
"because a lighting change does not prove the surface did not move. Off by default: on a\n"
"flickering surface it asks DLSS to drop exactly the history that would smooth the flicker.";
> = false;
uniform float LUMA_TOLERANCE <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_type = "drag"; ui_min = 0.0; ui_max = 1.0; ui_step = 0.01;
ui_label = "Luma tolerance";
ui_tooltip = "How far outside the current 3x3 neighbourhood's luma range the reprojected previous luma\n"
"may fall (relative to that range's maximum). Lower = stricter.";
> = 0.25;
uniform bool VALIDATE_DEPTH <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_label = "Depth test (zeroes the vector)";
ui_tooltip = "The reprojected previous linear depth must match the current one: a mismatch means the vector\n"
"points at a different surface (disocclusion), so it is zeroed and masked. Sky is exempt.";
> = true;
uniform float DEPTH_TOLERANCE <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_type = "drag"; ui_min = 0.0; ui_max = 0.5; ui_step = 0.005;
ui_label = "Depth tolerance";
ui_tooltip = "Allowed relative difference between the reprojected previous linear depth and the current one.";
> = 0.10;
uniform bool VALIDATE_MV <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_label = "Consistency test (zeroes the vector)";
ui_tooltip = "This frame's vector must resemble the previous frame's vector at the spot it points to.\n"
"Real motion is smooth frame to frame; optical flow on fire, smoke or a flickering wall is not.\n"
"A failure zeroes the vector and masks the pixel.";
> = true;
uniform float MV_CONSISTENCY <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_type = "drag"; ui_min = 0.0; ui_max = 16.0; ui_step = 0.1;
ui_label = "Vector consistency (px)";
ui_tooltip = "Allowed change, in pixels, between this frame's vector and the previous frame's vector at\n"
"the reprojected spot, plus 50% of the vector length. Raise it if plain camera motion\n"
"shows blue in the 'Validation tests' debug view.";
> = 1.4;
uniform float MASK_STRENGTH <
ui_category = "Validation (flicker / flames / disocclusion)";
ui_type = "drag"; ui_min = 0.0; ui_max = 1.0; ui_step = 0.05;
ui_label = "Bias-current-colour mask strength";
ui_tooltip = "How strongly a distrusted pixel asks DLSS to favour the current frame (DLSS5_Mask).\n"
"1 = fully; 0 = only zero the vector, do not mask.";
> = 1.0;
uniform float2 MV_SIGN <
ui_type = "drag";
ui_min = -1.0; ui_max = 1.0; ui_step = 2.0;
ui_label = "Motion vector sign (x, y)";
ui_tooltip = "Flip a component if the DLAA output doubles/smears in that direction while moving.\n"
"Default (1, 1) matches the convention every supported provider uses (prev_uv = uv + mv).";
> = float2(1.0, 1.0);
uniform float MV_SCALE <
ui_type = "drag";
ui_min = 0.0; ui_max = 4.0; ui_step = 0.01;
ui_label = "Motion vector scale";
ui_tooltip = "1.0 = the provider's estimate as-is. Diagnostic only.";
> = 1.0;
uniform int DEBUG_VIEW <
ui_type = "combo";
ui_items = "Motion vectors (colour = direction, brightness = speed)\0"
"Raw depth\0"
"Provider confidence (LumeniteFX only; white = confident)\0"
"Validation mask (white = vector distrusted, DLSS uses current frame)\0"
"Validation mask over the image\0"
"Validation tests over the image (red = luma, green = depth, blue = consistency, yellow = vector zeroed, orange = static held back)\0"
"Geometry model vectors (colour = direction, brightness = speed)\0"
"Geometry decision over the image (green = model, red = provider won as moving object, blue = provider rejected)\0"
"Geometry fit quality (grey = inlier share; top strip = fit error, black 0 px .. white 8 px)\0";
ui_label = "Debug view (DLSS5_Feed_Debug technique)";
> = 0;
// Outputs for the add-on
texture DLSS5_MV { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RG16F; };
texture DLSS5_Depth { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R32F; };
texture DLSS5_Mask { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R8; };
sampler sDLSS5_MV { Texture = DLSS5_MV; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
sampler sDLSS5_Depth { Texture = DLSS5_Depth; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
sampler sDLSS5_Mask { Texture = DLSS5_Mask; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
// Previous-frame history for validation (written at the end of the technique)
texture DLSS5_PrevLuma { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; };
texture DLSS5_PrevDepth { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; };
texture DLSS5_PrevMV { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RG16F; };
// Luma may be interpolated (a smooth quantity); depth and vectors must NOT be -- bilinear
// across an object edge mixes two surfaces' values and fails the test on every edge in motion.
sampler sDLSS5_PrevLuma { Texture = DLSS5_PrevLuma; AddressU = Clamp; AddressV = Clamp; MinFilter = LINEAR; MagFilter = LINEAR; MipFilter = POINT; };
sampler sDLSS5_PrevDepth { Texture = DLSS5_PrevDepth; AddressU = Clamp; AddressV = Clamp; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
sampler sDLSS5_PrevMV { Texture = DLSS5_PrevMV; AddressU = Clamp; AddressV = Clamp; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
// The static-hypothesis decision, this frame and last. The test has no memory of its own,
// so on a low-contrast surface under a slow pan it can win on one frame and lose on the
// next; the vector then alternates between the provider's and zero, and DLSS alternately
// reprojects and does not. That is a flicker/judder that no consumer can smooth out, and
// it comes and goes with the surface (The Surge 2, 2026-09-02). Guides writes StaticNow,
// History copies it into PrevStatic, and the next frame's Guides reads that -- a texture
// cannot be sampled and written in the same pass, which is why it takes two of them.
texture DLSS5_StaticNow { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R8; };
texture DLSS5_PrevStatic { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R8; };
sampler sDLSS5_StaticNow { Texture = DLSS5_StaticNow; AddressU = Clamp; AddressV = Clamp; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
sampler sDLSS5_PrevStatic { Texture = DLSS5_PrevStatic; AddressU = Clamp; AddressV = Clamp; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
// Camera-model fit: a sparse sample grid of (x, y, w, valid | u, v), and the solved model as
// six 1x1 RGBA32F texels (18 parameters + fit statistics).
#define DLSS5_FIT_W 40
#define DLSS5_FIT_H 23
texture DLSS5_FitA { Width = DLSS5_FIT_W; Height = DLSS5_FIT_H; Format = RGBA32F; };
texture DLSS5_FitB { Width = DLSS5_FIT_W; Height = DLSS5_FIT_H; Format = RGBA32F; };
sampler sDLSS5_FitA { Texture = DLSS5_FitA; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
sampler sDLSS5_FitB { Texture = DLSS5_FitB; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
texture DLSS5_Cam0 { Width = 1; Height = 1; Format = RGBA32F; };
texture DLSS5_Cam1 { Width = 1; Height = 1; Format = RGBA32F; };
texture DLSS5_Cam2 { Width = 1; Height = 1; Format = RGBA32F; };
texture DLSS5_Cam3 { Width = 1; Height = 1; Format = RGBA32F; };
texture DLSS5_Cam4 { Width = 1; Height = 1; Format = RGBA32F; };
texture DLSS5_Cam5 { Width = 1; Height = 1; Format = RGBA32F; };
sampler sDLSS5_Cam0 { Texture = DLSS5_Cam0; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
sampler sDLSS5_Cam1 { Texture = DLSS5_Cam1; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
sampler sDLSS5_Cam2 { Texture = DLSS5_Cam2; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
sampler sDLSS5_Cam3 { Texture = DLSS5_Cam3; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
sampler sDLSS5_Cam4 { Texture = DLSS5_Cam4; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
sampler sDLSS5_Cam5 { Texture = DLSS5_Cam5; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; };
// ---------------------------------------------------------------------------------------------
// The selected provider's vector at uv, as delta UV (prev_uv = uv + mv).
float2 ProviderMV(float2 uv)
{
float4 c = float4(uv, 0.0, 0.0);
#if DLSS5_MV_LOWRES
return MV_LOWRES_FILTER == 0 ? tex2Dlod(sDLSS5_ProviderMV, c).xy : tex2Dlod(sDLSS5_ProviderMVPoint, c).xy;
#else
return tex2Dlod(sDLSS5_ProviderMV, c).xy;
#endif
}
float Luma(float2 uv)
{
return dot(tex2Dlod(sDLSS5_ColorInput, float4(uv, 0.0, 0.0)).rgb, float3(0.299, 0.587, 0.114));
}
// Illumination-normalised 3x3 structure difference between the current frame at uv_cur and
// the previous frame at uv_prev: each patch has its own mean removed first, so a brightness
// change (flicker) contributes nothing and only the pattern is compared.
// Also returns the current patch's contrast (mean absolute deviation): a patch with no
// structure cannot decide anything, and the caller must not pretend it can.
float PatchError(float2 uv_cur, float2 uv_prev, out float contrast)
{
const float2 px = BUFFER_PIXEL_SIZE;
float c[9], p[9];
float mc = 0.0, mp = 0.0;
[unroll] for (int i = 0; i < 9; ++i)
{
const float2 o = float2(i % 3 - 1, i / 3 - 1) * px;
c[i] = Luma(uv_cur + o);
p[i] = tex2Dlod(sDLSS5_PrevLuma, float4(uv_prev + o, 0.0, 0.0)).x;
mc += c[i]; mp += p[i];
}
mc /= 9.0; mp /= 9.0;
float err = 0.0;
contrast = 0.0;
[unroll] for (int j = 0; j < 9; ++j)
{
err += abs((c[j] - mc) - (p[j] - mp));
contrast += abs(c[j] - mc);
}
contrast /= 9.0;
return err / 9.0;
}
// Per-test failure (0 = fine, 1 = failed, soft in between): x = luma, y = depth, z = consistency,
// w = the static hypothesis won. Luma failing says "this pixel's appearance changed"; depth or
// consistency failing says "this vector points at the wrong thing"; static winning says "no
// vector explains this pixel better than zero". Only y, z and w justify zeroing the vector, and
// only x, y, z justify asking DLSS to distrust history.
float4 ValidateTests(float2 uv, float2 mv)
{
const float2 puv = uv + mv;
float4 bad = 0.0;
// Reprojecting off-screen: nothing to compare against. Keep the vector (DLSS handles
// it) and let the mask lean on the current frame.
if (any(puv < 0.0) || any(puv > 1.0)) return float4(1.0, 0.0, 0.0, 0.0);
// 0. Static hypothesis: does "did not move" explain this pixel at least as well as the
// vector does? Scored on mean-removed structure, so flicker is not motion. Skipped for
// vectors under half a pixel (nothing to decide).
if (VALIDATE_STATIC && length(mv * BUFFER_SCREEN_SIZE) > 0.5)
{
float sc, unused;
const float es = PatchError(uv, uv, sc);
const float ef = PatchError(uv, puv, unused);
// Only a patch with structure can tell the two apart. Below the contrast floor the
// scores tie for lack of evidence, and a tie must go to the provider (its flow is
// propagated from textured neighbours -- the right guess for a moving flat wall).
// With structure, static wins only if it beats the vector by a share of that contrast.
if (sc >= STATIC_MIN_CONTRAST)
bad.w = es + 0.25 * sc <= ef * (1.0 + STATIC_BIAS) ? 1.0 : 0.0;
}
// 1. Luma: current 3x3 range vs the previous luma at the reprojected spot.
if (VALIDATE_LUMA)
{
const float2 px = BUFFER_PIXEL_SIZE;
float lc = Luma(uv), lmin = lc, lmax = lc;
[unroll] for (int y = -1; y <= 1; ++y)
[unroll] for (int x = -1; x <= 1; ++x)
{
const float l = Luma(uv + float2(x, y) * px);
lmin = min(lmin, l); lmax = max(lmax, l);
}
const float lp = tex2Dlod(sDLSS5_PrevLuma, float4(puv, 0.0, 0.0)).x;
const float margin = LUMA_TOLERANCE * max(lmax, 0.05) + 2.0 / 255.0;
bad.x = saturate(max(lmin - lp, lp - lmax) / margin);
}
// 2. Depth: previous linear depth at the reprojected spot vs the current one (sky exempt).
const float dc = ReShade::GetLinearizedDepth(uv);
if (VALIDATE_DEPTH && dc < 0.999)
{
const float dp = tex2Dlod(sDLSS5_PrevDepth, float4(puv, 0.0, 0.0)).x;
const float tol = DEPTH_TOLERANCE * max(dc, 1e-3);
bad.y = saturate((abs(dp - dc) - tol) / (tol + 1e-5));
}
// 3. Consistency: the previous frame's vector where this pixel came from vs this one.
if (VALIDATE_MV && MV_CONSISTENCY > 0.0)
{
const float2 pmv = tex2Dlod(sDLSS5_PrevMV, float4(puv, 0.0, 0.0)).xy;
const float diff = length((mv - pmv) * BUFFER_SCREEN_SIZE);
const float allow = MV_CONSISTENCY + 0.5 * length(mv * BUFFER_SCREEN_SIZE);
bad.z = saturate((diff - allow) / allow);
}
return bad;
}
// ---------------------------------------------------------------------------------------------
// Camera model. Screen position x, y in -0.5..0.5, inverse-depth term w = s / (depth + s).
// Basis (9 terms): 1, x, y, x^2, xy, y^2, w, xw, yw -- the small-rotation flow field of a
// pinhole camera is quadratic in the image position, and translation adds terms in 1/Z.
// Both flow components share the basis; the fit solves them together (two right-hand sides).
// ---------------------------------------------------------------------------------------------
#define DLSS5_BASIS(B, x, y, w) \
B[0] = 1.0; B[1] = x; B[2] = y; B[3] = x * x; B[4] = x * y; B[5] = y * y; B[6] = w; B[7] = x * w; B[8] = y * w;
float ParallaxW(float d) { return GEOM_PARALLAX / (d + GEOM_PARALLAX); }
// The model's predicted delta-UV at uv for linear depth d.
float2 PredictMV(float2 uv, float d)
{
const float4 c = float4(0.5, 0.5, 0.0, 0.0);
const float4 p0 = tex2Dlod(sDLSS5_Cam0, c), p1 = tex2Dlod(sDLSS5_Cam1, c), p2 = tex2Dlod(sDLSS5_Cam2, c);
const float4 p3 = tex2Dlod(sDLSS5_Cam3, c), p4 = tex2Dlod(sDLSS5_Cam4, c);
const float x = uv.x - 0.5, y = uv.y - 0.5, w = ParallaxW(d);
float B[9]; DLSS5_BASIS(B, x, y, w)
// u: p0.xyzw p1.xyzw p2.x v: p2.yzw p3.xyzw p4.xy
const float u = p0.x * B[0] + p0.y * B[1] + p0.z * B[2] + p0.w * B[3] + p1.x * B[4] + p1.y * B[5] + p1.z * B[6] + p1.w * B[7] + p2.x * B[8];
const float v = p2.y * B[0] + p2.z * B[1] + p2.w * B[2] + p3.x * B[3] + p3.y * B[4] + p3.z * B[5] + p3.w * B[6] + p4.x * B[7] + p4.y * B[8];
return float2(u, v);
}
bool FitIsUsable()
{
const float4 s = tex2Dlod(sDLSS5_Cam5, float4(0.5, 0.5, 0.0, 0.0)); // x = inlier share, y = rms px, z = samples used
return s.z >= 40.0 && s.x >= 0.25;
}
// Pass 1: sample the provider's flow and the depth on a sparse grid.
//
// ReShade cannot skip a whole pass on a uniform, so both fit passes start by checking the
// one uniform that decides whether anything downstream will ever read them. It matters:
// PS_FitSolve is a ONE-pixel shader that runs 2 x 920 iterations with two fetches each and
// a 9x9 Gauss-Jordan solve -- a long serial latency chain on a single lane, every frame,
// for a result only GeometryDecide consumes. GEOM_ENABLE is off by default.
void PS_FitSamples(float4 vpos : SV_Position, float2 uv : TEXCOORD, out float4 A : SV_Target0, out float4 B : SV_Target1)
{
if (!GEOM_ENABLE) { A = 0.0; B = 0.0; return; }
const float2 suv = (floor(vpos.xy) + 0.5) / float2(DLSS5_FIT_W, DLSS5_FIT_H);
const float d = ReShade::GetLinearizedDepth(suv);
const float2 mv = ProviderMV(suv);
const bool valid = d > 0.001 && all(abs(mv * BUFFER_SCREEN_SIZE) < 512.0);
A = float4(suv.x - 0.5, suv.y - 0.5, ParallaxW(d), valid ? 1.0 : 0.0);
B = float4(mv, 0.0, 0.0);
}
// Pass 2 (one pixel): robust least squares. Pass one fits everything; pass two refits on the
// samples the first fit explains to within GEOM_OUTLIER_PX, which drops moving objects,
// flames and the weapon from the camera estimate.
void PS_FitSolve(float4 vpos : SV_Position, float2 uv : TEXCOORD,
out float4 P0 : SV_Target0, out float4 P1 : SV_Target1, out float4 P2 : SV_Target2,
out float4 P3 : SV_Target3, out float4 P4 : SV_Target4, out float4 P5 : SV_Target5)
{
// See PS_FitSamples. P5.z is the sample count FitIsUsable() tests against 40, so a zeroed
// P5 also reads as "no usable fit" for anything that looks at it anyway.
if (!GEOM_ENABLE) { P0 = 0.0; P1 = 0.0; P2 = 0.0; P3 = 0.0; P4 = 0.0; P5 = 0.0; return; }
float p[18];
[unroll] for (int z = 0; z < 18; ++z) p[z] = 0.0;
float inlier = 0.0, rms = 0.0, used = 0.0;
const int total = DLSS5_FIT_W * DLSS5_FIT_H;
[loop] for (int it = 0; it < 2; ++it)
{
float M[45]; // upper triangle of the 9x9 normal matrix
float ru[9], rv[9];
[unroll] for (int z0 = 0; z0 < 45; ++z0) M[z0] = 0.0;
[unroll] for (int z1 = 0; z1 < 9; ++z1) { ru[z1] = 0.0; rv[z1] = 0.0; }
int n = 0;
float se = 0.0;
[loop] for (int s = 0; s < total; ++s)
{
const int2 cell = int2(s % DLSS5_FIT_W, s / DLSS5_FIT_W);
const float4 a = tex2Dfetch(sDLSS5_FitA, cell);
const float4 b = tex2Dfetch(sDLSS5_FitB, cell);
if (a.w < 0.5) continue;
float B[9]; DLSS5_BASIS(B, a.x, a.y, a.z)
if (it > 0)
{
float pu = 0.0, pv = 0.0;
[unroll] for (int i0 = 0; i0 < 9; ++i0) { pu += p[i0] * B[i0]; pv += p[9 + i0] * B[i0]; }
const float r = length((float2(pu, pv) - b.xy) * BUFFER_SCREEN_SIZE);
if (r > GEOM_OUTLIER_PX) continue;
se += r * r;
}
++n;
int k = 0;
[unroll] for (int i = 0; i < 9; ++i)
{
ru[i] += B[i] * b.x;
rv[i] += B[i] * b.y;
[unroll] for (int j = i; j < 9; ++j) { M[k] += B[i] * B[j]; ++k; }
}
}
if (n < 40) break; // not enough evidence: keep whatever the previous pass produced
// Augmented 9 x (9 + 2) system, Gauss-Jordan with partial pivoting, tiny ridge for
// the degenerate cases (flat depth makes w collinear with 1; a still camera makes
// everything zero).
float G[99];
{
int k2 = 0;
[unroll] for (int i = 0; i < 9; ++i)
{
[unroll] for (int j = i; j < 9; ++j) { G[i * 11 + j] = M[k2]; G[j * 11 + i] = M[k2]; ++k2; }
G[i * 11 + i] += 1e-5 * n;
G[i * 11 + 9] = ru[i];
G[i * 11 + 10] = rv[i];
}
}
bool singular = false;
[loop] for (int col = 0; col < 9; ++col)
{
int piv = col;
float best = abs(G[col * 11 + col]);
[loop] for (int r0 = col + 1; r0 < 9; ++r0)
{
const float v0 = abs(G[r0 * 11 + col]);
if (v0 > best) { best = v0; piv = r0; }
}
if (best < 1e-12) { singular = true; break; }
if (piv != col)
[unroll] for (int c0 = 0; c0 < 11; ++c0) { const float t = G[col * 11 + c0]; G[col * 11 + c0] = G[piv * 11 + c0]; G[piv * 11 + c0] = t; }
const float inv = 1.0 / G[col * 11 + col];
[unroll] for (int c1 = 0; c1 < 11; ++c1) G[col * 11 + c1] *= inv;
[loop] for (int r1 = 0; r1 < 9; ++r1)
{
if (r1 == col) continue;
const float f = G[r1 * 11 + col];
if (f == 0.0) continue;
[unroll] for (int c2 = 0; c2 < 11; ++c2) G[r1 * 11 + c2] -= f * G[col * 11 + c2];
}
}
if (singular) break;
[unroll] for (int i2 = 0; i2 < 9; ++i2) { p[i2] = G[i2 * 11 + 9]; p[9 + i2] = G[i2 * 11 + 10]; }
used = n;
inlier = float(n) / float(total);
if (it > 0) rms = sqrt(se / max(n, 1));
}
P0 = float4(p[0], p[1], p[2], p[3]);
P1 = float4(p[4], p[5], p[6], p[7]);
P2 = float4(p[8], p[9], p[10], p[11]);
P3 = float4(p[12], p[13], p[14], p[15]);
P4 = float4(p[16], p[17], 0.0, 0.0);
P5 = float4(inlier, rms, used, 0.0);
}
// Per-pixel decision: x = final delta-UV vector, .z = 0 model / 1 provider (moving object) /
// 2 provider rejected, .w = mask contribution from that decision.
float4 GeometryDecide(float2 uv, float d, float2 flow)
{
const float2 pred = PredictMV(uv, d);
const float r = length((flow - pred) * BUFFER_SCREEN_SIZE);
const float agree = GEOM_AGREE_PX + 0.1 * length(pred * BUFFER_SCREEN_SIZE);
if (r <= agree) return float4(pred, 0.0, 0.0);
float cp, cf;
const float ep = PatchError(uv, uv + pred, cp);
const float ef = PatchError(uv, uv + flow, cf);
const bool dynamic = cp >= STATIC_MIN_CONTRAST && ef <= ep * (1.0 - GEOM_DYNAMIC_MARGIN) - 1.0 / 255.0;
if (dynamic) return float4(flow, 1.0, 0.0);
return float4(pred, 2.0, GEOM_MASK_REJECTED * saturate((r - agree) / (4.0 * agree)));
}
float RawDepth(float2 uv)
{
// Raw hardware depth, exactly as the game wrote it -- the same orientation/offset
// corrections ReShade.fxh applies in GetLinearizedDepth(), minus the linearisation
// (DLSS must receive the raw values; the add-on tells it whether the range is reversed).
float2 t = uv;
#if RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN
t.y = 1.0 - t.y;
#endif
t.x /= RESHADE_DEPTH_INPUT_X_SCALE;
t.y /= RESHADE_DEPTH_INPUT_Y_SCALE;
#if RESHADE_DEPTH_INPUT_X_PIXEL_OFFSET
t.x -= RESHADE_DEPTH_INPUT_X_PIXEL_OFFSET * BUFFER_RCP_WIDTH;
#else
t.x -= RESHADE_DEPTH_INPUT_X_OFFSET / 2.000000001;
#endif
#if RESHADE_DEPTH_INPUT_Y_PIXEL_OFFSET
t.y += RESHADE_DEPTH_INPUT_Y_PIXEL_OFFSET * BUFFER_RCP_HEIGHT;
#else
t.y += RESHADE_DEPTH_INPUT_Y_OFFSET / 2.000000001;
#endif
return tex2Dlod(ReShade::DepthBuffer, float4(t, 0.0, 0.0)).x;
}
void PS_MotionVectors(float4 vpos : SV_Position, float2 uv : TEXCOORD,
out float2 mv_out : SV_Target0, out float mask : SV_Target1,
out float depth : SV_Target2, out float static_now : SV_Target3)
{
// Providers hand out "delta UV": previous position = uv + mv. DLSS wants the same
// direction, in pixels.
const float2 flow = ProviderMV(uv);
float2 mv = flow;
float distrust = 0.0;
static_now = 0.0; // the geometry path does not run the static test
if (GEOM_ENABLE && FitIsUsable())
{
const float d = ReShade::GetLinearizedDepth(uv);
const float4 g = GeometryDecide(uv, d, flow);
mv = g.xy;
distrust = g.w;
// Disocclusion: the geometric vector on a newly revealed pixel points into the
// occluder's old position; the depth test catches that and asks for the current frame.
if (VALIDATE_DEPTH && d < 0.999)
{
const float2 puv = uv + mv;
if (all(puv >= 0.0) && all(puv <= 1.0))
{
const float dp = tex2Dlod(sDLSS5_PrevDepth, float4(puv, 0.0, 0.0)).x;
const float tol = DEPTH_TOLERANCE * max(d, 1e-3);
distrust = max(distrust, saturate((abs(dp - d) - tol) / (tol + 1e-5)));
}
}
}
else if (MV_VALIDATE)
{
const float4 bad = ValidateTests(uv, flow);
static_now = bad.w; // the raw decision, for next frame's hysteresis
// The static test may only zero the vector once it has won twice in a row. On the
// first win the provider's vector is kept and the pixel is masked instead: "prefer
// the current frame here" is a safe answer either way, where a zeroed vector on a
// pixel that really is moving smears and a full vector on a pixel that really is
// static flickers.
float static_zero = bad.w;
if (STATIC_HYSTERESIS && bad.w > 0.5)
{
const float won_before = tex2Dlod(sDLSS5_PrevStatic, float4(uv, 0.0, 0.0)).x;
if (won_before <= 0.5) { static_zero = 0.0; distrust = max(distrust, GEOM_MASK_REJECTED); }
}
// Hard decision, not a blend: half a vector points at neither where the pixel came
// from nor where it is, so DLSS would warp history in from a place that means
// nothing. The soft scores stay in the mask, which IS a continuous quantity.
const bool zero_vector = max(bad.y, max(bad.z, static_zero)) > 0.5;
distrust = max(distrust, max(bad.x, max(bad.y, bad.z))); // appearance changed / wrong target
mv = zero_vector ? float2(0.0, 0.0) : flow;
}
mv_out = mv * float2(BUFFER_WIDTH, BUFFER_HEIGHT) * MV_SIGN * MV_SCALE;
mask = saturate(distrust) * MASK_STRENGTH;
depth = RawDepth(uv);
}
// End of the technique: this frame becomes next frame's history. The raw provider vector is
// stored (not the validated one), so one distrusted frame does not poison the next test.
// prev_static carries this frame's static decision over to the next (the Guides pass cannot
// both sample and write one texture, so it lands here).
void PS_StoreHistory(float4 vpos : SV_Position, float2 uv : TEXCOORD,
out float luma : SV_Target0, out float depth : SV_Target1, out float2 mv : SV_Target2,
out float prev_static : SV_Target3)
{
luma = Luma(uv);
depth = ReShade::GetLinearizedDepth(uv);
mv = ProviderMV(uv);
prev_static = tex2Dfetch(sDLSS5_StaticNow, int2(vpos.xy)).x;
}
float3 PS_Debug(float4 vpos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
if (DEBUG_VIEW == 1)
{
const float raw_depth = tex2Dlod(sDLSS5_Depth, float4(uv, 0.0, 0.0)).x;
#if RESHADE_DEPTH_INPUT_IS_REVERSED
const float proximity = raw_depth;
#else
const float proximity = 1.0 - raw_depth;
#endif
// Display-only contrast curve: DLSS5_Depth itself remains raw and untouched.
return pow(saturate(proximity), 0.125).xxx;
}
if (DEBUG_VIEW == 2)
{
#if DLSS5_MV_LOWRES
return saturate(tex2Dlod(sDLSS5_ProviderConfidence, float4(uv, 0.0, 0.0)).x).xxx;
#else
return (0.25).xxx; // this provider publishes no confidence map
#endif
}
if (DEBUG_VIEW == 3)
return tex2Dlod(sDLSS5_Mask, float4(uv, 0.0, 0.0)).xxx;
if (DEBUG_VIEW == 4)
{
const float m = tex2Dlod(sDLSS5_Mask, float4(uv, 0.0, 0.0)).x;
const float3 img = tex2Dlod(sDLSS5_ColorInput, float4(uv, 0.0, 0.0)).rgb;
return lerp(img, float3(1.0, 0.2, 0.1), m * 0.75);
}
if (DEBUG_VIEW == 5)
{
// Recomputed here against the same history the feed pass used this frame.
const float2 flow = ProviderMV(uv);
const float4 bad = ValidateTests(uv, flow);
const float3 img = tex2Dlod(sDLSS5_ColorInput, float4(uv, 0.0, 0.0)).rgb * 0.5;
// Yellow is what the feed pass ACTUALLY did, not what the static test proposed: with
// hysteresis on, a test that won only this frame keeps its vector. Watch a slow pan
// over a flat surface -- yellow that blinks on and off frame by frame is the flicker.
const bool moved = length(flow * BUFFER_SCREEN_SIZE) > 0.5;
const bool zeroed = moved && length(tex2Dlod(sDLSS5_MV, float4(uv, 0.0, 0.0)).xy) < 1e-4;
// Dim orange: the static test won this frame but hysteresis kept the vector (masked instead).
const bool held = moved && !zeroed && tex2Dlod(sDLSS5_StaticNow, float4(uv, 0.0, 0.0)).x > 0.5;
return saturate(img + bad.xyz * 0.9 + (zeroed ? float3(0.6, 0.6, 0.0) : float3(0.0, 0.0, 0.0))
+ (held ? float3(0.35, 0.18, 0.0) : float3(0.0, 0.0, 0.0)));
}
if (DEBUG_VIEW == 6)
{
const float2 pv = PredictMV(uv, ReShade::GetLinearizedDepth(uv)) * BUFFER_SCREEN_SIZE;
const float angle = atan2(pv.y, pv.x), speed = length(pv);
const float3 rgb = saturate(3.0 * abs(2.0 * frac(angle / 6.283185 + float3(0.0, -1.0 / 3.0, 1.0 / 3.0)) - 1.0) - 1.0);
return lerp(0.5, rgb, saturate(speed / 16.0));
}
if (DEBUG_VIEW == 7)
{
const float3 img = tex2Dlod(sDLSS5_ColorInput, float4(uv, 0.0, 0.0)).rgb * 0.5;
if (!FitIsUsable()) return img; // no usable fit this frame: nothing to show
const float4 g = GeometryDecide(uv, ReShade::GetLinearizedDepth(uv), ProviderMV(uv));
const float3 tint = g.z < 0.5 ? float3(0.0, 0.5, 0.0) : g.z < 1.5 ? float3(0.9, 0.0, 0.0) : float3(0.0, 0.2, 0.9);
return saturate(img + tint);
}
if (DEBUG_VIEW == 8)
{
const float4 s = tex2Dlod(sDLSS5_Cam5, float4(0.5, 0.5, 0.0, 0.0));
if (uv.y < 0.05) return saturate(s.y / 8.0).xxx; // fit error strip
return s.x.xxx; // inlier share
}
float2 mv = tex2Dlod(sDLSS5_MV, float4(uv, 0.0, 0.0)).xy; // pixels
float angle = atan2(mv.y, mv.x);
float speed = length(mv);
float3 rgb = saturate(3.0 * abs(2.0 * frac(angle / 6.283185 + float3(0.0, -1.0 / 3.0, 1.0 / 3.0)) - 1.0) - 1.0);
return lerp(0.5, rgb, saturate(speed / 16.0)); // 16 px/frame saturates the colour
}
// ---------------------------------------------------------------------------------------------
technique DLSS5_Feed
<
ui_label = "DLSS 5 Feed (place below your motion-vector provider)";
ui_tooltip = "Prepares motion vectors + depth (+ a trust mask) for the DLSS 5 Feed add-on.\n\n"
"Provider: " DLSS5_MV_PROVIDER_NAME "\n"
"Change it with the DLSS5_MV_PROVIDER preprocessor definition (0 texMotionVectors,\n"
"1 Launchpad, 2 VORT, 3 LumeniteFX Kernel, 4 LumeniteFX QuantMotion) and enable\n"
"that provider's technique ABOVE this one.";
>
{
pass FitSamples { VertexShader = PostProcessVS; PixelShader = PS_FitSamples; RenderTarget0 = DLSS5_FitA; RenderTarget1 = DLSS5_FitB; }
pass FitSolve { VertexShader = PostProcessVS; PixelShader = PS_FitSolve; RenderTarget0 = DLSS5_Cam0; RenderTarget1 = DLSS5_Cam1; RenderTarget2 = DLSS5_Cam2; RenderTarget3 = DLSS5_Cam3; RenderTarget4 = DLSS5_Cam4; RenderTarget5 = DLSS5_Cam5; }
pass Guides { VertexShader = PostProcessVS; PixelShader = PS_MotionVectors; RenderTarget0 = DLSS5_MV; RenderTarget1 = DLSS5_Mask; RenderTarget2 = DLSS5_Depth; RenderTarget3 = DLSS5_StaticNow; }
pass History { VertexShader = PostProcessVS; PixelShader = PS_StoreHistory; RenderTarget0 = DLSS5_PrevLuma; RenderTarget1 = DLSS5_PrevDepth; RenderTarget2 = DLSS5_PrevMV; RenderTarget3 = DLSS5_PrevStatic; }
DLSS5_MV_REQUEST_PASS // Launchpad only: ask it to compute optical flow again next frame
}
technique DLSS5_Feed_Debug
<
ui_label = "DLSS 5 Feed - debug view";
ui_tooltip = "Shows the motion vectors / depth / mask the add-on will send to DLSS. Enable only for checking.";
>
{
pass { VertexShader = PostProcessVS; PixelShader = PS_Debug; }
}
@@ -0,0 +1,73 @@
/**
* Daltonization algorithm by daltonize.org
* http://www.daltonize.org/2010/05/lms-daltonization-algorithm.html
* Originally ported to ReShade by IDDQD, modified for ReShade 3.0 by crosire
*/
uniform int Type <
ui_type = "combo";
ui_items = "Protanopia\0Deuteranopia\0Tritanopia\0";
> = 0;
#include "ReShade.fxh"
float3 PS_DaltonizeFXmain(float4 vpos : SV_Position, float2 texcoord : TexCoord) : SV_Target
{
float3 input = tex2D(ReShade::BackBuffer, texcoord).rgb;
// RGB to LMS matrix conversion
float OnizeL = (17.8824f * input.r) + (43.5161f * input.g) + (4.11935f * input.b);
float OnizeM = (3.45565f * input.r) + (27.1554f * input.g) + (3.86714f * input.b);
float OnizeS = (0.0299566f * input.r) + (0.184309f * input.g) + (1.46709f * input.b);
// Simulate color blindness
float Daltl, Daltm, Dalts;
if (Type == 0) // Protanopia - reds are greatly reduced (1% men)
{
Daltl = 0.0f * OnizeL + 2.02344f * OnizeM + -2.52581f * OnizeS;
Daltm = 0.0f * OnizeL + 1.0f * OnizeM + 0.0f * OnizeS;
Dalts = 0.0f * OnizeL + 0.0f * OnizeM + 1.0f * OnizeS;
}
else if (Type == 1) // Deuteranopia - greens are greatly reduced (1% men)
{
Daltl = 1.0f * OnizeL + 0.0f * OnizeM + 0.0f * OnizeS;
Daltm = 0.494207f * OnizeL + 0.0f * OnizeM + 1.24827f * OnizeS;
Dalts = 0.0f * OnizeL + 0.0f * OnizeM + 1.0f * OnizeS;
}
else if (Type == 2) // Tritanopia - blues are greatly reduced (0.003% population)
{
Daltl = 1.0f * OnizeL + 0.0f * OnizeM + 0.0f * OnizeS;
Daltm = 0.0f * OnizeL + 1.0f * OnizeM + 0.0f * OnizeS;
Dalts = -0.395913f * OnizeL + 0.801109f * OnizeM + 0.0f * OnizeS;
}
// LMS to RGB matrix conversion
float3 error;
error.r = (0.0809444479f * Daltl) + (-0.130504409f * Daltm) + (0.116721066f * Dalts);
error.g = (-0.0102485335f * Daltl) + (0.0540193266f * Daltm) + (-0.113614708f * Dalts);
error.b = (-0.000365296938f * Daltl) + (-0.00412161469f * Daltm) + (0.693511405f * Dalts);
// Isolate invisible colors to color vision deficiency (calculate error matrix)
error = (input - error);
// Shift colors towards visible spectrum (apply error modifications)
float3 correction;
correction.r = 0; // (error.r * 0.0) + (error.g * 0.0) + (error.b * 0.0);
correction.g = (error.r * 0.7) + (error.g * 1.0); // + (error.b * 0.0);
correction.b = (error.r * 0.7) + (error.b * 1.0); // + (error.g * 0.0);
// Add compensation to original values
correction = input + correction;
return correction;
}
technique Daltonize
{
pass
{
VertexShader = PostProcessVS;
PixelShader = PS_DaltonizeFXmain;
}
}
@@ -0,0 +1,252 @@
/**
* Deband shader by haasn
* https://github.com/haasn/gentoo-conf/blob/xor/home/nand/.mpv/shaders/deband-pre.glsl
*
* Copyright (c) 2015 Niklas Haas
*
* 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.
*
* Modified and optimized for ReShade by JPulowski
* https://reshade.me/forum/shader-presentation/768-deband
*
* Do not distribute without giving credit to the original author(s).
*
* 1.0 - Initial release
* 1.1 - Replaced the algorithm with the one from MPV
* 1.1a - Minor optimizations
* - Removed unnecessary lines and replaced them with ReShadeFX intrinsic counterparts
* 2.0 - Replaced "grain" with CeeJay.dk's ordered dithering algorithm and enabled it by default
* - The configuration is now more simpler and straightforward
* - Some minor code changes and optimizations
* - Improved the algorithm and made it more robust by adding some of the madshi's
* improvements to flash3kyuu_deband which should cause an increase in quality. Higher
* iterations/ranges should now yield higher quality debanding without too much decrease
* in quality.
* - Changed licensing text and original source code URL
* 3.0 - Replaced the entire banding detection algorithm with modified standard deviation and
* Weber ratio analyses which give more accurate and error-free results compared to the
* previous algorithm
* - Added banding map debug view
* - Added and redefined UI categories
* - Added depth detection (credits to spiro) which should be useful when banding only
* occurs in the sky texture for example
* - Fixed a bug in random number generation which was causing artifacts on the upper left
* side of the screen
* - Dithering is now applied only when debanding a pixel as it should be which should
* reduce the overall noise in the final texture
* - Minor code optimizations
* 3.1 - Switched to chroma-based analysis from luma-based analysis which was causing artifacts
* under some scenarios
* - Changed parts of the code which was causing compatibility issues on some renderers
*/
#include "ReShadeUI.fxh"
#include "ReShade.fxh"
uniform bool enable_weber <
ui_category = "Banding analysis";
ui_label = "Weber ratio";
ui_tooltip = "Weber ratio analysis that calculates the ratio of the each local pixel's intensity to average background intensity of all the local pixels.";
ui_type = "radio";
> = true;
uniform bool enable_sdeviation <
ui_category = "Banding analysis";
ui_label = "Standard deviation";
ui_tooltip = "Modified standard deviation analysis that calculates nearby pixels' intensity deviation from the current pixel instead of the mean.";
ui_type = "radio";
> = true;
uniform bool enable_depthbuffer <
ui_category = "Banding analysis";
ui_label = "Depth detection";
ui_tooltip = "Allows depth information to be used when analysing banding, pixels will only be analysed if they are in a certain depth. (e.g. debanding only the sky)";
ui_type = "radio";
> = false;
uniform float t1 <
ui_category = "Banding analysis";
ui_label = "Standard deviation threshold";
ui_max = 0.5;
ui_min = 0.0;
ui_step = 0.001;
ui_tooltip = "Standard deviations lower than this threshold will be flagged as flat regions with potential banding.";
ui_type = "slider";
> = 0.007;
uniform float t2 <
ui_category = "Banding analysis";
ui_label = "Weber ratio threshold";
ui_max = 2.0;
ui_min = 0.0;
ui_step = 0.01;
ui_tooltip = "Weber ratios lower than this threshold will be flagged as flat regions with potential banding.";
ui_type = "slider";
> = 0.04;
uniform float banding_depth <
ui_category = "Banding analysis";
ui_label = "Banding depth";
ui_max = 1.0;
ui_min = 0.0;
ui_step = 0.001;
ui_tooltip = "Pixels under this depth threshold will not be processed and returned as they are.";
ui_type = "slider";
> = 1.0;
uniform float range <
ui_category = "Banding detection & removal";
ui_label = "Radius";
ui_max = 32.0;
ui_min = 1.0;
ui_step = 1.0;
ui_tooltip = "The radius increases linearly for each iteration. A higher radius will find more gradients, but a lower radius will smooth more aggressively.";
ui_type = "slider";
> = 24.0;
uniform int iterations <
ui_category = "Banding detection & removal";
ui_label = "Iterations";
ui_max = 4;
ui_min = 1;
ui_tooltip = "The number of debanding steps to perform per sample. Each step reduces a bit more banding, but takes time to compute.";
ui_type = "slider";
> = 1;
uniform int debug_output <
ui_category = "Debug";
ui_items = "None\0Blurred (LPF) image\0Banding map\0";
ui_label = "Debug view";
ui_tooltip = "Blurred (LPF) image: Useful when tweaking radius and iterations to make sure all banding regions are blurred enough.\nBanding map: Useful when tweaking analysis parameters, continuous green regions indicate flat (i.e. banding) regions.";
ui_type = "combo";
> = 0;
// Reshade uses C rand for random, max cannot be larger than 2^15-1
uniform int drandom < source = "random"; min = 0; max = 32767; >;
float rand(float x)
{
return frac(x / 41.0);
}
float permute(float x)
{
return ((34.0 * x + 1.0) * x) % 289.0;
}
float3 PS_Deband(float4 vpos : SV_Position, float2 texcoord : TexCoord) : SV_Target
{
float3 ori = tex2Dlod(ReShade::BackBuffer, float4(texcoord, 0.0, 0.0)).rgb;
if (enable_depthbuffer && (ReShade::GetLinearizedDepth(texcoord) < banding_depth))
return ori;
// Initialize the PRNG by hashing the position + a random uniform
float3 m = float3(texcoord + 1.0, (drandom / 32767.0) + 1.0);
float h = permute(permute(permute(m.x) + m.y) + m.z);
// Compute a random angle
float dir = rand(permute(h)) * 6.2831853;
float2 o;
sincos(dir, o.y, o.x);
// Distance calculations
float2 pt;
float dist;
for (int i = 1; i <= iterations; ++i) {
dist = rand(h) * range * i;
pt = dist * BUFFER_PIXEL_SIZE;
h = permute(h);
}
// Sample at quarter-turn intervals around the source pixel
float3 ref[4] = {
tex2Dlod(ReShade::BackBuffer, float4(mad(pt, o, texcoord), 0.0, 0.0)).rgb, // SE
tex2Dlod(ReShade::BackBuffer, float4(mad(pt, -o, texcoord), 0.0, 0.0)).rgb, // NW
tex2Dlod(ReShade::BackBuffer, float4(mad(pt, float2(-o.y, o.x), texcoord), 0.0, 0.0)).rgb, // NE
tex2Dlod(ReShade::BackBuffer, float4(mad(pt, float2( o.y, -o.x), texcoord), 0.0, 0.0)).rgb // SW
};
// Calculate weber ratio
float3 mean = (ori + ref[0] + ref[1] + ref[2] + ref[3]) * 0.2;
float3 k = abs(ori - mean);
for (int j = 0; j < 4; ++j) {
k += abs(ref[j] - mean);
}
k = k * 0.2 / mean;
// Calculate std. deviation
float3 sd = 0.0;
for (int j = 0; j < 4; ++j) {
sd += pow(ref[j] - ori, 2);
}
sd = sqrt(sd * 0.25);
// Generate final output
float3 output;
if (debug_output == 2)
output = float3(0.0, 1.0, 0.0);
else
output = (ref[0] + ref[1] + ref[2] + ref[3]) * 0.25;
// Generate a binary banding map
bool3 banding_map = true;
if (debug_output != 1) {
if (enable_weber)
banding_map = banding_map && k <= t2 * iterations;
if (enable_sdeviation)
banding_map = banding_map && sd <= t1 * iterations;
}
/*------------------------.
| :: Ordered Dithering :: |
'------------------------*/
//Calculate grid position
float grid_position = frac(dot(texcoord, (BUFFER_SCREEN_SIZE * float2(1.0 / 16.0, 10.0 / 36.0)) + 0.25));
//Calculate how big the shift should be
float dither_shift = 0.25 * (1.0 / (pow(2, BUFFER_COLOR_BIT_DEPTH) - 1.0));
//Shift the individual colors differently, thus making it even harder to see the dithering pattern
float3 dither_shift_RGB = float3(dither_shift, -dither_shift, dither_shift); //subpixel dithering
//modify shift acording to grid position.
dither_shift_RGB = lerp(2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position); //shift acording to grid position.
return banding_map ? output + dither_shift_RGB : ori;
}
technique Deband <
ui_tooltip = "Alleviates color banding by trying to approximate original color values.";
>
{
pass
{
VertexShader = PostProcessVS;
PixelShader = PS_Deband;
}
}
@@ -0,0 +1,427 @@
/*
DisplayDepth by CeeJay.dk (with many updates and additions by the Reshade community)
Visualizes the depth buffer. The distance of pixels determine their brightness.
Close objects are dark. Far away objects are bright.
Use this to configure the depth input preprocessor definitions (RESHADE_DEPTH_INPUT_*).
*/
#include "ReShade.fxh"
// -- Basic options --
#if RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN
#define TEXT_UPSIDE_DOWN "1"
#define TEXT_UPSIDE_DOWN_ALTER "0"
#else
#define TEXT_UPSIDE_DOWN "0"
#define TEXT_UPSIDE_DOWN_ALTER "1"
#endif
#if RESHADE_DEPTH_INPUT_IS_REVERSED
#define TEXT_REVERSED "1"
#define TEXT_REVERSED_ALTER "0"
#else
#define TEXT_REVERSED "0"
#define TEXT_REVERSED_ALTER "1"
#endif
#if RESHADE_DEPTH_INPUT_IS_LOGARITHMIC
#define TEXT_LOGARITHMIC "1"
#define TEXT_LOGARITHMIC_ALTER "0"
#else
#define TEXT_LOGARITHMIC "0"
#define TEXT_LOGARITHMIC_ALTER "1"
#endif
// "ui_text" was introduced in ReShade 4.5, so cannot show instructions in older versions
uniform int iUIPresentType <
ui_label = "Present type";
ui_label_ja_jp = "画面効果";
ui_type = "combo";
ui_items = "Depth map\0Normal map\0Show both (Vertical 50/50)\0";
ui_items_ja_jp = "深度マップ\0法線マップ\0両方を表示 (左右分割)\0";
#if __RESHADE__ < 40500
ui_tooltip =
#else
ui_text =
#endif
"The right settings need to be set in the dialog that opens after clicking the \"Edit global preprocessor definitions\" button above.\n"
"\n"
"RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN is currently set to " TEXT_UPSIDE_DOWN ".\n"
"If the Depth map is shown upside down set it to " TEXT_UPSIDE_DOWN_ALTER ".\n"
"\n"
"RESHADE_DEPTH_INPUT_IS_REVERSED is currently set to " TEXT_REVERSED ".\n"
"If close objects in the Depth map are bright and far ones are dark set it to " TEXT_REVERSED_ALTER ".\n"
"Also try this if you can see the normals, but the depth view is all black.\n"
"\n"
"RESHADE_DEPTH_INPUT_IS_LOGARITHMIC is currently set to " TEXT_LOGARITHMIC ".\n"
"If the Normal map has banding artifacts (extra stripes) set it to " TEXT_LOGARITHMIC_ALTER ".";
ui_text_ja_jp =
#if ADDON_ADJUST_DEPTH
"Adjust Depthアドオンのインストールを検出しました。\n"
"'設定に保存して反映する'ボタンをクリックすると、このエフェクトで調節した全ての変数が共通設定に反映されます。\n"
"または、上の'プリプロセッサの定義を編集'ボタンをクリックした後に開くダイアログで直接編集する事もできます。";
#else
"調節が終わったら、上の'プリプロセッサの定義を編集'ボタンをクリックした後に開くダイアログに入力する必要があります。\n"
"\n"
"RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWNは現在" TEXT_UPSIDE_DOWN "に設定されています。\n"
"深度マップが上下逆さまに表示されている場合は" TEXT_UPSIDE_DOWN_ALTER "に変更して下さい。\n"
"\n"
"RESHADE_DEPTH_INPUT_IS_REVERSEDは現在" TEXT_REVERSED "に設定されています。\n"
"画面効果が深度マップのとき、近くの形状がより白く、遠くの形状がより黒い場合は" TEXT_REVERSED_ALTER "に変更して下さい。\n"
"また、法線マップで形が判別出来るが、深度マップが真っ暗に見えるという場合も、この設定の変更を試して下さい。\n"
"\n"
"RESHADE_DEPTH_INPUT_IS_LOGARITHMICは現在" TEXT_LOGARITHMIC "に設定されています。\n"
"画面効果に実際のレンダリングと合致しない縞模様がある場合は" TEXT_LOGARITHMIC_ALTER "に変更して下さい。";
#endif
ui_tooltip_ja_jp =
"'深度マップ'は、形状の遠近を白黒で表現します。正しい見え方では、近くの形状ほど黒く、遠くの形状ほど白くなります。\n"
"'法線マップ'は、形状を滑らかに表現します。正しい見え方では、全体的に青緑風で、地平線を見たときに地面が緑掛かった色合いになります。\n"
"'両方を表示 (左右分割)'が選択された場合は、左に法線マップ、右に深度マップを表示します。";
> = 2;
uniform bool bUIShowOffset <
ui_label = "Blend Depth map into the image (to help with finding the right offset)";
ui_label_ja_jp = "透かし比較";
ui_tooltip_ja_jp = "補正作業を支援するために、画面効果を半透過で適用します。";
> = false;
uniform bool bUIUseLivePreview <
ui_category = "Preview settings";
ui_category_ja_jp = "基本的な補正";
#if __RESHADE__ <= 50902
ui_category_closed = true;
#elif !ADDON_ADJUST_DEPTH
ui_category_toggle = true;
#endif
ui_label = "Show live preview and ignore preprocessor definitions";
ui_label_ja_jp = "プリプロセッサの定義を無視 (補正プレビューをオン)";
ui_tooltip = "Enable this to preview with the current preset settings instead of the global preprocessor settings.";
ui_tooltip_ja_jp =
"共通設定に保存されたプリプロセッサの定義ではなく、これより下のプレビュー設定を使用するには、これを有効にします。\n"
#if ADDON_ADJUST_DEPTH
"設定の準備が出来たら、'設定に保存して反映する'ボタンをクリックしてから、このチェックボックスをオフにして下さい。"
#else
"設定の準備が出来たら、上の'プリプロセッサの定義を編集'ボタンをクリックした後に開くダイアログに入力して下さい。"
#endif
"\n\n"
"プレビューをオンにした場合と比較して画面効果がまったく同じになれば、正しく設定が反映されています。";
> = false;
#if __RESHADE__ <= 50902
uniform int iUIUpsideDown <
#else
uniform bool iUIUpsideDown <
#endif
ui_category = "Preview settings";
ui_label = "Upside Down";
ui_label_ja_jp = "深度バッファの上下反転を修正";
#if __RESHADE__ <= 50902
ui_type = "combo";
ui_items = "Off\0On\0";
#endif
ui_text_ja_jp =
"\n"
#if ADDON_ADJUST_DEPTH
"項目にカーソルを合わせると、設定が必要な状況の説明が表示されます。"
#else
"項目にカーソルを合わせると、設定が必要な状況の説明と、プリプロセッサの定義が表示されます。"
#endif
;
ui_tooltip_ja_jp =
"深度マップが上下逆さまに表示されている場合は変更して下さい。"
#if !ADDON_ADJUST_DEPTH
"\n\n"
"定義名は次の通りです。文字は完全に一致する必要があり、半角大文字の英字とアンダーバーを用いなければなりません。\n"
"RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN=値\n"
"定義値は次の通りです。オンの場合は1、オフの場合は0を指定して下さい。\n"
"RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN=1\n"
"RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN=0"
#endif
;
> = RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN;
#if __RESHADE__ <= 50902
uniform int iUIReversed <
#else
uniform bool iUIReversed <
#endif
ui_category = "Preview settings";
ui_label = "Reversed";
ui_label_ja_jp = "深度バッファの奥行反転を修正";
#if __RESHADE__ <= 50902
ui_type = "combo";
ui_items = "Off\0On\0";
#endif
ui_tooltip_ja_jp =
"画面効果が深度マップのとき、近くの形状が明るく、遠くの形状が暗い場合は変更して下さい。\n"
"また、法線マップで形が判別出来るが、深度マップが真っ暗に見えるという場合も、この設定の変更を試して下さい。"
#if !ADDON_ADJUST_DEPTH
"\n\n"
"定義名は次の通りです。文字は完全に一致する必要があり、半角大文字の英字とアンダーバーを用いなければなりません。\n"
"RESHADE_DEPTH_INPUT_IS_REVERSED=値\n"
"定義値は次の通りです。オンの場合は1、オフの場合は0を指定して下さい。\n"
"RESHADE_DEPTH_INPUT_IS_REVERSED=1\n"
"RESHADE_DEPTH_INPUT_IS_REVERSED=0"
#endif
;
> = RESHADE_DEPTH_INPUT_IS_REVERSED;
#if __RESHADE__ <= 50902
uniform int iUILogarithmic <
#else
uniform bool iUILogarithmic <
#endif
ui_category = "Preview settings";
ui_label = "Logarithmic";
ui_label_ja_jp = "深度バッファを対数分布として扱うように修正";
#if __RESHADE__ <= 50902
ui_type = "combo";
ui_items = "Off\0On\0";
#endif
ui_tooltip = "Change this setting if the displayed surface normals have stripes in them.";
ui_tooltip_ja_jp =
"画面効果に実際のゲーム画面と合致しない縞模様がある場合は変更して下さい。"
#if !ADDON_ADJUST_DEPTH
"\n\n"
"定義名は次の通りです。文字は完全に一致する必要があり、半角大文字の英字とアンダーバーを用いなければなりません。\n"
"RESHADE_DEPTH_INPUT_IS_LOGARITHMIC=値\n"
"定義値は次の通りです。オンの場合は1、オフの場合は0を指定して下さい。\n"
"RESHADE_DEPTH_INPUT_IS_LOGARITHMIC=1\n"
"RESHADE_DEPTH_INPUT_IS_LOGARITHMIC=0"
#endif
;
> = RESHADE_DEPTH_INPUT_IS_LOGARITHMIC;
// -- Advanced options --
uniform float2 fUIScale <
ui_category = "Preview settings";
ui_label = "Scale";
ui_label_ja_jp = "拡大率";
ui_type = "drag";
ui_text =
"\n"
" * Advanced options\n"
"\n"
"The following settings also need to be set using \"Edit global preprocessor definitions\" above in order to take effect.\n"
"You can preview how they will affect the Depth map using the controls below.\n"
"\n"
"It is rarely necessary to change these though, as their defaults fit almost all games.\n\n";
ui_text_ja_jp =
"\n"
" * その他の補正 (不定形またはその他)\n"
"\n"
"これより下は、深度バッファが不定形など、特別なケース向けの設定です。\n"
"通常はこれより上の'基本的な補正'のみでほとんどのゲームに適合します。\n"
"また、これらの設定は画質の向上にはまったく役に立ちません。\n\n";
ui_tooltip =
"Best use 'Present type'->'Depth map' and enable 'Offset' in the options below to set the scale.\n"
"Use these values for:\nRESHADE_DEPTH_INPUT_X_SCALE=<left value>\nRESHADE_DEPTH_INPUT_Y_SCALE=<right value>\n"
"\n"
"If you know the right resolution of the games depth buffer then this scale value is simply the ratio\n"
"between the correct resolution and the resolution Reshade thinks it is.\n"
"For example:\n"
"If it thinks the resolution is 1920 x 1080, but it's really 1280 x 720 then the right scale is (1.5 , 1.5)\n"
"because 1920 / 1280 is 1.5 and 1080 / 720 is also 1.5, so 1.5 is the right scale for both the x and the y";
ui_tooltip_ja_jp =
"深度バッファの解像度がクライアント解像度と異なる場合に変更して下さい。\n"
"このスケール値は、深度バッファの解像度とクライアント解像度との単純な比率になります。\n"
"深度バッファの解像度が1280×720でクライアント解像度が1920×1080の場合、横の比率が1920÷1280、縦の比率が1080÷720となります。\n"
"計算した結果を設定すると、値はそれぞれX_SCALE=1.5、Y_SCALE=1.5となります。"
#if !ADDON_ADJUST_DEPTH
"\n\n"
"定義名は次の通りです。文字は完全に一致する必要があり、半角大文字の英字とアンダーバーを用いなければなりません。\n"
"RESHADE_DEPTH_INPUT_X_SCALE=横の値\n"
"RESHADE_DEPTH_INPUT_Y_SCALE=縦の値\n"
"定義値は次の通りです。横の値はX_SCALE、縦の値はY_SCALEに指定して下さい。\n"
"RESHADE_DEPTH_INPUT_X_SCALE=1.0\n"
"RESHADE_DEPTH_INPUT_Y_SCALE=1.0"
#endif
;
ui_min = 0.0; ui_max = 2.0;
ui_step = 0.001;
> = float2(RESHADE_DEPTH_INPUT_X_SCALE, RESHADE_DEPTH_INPUT_Y_SCALE);
uniform int2 iUIOffset <
ui_category = "Preview settings";
ui_label = "Offset";
ui_label_ja_jp = "位置オフセット";
ui_type = "slider";
ui_tooltip =
"Best use 'Present type'->'Depth map' and enable 'Offset' in the options below to set the offset in pixels.\n"
"Use these values for:\nRESHADE_DEPTH_INPUT_X_PIXEL_OFFSET=<left value>\nRESHADE_DEPTH_INPUT_Y_PIXEL_OFFSET=<right value>";
ui_tooltip_ja_jp =
"深度バッファにレンダリングされた物体の形状が画面効果と重なり合っていない場合に変更して下さい。\n"
"この値は、ピクセル単位で指定します。"
#if !ADDON_ADJUST_DEPTH
"\n\n"
"定義名は次の通りです。文字は完全に一致する必要があり、半角大文字の英字とアンダーバーを用いなければなりません。\n"
"RESHADE_DEPTH_INPUT_X_PIXEL_OFFSET=横の値\n"
"RESHADE_DEPTH_INPUT_Y_PIXEL_OFFSET=縦の値\n"
"定義値は次の通りです。横の値はX_PIXEL_OFFSET、縦の値はY_PIXEL_OFFSETに指定して下さい。\n"
"RESHADE_DEPTH_INPUT_X_PIXEL_OFFSET=0.0\n"
"RESHADE_DEPTH_INPUT_Y_PIXEL_OFFSET=0.0"
#endif
;
ui_min = -BUFFER_SCREEN_SIZE;
ui_max = BUFFER_SCREEN_SIZE;
ui_step = 1;
> = int2(RESHADE_DEPTH_INPUT_X_PIXEL_OFFSET, RESHADE_DEPTH_INPUT_Y_PIXEL_OFFSET);
uniform float fUIFarPlane <
ui_category = "Preview settings";
ui_label = "Far Plane";
ui_label_ja_jp = "遠点距離";
ui_type = "drag";
ui_tooltip =
"RESHADE_DEPTH_LINEARIZATION_FAR_PLANE=<value>\n"
"Changing this value is not necessary in most cases.";
ui_tooltip_ja_jp =
"深度マップの色合いが距離感と合致しない、法線マップの表面が平面に見える、などの場合に変更して下さい。\n"
"遠点距離を1000に設定すると、ゲームの描画距離が1000メートルであると見なします。\n\n"
"このプレビュー画面はあくまでプレビューであり、ほとんどの場合、深度バッファは深度マップの色数より遥かに高い精度で表現されています。\n"
"例えば、10m前後の距離の形状が純粋な黒に見えるからという理由で値を変更しないで下さい。"
#if !ADDON_ADJUST_DEPTH
"\n\n"
"定義名は次の通りです。文字は完全に一致する必要があり、半角大文字の英字とアンダーバーを用いなければなりません。\n"
"RESHADE_DEPTH_LINEARIZATION_FAR_PLANE=値\n"
"定義値は次の通りです。\n"
"RESHADE_DEPTH_LINEARIZATION_FAR_PLANE=1000.0"
#endif
;
ui_min = 0.0; ui_max = 1000.0;
ui_step = 0.1;
> = RESHADE_DEPTH_LINEARIZATION_FAR_PLANE;
uniform float fUIDepthMultiplier <
ui_category = "Preview settings";
ui_label = "Multiplier";
ui_label_ja_jp = "深度乗数";
ui_type = "drag";
ui_tooltip = "RESHADE_DEPTH_MULTIPLIER=<value>";
ui_tooltip_ja_jp =
"特定のエミュレータソフトウェアにおける深度バッファを修正するため、特別に追加された変数です。\n"
"この値は僅かな変更でも計算式を破壊するため、設定すべき値を知らない場合は変更しないで下さい。"
#if !ADDON_ADJUST_DEPTH
"\n\n"
"定義名は次の通りです。文字は完全に一致する必要があり、半角大文字の英字とアンダーバーを用いなければなりません。\n"
"RESHADE_DEPTH_MULTIPLIER=値\n"
"定義値は次の通りです。\n"
"RESHADE_DEPTH_MULTIPLIER=1.0"
#endif
;
ui_min = 0.0; ui_max = 1000.0;
ui_step = 0.001;
> = RESHADE_DEPTH_MULTIPLIER;
float GetLinearizedDepth(float2 texcoord)
{
if (!bUIUseLivePreview)
{
return ReShade::GetLinearizedDepth(texcoord);
}
else
{
if (iUIUpsideDown) // RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN
texcoord.y = 1.0 - texcoord.y;
texcoord.x /= fUIScale.x; // RESHADE_DEPTH_INPUT_X_SCALE
texcoord.y /= fUIScale.y; // RESHADE_DEPTH_INPUT_Y_SCALE
texcoord.x -= iUIOffset.x * BUFFER_RCP_WIDTH; // RESHADE_DEPTH_INPUT_X_PIXEL_OFFSET
texcoord.y += iUIOffset.y * BUFFER_RCP_HEIGHT; // RESHADE_DEPTH_INPUT_Y_PIXEL_OFFSET
float depth = tex2Dlod(ReShade::DepthBuffer, float4(texcoord, 0, 0)).x * fUIDepthMultiplier;
const float C = 0.01;
if (iUILogarithmic) // RESHADE_DEPTH_INPUT_IS_LOGARITHMIC
depth = (exp(depth * log(C + 1.0)) - 1.0) / C;
if (iUIReversed) // RESHADE_DEPTH_INPUT_IS_REVERSED
depth = 1.0 - depth;
const float N = 1.0;
depth /= fUIFarPlane - depth * (fUIFarPlane - N);
return depth;
}
}
float3 GetScreenSpaceNormal(float2 texcoord)
{
float3 offset = float3(BUFFER_PIXEL_SIZE, 0.0);
float2 posCenter = texcoord.xy;
float2 posNorth = posCenter - offset.zy;
float2 posEast = posCenter + offset.xz;
float3 vertCenter = float3(posCenter - 0.5, 1) * GetLinearizedDepth(posCenter);
float3 vertNorth = float3(posNorth - 0.5, 1) * GetLinearizedDepth(posNorth);
float3 vertEast = float3(posEast - 0.5, 1) * GetLinearizedDepth(posEast);
return normalize(cross(vertCenter - vertNorth, vertCenter - vertEast)) * 0.5 + 0.5;
}
void PS_DisplayDepth(in float4 position : SV_Position, in float2 texcoord : TEXCOORD, out float3 color : SV_Target)
{
float3 depth = GetLinearizedDepth(texcoord).xxx;
float3 normal = GetScreenSpaceNormal(texcoord);
// Ordered dithering
#if 1
const float dither_bit = 8.0; // Number of bits per channel. Should be 8 for most monitors.
// Calculate grid position
float grid_position = frac(dot(texcoord, (BUFFER_SCREEN_SIZE * float2(1.0 / 16.0, 10.0 / 36.0)) + 0.25));
// Calculate how big the shift should be
float dither_shift = 0.25 * (1.0 / (pow(2, dither_bit) - 1.0));
// Shift the individual colors differently, thus making it even harder to see the dithering pattern
float3 dither_shift_RGB = float3(dither_shift, -dither_shift, dither_shift); // Subpixel dithering
// Modify shift acording to grid position.
dither_shift_RGB = lerp(2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position);
depth += dither_shift_RGB;
#endif
color = depth;
if (iUIPresentType == 1)
color = normal;
if (iUIPresentType == 2)
color = lerp(normal, depth, step(BUFFER_WIDTH * 0.5, position.x));
if (bUIShowOffset)
{
float3 color_orig = tex2D(ReShade::BackBuffer, texcoord).rgb;
// Blend depth and back buffer color with 'overlay' so the offset is more noticeable
color = lerp(2 * color * color_orig, 1.0 - 2.0 * (1.0 - color) * (1.0 - color_orig), max(color.r, max(color.g, color.b)) < 0.5 ? 0.0 : 1.0);
}
}
technique DisplayDepth <
ui_tooltip =
"This shader helps you set the right preprocessor settings for depth input.\n"
"To set the settings click on 'Edit global preprocessor definitions' and set them there - not in this shader.\n"
"The settings will then take effect for all shaders, including this one.\n"
"\n"
"By default calculated normals and depth are shown side by side.\n"
"Normals (on the left) should look smooth and the ground should be greenish when looking at the horizon.\n"
"Depth (on the right) should show close objects as dark and use gradually brighter shades the further away objects are.\n";
ui_tooltip_ja_jp =
"これは、深度バッファの入力をReShade側の計算式に合わせる調節をするための、設定作業の支援に特化した特殊な扱いのエフェクトです。\n"
"初期状態では「両方を表示」が選択されており、左に法線マップ、右に深度マップが表示されます。\n"
"\n"
"法線マップ(左側)は、形状を滑らかに表現します。正しい設定では、全体的に青緑風で、地平線を見たときに地面が緑を帯びた色になります。\n"
"深度マップ(右側)は、形状の遠近を白黒で表現します。正しい設定では、近くの形状ほど黒く、遠くの形状ほど白くなります。\n"
"\n"
#if ADDON_ADJUST_DEPTH
"設定を完了するには、DisplayDepth.fxエフェクトの変数の一覧にある'設定に保存して反映する'ボタンをクリックして下さい。\n"
#else
"設定を完了するには、エフェクト変数の編集画面にある'プリプロセッサの定義を編集'ボタンをクリックした後に開くダイアログに入力して下さい。\n"
#endif
"すると、インストール先のゲームに対して共通の設定として保存され、他のプリセットでも正しく表示されるようになります。";
>
{
pass
{
VertexShader = PostProcessVS;
PixelShader = PS_DisplayDepth;
}
}
@@ -0,0 +1,228 @@
#ifndef _DRAWTEXT_H_
#define _DRAWTEXT_H_
#define _DRAWTEXT_GRID_X 14.0
#define _DRAWTEXT_GRID_Y 7.0
///////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// DrawText.fxh by kingreic1992 ( update: Sep.28.2019 ) //
// //
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
// //
// Available functions: //
// DrawText_String( offset, text size, xy ratio, input coord, string array, array size, output) //
// float2 offset = top left corner of string, screen hight pixel unit. //
// float text size = text size, screen hight pixel unit. //
// float xy ratio = xy ratio of text. //
// float2 input coord = current texture coord. //
// int string array = string data in float2 array format, ex: "Demo Text" //
// int String0[9] = { __D, __e, __m, __o, __Space, __T, __e, __x, __t}; //
// int string size = size of the string array. //
// float output = output. //
// //
// DrawText_Digit( offset, text size, xy ratio, input coord, precision after dot, data, output) //
// float2 offset = same as DrawText_String. //
// float text size = same as DrawText_String. //
// float xy ratio = same as DrawText_String. //
// float2 input coord = same as DrawText_String. //
// int precision = digits after dot. //
// float data = input float. //
// float output = output. //
// //
// float2 DrawText_Shift(offset, shift, text size, xy ratio) //
// float2 offset = same as DrawText_String. //
// float2 shift = shift line(y) and column. //
// float text size = same as DrawText_String. //
// float xy ratio = same as DrawText_String. //
// //
///////////////////////////////////////////////////////////////////////////////////////////////////////
//Sample Usage
/*
#include "DrawText.fxh"
float4 main_fragment( float4 position : POSITION,
float2 txcoord : TEXCOORD) : COLOR {
float res = 0.0;
int line0[9] = { __D, __e, __m, __o, __Space, __T, __e, __x, __t }; //Demo Text
int line1[15] = { __b, __y, __Space, __k, __i, __n, __g, __e, __r, __i, __c, __1, __9, __9, __2 }; //by kingeric1992
int line2[6] = { __S, __i, __z, __e, __Colon, __Space }; // Size: %d.
DrawText_String(float2(100.0 , 100.0), 32, 1, txcoord, line0, 9, res);
DrawText_String(float2(100.0 , 134.0), textSize, 1, txcoord, line1, 15, res);
DrawText_String(DrawText_Shift(float2(100.0 , 134.0), int2(0, 1), textSize, 1), 18, 1, txcoord, line2, 6, res);
DrawText_Digit(DrawText_Shift(DrawText_Shift(float2(100.0 , 134.0), int2(0, 1), textSize, 1), int2(8, 0), 18, 1),
18, 1, txcoord, 0, textSize, res);
return res;
}
*/
//Text display
//Character indexing
#define __Space 0 // (space)
#define __Exclam 1 // !
#define __Quote 2 // "
#define __Pound 3 // #
#define __Dollar 4 // $
#define __Percent 5 // %
#define __And 6 // &
#define __sQuote 7 // '
#define __rBrac_O 8 // (
#define __rBrac_C 9 // )
#define __Asterisk 10 // *
#define __Plus 11 // +
#define __Comma 12 // ,
#define __Minus 13 // -
#define __Dot 14 // .
#define __Slash 15 // /
#define __0 16 // 0
#define __1 17 // 1
#define __2 18 // 2
#define __3 19 // 3
#define __4 20 // 4
#define __5 21 // 5
#define __6 22 // 6
#define __7 23 // 7
#define __8 24 // 8
#define __9 25 // 9
#define __Colon 26 // :
#define __sColon 27 // ;
#define __Less 28 // <
#define __Equals 29 // =
#define __Greater 30 // >
#define __Question 31 // ?
#define __at 32 // @
#define __A 33 // A
#define __B 34 // B
#define __C 35 // C
#define __D 36 // D
#define __E 37 // E
#define __F 38 // F
#define __G 39 // G
#define __H 40 // H
#define __I 41 // I
#define __J 42 // J
#define __K 43 // K
#define __L 44 // L
#define __M 45 // M
#define __N 46 // N
#define __O 47 // O
#define __P 48 // P
#define __Q 49 // Q
#define __R 50 // R
#define __S 51 // S
#define __T 52 // T
#define __U 53 // U
#define __V 54 // V
#define __W 55 // W
#define __X 56 // X
#define __Y 57 // Y
#define __Z 58 // Z
#define __sBrac_O 59 // [
#define __Backslash 60 // \..
#define __sBrac_C 61 // ]
#define __Caret 62 // ^
#define __Underscore 63 // _
#define __Punc 64 // `
#define __a 65 // a
#define __b 66 // b
#define __c 67 // c
#define __d 68 // d
#define __e 69 // e
#define __f 70 // f
#define __g 71 // g
#define __h 72 // h
#define __i 73 // i
#define __j 74 // j
#define __k 75 // k
#define __l 76 // l
#define __m 77 // m
#define __n 78 // n
#define __o 79 // o
#define __p 80 // p
#define __q 81 // q
#define __r 82 // r
#define __s 83 // s
#define __t 84 // t
#define __u 85 // u
#define __v 86 // v
#define __w 87 // w
#define __x 88 // x
#define __y 89 // y
#define __z 90 // z
#define __cBrac_O 91 // {
#define __vBar 92 // |
#define __cBrac_C 93 // }
#define __Tilde 94 // ~
#define __tridot 95 // (...)
#define __empty0 96 // (null)
#define __empty1 97 // (null)
//Character indexing ends
texture Texttex < source = "FontAtlas.png"; > {
Width = 512;
Height = 512;
};
sampler samplerText {
Texture = Texttex;
};
//accomodate for undef array size.
#define DrawText_String( pos, size, ratio, tex, array, arrSize, output ) \
{ float text = 0.0; \
float2 uv = (tex * float2(BUFFER_WIDTH, BUFFER_HEIGHT) - pos) / size; \
uv.y = saturate(uv.y); \
uv.x *= ratio * 2.0; \
float id = array[int(trunc(uv.x))]; \
if(uv.x <= arrSize && uv.x >= 0.0) \
text = tex2D(samplerText, (frac(uv) + float2( id % 14.0, trunc(id / 14.0))) \
/ float2( _DRAWTEXT_GRID_X, _DRAWTEXT_GRID_Y) ).x; \
output += text; }
float2 DrawText_Shift( float2 pos, int2 shift, float size, float ratio ) {
return pos + size * shift * float2(0.5, 1.0) / ratio;
}
void DrawText_Digit( float2 pos, float size, float ratio, float2 tex, int digit, float data, inout float res) {
int digits[13] = {
__0, __1, __2, __3, __4, __5, __6, __7, __8, __9, __Minus, __Space, __Dot
};
float2 uv = (tex * float2(BUFFER_WIDTH, BUFFER_HEIGHT) - pos) / size;
uv.y = saturate(uv.y);
uv.x *= ratio * 2.0;
float t = abs(data);
int radix = floor(t)? ceil(log2(t)/3.32192809):0;
//early exit:
if(uv.x > digit+1 || -uv.x > radix+1) return;
float index = t;
if(floor(uv.x) > 0)
for(int i = ceil(-uv.x); i<0; i++) index *= 10.;
else
for(int i = ceil(uv.x); i<0; i++) index /= 10.;
index = (uv.x >= -radix-!radix)? index%10 : (10+step(0, data)); //adding sign
index = (uv.x > 0 && uv.x < 1)? 12:index; //adding dot
index = digits[(uint)index];
res += tex2D(samplerText, (frac(uv) + float2( index % 14.0, trunc(index / 14.0))) /
float2( _DRAWTEXT_GRID_X, _DRAWTEXT_GRID_Y)).x;
}
#endif
@@ -0,0 +1,80 @@
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ReShade effect file
// visit facebook.com/MartyMcModding for news/updates
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Marty's LUT shader 1.0 for ReShade 3.0
// Copyright © 2008-2016 Marty McFly
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#ifndef fLUT_TextureName
#define fLUT_TextureName "lut.png"
#endif
#ifndef fLUT_TileSizeXY
#define fLUT_TileSizeXY 32
#endif
#ifndef fLUT_TileAmount
#define fLUT_TileAmount 32
#endif
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include "ReShadeUI.fxh"
uniform float fLUT_AmountChroma < __UNIFORM_SLIDER_FLOAT1
ui_min = 0.00; ui_max = 1.00;
ui_label = "LUT chroma amount";
ui_tooltip = "Intensity of color/chroma change of the LUT.";
> = 1.00;
uniform float fLUT_AmountLuma < __UNIFORM_SLIDER_FLOAT1
ui_min = 0.00; ui_max = 1.00;
ui_label = "LUT luma amount";
ui_tooltip = "Intensity of luma change of the LUT.";
> = 1.00;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include "ReShade.fxh"
texture texLUT < source = fLUT_TextureName; > { Width = fLUT_TileSizeXY*fLUT_TileAmount; Height = fLUT_TileSizeXY; Format = RGBA8; };
sampler SamplerLUT { Texture = texLUT; };
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void PS_LUT_Apply(float4 vpos : SV_Position, float2 texcoord : TEXCOORD, out float4 res : SV_Target0)
{
float4 color = tex2D(ReShade::BackBuffer, texcoord.xy);
float2 texelsize = 1.0 / fLUT_TileSizeXY;
texelsize.x /= fLUT_TileAmount;
float3 lutcoord = float3((color.xy*fLUT_TileSizeXY-color.xy+0.5)*texelsize.xy,color.z*fLUT_TileSizeXY-color.z);
float lerpfact = frac(lutcoord.z);
lutcoord.x += (lutcoord.z-lerpfact)*texelsize.y;
float3 lutcolor = lerp(tex2D(SamplerLUT, lutcoord.xy).xyz, tex2D(SamplerLUT, float2(lutcoord.x+texelsize.y,lutcoord.y)).xyz,lerpfact);
color.xyz = lerp(normalize(color.xyz), normalize(lutcolor.xyz), fLUT_AmountChroma) *
lerp(length(color.xyz), length(lutcolor.xyz), fLUT_AmountLuma);
res.xyz = color.xyz;
res.w = 1.0;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
technique LUT
{
pass LUT_Apply
{
VertexShader = PostProcessVS;
PixelShader = PS_LUT_Apply;
}
}
@@ -0,0 +1,625 @@
////////////////////////////////////////////////////////////
// BASIC MACROS FOR RESHADE 4 //
// AUTHOR: TREYM //
////////////////////////////////////////////////////////////
// Modified by dddfault //
// //
// Changelogs : //
// Added Sampler texture boundary resolver option //
// Added float2 parameters option //
////////////////////////////////////////////////////////////
// Macros Guide: //
////////////////////////////////////////////////////////////
/* //////////////////////////////////////////////////// *
* //////////////////////////////////////////////////// *
Usage of these macros is very simple once you understand
the syntax and variable names. Let's start with a Simple
integer slider. To begin, type:
UI_INT
Next we need to add _S to indicate that this is a
"slider" widget. Follow the syntax below:
UI_INT_S(INT_NAME, "Label", "Tooltip", 0, 100, 50)
Using just a single line of code, we have created a UI
tweakable integer named INT_NAME with a minimum value of
0, a maximum value of 100, and a default value of 50.
Next, let's create that same widget, but within a UI
category. This time, we'll type:
CAT_INT_S(INT_NAME, "Category", "Label", "Tooltip", 0, 100, 50)
As you can see, the syntax follows the same pattern but
with a new input for "Category"
Below you will find a useful list of examples to get you
started. I hope you find these useful and they help your
workflow. Happy coding!
- TreyM
* //////////////////////////////////////////////////// *
* //////////////////////////////////////////////////// *
Widget Types
Input = _I
Slider = _S
Drag = _D
* //////////////////////////////////////////////////// *
BOOLEAN Macro
UI_BOOL(BOOL_NAME, "Label", "Tooltip", true)
BOOLEAN Categorized Macro
CAT_BOOL(BOOL_NAME, "Category", "Label", "Tooltip", true)
* //////////////////////////////////////////////////// *
INTEGER Combo Widget
UI_COMBO(INT_NAME, "Label", "Tooltip", 0, 2, 0, "Item 1\0Item 2\0Item 3\0")
INTEGER Drag Widget
UI_INT_D(INT_NAME, "Label", "Tooltip", 0, 100, 50)
INTEGER Input Widget
UI_INT_I(INT_NAME, "Label", "Tooltip", 0, 100, 50)
INTEGER Radio Widget
UI_RADIO(INT_NAME, "Label", "Tooltip", 0, 2, 0, " Item 1 \0 Item 2 \0 Item 3\0")
INTEGER Slider Widget
UI_INT_S(INT_NAME, "Label", "Tooltip", 0, 100, 50)
INTEGER Categorized Combo Widget
CAT_COMBO(INT_NAME, "Category", "Label", "Tooltip", 0, 2, 0, " Item 1 \0 Item 2 \0 Item 3\0")
INTEGER Categorized Drag Widget
CAT_INT_D(INT_NAME, "Category", "Label", "Tooltip", 0, 100, 50)
INTEGER Categorized Input Widget
CAT_INT_I(INT_NAME, "Category", "Label", "Tooltip", 0, 100, 50)
INTEGER Categorized Radio Widget
CAT_RADIO(INT_NAME, "Category", "Label", "Tooltip", 0, 2, 0, " Item 1 \0 Item 2 \0 Item 3\0")
INTEGER Categorized Slider Widget
CAT_INT_S(INT_NAME, "Category", "Label", "Tooltip", 0, 100, 50)
* //////////////////////////////////////////////////// *
FLOAT Drag Widget
UI_FLOAT_D(FLOAT_NAME, "Label", "Tooltip", 0.0, 1.0, 0.5)
FLOAT Input Widget
UI_FLOAT_I(FLOAT_NAME, "Label", "Tooltip", 0.0, 1.0, 0.5)
FLOAT Slider Widget
UI_FLOAT_S(FLOAT_NAME, "Label", "Tooltip", 0.0, 1.0, 0.5)
FLOAT Categorized Drag Widget
CAT_FLOAT_D(FLOAT_NAME, "Category", "Label", "Tooltip", 0.0, 1.0, 0.5)
FLOAT Categorized Input Widget
CAT_FLOAT_I(FLOAT_NAME, "Category", "Label", "Tooltip", 0.0, 1.0, 0.5)
FLOAT Categorized Slider Widget
CAT_FLOAT_S(FLOAT_NAME, "Category", "Label", "Tooltip", 0.0, 1.0, 0.5)
FLOAT macro with full control (value after "Tooltip" is ui_step)
UI_FLOAT_FULL(FLOAT_NAME, "ui_type", "Label", "Tooltip", 0.1, 0.0, 1.0, 0.5)
FLOAT Categorized macro with full control (value after "Tooltip" is ui_step)
CAT_FLOAT_FULL(FLOAT_NAME, "ui_type", "Category", "Label", "Tooltip", 0.1, 0.0, 1.0, 0.5)
* //////////////////////////////////////////////////// *
FLOAT2 Drag Widget
UI_FLOAT2_D(FLOAT_NAME, "Label", "Tooltip", 0.0, 1.0, 0.5, 0.5)
FLOAT2 Input Widget
UI_FLOAT2_I(FLOAT_NAME, "Label", "Tooltip", 0.0, 1.0, 0.5, 0.5)
FLOAT2 Slider Widget
UI_FLOAT2_S(FLOAT_NAME, "Label", "Tooltip", 0.0, 1.0, 0.5, 0.5)
FLOAT2 Categorized Drag Widget
CAT_FLOAT2_D(FLOAT_NAME, "Category", "Label", "Tooltip", 0.0, 1.0, 0.5, 0.5)
FLOAT2 Categorized Input Widget
CAT_FLOAT2_I(FLOAT_NAME, "Category", "Label", "Tooltip", 0.0, 1.0, 0.5, 0.5)
FLOAT2 Categorized Slider Widget
CAT_FLOAT2_S(FLOAT_NAME, "Category", "Label", "Tooltip", 0.0, 1.0, 0.5, 0.5)
FLOAT2 macro with full control (value after "Tooltip" is ui_step)
UI_FLOAT2_FULL(FLOAT_NAME, "ui_type", "Label", "Tooltip", 0.1, 0.0, 1.0, 0.5, 0.5)
FLOAT2 Categorized macro with full control (value after "Tooltip" is ui_step)
CAT_FLOAT2_FULL(FLOAT_NAME, "ui_type", "Category", "Label", "Tooltip", 0.1, 0.0, 1.0, 0.5, 0.5)
* //////////////////////////////////////////////////// *
FLOAT3 Drag Widget
UI_FLOAT3_D(FLOAT_NAME, "Label", "Tooltip", 0.5, 0.5, 0.5)
FLOAT3 Input Widget
UI_FLOAT3_I(FLOAT_NAME, "Label", "Tooltip", 0.5, 0.5, 0.5)
FLOAT3 Slider Widget
UI_FLOAT3_S(FLOAT_NAME, "Label", "Tooltip", 0.5, 0.5, 0.5)
FLOAT3 Categorized Drag Widget
CAT_FLOAT3_D(FLOAT_NAME, "Category", "Label", "Tooltip", 0.5, 0.5, 0.5)
FLOAT3 Categorized Input Widget
CAT_FLOAT3_I(FLOAT_NAME, "Category", "Label", "Tooltip", 0.5, 0.5, 0.5)
FLOAT3 Categorized Slider Widget
CAT_FLOAT3_S(FLOAT_NAME, "Category", "Label", "Tooltip", 0.5, 0.5, 0.5)
* //////////////////////////////////////////////////// *
FLOAT3 Color Widget
UI_COLOR(FLOAT_NAME, "Label", "Tooltip", 0.5, 0.5, 0.5)
FLOAT3 Categorized Color Widget
CAT_COLOR(FLOAT_NAME, "Category", "Label", "Tooltip", 0.5, 0.5, 0.5)
* //////////////////////////////////////////////////// *
SAMPLER Macro
SAMPLER(SamplerName, TextureName)
SAMPLER Macro with texture boundary resolver option
SAMPLER_UV(SamplerName, TextureName, ResolverType)
TEXTURE Macro
TEXTURE(TextureName, "TexturePath")
TEXTURE Full Macro
TEXTURE_FULL(TextureName, "TexturePath", Width, Height, Format)
* //////////////////////////////////////////////////// *
TECHNIQUE Macro
TECHNIQUE(TechniqueName, PassMacro)
PASS Macro
PASS(PassID, VertexShader, PixelShader)
PASS Macro with RenderTarget
PASS_RT(PassID, VertexShader, PixelShader, RenderTarget)
////////////////////////////////////////////////////
* //////////////////////////////////////////////////// */
// INTEGER MACROS ////////////////////////////////
#define UI_COMBO(var, label, tooltip, minval, maxval, defval, items) \
uniform int var \
< \
ui_type = "combo"; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_items = items; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define CAT_COMBO(var, category, label, tooltip, minval, maxval, defval, items) \
uniform int var \
< \
ui_type = "combo"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_items = items; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define UI_INT_I(var, label, tooltip, minval, maxval, defval) \
uniform int var \
< \
ui_type = "input"; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define CAT_INT_I(var, category, label, tooltip, minval, maxval, defval) \
uniform int var \
< \
ui_type = "input"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define UI_INT_S(var, label, tooltip, minval, maxval, defval) \
uniform int var \
< \
ui_type = "slider"; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define CAT_INT_S(var, category, label, tooltip, minval, maxval, defval) \
uniform int var \
< \
ui_type = "slider"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define UI_INT_D(var, label, tooltip, minval, maxval, defval) \
uniform int var \
< \
ui_type = "drag"; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define CAT_INT_D(var, category, label, tooltip, minval, maxval, defval) \
uniform int var \
< \
ui_type = "drag"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define UI_RADIO(var, label, tooltip, minval, maxval, defval, items) \
uniform int var \
< \
ui_type = "radio"; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_items = items; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define CAT_RADIO(var, category, label, tooltip, minval, maxval, defval, items) \
uniform int var \
< \
ui_type = "radio"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_items = items; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
// BOOL MACROS ///////////////////////////////////
#define UI_BOOL(var, label, tooltip, def) \
uniform bool var \
< \
ui_label = label; \
ui_tooltip = tooltip; \
> = def;
#define CAT_BOOL(var, category, label, tooltip, def) \
uniform bool var \
< \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
> = def;
// FLOAT MACROS //////////////////////////////////
#define UI_FLOAT_D(var, label, tooltip, minval, maxval, defval) \
uniform float var \
< \
ui_type = "drag"; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define CAT_FLOAT_D(var, category, label, tooltip, minval, maxval, defval) \
uniform float var \
< \
ui_type = "drag"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define UI_FLOAT_FULL(var, uitype, label, tooltip, uistep, minval, maxval, defval) \
uniform float var \
< \
ui_type = uitype; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_step = uistep; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define CAT_FLOAT_FULL(var, uitype, category, label, tooltip, uistep, minval, maxval, defval) \
uniform float var \
< \
ui_type = uitype; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_step = uistep; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define UI_FLOAT_I(var, label, tooltip, minval, maxval, defval) \
uniform float var \
< \
ui_type = "input"; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define CAT_FLOAT_I(var, category, label, tooltip, minval, maxval, defval) \
uniform float var \
< \
ui_type = "input"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define UI_FLOAT_S(var, label, tooltip, minval, maxval, defval) \
uniform float var \
< \
ui_type = "slider"; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define CAT_FLOAT_S(var, category, label, tooltip, minval, maxval, defval) \
uniform float var \
< \
ui_type = "slider"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = defval;
#define UI_FLOAT2_D(var, label, tooltip, minval, maxval, defval1, defval2) \
uniform float2 var \
< \
ui_type = "drag"; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = float2(defval1, defval2);
#define CAT_FLOAT2_D(var, category, label, tooltip, minval, maxval, defval1, defval2) \
uniform float2 var \
< \
ui_type = "drag"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = float2(defval1, defval2);
#define UI_FLOAT2_FULL(var, uitype, label, tooltip, uistep, minval, maxval, defval1, defval2) \
uniform float2 var \
< \
ui_type = uitype; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_step = uistep; \
ui_min = minval; \
ui_max = maxval; \
> = float2(defval1, defval2);
#define CAT_FLOAT2_FULL(var, uitype, category, label, tooltip, uistep, minval, defval1, defval2) \
uniform float2 var \
< \
ui_type = uitype; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_step = uistep; \
ui_min = minval; \
ui_max = maxval; \
> = float2(defval1, defval2);
#define UI_FLOAT2_I(var, label, tooltip, minval, maxval, defval1, defval2) \
uniform float2 var \
< \
ui_type = "input"; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = float2(defval1, defval2);
#define CAT_FLOAT2_I(var, category, label, tooltip, minval, maxval, defval1, defval2) \
uniform float2 var \
< \
ui_type = "input"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = float2(defval1, defval2);
#define UI_FLOAT2_S(var, label, tooltip, minval, maxval, defval1, defval2) \
uniform float2 var \
< \
ui_type = "slider"; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = float2(defval1, defval2);
#define CAT_FLOAT2_S(var, category, label, tooltip, minval, maxval, defval1, defval2) \
uniform float2 var \
< \
ui_type = "slider"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
ui_min = minval; \
ui_max = maxval; \
> = float2(defval1, defval2);
#define UI_FLOAT3_D(var, label, tooltip, defval1, defval2, defval3) \
uniform float3 var \
< \
ui_type = "drag"; \
ui_label = label; \
ui_tooltip = tooltip; \
> = float3(defval1, defval2, defval3);
#define CAT_FLOAT3_D(var, category, label, tooltip, defval1, defval2, defval3) \
uniform float3 var \
< \
ui_type = "drag"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
> = float3(defval1, defval2, defval3);
#define UI_FLOAT3_I(var, label, tooltip, defval1, defval2, defval3) \
uniform float3 var \
< \
ui_type = "input"; \
ui_label = label; \
ui_tooltip = tooltip; \
> = float3(defval1, defval2, defval3);
#define CAT_FLOAT3_I(var, category, label, tooltip, defval1, defval2, defval3) \
uniform float3 var \
< \
ui_type = "input"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
> = float3(defval1, defval2, defval3);
#define UI_FLOAT3_S(var, label, tooltip, defval1, defval2, defval3) \
uniform float3 var \
< \
ui_type = "slider"; \
ui_label = label; \
ui_tooltip = tooltip; \
> = float3(defval1, defval2, defval3);
#define CAT_FLOAT3_S(var, category, label, tooltip, defval1, defval2, defval3) \
uniform float3 var \
< \
ui_type = "slider"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
> = float3(defval1, defval2, defval3);
// COLOR WIDGET MACROS ///////////////////////////
#define UI_COLOR(var, label, tooltip, defval1, defval2, defval3) \
uniform float3 var \
< \
ui_type = "color"; \
ui_label = label; \
ui_tooltip = tooltip; \
> = float3(defval1, defval2, defval3);
#define CAT_COLOR(var, category, label, tooltip, defval1, defval2, defval3) \
uniform float3 var \
< \
ui_type = "color"; \
ui_category = category; \
ui_label = label; \
ui_tooltip = tooltip; \
> = float3(defval1, defval2, defval3);
// SAMPLER MACRO /////////////////////////////////
#define SAMPLER(sname, tname) \
sampler sname \
{ \
Texture = tname; \
};
#define SAMPLER_UV(sname, tname, addUVW) \
sampler sname \
{ \
Texture = tname; \
AddressU = addUVW; \
AddressV = addUVW; \
AddressW = addUVW; \
};
// TEXTURE MACROs ////////////////////////////////
#define TEXTURE(tname, src) \
texture tname <source=src;> \
{ \
Width = BUFFER_WIDTH; \
Height = BUFFER_HEIGHT; \
Format = RGBA8; \
};
#define TEXTURE_FULL(tname, src, width, height, fomat) \
texture tname <source=src;> \
{ \
Width = width; \
Height = height; \
Format = fomat; \
};
// TECHNIQUE MACROS //////////////////////////////
#define TECHNIQUE(tname, pass) \
technique tname \
{ \
pass \
}
#define PASS(ID, vs, ps) pass \
{ \
VertexShader = vs; \
PixelShader = ps; \
}
#define PASS_RT(ID, vs, ps, rt) pass \
{ \
VertexShader = vs; \
PixelShader = ps; \
RenderTarget = rt; \
}
@@ -0,0 +1,124 @@
/*
* SPDX-License-Identifier: CC0-1.0
*/
#pragma once
#if !defined(__RESHADE__) || __RESHADE__ < 30000
#error "ReShade 3.0+ is required to use this header file"
#endif
#ifndef RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN
#define RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN 0
#endif
#ifndef RESHADE_DEPTH_INPUT_IS_REVERSED
#define RESHADE_DEPTH_INPUT_IS_REVERSED 1
#endif
#ifndef RESHADE_DEPTH_INPUT_IS_MIRRORED
#define RESHADE_DEPTH_INPUT_IS_MIRRORED 0
#endif
#ifndef RESHADE_DEPTH_INPUT_IS_LOGARITHMIC
#define RESHADE_DEPTH_INPUT_IS_LOGARITHMIC 0
#endif
#ifndef RESHADE_DEPTH_MULTIPLIER
#define RESHADE_DEPTH_MULTIPLIER 1
#endif
#ifndef RESHADE_DEPTH_LINEARIZATION_FAR_PLANE
#define RESHADE_DEPTH_LINEARIZATION_FAR_PLANE 1000.0
#endif
// Above 1 expands coordinates, below 1 contracts and 1 is equal to no scaling on any axis
#ifndef RESHADE_DEPTH_INPUT_Y_SCALE
#define RESHADE_DEPTH_INPUT_Y_SCALE 1
#endif
#ifndef RESHADE_DEPTH_INPUT_X_SCALE
#define RESHADE_DEPTH_INPUT_X_SCALE 1
#endif
// An offset to add to the Y coordinate, (+) = move up, (-) = move down
#ifndef RESHADE_DEPTH_INPUT_Y_OFFSET
#define RESHADE_DEPTH_INPUT_Y_OFFSET 0
#endif
#ifndef RESHADE_DEPTH_INPUT_Y_PIXEL_OFFSET
#define RESHADE_DEPTH_INPUT_Y_PIXEL_OFFSET 0
#endif
// An offset to add to the X coordinate, (+) = move right, (-) = move left
#ifndef RESHADE_DEPTH_INPUT_X_OFFSET
#define RESHADE_DEPTH_INPUT_X_OFFSET 0
#endif
#ifndef RESHADE_DEPTH_INPUT_X_PIXEL_OFFSET
#define RESHADE_DEPTH_INPUT_X_PIXEL_OFFSET 0
#endif
#define BUFFER_PIXEL_SIZE float2(BUFFER_RCP_WIDTH, BUFFER_RCP_HEIGHT)
#define BUFFER_SCREEN_SIZE float2(BUFFER_WIDTH, BUFFER_HEIGHT)
#define BUFFER_ASPECT_RATIO (BUFFER_WIDTH * BUFFER_RCP_HEIGHT)
namespace ReShade
{
#if defined(__RESHADE_FXC__)
float GetAspectRatio() { return BUFFER_WIDTH * BUFFER_RCP_HEIGHT; }
float2 GetPixelSize() { return float2(BUFFER_RCP_WIDTH, BUFFER_RCP_HEIGHT); }
float2 GetScreenSize() { return float2(BUFFER_WIDTH, BUFFER_HEIGHT); }
#define AspectRatio GetAspectRatio()
#define PixelSize GetPixelSize()
#define ScreenSize GetScreenSize()
#else
// These are deprecated and will be removed eventually.
static const float AspectRatio = BUFFER_WIDTH * BUFFER_RCP_HEIGHT;
static const float2 PixelSize = float2(BUFFER_RCP_WIDTH, BUFFER_RCP_HEIGHT);
static const float2 ScreenSize = float2(BUFFER_WIDTH, BUFFER_HEIGHT);
#endif
// Global textures and samplers
texture BackBufferTex : COLOR;
texture DepthBufferTex : DEPTH;
sampler BackBuffer { Texture = BackBufferTex; };
sampler DepthBuffer { Texture = DepthBufferTex; };
// Helper functions
float GetLinearizedDepth(float2 texcoord)
{
#if RESHADE_DEPTH_INPUT_IS_UPSIDE_DOWN
texcoord.y = 1.0 - texcoord.y;
#endif
#if RESHADE_DEPTH_INPUT_IS_MIRRORED
texcoord.x = 1.0 - texcoord.x;
#endif
texcoord.x /= RESHADE_DEPTH_INPUT_X_SCALE;
texcoord.y /= RESHADE_DEPTH_INPUT_Y_SCALE;
#if RESHADE_DEPTH_INPUT_X_PIXEL_OFFSET
texcoord.x -= RESHADE_DEPTH_INPUT_X_PIXEL_OFFSET * BUFFER_RCP_WIDTH;
#else // Do not check RESHADE_DEPTH_INPUT_X_OFFSET, since it may be a decimal number, which the preprocessor cannot handle
texcoord.x -= RESHADE_DEPTH_INPUT_X_OFFSET / 2.000000001;
#endif
#if RESHADE_DEPTH_INPUT_Y_PIXEL_OFFSET
texcoord.y += RESHADE_DEPTH_INPUT_Y_PIXEL_OFFSET * BUFFER_RCP_HEIGHT;
#else
texcoord.y += RESHADE_DEPTH_INPUT_Y_OFFSET / 2.000000001;
#endif
float depth = tex2Dlod(DepthBuffer, float4(texcoord, 0, 0)).x * RESHADE_DEPTH_MULTIPLIER;
#if RESHADE_DEPTH_INPUT_IS_LOGARITHMIC
const float C = 0.01;
depth = (exp(depth * log(C + 1.0)) - 1.0) / C;
#endif
#if RESHADE_DEPTH_INPUT_IS_REVERSED
depth = 1.0 - depth;
#endif
const float N = 1.0;
depth /= RESHADE_DEPTH_LINEARIZATION_FAR_PLANE - depth * (RESHADE_DEPTH_LINEARIZATION_FAR_PLANE - N);
return depth;
}
}
// Vertex shader generating a triangle covering the entire screen
// See also https://www.reddit.com/r/gamedev/comments/2j17wk/a_slightly_faster_bufferless_vertex_shader_trick/
void PostProcessVS(in uint id : SV_VertexID, out float4 position : SV_Position, out float2 texcoord : TEXCOORD)
{
texcoord.x = (id == 2) ? 2.0 : 0.0;
texcoord.y = (id == 1) ? 2.0 : 0.0;
position = float4(texcoord * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0);
}
@@ -0,0 +1,214 @@
#pragma once
#if !defined(__RESHADE__) || __RESHADE__ < 30000
#error "ReShade 3.0+ is required to use this header file"
#endif
#define RESHADE_VERSION(major,minor,build) (10000 * (major) + 100 * (minor) + (build))
#define SUPPORTED_VERSION(major,minor,build) (__RESHADE__ >= RESHADE_VERSION(major,minor,build))
// >= 3.0.0
// Commit current in-game user interface status
// https://github.com/crosire/reshade/commit/302bacc49ae394faedc2e29a296c1cebf6da6bb2#diff-82cf230afdb2a0d5174111e6f17548a5R1183
// Added various GUI related uniform variable annotations
// https://reshade.me/forum/releases/2341-3-0
#define __UNIFORM_INPUT_ANY ui_type = "input";
#define __UNIFORM_INPUT_BOOL1 __UNIFORM_INPUT_ANY
#define __UNIFORM_INPUT_BOOL2 __UNIFORM_INPUT_ANY
#define __UNIFORM_INPUT_BOOL3 __UNIFORM_INPUT_ANY
#define __UNIFORM_INPUT_BOOL4 __UNIFORM_INPUT_ANY
#define __UNIFORM_INPUT_INT1 __UNIFORM_INPUT_ANY
#define __UNIFORM_INPUT_INT2 __UNIFORM_INPUT_ANY
#define __UNIFORM_INPUT_INT3 __UNIFORM_INPUT_ANY
#define __UNIFORM_INPUT_INT4 __UNIFORM_INPUT_ANY
#define __UNIFORM_INPUT_FLOAT1 __UNIFORM_INPUT_ANY
#define __UNIFORM_INPUT_FLOAT2 __UNIFORM_INPUT_ANY
#define __UNIFORM_INPUT_FLOAT3 __UNIFORM_INPUT_ANY
#define __UNIFORM_INPUT_FLOAT4 __UNIFORM_INPUT_ANY
// >= 4.0.1
// Change slider widget to be used with new "slider" instead of a "drag" type annotation
// https://github.com/crosire/reshade/commit/746229f31cd6f311a3e72a543e4f1f23faa23f11#diff-59405a313bd8cbfb0ca6dd633230e504R1701
// Changed slider widget to be used with < ui_type = "slider"; > instead of < ui_type = "drag"; >
// https://reshade.me/forum/releases/4772-4-0
#if SUPPORTED_VERSION(4,0,1)
#define __UNIFORM_DRAG_ANY ui_type = "drag";
// >= 4.0.0
// Rework statistics tab and add drag widgets back
// https://github.com/crosire/reshade/commit/1b2c38795f00efd66c007da1f483f1441b230309
// Changed drag widget to a slider widget (old one is still available via < ui_type = "drag2"; >)
// https://reshade.me/forum/releases/4772-4-0
#elif SUPPORTED_VERSION(4,0,0)
#define __UNIFORM_DRAG_ANY ui_type = "drag2";
// >= 3.0.0
// Commit current in-game user interface status
// https://github.com/crosire/reshade/commit/302bacc49ae394faedc2e29a296c1cebf6da6bb2#diff-82cf230afdb2a0d5174111e6f17548a5R1187
// Added various GUI related uniform variable annotations
// https://reshade.me/forum/releases/2341-3-0
#else
#define __UNIFORM_DRAG_ANY ui_type = "drag";
#endif
#define __UNIFORM_DRAG_BOOL1 __UNIFORM_DRAG_ANY
#define __UNIFORM_DRAG_BOOL2 __UNIFORM_DRAG_ANY
#define __UNIFORM_DRAG_BOOL3 __UNIFORM_DRAG_ANY
#define __UNIFORM_DRAG_BOOL4 __UNIFORM_DRAG_ANY
#define __UNIFORM_DRAG_INT1 __UNIFORM_DRAG_ANY
#define __UNIFORM_DRAG_INT2 __UNIFORM_DRAG_ANY
#define __UNIFORM_DRAG_INT3 __UNIFORM_DRAG_ANY
#define __UNIFORM_DRAG_INT4 __UNIFORM_DRAG_ANY
#define __UNIFORM_DRAG_FLOAT1 __UNIFORM_DRAG_ANY
#define __UNIFORM_DRAG_FLOAT2 __UNIFORM_DRAG_ANY
#define __UNIFORM_DRAG_FLOAT3 __UNIFORM_DRAG_ANY
#define __UNIFORM_DRAG_FLOAT4 __UNIFORM_DRAG_ANY
// >= 4.0.1
// Change slider widget to be used with new "slider" instead of a "drag" type annotation
// https://github.com/crosire/reshade/commit/746229f31cd6f311a3e72a543e4f1f23faa23f11#diff-59405a313bd8cbfb0ca6dd633230e504R1699
// Changed slider widget to be used with < ui_type = "slider"; > instead of < ui_type = "drag"; >
// https://reshade.me/forum/releases/4772-4-0
#if SUPPORTED_VERSION(4,0,1)
#define __UNIFORM_SLIDER_ANY ui_type = "slider";
// >= 4.0.0
// Rework statistics tab and add drag widgets back
// https://github.com/crosire/reshade/commit/1b2c38795f00efd66c007da1f483f1441b230309
// Changed drag widget to a slider widget (old one is still available via < ui_type = "drag2"; >)
// https://reshade.me/forum/releases/4772-4-0
#elif SUPPORTED_VERSION(4,0,0)
#define __UNIFORM_SLIDER_ANY ui_type = "drag";
#else
#define __UNIFORM_SLIDER_ANY __UNIFORM_DRAG_ANY
#endif
#define __UNIFORM_SLIDER_BOOL1 __UNIFORM_SLIDER_ANY
#define __UNIFORM_SLIDER_BOOL2 __UNIFORM_SLIDER_ANY
#define __UNIFORM_SLIDER_BOOL3 __UNIFORM_SLIDER_ANY
#define __UNIFORM_SLIDER_BOOL4 __UNIFORM_SLIDER_ANY
#define __UNIFORM_SLIDER_INT1 __UNIFORM_SLIDER_ANY
#define __UNIFORM_SLIDER_INT2 __UNIFORM_SLIDER_ANY
#define __UNIFORM_SLIDER_INT3 __UNIFORM_SLIDER_ANY
#define __UNIFORM_SLIDER_INT4 __UNIFORM_SLIDER_ANY
#define __UNIFORM_SLIDER_FLOAT1 __UNIFORM_SLIDER_ANY
#define __UNIFORM_SLIDER_FLOAT2 __UNIFORM_SLIDER_ANY
#define __UNIFORM_SLIDER_FLOAT3 __UNIFORM_SLIDER_ANY
#define __UNIFORM_SLIDER_FLOAT4 __UNIFORM_SLIDER_ANY
// >= 3.0.0
// Add combo box display type for uniform variables and fix displaying of integer variable under Direct3D 9
// https://github.com/crosire/reshade/commit/b025bfae5f7343509ec0cacf6df0cff537c499f2#diff-82cf230afdb2a0d5174111e6f17548a5R1631
// Added various GUI related uniform variable annotations
// https://reshade.me/forum/releases/2341-3-0
#define __UNIFORM_COMBO_ANY ui_type = "combo";
// __UNIFORM_COMBO_BOOL1
#define __UNIFORM_COMBO_BOOL2 __UNIFORM_COMBO_ANY
#define __UNIFORM_COMBO_BOOL3 __UNIFORM_COMBO_ANY
#define __UNIFORM_COMBO_BOOL4 __UNIFORM_COMBO_ANY
#define __UNIFORM_COMBO_INT1 __UNIFORM_COMBO_ANY
#define __UNIFORM_COMBO_INT2 __UNIFORM_COMBO_ANY
#define __UNIFORM_COMBO_INT3 __UNIFORM_COMBO_ANY
#define __UNIFORM_COMBO_INT4 __UNIFORM_COMBO_ANY
#define __UNIFORM_COMBO_FLOAT1 __UNIFORM_COMBO_ANY
#define __UNIFORM_COMBO_FLOAT2 __UNIFORM_COMBO_ANY
#define __UNIFORM_COMBO_FLOAT3 __UNIFORM_COMBO_ANY
#define __UNIFORM_COMBO_FLOAT4 __UNIFORM_COMBO_ANY
// >= 4.0.0
// Add option to display boolean values as combo box instead of checkbox
// https://github.com/crosire/reshade/commit/aecb757c864c9679e77edd6f85a1521c49e489c1#diff-59405a313bd8cbfb0ca6dd633230e504R1147
// https://github.com/crosire/reshade/blob/v4.0.0/source/gui.cpp
// Added option to display boolean values as combo box instead of checkbox (via < ui_type = "combo"; >)
// https://reshade.me/forum/releases/4772-4-0
#define __UNIFORM_COMBO_BOOL1 __UNIFORM_COMBO_ANY
// >= 4.0.0
// Cleanup GUI code and rearrange some widgets
// https://github.com/crosire/reshade/commit/6751f7bd50ea7c0556cf0670f10a4b4ba912ee7d#diff-59405a313bd8cbfb0ca6dd633230e504R1711
// Added radio button widget (via < ui_type = "radio"; ui_items = "Button 1\0Button 2\0...\0"; >)
// https://reshade.me/forum/releases/4772-4-0
#if SUPPORTED_VERSION(4,0,0)
#define __UNIFORM_RADIO_ANY ui_type = "radio";
#else
#define __UNIFORM_RADIO_ANY __UNIFORM_COMBO_ANY
#endif
#define __UNIFORM_RADIO_BOOL1 __UNIFORM_RADIO_ANY
#define __UNIFORM_RADIO_BOOL2 __UNIFORM_RADIO_ANY
#define __UNIFORM_RADIO_BOOL3 __UNIFORM_RADIO_ANY
#define __UNIFORM_RADIO_BOOL4 __UNIFORM_RADIO_ANY
#define __UNIFORM_RADIO_INT1 __UNIFORM_RADIO_ANY
#define __UNIFORM_RADIO_INT2 __UNIFORM_RADIO_ANY
#define __UNIFORM_RADIO_INT3 __UNIFORM_RADIO_ANY
#define __UNIFORM_RADIO_INT4 __UNIFORM_RADIO_ANY
#define __UNIFORM_RADIO_FLOAT1 __UNIFORM_RADIO_ANY
#define __UNIFORM_RADIO_FLOAT2 __UNIFORM_RADIO_ANY
#define __UNIFORM_RADIO_FLOAT3 __UNIFORM_RADIO_ANY
#define __UNIFORM_RADIO_FLOAT4 __UNIFORM_RADIO_ANY
// >= 4.1.0
// Fix floating point uniforms with unknown "ui_type" not showing up in UI
// https://github.com/crosire/reshade/commit/50e5bf44dfc84bc4220c2b9f19d5f50c7a0fda66#diff-59405a313bd8cbfb0ca6dd633230e504R1788
// Fixed floating point uniforms with unknown "ui_type" not showing up in UI
// https://reshade.me/forum/releases/5021-4-1
#define __UNIFORM_COLOR_ANY ui_type = "color";
// >= 3.0.0
// Move technique list to preset configuration file
// https://github.com/crosire/reshade/blob/84bba3aa934c1ebe4c6419b69dfe1690d9ab9d34/source/runtime.cpp#L1328
// Added various GUI related uniform variable annotations
// https://reshade.me/forum/releases/2341-3-0
#define __UNIFORM_COLOR_BOOL1 __UNIFORM_COLOR_ANY
#define __UNIFORM_COLOR_BOOL2 __UNIFORM_COLOR_ANY
#define __UNIFORM_COLOR_BOOL3 __UNIFORM_COLOR_ANY
#define __UNIFORM_COLOR_BOOL4 __UNIFORM_COLOR_ANY
#define __UNIFORM_COLOR_INT1 __UNIFORM_COLOR_ANY
#define __UNIFORM_COLOR_INT2 __UNIFORM_COLOR_ANY
#define __UNIFORM_COLOR_INT3 __UNIFORM_COLOR_ANY
#define __UNIFORM_COLOR_INT4 __UNIFORM_COLOR_ANY
// __UNIFORM_COLOR_FLOAT1
#define __UNIFORM_COLOR_FLOAT2 __UNIFORM_COLOR_ANY
#define __UNIFORM_COLOR_FLOAT3 __UNIFORM_COLOR_ANY
#define __UNIFORM_COLOR_FLOAT4 __UNIFORM_COLOR_ANY
// >= 4.2.0
// Add alpha slider widget for single component uniform variables (#86)
// https://github.com/crosire/reshade/commit/87a740a8e3c4dcda1dd4eeec8d5cff7fa35fe829#diff-59405a313bd8cbfb0ca6dd633230e504R1820
// Added alpha slider widget for single component uniform variables
// https://reshade.me/forum/releases/5150-4-2
#if SUPPORTED_VERSION(4,2,0)
#define __UNIFORM_COLOR_FLOAT1 __UNIFORM_COLOR_ANY
#else
#define __UNIFORM_COLOR_FLOAT1 __UNIFORM_SLIDER_ANY
#endif
// >= 4.3.0
// Add new "list" GUI widget (#103)
// https://github.com/crosire/reshade/commit/515287d20ce615c19cf3d4c21b49f83896f04ddc#diff-59405a313bd8cbfb0ca6dd633230e504R1894
// Added new "list" GUI widget
// https://reshade.me/forum/releases/5417-4-3
#if SUPPORTED_VERSION(4,3,0)
#define __UNIFORM_LIST_ANY ui_type = "list";
#else
#define __UNIFORM_LIST_ANY __UNIFORM_COMBO_ANY
#endif
// __UNIFORM_LIST_BOOL1
#define __UNIFORM_LIST_BOOL2 __UNIFORM_LIST_ANY
#define __UNIFORM_LIST_BOOL3 __UNIFORM_LIST_ANY
#define __UNIFORM_LIST_BOOL4 __UNIFORM_LIST_ANY
#define __UNIFORM_LIST_INT1 __UNIFORM_LIST_ANY // >= 4.3.0
#define __UNIFORM_LIST_INT2 __UNIFORM_LIST_ANY
#define __UNIFORM_LIST_INT3 __UNIFORM_LIST_ANY
#define __UNIFORM_LIST_INT4 __UNIFORM_LIST_ANY
#define __UNIFORM_LIST_FLOAT1 __UNIFORM_LIST_ANY
#define __UNIFORM_LIST_FLOAT2 __UNIFORM_LIST_ANY
#define __UNIFORM_LIST_FLOAT3 __UNIFORM_LIST_ANY
#define __UNIFORM_LIST_FLOAT4 __UNIFORM_LIST_ANY
// For compatible with 'combo'
#define __UNIFORM_LIST_BOOL1 __UNIFORM_COMBO_ANY
@@ -0,0 +1,73 @@
////////////////////////////////////////////////////////////////////////////////
// Triangular Dither //
// By The Sandvich Maker //
// Ported to ReShade by TreyM //
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// //
// Usage: //
// Include this file in your shader like so: #include "TriDither.fx" //
// //
// For shader developers, use this syntax to do a function call in your //
// code as the last thing before exiting a given shader. You should dither //
// anytime data is going to be truncated to a lower bitdepth. Color input //
// must be a float3 value. //
// //
// input.rgb += TriDither(input.rgb, uv, bits); //
// //
// "bits" is an integer number that determines the bit depth //
// being dithered to. Usually 8, sometimes 10 //
// You can automate this by letting Reshade decide like so: //
// //
// input += TriDither(input, uv, BUFFER_COLOR_BIT_DEPTH); //
// //
// Manual setup looks something like this for an 8-bit backbuffer: //
// //
// input.rgb += TriDither(input.rgb, uv, 8); //
// //
////////////////////////////////////////////////////////////////////////////////
uniform float DitherTimer < source = "timer"; >;
#define remap(v, a, b) (((v) - (a)) / ((b) - (a)))
float rand21(float2 uv)
{
float2 noise = frac(sin(dot(uv, float2(12.9898, 78.233) * 2.0)) * 43758.5453);
return (noise.x + noise.y) * 0.5;
}
float rand11(float x)
{
return frac(x * 0.024390243);
}
float permute(float x)
{
return ((34.0 * x + 1.0) * x) % 289.0;
}
float3 TriDither(float3 color, float2 uv, int bits)
{
float bitstep = exp2(bits) - 1.0;
float lsb = 1.0 / bitstep;
float lobit = 0.5 / bitstep;
float hibit = (bitstep - 0.5) / bitstep;
float3 m = float3(uv, rand21(uv + (DitherTimer * 0.001))) + 1.0;
float h = permute(permute(permute(m.x) + m.y) + m.z);
float3 noise1, noise2;
noise1.x = rand11(h); h = permute(h);
noise2.x = rand11(h); h = permute(h);
noise1.y = rand11(h); h = permute(h);
noise2.y = rand11(h); h = permute(h);
noise1.z = rand11(h); h = permute(h);
noise2.z = rand11(h);
float3 lo = saturate(remap(color.xyz, 0.0, lobit));
float3 hi = saturate(remap(color.xyz, 1.0, hibit));
float3 uni = noise1 - 0.5;
float3 tri = noise1 - noise2;
return lerp(uni, tri, min(lo, hi)) * lsb;
}
@@ -0,0 +1,289 @@
/*
Simple UIMask shader by luluco250
I have no idea why this was never ported back to ReShade 3.0 from 2.0,
but if you missed it, here it is.
It doesn't feature the auto mask from the original shader.
It does feature a new multi-channnel masking feature. UI masks can now contain
separate 'modes' within each of the three color channels.
For example, you can have the regular hud on the red channel (the default one),
a mask for an inventory screen on the green channel and a mask for a quest menu
on the blue channel. You can then use keyboard keys to toggle each channel on or off.
Multiple channels can be active at once, they'll just add up to mask the image.
Simple/legacy masks are not affected by this, they'll work just as you'd expect,
so you can still make simple black and white masks that use all color channels, it'll
be no different than just having it on a single channel.
Tips:
--You can adjust how much it will affect your HUD by changing "Mask Intensity".
--You don't actually need to place the UIMask_Bottom technique at the bottom of
your shader pipeline, if you have any effects that don't necessarily affect
the visibility of the HUD you can place it before that.
For instance, if you use color correction shaders like LUT, you might want
to place UIMask_Bottom just before that.
--Preprocessor flags:
--UIMASK_MULTICHANNEL:
Enables having up to three different masks on each color channel.
--Refer to this page for keycodes:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
--To make a custom mask:
1-Take a screenshot of your game with the HUD enabled,
preferrably with any effects disabled for maximum visibility.
2-Open the screenshot with your preferred image editor program, I use GIMP.
3-Make a background white layer if there isn't one already.
Be sure to leave it behind your actual screenshot for the while.
4-Make an empty layer for the mask itself, you can call it "mask".
5-Having selected the mask layer, paint the places where HUD constantly is,
such as health bars, important messages, minimaps etc.
6-Delete or make your screenshot layer invisible.
7-Before saving your mask, let's do some gaussian blurring to improve it's look and feel:
For every step of blurring you want to do, make a new layer, such as:
Mask - Blur16x16
Mask - Blur8x8
Mask - Blur4x4
Mask - Blur2x2
Mask - NoBlur
You should use your image editor's default gaussian blurring filter, if there is one.
This avoids possible artifacts and makes the mask blend more easily on the eyes.
You may not need this if your mask is accurate enough and/or the HUD is simple enough.
8-Now save the final image with a unique name such as "MyUIMask.png" in your textures folder.
9-Set the preprocessor definition UIMASK_TEXTURE to the unique name of your image, with quotes.
You're done!
MIT Licensed:
Copyright (c) 2017 Lucas Melo
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.
*/
//#region Preprocessor
#include "ReShade.fxh"
#include "ReShadeUI.fxh"
#ifndef UIMASK_MULTICHANNEL
#define UIMASK_MULTICHANNEL 0
#endif
#if !UIMASK_MULTICHANNEL
#define TEXFORMAT R8
#else
#define TEXFORMAT RGBA8
#endif
#ifndef UIMASK_TEXTURE
#define UIMASK_TEXTURE "UIMask.png"
#endif
//#endregion
namespace UIMask
{
//#region Uniforms
uniform int _Help
<
ui_label = " ";
ui_text =
"For more detailed instructions, see the text at the top of this "
"effect's shader file (UIMask.fx).\n"
"\n"
"Available preprocessor definitions:\n"
" UIMASK_MULTICHANNEL:\n"
" If set to 1, each of the RGB color channels in the texture is "
"treated as a separate mask.\n"
"\n"
"How to create a mask:\n"
"\n"
"1. Take a screenshot with the game's UI appearing.\n"
"2. Open the screenshot in an image editor, GIMP or Photoshop are "
"recommended.\n"
"3. Create a new layer over the screenshot layer, fill it with black.\n"
"4. Reduce the layer opacity so you can see the screenshot layer "
"below.\n"
"5. Cover the UI with white to mask it from effects. The stronger the "
"mask white color, the more opaque the mask will be.\n"
"6. Set the mask layer opacity back to 100%.\n"
"7. Save the image in one of your texture folders, making sure to "
"use a unique name such as: \"MyUIMask.png\"\n"
"8. Set the preprocessor definition UIMASK_TEXTURE to the name of "
"your image, with quotes: \"MyUIMask.png\"\n"
;
ui_category = "Help";
ui_category_closed = true;
ui_type = "radio";
>;
uniform float fMask_Intensity
<
__UNIFORM_SLIDER_FLOAT1
ui_label = "Mask Intensity";
ui_tooltip =
"How much to mask effects from affecting the original image.\n"
"\nDefault: 1.0";
ui_min = 0.0;
ui_max = 1.0;
ui_step = 0.001;
> = 1.0;
uniform bool bDisplayMask <
ui_label = "Display Mask";
ui_tooltip =
"Display the mask texture.\n"
"Useful for testing multiple channels or simply the mask itself.\n"
"\nDefault: Off";
> = false;
#if UIMASK_MULTICHANNEL
uniform bool bToggleRed <
ui_label = "Toggle Red Channel";
ui_tooltip = "Toggle UI masking for the red channel.\n"
"Right click to assign a hotkey.\n"
"\nDefault: On";
> = true;
uniform bool bToggleGreen <
ui_label = "Toggle Green Channel";
ui_tooltip = "Toggle UI masking for the green channel.\n"
"Right click to assign a hotkey."
"\nDefault: On";
> = true;
uniform bool bToggleBlue <
ui_label = "Toggle Blue Channel";
ui_tooltip = "Toggle UI masking for the blue channel.\n"
"Right click to assign a hotkey."
"\nDefault: On";
> = true;
#endif
//#endregion
//#region Textures
texture BackupTex
{
Width = BUFFER_WIDTH;
Height = BUFFER_HEIGHT;
};
sampler Backup
{
Texture = BackupTex;
};
texture MaskTex <source=UIMASK_TEXTURE;>
{
Width = BUFFER_WIDTH;
Height = BUFFER_HEIGHT;
Format = TEXFORMAT;
};
sampler Mask
{
Texture = MaskTex;
};
//#endregion
//#region Shaders
float4 BackupPS(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target {
return tex2D(ReShade::BackBuffer, uv);
}
float4 MainPS(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target {
float4 color = tex2D(ReShade::BackBuffer, uv);
float4 backup = tex2D(Backup, uv);
#if !UIMASK_MULTICHANNEL
float mask = tex2D(Mask, uv).r;
#else
float3 mask_rgb = tex2D(Mask, uv).rgb;
// This just works, it basically adds masking with each channel that has
// been toggled.
float mask = saturate(
1.0 - dot(1.0 - mask_rgb,
float3(bToggleRed, bToggleGreen, bToggleBlue)));
#endif
color = lerp(color, backup, mask * fMask_Intensity);
color = bDisplayMask ? mask : color;
return color;
}
//#endregion
//#region Techniques
technique UIMask_Top
<
ui_tooltip = "Place this *above* the effects to be masked.";
>
{
pass
{
VertexShader = PostProcessVS;
PixelShader = BackupPS;
RenderTarget = BackupTex;
}
}
technique UIMask_Bottom
<
ui_tooltip =
"Place this *below* the effects to be masked.\n"
"If you want to add a toggle key for the effect, set it to this one.";
>
{
pass
{
VertexShader = PostProcessVS;
PixelShader = MainPS;
}
}
//#endregion
} // Namespace.
@@ -0,0 +1,252 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : lumenite_ColorManagement.fxh
Version : 2026.05.05
Author : Afzaal (Kaidō)
Description: Provides color management including color space detection,
color space transfers and tonemapping.
Supported colorbuffers:
- SDR (sRGB)
- HDR (scRGB / Linear)
- HDR (PQ / ST.2084)
- HDR (HLG)
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
#pragma once
/*-------------------.
| :: PREPROCESSOR :: |
'-------------------*/
#ifndef HDR_WHITELEVEL
#define HDR_WHITELEVEL 203
#endif
#if BUFFER_COLOR_SPACE > 0
//already defined by ReShade
#else
#if BUFFER_COLOR_BIT_DEPTH == 8
#undef BUFFER_COLOR_SPACE
#define BUFFER_COLOR_SPACE 1 //sRGB
#elif BUFFER_COLOR_BIT_DEPTH == 16
#undef BUFFER_COLOR_SPACE
#define BUFFER_COLOR_SPACE 2 //scRGB
#elif __RENDERER__ < 0xb000
#undef BUFFER_COLOR_SPACE
#define BUFFER_COLOR_SPACE 1 //D3D9/10 usually SDR
#endif
#endif
/*------------------.
| :: UI UNIFORMS :: |
'------------------*/
// uniform int SHOW_COLOR_SPACE <
// ui_category = "Color Management";
// ui_type = "combo";
// ui_label = "Colorspace";
// ui_tooltip = "Shows the detected color space.\n1=sRGB, 2=scRGB, 3=PQ, 4=HLG";
// hidden = true;
// #if BUFFER_COLOR_SPACE == 1
// ui_items = "sRGB (Detected)\0";
// #elif BUFFER_COLOR_SPACE == 2
// ui_items = "scRGB (Detected)\0";
// #elif BUFFER_COLOR_SPACE == 3
// ui_items = "PQ / ST.2084 (Detected)\0";
// #elif BUFFER_COLOR_SPACE == 4
// ui_items = "HLG (Detected)\0";
// #else
// ui_items = "Unknown (Defaulting to sRGB)\0";
// #endif
// > = 0;
#if BUFFER_COLOR_BIT_DEPTH > 8 || BUFFER_COLOR_SPACE > 1
#define COLORSPACE_CONVERSION 1 //use approx. transfer function; 0 for accurate
#else
#define COLORSPACE_CONVERSION 2 //N/A for 8-bit
#endif
#if BUFFER_COLOR_SPACE == 1
#define TONEMAPPER 1 //reinhard tonemapper workflow for SDR (sRGB) colorbuffer; 0 for None
#else
#define TONEMAPPER 0
#endif
/*-------------------------.
| :: TRANSFER FUNCTIONS :: |
'-------------------------*/
//sRGB
float3 sRGBtoLinearAccurate(float3 r) {
return (r <= 0.04045) ? (r / 12.92) : pow(abs(r + 0.055) / 1.055, 2.4);
}
float3 sRGBtoLinearFast(float3 r) {
return max(r / 12.92, r * r); //gamma 2.0 approx
}
float3 sRGBtoLinear(float3 r) {
if (COLORSPACE_CONVERSION == 1) return sRGBtoLinearFast(r);
else return sRGBtoLinearAccurate(r);
}
float3 linearToSRGBAccurate(float3 r) {
return (r <= 0.0031308) ? (r * 12.92) : (1.055 * pow(abs(r), 1.0 / 2.4) - 0.055);
}
float3 linearToSRGBFast(float3 r) {
return min(r * 12.92, sqrt(r)); //gamma 2.0 approx
}
float3 linearToSRGB(float3 r) {
if (COLORSPACE_CONVERSION == 1) return linearToSRGBFast(r);
else return linearToSRGBAccurate(r);
}
//PQ (ST.2084)
float3 PQtoLinearAccurate(float3 r) {
const float m1 = 1305.0/8192.0;
const float m2 = 2523.0/32.0;
const float c1 = 107.0/128.0;
const float c2 = 2413.0/128.0;
const float c3 = 2392.0/128.0;
float3 powr = pow(max(r, 0), 1.0/m2);
r = pow(max(max(powr - c1, 0) / (c2 - c3 * powr), 0), 1.0/m1);
//scale 10,000 nits down so Paper White (HDR_WHITELEVEL) maps to 1.0
return r * 10000.0 / HDR_WHITELEVEL;
}
float3 PQtoLinearFast(float3 r) {
float3 square = r * r;
float3 quad = square * square;
float3 oct = quad * quad;
r = max(max(square / 340.0, quad / 6.0), oct);
return r * 10000.0 / HDR_WHITELEVEL;
}
float3 PQtoLinear(float3 r) {
if (COLORSPACE_CONVERSION == 1) return PQtoLinearFast(r);
else return PQtoLinearAccurate(r);
}
float3 linearToPQAccurate(float3 r) {
const float m1 = 1305.0/8192.0;
const float m2 = 2523.0/32.0;
const float c1 = 107.0/128.0;
const float c2 = 2413.0/128.0;
const float c3 = 2392.0/128.0;
r = r * (HDR_WHITELEVEL / 10000.0); //rescale 1.0 back to nits
float3 powr = pow(max(r, 0), m1);
r = pow(max((c1 + c2 * powr) / (1 + c3 * powr), 0), m2);
return r;
}
float3 linearToPQFast(float3 r) {
r = r * (HDR_WHITELEVEL / 10000.0);
float3 squareroot = sqrt(r);
float3 quadroot = sqrt(squareroot);
float3 octroot = sqrt(quadroot);
r = min(octroot, min(sqrt(sqrt(6.0))*quadroot, sqrt(340.0)*squareroot));
return r;
}
float3 linearToPQ(float3 r) {
if (COLORSPACE_CONVERSION == 1) return linearToPQFast(r);
else return linearToPQAccurate(r);
}
//HLG (Hybrid Log Gamma)
float3 linearToHLG(float3 r) {
r = r * HDR_WHITELEVEL / 1000.0;
const float a = 0.17883277;
const float b = 0.28466892;
const float c = 0.55991073;
float3 s = sqrt(3 * r);
return (s < 0.5) ? s : (log(12 * r - b) * a + c);
}
float3 HLGtoLinear(float3 r) {
const float a = 0.17883277;
const float b = 0.28466892;
const float c = 0.55991073;
r = (r < 0.5) ? (r * r / 3.0) : ((exp((r - c) / a) + b) / 12.0);
return r * 1000.0 / HDR_WHITELEVEL;
}
//YCoCg
float3 linearToYCoCg(float3 r) {
float y = (r.r + 2.0 * r.g + r.b) * 0.25;
float co = (r.r - r.b) * 0.5;
float cg = (r.g - (r.r + r.b) * 0.5) * 0.5;
return float3(y, co, cg);
}
float3 YCoCgToLinear(float3 r) {
float y = r.x;
float co = r.y;
float cg = r.z;
float g = y + cg;
float rOut = y + co - cg;
float b = y - co - cg;
return float3(rOut, g, b);
}
/*--------------.
| :: HELPERS :: |
'--------------*/
float3 ToLinearColorspace(float3 r, bool tonemap) {
if (BUFFER_COLOR_SPACE == 2) r = r * (80.0 / HDR_WHITELEVEL); //scRGB
else if (BUFFER_COLOR_SPACE == 3) r = PQtoLinear(r);
else if (BUFFER_COLOR_SPACE == 4) r = HLGtoLinear(r);
else {
r = sRGBtoLinear(r);
if (TONEMAPPER == 1 && tonemap) r = r / max(1.0 - r, 0.001); //inverse reinhard
}
return r;
}
float3 ToOutputColorspace(float3 r, bool tonemap) {
if (BUFFER_COLOR_SPACE == 2) r = r * (HDR_WHITELEVEL / 80.0); //scRGB
else if (BUFFER_COLOR_SPACE == 3) r = linearToPQ(r);
else if (BUFFER_COLOR_SPACE == 4) r = linearToHLG(r);
else {
if (TONEMAPPER == 1 && tonemap) r = r / (1.0 + r); //forward reinhard
r = linearToSRGB(r);
}
return r;
}
//read the theoretical max value of the buffer (in linear scale)
float GetMaxColorValue() {
if (BUFFER_COLOR_SPACE == 4) return 1000.0 / HDR_WHITELEVEL;
if (BUFFER_COLOR_SPACE >= 2) return 10000.0 / HDR_WHITELEVEL;
return 1.0;
}
float GetLuminance(float3 color)
{
return dot(color, float3(0.2126, 0.7152, 0.0722));
}
float3 GetLinearColor(float2 uv, bool tonemap)
{
float3 color = tex2Dlod(ReShade::BackBuffer, float4(uv, 0, 0)).rgb;
return ToLinearColorspace(color, tonemap);
}
@@ -0,0 +1,54 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : lumenite_Compute.fxh
Version : 2026.05.09
Author : Afzaal (Kaidō)
Description: Header file for supporting compute enabled platforms.
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
#pragma once
#include "ReShade.fxh"
/*------------------.
| :: DEFINITIONS :: |
'------------------*/
#define D3D9 0x9000
#define D3D10 0xa000
#define D3D11 0xb000
#define D3D12 0xc000
#define OPENGL 0x10000
#define VULKAN 0x20000
#if __RENDERER__ >= D3D11
#define _COMPUTE_ENABLED_ 1
#else
#define _COMPUTE_ENABLED_ 0
#endif
struct CSInput
{
uint3 dispatchID : SV_DispatchThreadID; //global pixel coord (x, y, 0)
uint3 groupID : SV_GroupID; //which tile/group in grid
uint3 localID : SV_GroupThreadID; //thread inside group [0..CS_W-1]
uint flatIndex : SV_GroupIndex; //localID flattened: y*CS_W + x
};
@@ -0,0 +1,94 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : lumenite_Helpers.fxh
Version : 2026.05.30
Author : Afzaal (Kaidō)
Description: Helper functions for Lumenite shaders.
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
#pragma once
#include "ReShade.fxh"
/*------------------.
| :: DEFINITIONS :: |
'------------------*/
#define PI 3.14159265359
#define EPSILON 1e-6
//R2 sequence constants
static const float PHI_2 = 1.324717957244746;
static const float2 R2_CONSTANT = float2(1.0/PHI_2, 1.0/(PHI_2*PHI_2));
/*--------------.
| :: UNIFORMS ::|
'--------------*/
uniform float TIMER < source = "timer"; >; //ms since launch
uniform float FRAME_TIME < source = "frametime"; >; //ms last frame
uniform uint FRAME_COUNT < source = "framecount"; >;
uniform float2 MOUSE_POS < source = "mousepoint"; >; //in screen px
uniform bool MOUSE_DOWN < source = "mousebutton"; min = 0; max = 0; >;
/*--------------.
| :: HELPERS :: |
'--------------*/
bool CheckerboardSkip(uint2 currentPos, float scale)
{
//map current buffer pixel to full screen pixel.
//floor() to ensure we snap to the integer grid of the full screen
uint2 fullScreenPos = uint2(floor(currentPos.x * scale), floor(currentPos.y * scale));
return (((fullScreenPos.x + fullScreenPos.y + (FRAME_COUNT & 1)) & 1) == 1);
}
float GetDepth(float2 uv)
{
return ReShade::GetLinearizedDepth(uv);
}
bool IsOOB(float2 uv) {
return any(uv < 0.0) || any(uv > 1.0);
}
//QUASI-MONTE CARLO SEQUENCE
//fast Hilbert curve math (a 1D index from 2D coords)
uint HilbertIndex(uint x, uint y) {
uint index = 0;
[unroll] for (uint s = 64 / 2; s > 0; s /= 2) {
uint rx = (x & s) > 0;
uint ry = (y & s) > 0;
index += s * s * ((3 * rx) ^ ry);
if (ry == 0) {
if (rx == 1) {
x = 64 - 1 - x;
y = 64 - 1 - y;
}
uint t = x; x = y; y = t;
}
}
return index;
}
float2 GetStratifiedNoise(float2 vpos) {
uint2 screenPos = uint2(vpos.xy) % 64; //64x64 tiled pixel coords
uint hIndex = HilbertIndex(screenPos.x, screenPos.y); //Hilbert index (spatial)
uint totalIndex = hIndex + (uint(FRAME_COUNT % 64) * 288); //temporal offset: 288 (same as Intel XeGTAO implementation)
return frac(float(totalIndex) * R2_CONSTANT);
}
@@ -0,0 +1,96 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : lumenite_Projections.fxh
Version : 2026.04.11
Author : Afzaal (Kaidō)
Description: Camera projection functions for Lumenite shaders.
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
#pragma once
#include "ReShade.fxh"
/*--------------.
| :: HELPERS :: |
'--------------*/
//VERTEX SHADER
struct VSOUT
{
float4 vpos : SV_Position;
float2 uv : TEXCOORD0;
float tan_half_fov_x : TEXCOORD1;
float tan_half_fov_y : TEXCOORD2;
float inv_tan_half_fov_x : TEXCOORD3;
float inv_tan_half_fov_y : TEXCOORD4;
float near_ratio : TEXCOORD5;
float diff_ratio : TEXCOORD6;
};
#define TAN_HALF_FOV_Y tan(radians(FOV * 0.5))
#define ASPECT_RATIO_X_OVER_Y ((float)BUFFER_WIDTH / (float)BUFFER_HEIGHT)
#define TAN_HALF_FOV_X TAN_HALF_FOV_Y * ASPECT_RATIO_X_OVER_Y
#define INV_TAN_HALF_FOV_X rcp(TAN_HALF_FOV_X)
#define INV_TAN_HALF_FOV_Y rcp(TAN_HALF_FOV_Y)
VSOUT VS(uint id : SV_VertexID)
{
VSOUT o;
o.uv.x = (id == 2) ? 2.0 : 0.0;
o.uv.y = (id == 1) ? 2.0 : 0.0;
o.vpos = float4(mad(o.uv.x, 2.0, -1.0), mad(o.uv.y, -2.0, 1.0), 0.0, 1.0);
o.tan_half_fov_x = TAN_HALF_FOV_X;
o.tan_half_fov_y = TAN_HALF_FOV_Y;
o.inv_tan_half_fov_x = INV_TAN_HALF_FOV_X;
o.inv_tan_half_fov_y = INV_TAN_HALF_FOV_Y;
o.near_ratio = NEAR_PLANE / RESHADE_DEPTH_LINEARIZATION_FAR_PLANE;
o.diff_ratio = 1.0 - o.near_ratio; //lerp(a,b,t) = (a+t * (b-a)), precompute (b-a) or (1.0-near_ratio) here
return o;
}
//PROJECTION FUNCTIONS
//normalized frustum
//left-handed viewspace
//normals point outwards
//Z+ goes into the screen
float3 UVToViewSpace(float2 uv, float linear_depth_vs, VSOUT ps_input)
{
float projection_scale = mad(linear_depth_vs, ps_input.diff_ratio, ps_input.near_ratio); //faster lerp: a+t * diff
float3 view_pos;
float ndc_x = mad(uv.x, 2.0, -1.0);
float ndc_y = mad(uv.y, -2.0, 1.0);
view_pos.x = ndc_x * ps_input.tan_half_fov_x * projection_scale;
view_pos.y = ndc_y * ps_input.tan_half_fov_y * projection_scale;
view_pos.z = linear_depth_vs;
return view_pos;
}
float2 ViewSpaceToUV(float3 view_pos, VSOUT ps_input)
{
float inv_projection_scale = rcp(mad(view_pos.z, ps_input.diff_ratio, ps_input.near_ratio));
float2 ndc;
ndc.x = view_pos.x * ps_input.inv_tan_half_fov_x * inv_projection_scale;
ndc.y = view_pos.y * ps_input.inv_tan_half_fov_y * inv_projection_scale;
float2 uv;
uv.x = mad(ndc.x, 0.5, 0.5);
uv.y = mad(ndc.y, -0.5, 0.5);
return uv;
}
@@ -0,0 +1,511 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : lumenite_AnamorphicBloom.fx
Version : 2026.06.09
Author : Afzaal (Kaidō)
Description: Artistic bloom approximating the Anamorphic lens aesthetic.
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
/*------------------.
| :: DEFINITIONS :: |
'------------------*/
#ifndef ANAMORPHIC_BLOOM
#define ANAMORPHIC_BLOOM 1
#endif
#ifndef ANAMORPHIC_STREAKS
#define ANAMORPHIC_STREAKS 0
#endif
#ifndef COLOR_FRINGING
#define COLOR_FRINGING 0
#endif
#define BLOOM_THRESHOLD_SCALER 10.0
/*--------------.
| :: HEADERS :: |
'--------------*/
#include "ReShade.fxh"
#include "./include/lumenite_ColorManagement.fxh"
#include "./include/lumenite_Helpers.fxh"
/*---------------.
| :: UNIFORMS :: |
'---------------*/
#if ANAMORPHIC_BLOOM
uniform bool BLOOM_SKIP_SKYBOX <
ui_type = "radio";
ui_label = "Exclude Skybox (Bloom)";
ui_tooltip = "Prevents sky pixels from contributing to bloom.";
ui_category = "Anamorphic Bloom";
> = false;
uniform bool BLOOM_SHARP <
ui_type = "radio";
ui_label = "Add More Definition to Bloom Shape (Experimental)";
ui_tooltip = "Enables a sharper 1D horizontal kernel. May flicker with camera movement.";
ui_category = "Anamorphic Bloom";
> = false;
uniform float BLOOM_INTENSITY <
ui_type = "drag";
ui_min = 0.0; ui_max = 1.0; ui_step = 0.01;
ui_label = "Bloom Intensity";
ui_tooltip = "Scales the intensity of the Bloom effect.";
ui_category = "Anamorphic Bloom";
> = 1.0;
uniform float BLOOM_THRESHOLD <
ui_type = "drag";
ui_min = 0.0; ui_max = 1.0; ui_step = 0.01;
ui_label = "Bloom Threshold";
ui_tooltip = "Higher values bloom more of the scene.";
ui_category = "Anamorphic Bloom";
> = 0.7;
uniform float BLOOM_STRETCH <
ui_type = "drag";
ui_min = 0.0; ui_max = 7.5; ui_step = 0.01;
ui_label = "Bloom Stretch";
ui_tooltip = "Adjusts the horizontal elongation of the Bloom effect.";
ui_category = "Anamorphic Bloom";
> = 7.5;
#if COLOR_FRINGING
uniform float BLOOM_CA <
ui_type = "drag";
ui_min = 0.0; ui_max = 10.0; ui_step = 0.01;
ui_label = "Bloom Chromatic Shift";
ui_tooltip = "Shifts R/B channels within the bloom passes.";
ui_category = "Anamorphic Bloom";
> = 10.0;
#endif
#endif
#if ANAMORPHIC_STREAKS
uniform bool STREAK_SKIP_SKYBOX <
ui_type = "radio";
ui_label = "Exclude Skybox (Streaks)";
ui_tooltip = "Prevents sky pixels from contributing to light streaks.";
ui_category = "Anamorphic Streaks";
> = false;
uniform float STREAK_INTENSITY <
ui_type = "drag";
ui_min = 0.0; ui_max = 1.0; ui_step = 0.01;
ui_label = "Streak Intensity";
ui_tooltip = "Scales the intensity of the light streaks.";
ui_category = "Anamorphic Streaks";
> = 1.0;
uniform float STREAK_THRESHOLD <
ui_type = "drag";
ui_min = 0.0; ui_max = 1.0; ui_step = 0.01;
ui_label = "Streak Threshold";
ui_tooltip = "Higher values considers more of the scene.";
ui_category = "Anamorphic Streaks";
> = 0.5;
uniform float STREAK_STRETCH <
ui_type = "drag";
ui_min = 0.0; ui_max = 10.0; ui_step = 0.01;
ui_label = "Streak Stretch";
ui_tooltip = "Adjusts the horizontal elongation of the light streaks.";
ui_category = "Anamorphic Streaks";
> = 10.0;
uniform float3 STREAK_TINT <
ui_type = "color";
ui_label = "Tint";
ui_tooltip = "Tints the light streaks with chosen color. Set to white (1, 1, 1) for pass-through.";
ui_category = "Anamorphic Streaks";
> = float3(0.55, 0.55, 1.0);
#if COLOR_FRINGING
uniform float STREAK_CA <
ui_type = "drag";
ui_min = 0.0; ui_max = 10.0; ui_step = 0.01;
ui_label = "Streak Chromatic Shift";
ui_tooltip = "Shifts R/B channels of the light streaks.";
ui_category = "Anamorphic Streaks";
> = 10.0;
#endif
#endif
uniform int USER_GUIDE <
ui_type = "radio";
ui_category = "";
ui_label = " ";
ui_text = "Exclude Skybox: Requires access to properly configured depth buffer.";
>;
namespace LumeniteAnamorphicBloom {
/*-------------.
| :: MACROS :: |
'-------------*/
#if ANAMORPHIC_BLOOM
#define BLOOM_SHIFT (float2(BLOOM_CA * BUFFER_PIXEL_SIZE.x, 0.0)) //once per pass
#if COLOR_FRINGING
#define SAMPLE_BLOOM_TEX(s, uv) float3( \
tex2D(s, (uv) - BLOOM_SHIFT).r, \
tex2D(s, (uv)).g, \
tex2D(s, (uv) + BLOOM_SHIFT).b \
)
#else
#define SAMPLE_BLOOM_TEX(s, uv) tex2D(s, uv).rgb
#endif
#endif
#if ANAMORPHIC_STREAKS
#define STREAK_SHIFT (STREAK_CA * BUFFER_PIXEL_SIZE.x)
#if COLOR_FRINGING
#define SAMPLE_STREAK_TEX(s, uv, o) float3( \
tex2D(s, uv + float2(o - STREAK_SHIFT, 0.0)).r, \
tex2D(s, uv + float2(o, 0.0)).g, \
tex2D(s, uv + float2(o + STREAK_SHIFT, 0.0)).b \
)
#else
#define SAMPLE_STREAK_TEX(s, uv, o) tex2D(s, uv + float2(o, 0.0)).rgb
#endif
#endif
/*---------------------.
| :: RENDER TARGETS :: |
'---------------------*/
texture2D tUnpackedColor { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; };
sampler2D sUnpackedColor { Texture = tUnpackedColor; };
#if ANAMORPHIC_BLOOM
texture2D tBloomDown0 { Width = BUFFER_WIDTH/2; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler2D sBloomDown0 { Texture = tBloomDown0; };
texture2D tBloomDown1 { Width = BUFFER_WIDTH/4; Height = BUFFER_HEIGHT/4; Format = RGBA16F; };
sampler2D sBloomDown1 { Texture = tBloomDown1; };
texture2D tBloomDown2 { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RGBA16F; };
sampler2D sBloomDown2 { Texture = tBloomDown2; };
texture2D tBloomDown3 { Width = BUFFER_WIDTH/16; Height = BUFFER_HEIGHT/16; Format = RGBA16F; };
sampler2D sBloomDown3 { Texture = tBloomDown3; };
texture2D tBloomDown4 { Width = BUFFER_WIDTH/32; Height = BUFFER_HEIGHT/32; Format = RGBA16F; };
sampler2D sBloomDown4 { Texture = tBloomDown4; };
texture2D tBloomUp3 { Width = BUFFER_WIDTH/16; Height = BUFFER_HEIGHT/16; Format = RGBA16F; };
sampler2D sBloomUp3 { Texture = tBloomUp3; };
texture2D tBloomUp2 { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RGBA16F; };
sampler2D sBloomUp2 { Texture = tBloomUp2; };
texture2D tBloomUp1 { Width = BUFFER_WIDTH/4; Height = BUFFER_HEIGHT/4; Format = RGBA16F; };
sampler2D sBloomUp1 { Texture = tBloomUp1; };
texture2D tBloomUp0 { Width = BUFFER_WIDTH/2; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler2D sBloomUp0 { Texture = tBloomUp0; };
texture2D tBloomUp4 { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; };
sampler2D sBloomUp4 { Texture = tBloomUp4; };
#endif
#if ANAMORPHIC_STREAKS
texture2D tStreakDown0 { Width = BUFFER_WIDTH/2; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler2D sStreakDown0 { Texture = tStreakDown0; };
texture2D tStreakDown1 { Width = BUFFER_WIDTH/4; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler2D sStreakDown1 { Texture = tStreakDown1; };
texture2D tStreakDown2 { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler2D sStreakDown2 { Texture = tStreakDown2; };
texture2D tStreakDown3 { Width = BUFFER_WIDTH/16; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler2D sStreakDown3 { Texture = tStreakDown3; };
texture2D tStreakDown4 { Width = BUFFER_WIDTH/32; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler2D sStreakDown4 { Texture = tStreakDown4; };
texture2D tStreakUp3 { Width = BUFFER_WIDTH/16; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler2D sStreakUp3 { Texture = tStreakUp3; };
texture2D tStreakUp2 { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler2D sStreakUp2 { Texture = tStreakUp2; };
texture2D tStreakUp1 { Width = BUFFER_WIDTH/4; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler2D sStreakUp1 { Texture = tStreakUp1; };
texture2D tStreakUp0 { Width = BUFFER_WIDTH/2; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler2D sStreakUp0 { Texture = tStreakUp0; };
#endif
/*--------------.
| :: HELPERS :: |
'--------------*/
#if ANAMORPHIC_BLOOM
float3 TentFilter13Anisotropic(sampler2D src, float2 uv, float2 radius)
{
float dx = radius.x;
float dy = radius.y;
[branch] if (BLOOM_SHARP)
{
float3 center = SAMPLE_BLOOM_TEX(src, uv);
float3 innerLeft = SAMPLE_BLOOM_TEX(src, uv + float2(-dx, 0));
float3 innerRight = SAMPLE_BLOOM_TEX(src, uv + float2( dx, 0));
float3 outerLeft = SAMPLE_BLOOM_TEX(src, uv + float2(-2*dx, 0));
float3 outerRight = SAMPLE_BLOOM_TEX(src, uv + float2( 2*dx, 0));
return center * 0.25 + (innerLeft + innerRight) * 0.25 + (outerLeft + outerRight) * 0.125;
}
float3 a = SAMPLE_BLOOM_TEX(src, uv + float2(-2*dx, 2*dy)).rgb;
float3 b = SAMPLE_BLOOM_TEX(src, uv + float2( 0, 2*dy)).rgb;
float3 c = SAMPLE_BLOOM_TEX(src, uv + float2( 2*dx, 2*dy)).rgb;
float3 d = SAMPLE_BLOOM_TEX(src, uv + float2(-2*dx, 0)).rgb;
float3 e = SAMPLE_BLOOM_TEX(src, uv + float2( 0, 0)).rgb;
float3 f = SAMPLE_BLOOM_TEX(src, uv + float2( 2*dx, 0)).rgb;
float3 g = SAMPLE_BLOOM_TEX(src, uv + float2(-2*dx, -2*dy)).rgb;
float3 h = SAMPLE_BLOOM_TEX(src, uv + float2( 0, -2*dy)).rgb;
float3 i = SAMPLE_BLOOM_TEX(src, uv + float2( 2*dx, -2*dy)).rgb;
float3 j = SAMPLE_BLOOM_TEX(src, uv + float2(-dx, dy)).rgb;
float3 k = SAMPLE_BLOOM_TEX(src, uv + float2( dx, dy)).rgb;
float3 l = SAMPLE_BLOOM_TEX(src, uv + float2(-dx, -dy)).rgb;
float3 m = SAMPLE_BLOOM_TEX(src, uv + float2( dx, -dy)).rgb;
return e * 0.125 + (a + c + g + i) * 0.03125 + (b + d + f + h) * 0.0625 + (j + k + l + m) * 0.125;
}
float3 TentFilter9Anisotropic(sampler2D src, float2 uv, float2 radius)
{
float dx = radius.x;
float dy = radius.y;
[branch] if (BLOOM_SHARP)
{
float3 center = SAMPLE_BLOOM_TEX(src, uv);
float3 left = SAMPLE_BLOOM_TEX(src, uv + float2(-dx, 0));
float3 right = SAMPLE_BLOOM_TEX(src, uv + float2( dx, 0));
return center * 0.5 + (left + right) * 0.25;
}
float3 a = SAMPLE_BLOOM_TEX(src, uv + float2(-dx, dy)).rgb;
float3 b = SAMPLE_BLOOM_TEX(src, uv + float2( 0, dy)).rgb;
float3 c = SAMPLE_BLOOM_TEX(src, uv + float2( dx, dy)).rgb;
float3 d = SAMPLE_BLOOM_TEX(src, uv + float2(-dx, 0)).rgb;
float3 e = SAMPLE_BLOOM_TEX(src, uv + float2( 0, 0)).rgb;
float3 f = SAMPLE_BLOOM_TEX(src, uv + float2( dx, 0)).rgb;
float3 g = SAMPLE_BLOOM_TEX(src, uv + float2(-dx, -dy)).rgb;
float3 h = SAMPLE_BLOOM_TEX(src, uv + float2( 0, -dy)).rgb;
float3 i = SAMPLE_BLOOM_TEX(src, uv + float2( dx, -dy)).rgb;
return (e * 4.0 + (b + d + f + h) * 2.0 + (a + c + g + i)) * 0.0625;
}
#endif
#if ANAMORPHIC_STREAKS
float3 StreakFilter(sampler2D src, float2 uv, float radius)
{
float dx = BUFFER_PIXEL_SIZE.x * radius;
return SAMPLE_STREAK_TEX(src, uv, -dx * 2.0) * 0.1 +
SAMPLE_STREAK_TEX(src, uv, -dx) * 0.25 +
SAMPLE_STREAK_TEX(src, uv, 0.0) * 0.3 +
SAMPLE_STREAK_TEX(src, uv, dx) * 0.25 +
SAMPLE_STREAK_TEX(src, uv, dx * 2.0) * 0.1;
}
#endif
/*--------------.
| :: SHADERS :: |
'--------------*/
float4 PS_StoreUnpackedColor(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return float4(GetLinearColor(uv, false), 1);
}
#if ANAMORPHIC_BLOOM
//downsample with anisotropic blur (13-tap)
float4 PS_BloomDownsample0(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float2 radius = float2(BLOOM_STRETCH, 1.0) * BUFFER_PIXEL_SIZE;
float3 downsample = TentFilter13Anisotropic(sUnpackedColor, uv, radius);
if (BLOOM_SKIP_SKYBOX) downsample *= (GetDepth(uv) < 1.0);
downsample = downsample * smoothstep(0.0, max(1.0 - BLOOM_THRESHOLD, 0.07)*BLOOM_THRESHOLD_SCALER, GetLuminance(downsample));
return float4(downsample, 1);
}
float4 PS_BloomDownsample1(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float2 radius = float2(BLOOM_STRETCH, 1.0) * BUFFER_PIXEL_SIZE * 2.0;
return float4(TentFilter13Anisotropic(sBloomDown0, uv, radius), 1);
}
float4 PS_BloomDownsample2(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float2 radius = float2(BLOOM_STRETCH, 1.0) * BUFFER_PIXEL_SIZE * 4.0;
return float4(TentFilter13Anisotropic(sBloomDown1, uv, radius), 1);
}
float4 PS_BloomDownsample3(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float2 radius = float2(BLOOM_STRETCH, 1.0) * BUFFER_PIXEL_SIZE * 8.0;
return float4(TentFilter13Anisotropic(sBloomDown2, uv, radius), 1);
}
float4 PS_BloomDownsample4(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float2 radius = float2(BLOOM_STRETCH, 1.0) * BUFFER_PIXEL_SIZE * 16.0;
return float4(TentFilter13Anisotropic(sBloomDown3, uv, radius), 1);
}
//upsample with anisotropic blur (9-tap)
float4 PS_BloomUpsample0(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float2 radius = float2(BLOOM_STRETCH, 0.0) * BUFFER_PIXEL_SIZE * 32.0 * float2(1.0, rcp(BUFFER_ASPECT_RATIO));
float3 upsample = TentFilter9Anisotropic(sBloomDown4, uv, radius);
float3 previous = tex2D(sBloomDown3, uv).rgb;
return float4(upsample + previous, 1);
}
float4 PS_BloomUpsample1(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float2 radius = float2(BLOOM_STRETCH, 0.0) * BUFFER_PIXEL_SIZE * 16.0 * float2(1.0, rcp(BUFFER_ASPECT_RATIO));
float3 upsample = TentFilter9Anisotropic(sBloomUp3, uv, radius);
float3 previous = tex2D(sBloomDown2, uv).rgb;
return float4(upsample + previous, 1);
}
float4 PS_BloomUpsample2(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float2 radius = float2(BLOOM_STRETCH, 0.0) * BUFFER_PIXEL_SIZE * 8.0 * float2(1.0, rcp(BUFFER_ASPECT_RATIO));
float3 upsample = TentFilter9Anisotropic(sBloomUp2, uv, radius);
float3 previous = tex2D(sBloomDown1, uv).rgb;
return float4(upsample + previous, 1);
}
float4 PS_BloomUpsample3(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float2 radius = float2(BLOOM_STRETCH, 0.0) * BUFFER_PIXEL_SIZE * 4.0 * float2(1.0, rcp(BUFFER_ASPECT_RATIO));
float3 upsample = TentFilter9Anisotropic(sBloomUp1, uv, radius);
float3 previous = tex2D(sBloomDown0, uv).rgb;
return float4(upsample + previous, 1);
}
float4 PS_BloomUpsample4(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float2 radius = float2(BLOOM_STRETCH, 0.0) * BUFFER_PIXEL_SIZE * 2.0 * float2(1.0, rcp(BUFFER_ASPECT_RATIO));
float3 upsample = TentFilter9Anisotropic(sBloomUp0, uv, radius);
float3 previous = tex2D(sBloomDown0, uv).rgb;
return float4(upsample + previous, 1);
}
#endif
#if ANAMORPHIC_STREAKS
//thresholding pass
float4 PS_Prefilter(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float3 color = tex2D(sUnpackedColor, uv).rgb;
if (STREAK_SKIP_SKYBOX) color *= (GetDepth(uv) < 1.0);
float br = max(color.r, max(color.g, color.b));
float nm = max(0.0, br - (1.0 - STREAK_THRESHOLD));
return float4(color * (nm / max(br, 0.0001)), 1.0);
}
float4 PS_StreakDownsample0(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target { return float4(StreakFilter(sStreakDown0, uv, 1.0 * STREAK_STRETCH), 1); }
float4 PS_StreakDownsample1(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target { return float4(StreakFilter(sStreakDown1, uv, 2.0 * STREAK_STRETCH), 1); }
float4 PS_StreakDownsample2(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target { return float4(StreakFilter(sStreakDown2, uv, 4.0 * STREAK_STRETCH), 1); }
float4 PS_StreakDownsample3(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target { return float4(StreakFilter(sStreakDown3, uv, 8.0 * STREAK_STRETCH), 1); }
float4 PS_StreakUpsample0(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target { return float4(StreakFilter(sStreakUp3, uv, 8.0 * STREAK_STRETCH) + tex2D(sStreakDown2, uv).rgb, 1); }
float4 PS_StreakUpsample1(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target { return float4(StreakFilter(sStreakUp2, uv, 4.0 * STREAK_STRETCH) + tex2D(sStreakDown1, uv).rgb, 1); }
float4 PS_StreakUpsample2(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target { return float4(StreakFilter(sStreakUp1, uv, 2.0 * STREAK_STRETCH) + tex2D(sStreakDown0, uv).rgb, 1); }
float4 PS_StreakUpsample3(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target { return float4(StreakFilter(sStreakDown4, uv, 16.0 * STREAK_STRETCH) + tex2D(sStreakDown3, uv).rgb, 1); }
#endif
float4 PS_ToDisplay(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float3 unpackedColor = tex2D(sUnpackedColor, uv).rgb;
float3 light = 0;
#if ANAMORPHIC_BLOOM
light = tex2D(sBloomUp4, uv).rgb * BLOOM_INTENSITY;
#endif
#if ANAMORPHIC_STREAKS
light = max(light, tex2D(sStreakUp0, uv).rgb * STREAK_TINT * STREAK_INTENSITY);
#endif
float3 toDisplay;
#if (BUFFER_COLOR_SPACE == 1)
//sRGB colorspace
toDisplay = 1.0 - (1.0 - unpackedColor) * (1.0 - light);
#else
toDisplay = unpackedColor + light;
#endif
toDisplay = ToOutputColorspace(toDisplay, false);
return float4(toDisplay, 1);
}
/*----------------.
| :: TECHNIQUE :: |
'----------------*/
technique Lumenite_AnamorphicBloom <
ui_label = "LUMENITE: AnamorphicBloom";
ui_tooltip = "Artistic bloom & Lens Flare approximating the Anamorphic lens aesthetic.";
>
{
pass { VertexShader = PostProcessVS; PixelShader = PS_StoreUnpackedColor; RenderTarget = tUnpackedColor; }
//bloom pyramid
#if ANAMORPHIC_BLOOM
pass { VertexShader = PostProcessVS; PixelShader = PS_BloomDownsample0; RenderTarget = tBloomDown0; }
pass { VertexShader = PostProcessVS; PixelShader = PS_BloomDownsample1; RenderTarget = tBloomDown1; }
pass { VertexShader = PostProcessVS; PixelShader = PS_BloomDownsample2; RenderTarget = tBloomDown2; }
pass { VertexShader = PostProcessVS; PixelShader = PS_BloomDownsample3; RenderTarget = tBloomDown3; }
pass { VertexShader = PostProcessVS; PixelShader = PS_BloomDownsample4; RenderTarget = tBloomDown4; }
pass { VertexShader = PostProcessVS; PixelShader = PS_BloomUpsample0; RenderTarget = tBloomUp3; }
pass { VertexShader = PostProcessVS; PixelShader = PS_BloomUpsample1; RenderTarget = tBloomUp2; }
pass { VertexShader = PostProcessVS; PixelShader = PS_BloomUpsample2; RenderTarget = tBloomUp1; }
pass { VertexShader = PostProcessVS; PixelShader = PS_BloomUpsample3; RenderTarget = tBloomUp0; }
pass { VertexShader = PostProcessVS; PixelShader = PS_BloomUpsample4; RenderTarget = tBloomUp4; }
#endif
//streak pyramid
#if ANAMORPHIC_STREAKS
pass { VertexShader = PostProcessVS; PixelShader = PS_Prefilter; RenderTarget = tStreakDown0; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StreakDownsample0; RenderTarget = tStreakDown1; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StreakDownsample1; RenderTarget = tStreakDown2; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StreakDownsample2; RenderTarget = tStreakDown3; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StreakDownsample3; RenderTarget = tStreakDown4; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StreakUpsample3; RenderTarget = tStreakUp3; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StreakUpsample0; RenderTarget = tStreakUp2; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StreakUpsample1; RenderTarget = tStreakUp1; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StreakUpsample2; RenderTarget = tStreakUp0; }
#endif
pass { VertexShader = PostProcessVS; PixelShader = PS_ToDisplay; }
}
}
@@ -0,0 +1,993 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : lumenite_Kernel.fx
Version : 2026.09.06
Author : Afzaal (Kaidō)
Description: Pre-effect for various LumeniteFX shaders.
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
/*------------------.
| :: DEFINITIONS :: |
'------------------*/
#define FOV 60.0
#define NEAR_PLANE 0.01
#ifndef IMAGE_SPACE
#define IMAGE_SPACE 0
#endif
#ifndef DEBUG_KERNEL
#define DEBUG_KERNEL 0
#endif
#ifndef SMOOTH_NORMALS
#define SMOOTH_NORMALS 0
#endif
#define RES_SCALE ((BUFFER_HEIGHT) / 2160.0) //DO NOT modify this
/*--------------.
| :: HEADERS :: |
'--------------*/
#include "ReShade.fxh"
// #if DEBUG_KERNEL
// #include "DrawText.fxh"
// #endif
#include "./include/lumenite_Projections.fxh"
#include "./include/lumenite_Helpers.fxh"
#include "./include/lumenite_Compute.fxh"
/*---------------.
| :: UNIFORMS :: |
'---------------*/
#if DEBUG_KERNEL
uniform int DEBUG_VIEW <
ui_type = "combo";
ui_items = "Split View\0"
"Normals/Depth\0"
"Optical Flow\0"
"Motion Vectors\0"
"Motion Confidence\0"
;
ui_label = "Debug View";
ui_category = "Kernel";
> = 0;
#endif
#if IMAGE_SPACE == 0
#if SMOOTH_NORMALS
uniform float LUMA_DETAIL <
ui_type = "drag";
ui_min = -2.0; ui_max = 2.0;
ui_label = "Surface Relief";
ui_tooltip = "How much texture gets carved into smoothed normals. sign inverts the relief.";
> = 0.0;
uniform int LUMA_DETAIL_LOD <
ui_type = "slider";
ui_min = 0; ui_max = 4; ui_step = 1;
ui_label = "Texture LOD";
ui_tooltip = "1 = finest carving, 2 = fine relief, 4 = broad folds";
> = 2;
#endif
#endif
namespace Kernel {
/*---------------------.
| :: RENDER TARGETS :: |
'---------------------*/
texture2D tFlow { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
sampler2D sFlow { Texture = tFlow; MagFilter = POINT; MinFilter = POINT; };
texture2D tConfidence { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
sampler2D sConfidence { Texture = tConfidence; };
texture tNormals { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; MipLevels = 4; };
sampler sNormals { Texture = tNormals; };
#if IMAGE_SPACE == 0
#if SMOOTH_NORMALS
texture tGuideNormals { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; };
sampler sGuideNormals { Texture = tGuideNormals; };
texture texHRAN_H0 { Width = BUFFER_WIDTH/2; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler sHRAN_H0 { Texture = texHRAN_H0; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; };
texture texHRAN_HA { Width = BUFFER_WIDTH/2; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler sHRAN_HA { Texture = texHRAN_HA; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; };
texture texHRAN_HB { Width = BUFFER_WIDTH/2; Height = BUFFER_HEIGHT/2; Format = RGBA16F; };
sampler sHRAN_HB { Texture = texHRAN_HB; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; };
#endif
#endif
texture2D tDepth { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; MipLevels = 4; };
sampler2D sDepth { Texture = tDepth; };
texture2D tCurrLuma { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; MipLevels = 8; };
sampler2D sCurrLuma { Texture = tCurrLuma; MagFilter = LINEAR; MinFilter = LINEAR; MipFilter = LINEAR; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tPrevLuma { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; MipLevels = 8; };
sampler2D sPrevLuma { Texture = tPrevLuma; MagFilter = LINEAR; MinFilter = LINEAR; MipFilter = LINEAR; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow128 { Width = BUFFER_WIDTH/128; Height = BUFFER_HEIGHT/128; Format = RG16F; };
sampler2D sFlow128 { Texture = tFlow128; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow64A { Width = BUFFER_WIDTH/64; Height = BUFFER_HEIGHT/64; Format = RG16F; };
sampler2D sFlow64A { Texture = tFlow64A; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow64B { Width = BUFFER_WIDTH/64; Height = BUFFER_HEIGHT/64; Format = RG16F; };
sampler2D sFlow64B { Texture = tFlow64B; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow32A { Width = BUFFER_WIDTH/32; Height = BUFFER_HEIGHT/32; Format = RG16F; };
sampler2D sFlow32A { Texture = tFlow32A; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow32B { Width = BUFFER_WIDTH/32; Height = BUFFER_HEIGHT/32; Format = RG16F; };
sampler2D sFlow32B { Texture = tFlow32B; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow16A { Width = BUFFER_WIDTH/16; Height = BUFFER_HEIGHT/16; Format = RG16F; };
sampler2D sFlow16A { Texture = tFlow16A; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow16B { Width = BUFFER_WIDTH/16; Height = BUFFER_HEIGHT/16; Format = RG16F; };
sampler2D sFlow16B { Texture = tFlow16B; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow8 { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
sampler2D sFlow8 { Texture = tFlow8; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tPrevFrameFlow { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
sampler2D sPrevFrameFlow { Texture = tPrevFrameFlow; MagFilter = POINT; MinFilter = POINT; };
texture2D tPrevConfidence { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
sampler2D sPrevConfidence { Texture = tPrevConfidence; };
/*--------------.
| :: HELPERS :: |
'--------------*/
float3 GetColor(float2 uv)
{
return tex2Dlod(ReShade::BackBuffer, float4(uv, 0, 0)).rgb;
}
float3 DepthGradient(float t, float2 uv)
{
//grayscale: close=dark, far=bright
float3 depth = saturate(t).xxx;
const float ditherBit = 8.0;
float gridPos = frac(dot(uv, (BUFFER_SCREEN_SIZE * float2(1.0 / 16.0, 10.0 / 36.0)) + 0.25));
float ditherShift = 0.25 * (1.0 / (pow(2.0, ditherBit) - 1.0));
float3 ditherShiftRGB = float3(ditherShift, -ditherShift, ditherShift); //subpixel dithering
ditherShiftRGB = lerp(2.0 * ditherShiftRGB, -2.0 * ditherShiftRGB, gridPos);
return depth + ditherShiftRGB;
}
float3 MotionToColor(float2 motion)
{
float angle = atan2(-motion.y, -motion.x) / 6.283 + 0.5;
float rawLength = length(motion) / (15.0 * BUFFER_PIXEL_SIZE.x);
float compressed = rawLength / (1.0 + rawLength * 1.4); //asymptotic squash
float boosted = pow(compressed, 0.5); //lift shadows
float magnitude = saturate(lerp(compressed, boosted, saturate(rawLength * 3.0)));
float3 hsv = float3(angle, 1, magnitude);
float4 K = float4(1, 2/3.0, 1/3.0, 3);
float3 p = abs(frac(hsv.xxx + K.xyz) * 6 - K.www);
return hsv.z * lerp(K.xxx, clamp(p - K.xxx, 0, 1), hsv.y) + 0.1;
}
float SegmentDist(float2 p, float2 a, float2 b) //anti-aliased distance from point p to segment a-b
{
float2 pa = p - a;
float2 ba = b - a;
float h = saturate(dot(pa, ba) / (dot(ba, ba) + EPSILON));
return length(pa - ba * h);
}
float4 DrawMotionVectors(float2 uv)
{
static const int GATHER = 2; //cell radius searched (5x5); always MAX_LENGTH <= GATHER*GRID_SPACING
static const float GRID_SPACING = 16.0; //px between grid nodes
static const float DOT_RADIUS = 2.0; //px radius of node dots
static const float GRID_OPACITY = 0.20; //0..1 lattice visibility
static const float3 GRID_TINT = float3(0.55, 0.55, 0.60);
static const float SHAFT_THICKNESS = 1.5; //px half-width of shaft (larger)
static const float HEAD_LENGTH = 6.0; //px length of arrowhead (larger)
static const float HEAD_HALF_WIDTH = 4.0; //px half-width of head base (larger)
static const float MIN_LENGTH = 7.0; //px shortest arrow
static const float MAX_LENGTH = 30.0; //px longest arrow (<= GATHER*GRID_SPACING)
static const float LENGTH_SCALE = 2.5; //arrow px per motion px (elongation gain)
static const float AA = 0.9; //px edge softness
float3 baseColor = GetColor(uv);
float2 pixelPos = uv * BUFFER_SCREEN_SIZE;
//dotted grid
float2 g = pixelPos / GRID_SPACING;
float2 nearest = round(g) * GRID_SPACING; //nearest node centre, px
float dDot = length(pixelPos - nearest); //px distance to that node
float gridCov = (1.0 - smoothstep(DOT_RADIUS - AA, DOT_RADIUS + AA, dDot)) * GRID_OPACITY;
float bestCov = 0.0;
float3 bestColor = float3(0.0, 0.0, 0.0);
//union of arrows from the (2*GATHER+1)^2 nearest nodes (roots on grid crossings)
float2 baseNode = round(g);
[unroll] for (int ny = -GATHER; ny <= GATHER; ny++)
[unroll] for (int nx = -GATHER; nx <= GATHER; nx++)
{
float2 rootPx = (baseNode + float2(nx, ny)) * GRID_SPACING; //node sits on a crossing
float2 rootUV = rootPx * BUFFER_PIXEL_SIZE;
float2 motion = tex2Dlod(sFlow, float4(rootUV, 0, 0)).xy;
float2 motionPx = motion * BUFFER_SCREEN_SIZE;
float magPx = length(motionPx);
bool valid = (magPx >= 0.4) && (tex2Dlod(sDepth, float4(rootUV, 0, 0)).r < 0.999);
float len = clamp(magPx * LENGTH_SCALE, MIN_LENGTH, MAX_LENGTH); //elongates with this node's motion
float2 fwd = -motionPx / (magPx + EPSILON); //negate for forward motion
float2 tip = rootPx + fwd * len;
float2 perp = float2(-fwd.y, fwd.x);
//shaft
float2 shaftEnd = rootPx + fwd * max(len - HEAD_LENGTH, 0.0);
float dShaft = SegmentDist(pixelPos, rootPx, shaftEnd);
float covShaft = 1.0 - smoothstep(SHAFT_THICKNESS - AA, SHAFT_THICKNESS + AA, dShaft);
//head
float2 toTip = pixelPos - tip;
float along = dot(toTip, -fwd);
float side = abs(dot(toTip, perp));
float halfW = HEAD_HALF_WIDTH * saturate(along / HEAD_LENGTH);
float covAlong = smoothstep(-AA, AA, along) * (1.0 - smoothstep(HEAD_LENGTH - AA, HEAD_LENGTH + AA, along));
float covHead = covAlong * (1.0 - smoothstep(halfW - AA, halfW + AA, side));
float cov = max(covShaft, covHead) * (valid ? 1.0 : 0.0);
if (cov > bestCov) { bestCov = cov; bestColor = MotionToColor(motion); }
}
float3 outColor = lerp(baseColor, GRID_TINT, gridCov); //lattice underneath
outColor = lerp(outColor, bestColor, bestCov); //arrows on top
return float4(outColor, 1.0);
}
float ZMSAD(sampler2D currLumaSrc, sampler2D prevLumaSrc, float2 posA, float2 posB, float2 texelSize, uint mip)
{
static const int2 offsets[9] = {
int2(0, 3),
int2(0, 1),
int2(-3,0), int2(-1,0), int2(0, 0), int2(1,0), int2(3,0),
int2(0,-1),
int2(0,-3)
};
//gather samples and calculate the mean for each patch
float samplesA[9], samplesB[9];
float meanA = 0.0, meanB = 0.0;
[unroll] for(int i = 0; i < 9; i++) {
float2 offset = float2(offsets[i]) * texelSize;
samplesA[i] = tex2Dlod(currLumaSrc, float4(posA + offset, 0, mip)).r;
samplesB[i] = tex2Dlod(prevLumaSrc, float4(posB + offset, 0, mip)).r;
meanA += samplesA[i];
meanB += samplesB[i];
}
meanA /= 9.0;
meanB /= 9.0;
//SAD on the normalized samples
float err = 0.0;
[unroll] for(int i = 0; i < 9; i++)
err += abs((samplesA[i] - meanA) - (samplesB[i] - meanB));
return ((err / 9.0) + EPSILON);
}
float2 Median9(sampler2D flowSrc, float2 uv, float2 texelSize, uint mip)
{
float2 v[9];
int idx = 0;
[unroll] for(int dy = -1; dy <= 1; dy++) for(int dx = -1; dx <= 1; dx++)
v[idx++] = tex2Dlod(flowSrc, float4(uv + float2(dx, dy) * texelSize, 0, mip)).xy;
//bubble sort ensures the Median lands in v[4], only needs 5 passes
//indices 4,5,6,7,8 contain the 5 largest items, so v[4] is the median
[unroll] for(int k = 0; k < 5; k++) for(int i = 0; i < 8 - k; i++) { //checks decrease as right side gets sorted
float2 a = v[i];
float2 b = v[i+1];
v[i] = min(a, b);
v[i+1] = max(a, b);
}
return v[4];
}
float2 BilateralMedian9(sampler2D flowSrc, float2 uv, float2 texelSize, uint mip)
{
static const int2 DENSE_3X3[9] = {
int2(-1,-1), int2(0,-1), int2(1,-1),
int2(-1, 0), int2(0, 0), int2(1, 0),
int2(-1, 1), int2(0, 1), int2(1, 1)
};
float lumaC = tex2Dlod(sCurrLuma, float4(uv, 0, mip)).x;
float lumaW = tex2Dlod(sCurrLuma, float4(uv + float2(-1.0, 0.0) * texelSize, 0, mip)).x;
float lumaE = tex2Dlod(sCurrLuma, float4(uv + float2( 1.0, 0.0) * texelSize, 0, mip)).x;
float lumaN = tex2Dlod(sCurrLuma, float4(uv + float2( 0.0,-1.0) * texelSize, 0, mip)).x;
float lumaS = tex2Dlod(sCurrLuma, float4(uv + float2( 0.0, 1.0) * texelSize, 0, mip)).x;
//central-difference gradient, wider baseline than quad ddx/ddy, derived from real samples
float dxLuma = (lumaE - lumaW) * 0.5;
float dyLuma = (lumaS - lumaN) * 0.5;
float2 v[9];
uint validCount = 0;
[unroll] for (int i = 0; i < 9; i++) {
int2 off = DENSE_3X3[i];
float2 sampleUV = uv + float2(off) * texelSize;
//cardinals + center use sampled luma; diagonals get linear prediction
float sampleLuma = lumaC; //covers (0,0)
if (off.x == -1 && off.y == 0) sampleLuma = lumaW;
else if (off.x == 1 && off.y == 0) sampleLuma = lumaE;
else if (off.x == 0 && off.y == -1) sampleLuma = lumaN;
else if (off.x == 0 && off.y == 1) sampleLuma = lumaS;
else if (off.x != 0 && off.y != 0) sampleLuma = lumaC + float(off.x) * dxLuma + float(off.y) * dyLuma;
bool isValid = abs(lumaC - sampleLuma) <= 0.05;
v[i] = isValid ? tex2Dlod(flowSrc, float4(sampleUV, 0, 0)).xy : float2(1e38, 1e38);
validCount += uint(isValid);
}
if(validCount < 3u) return v[4];
//right-to-left bubble: smallest reaches v[0] per pass; after 5 passes, v[0..4] sorted ascending
[unroll] for(int k = 0; k < 5; k++) for(int j = 7; j >= k; j--) {
float2 a = v[j];
float2 b = v[j+1];
v[j] = min(a, b);
v[j+1] = max(a, b);
}
uint medianIdx = validCount / 2u;
float2 result = v[1]; //fallback for validCount == 3 (medianIdx 1)
if (medianIdx == 2u) result = v[2];
if (medianIdx == 3u) result = v[3];
if (medianIdx == 4u) result = v[4];
return result;
}
float2 ATrousFilter(sampler2D motionSrc, float2 uv, uint dilation, uint mip)
{
static const int2 offsets[8] = { int2(-1,-1), int2(0,-1), int2(1,-1),
int2(-1, 0), int2(1, 0),
int2(-1, 1), int2(0, 1), int2(1, 1) };
float centerLuma = tex2Dlod(sCurrLuma, float4(uv, 0, mip)).r;
#if IMAGE_SPACE == 0
float centerDepth = tex2Dlod(sDepth, float4(uv, 0, mip)).r;
#endif
float2 centerFlow = tex2Dlod(motionSrc, float4(uv, 0, 0)).xy;
float centerConf = max(tex2Dlod(sConfidence, float4(uv, 0, 0)).r, 0.01); //0.01 floor prevents NaN if conf hits 0
float2 sum = centerFlow * centerConf;
float totalWeight = centerConf;
[unroll] for (int i = 0; i < 8; i++) {
float2 sampleUV = uv + float2(offsets[i]) * dilation * BUFFER_PIXEL_SIZE * 8.0; //*8 = stride of flow grid
float2 sampleFlow = tex2Dlod(motionSrc, float4(sampleUV, 0, 0)).xy;
float sampleConf = tex2Dlod(sConfidence, float4(sampleUV, 0, 0)).r;
float confWeight = pow(sampleConf, 3.0);
float discontinuityGate;
#if IMAGE_SPACE == 0
float sampleDepth = tex2Dlod(sDepth, float4(sampleUV, 0, mip)).r;
float absDepthDiff = abs(centerDepth - sampleDepth);
float depthWeight = (absDepthDiff < 0.003) ? 1.0 : 0.0;
discontinuityGate = depthWeight;
#else
float2 flowDeltaPx = (sampleFlow - centerFlow) * BUFFER_SCREEN_SIZE; //measure flow disagreement in full-res px
float rawMotionGate = exp2(-dot(flowDeltaPx, flowDeltaPx) / (0.01 + EPSILON));
float motionGate = lerp(1.0, rawMotionGate, saturate(centerConf)); //if center flow is unreliable; relax gate so confident neighbors repair it
discontinuityGate = motionGate;
#endif
float sampleLuma = tex2Dlod(sCurrLuma, float4(sampleUV, 0, mip)).r;
float absLumaDiff = abs(centerLuma - sampleLuma);
float lumaWeight = saturate(1.0 - absLumaDiff * 10.0); //10.0: scale, 4.0: sharpness
float weight = confWeight * lumaWeight * discontinuityGate;
sum += sampleFlow * weight;
totalWeight += weight;
}
return sum / (totalWeight + EPSILON);
}
float2 UpscaleFlow(sampler2D coarseSrc, sampler2D currLumaSrc, sampler2D prevLumaSrc, float2 uv, float2 texelSize, uint mip)
{
if(FRAME_COUNT == 0) return float2(0, 0);
float2 coarseTexelSize = rcp(float2(tex2Dsize(coarseSrc, 0)));
//pool candidates for tournament selection. order matters here
float2 candidates[10];
candidates[0] = tex2D(coarseSrc, uv).xy ;
candidates[1] = tex2D(coarseSrc, uv + float2(0, -coarseTexelSize.y)).xy ;
candidates[2] = tex2D(coarseSrc, uv + float2(0, coarseTexelSize.y)).xy ;
candidates[3] = tex2D(coarseSrc, uv - float2(coarseTexelSize.x, 0)).xy ;
candidates[4] = tex2D(coarseSrc, uv + float2(coarseTexelSize.x, 0)).xy ;
candidates[5] = tex2D(coarseSrc, uv + float2(-coarseTexelSize.x, -coarseTexelSize.y)).xy ;
candidates[6] = tex2D(coarseSrc, uv + float2( coarseTexelSize.x, -coarseTexelSize.y)).xy ;
candidates[7] = tex2D(coarseSrc, uv + float2(-coarseTexelSize.x, coarseTexelSize.y)).xy ;
candidates[8] = tex2D(coarseSrc, uv + float2(coarseTexelSize.x, coarseTexelSize.y)).xy ;
candidates[9] = tex2D(sPrevFrameFlow, uv).xy;
float minCost = 1e6;
float2 prediction = candidates[0];
[loop] for (int i = 0; i < 10; i++) {
float cost = ZMSAD(currLumaSrc, prevLumaSrc, uv, uv + candidates[i], texelSize, mip);
if (cost < minCost) {
minCost = cost;
prediction = candidates[i];
}
}
//refinement with parabolic fitting
float costLeft = ZMSAD(currLumaSrc, prevLumaSrc, uv, uv + prediction - float2(texelSize.x, 0), texelSize, mip);
float costRight = ZMSAD(currLumaSrc, prevLumaSrc, uv, uv + prediction + float2(texelSize.x, 0), texelSize, mip);
float costDown = ZMSAD(currLumaSrc, prevLumaSrc, uv, uv + prediction - float2(0, texelSize.y), texelSize, mip);
float costUp = ZMSAD(currLumaSrc, prevLumaSrc, uv, uv + prediction + float2(0, texelSize.y), texelSize, mip);
//sub-pixel offset (parabolic fitting)
float2 subpixelOffset;
subpixelOffset.x = (costLeft - costRight) / (4.0 * (costLeft + costRight - 2.0 * minCost) + EPSILON); //EPSILON for flat surface handling
subpixelOffset.y = (costDown - costUp) / (4.0 * (costDown + costUp - 2.0 * minCost) + EPSILON);
//clamp offset to a reasonable range
subpixelOffset = clamp(subpixelOffset, -0.5, 0.5);
return (prediction+subpixelOffset*texelSize);
}
/*--------------.
| :: SHADERS :: |
'--------------*/
float PS_PackFeatures(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float3 color = GetColor(uv);
float luma = dot(color, float3(0.2126, 0.7152, 0.0722));
return luma * rcp(1.0 + luma);
}
#if IMAGE_SPACE == 0
void PS_ReconstructNormals(VSOUT input, out float4 gbuffer : SV_Target0, out float depthC : SV_Target1)
{
depthC = GetDepth(input.uv);
const float2 offsetX = float2(BUFFER_PIXEL_SIZE.x, 0);
const float2 offsetY = float2(0, BUFFER_PIXEL_SIZE.y);
float3 pC = UVToViewSpace(input.uv, depthC, input);
float3 pL = UVToViewSpace(input.uv - offsetX, GetDepth(input.uv - offsetX), input);
float3 pR = UVToViewSpace(input.uv + offsetX, GetDepth(input.uv + offsetX), input);
float3 pT = UVToViewSpace(input.uv - offsetY, GetDepth(input.uv - offsetY), input);
float3 pB = UVToViewSpace(input.uv + offsetY, GetDepth(input.uv + offsetY), input);
float3 diffX2 = pR - pC;
float3 diffX1 = pC - pL;
float3 diffY2 = pB - pC;
float3 diffY1 = pC - pT;
float lenSqX2 = dot(diffX2, diffX2);
float lenSqX1 = dot(diffX1, diffX1);
float lenSqY2 = dot(diffY2, diffY2);
float lenSqY1 = dot(diffY1, diffY1);
float3 ddx = lenSqX2 < lenSqX1 ? diffX2 : diffX1;
float3 ddy = lenSqY2 < lenSqY1 ? diffY2 : diffY1;
float3 geoNormal = normalize(cross(ddx, ddy));
gbuffer = float4(geoNormal, depthC);
}
#if SMOOTH_NORMALS
static const float2 HRAN_SIZE = float2(BUFFER_WIDTH/2, BUFFER_HEIGHT/2);
static const float2 HRAN_PX = float2(2.0, 2.0) / float2(BUFFER_WIDTH, BUFFER_HEIGHT);
static const float HRAN_TOL_SLOPE = 0.005 / RES_SCALE;
static const float HRAN_TOL_FLOOR = 0.00005 / RES_SCALE;
static const float CURV_LO = 0.0;
static const float CURV_HI = 0.475;
static const float MERGE_CENTER_WEIGHT = 1.0;
static const float CURV_OPEN_WINDOW = 1.3333333;
static const float COHERENCE_LO = 0.86;
static const float COHERENCE_HI = 0.85;
static const float STRIDE_NEAR_REF = 0.12 * RES_SCALE;
static const float STRIDE_MAX = 24.0 * RES_SCALE;
static const float DETAIL_GAIN = 1.25 * RES_SCALE;
static const float DEPTH_TOL_SLOPE = 0.005;
float4 PS_HRAN_Half(VSOUT input) : SV_Target
{
float2 hc = floor(input.uv * HRAN_SIZE);
float2 uvC = (hc * 2.0 + 0.5) * BUFFER_PIXEL_SIZE;
float zC = GetDepth(uvC);
if (zC >= 0.999) return float4(0.0, 0.0, -1.0, zC); //sky
float b = clamp(STRIDE_NEAR_REF * rcp(max(zC, 1e-5)), RES_SCALE, STRIDE_MAX) * 2.0; //half-px -> full px
//border guard
float2 pxPos = uvC * BUFFER_SCREEN_SIZE;
float bx = max(min(floor(b + 0.5), min(pxPos.x, BUFFER_SCREEN_SIZE.x - 1.0 - pxPos.x)), 1.0);
float by = max(min(floor(b + 0.5), min(pxPos.y, BUFFER_SCREEN_SIZE.y - 1.0 - pxPos.y)), 1.0);
float2 offX = float2(bx, 0.0) * BUFFER_PIXEL_SIZE.x;
float2 offY = float2(0.0, by) * BUFFER_PIXEL_SIZE.y;
float3 pC = UVToViewSpace(uvC, zC, input);
float3 pL = UVToViewSpace(uvC - offX, GetDepth(uvC - offX), input);
float3 pR = UVToViewSpace(uvC + offX, GetDepth(uvC + offX), input);
float3 pT = UVToViewSpace(uvC - offY, GetDepth(uvC - offY), input);
float3 pB = UVToViewSpace(uvC + offY, GetDepth(uvC + offY), input);
//best-fit selection
float3 dX2 = pR - pC, dX1 = pC - pL;
float3 dY2 = pB - pC, dY1 = pC - pT;
float3 ddxV = dot(dX2, dX2) < dot(dX1, dX1) ? dX2 : dX1;
float3 ddyV = dot(dY2, dY2) < dot(dY1, dY1) ? dY2 : dY1;
float3 n = cross(ddxV, ddyV);
n *= rsqrt(max(dot(n, n), 1e-30)); //scale-safe normalize
return float4(n, zC);
}
float4 ATrousNormalsH(sampler2D gbufferSrc, float2 uv, uint dilation)
{
static const int2 offsets[4] = { int2(0,-1),
int2(-1, 0), int2(1, 0),
int2(0, 1) };
float4 centerGeo = tex2Dlod(gbufferSrc, float4(uv, 0, 0));
float detail = saturate(dot(fwidth(centerGeo.rgb), float3(1,1,1)) * DETAIL_GAIN); //0 = facet interior/flat, 1 = dense variation
if (centerGeo.a >= 0.999) return centerGeo; //sky/far
float strideScale = clamp(STRIDE_NEAR_REF * exp2(-detail) / max(centerGeo.a, 1e-5), RES_SCALE, STRIDE_MAX); //world-locked footprint
float ringR = dilation * strideScale; //hoist: shared by rotation gate and every tap
float rotAng = (ringR > 1.5) ? frac(GetStratifiedNoise(uv * HRAN_SIZE).x + float(dilation) * 0.6180339887) * 1.5707963268 : 0.0; //rotate cross: scrambles band phase into grain the next pass averages away
float rotS, rotC; sincos(rotAng, rotS, rotC);
float invDepthTol = 1.0 / (centerGeo.a * DEPTH_TOL_SLOPE * sqrt(strideScale / RES_SCALE) + EPSILON); //slope term ~ z*sqrt(stride) covers curvature headroom
float invDepthTolL2 = invDepthTol * 1.4426950408; //log2(e) prefold: exp(-x)==exp2(-x*log2e)
float3 armSum = 0.0; //arms accumulate FIRST; the centre's weight is decided after,
float armWeight = 0.0; //once we know how many of them actually survived the gates
float4 geo[4];
[unroll] for (int i = 0; i < 2; i++) {
float2 offIdeal = float2(offsets[i]) * ringR; //full-res grid stride, depth-adaptive
float2 offPx = float2(offIdeal.x * rotC - offIdeal.y * rotS, offIdeal.x * rotS + offIdeal.y * rotC);
offPx = floor(offPx + 0.5); //texel snap
//border guard: scale the MIRRORED pair down so both taps stay on the half grid
float2 hcPos = uv * HRAN_SIZE;
float2 avail = max(min(hcPos, HRAN_SIZE - 1.0 - hcPos), 0.0);
float bsc = min(1.0, min(avail.x / max(abs(offPx.x), 1e-3), avail.y / max(abs(offPx.y), 1e-3)));
offPx = floor(offPx * bsc + 0.5);
float2 sampleUV = uv + offPx * HRAN_PX;
geo[i] = tex2Dlod(gbufferSrc, float4(sampleUV, 0, 0)); //one fetch = signal + both guides
geo[3 - i] = tex2Dlod(gbufferSrc, float4(uv - offPx * HRAN_PX, 0, 0)); //mirrored partner, same snapped offset
}
//curvature consistency
float3 d2x = geo[1].rgb + geo[2].rgb - 2.0 * centerGeo.rgb;
float3 d2y = geo[0].rgb + geo[3].rgb - 2.0 * centerGeo.rgb;
float curv = (length(d2x) + length(d2y)) * 0.5;
bool ringValid = (geo[0].a < 0.999) && (geo[1].a < 0.999) && (geo[2].a < 0.999) && (geo[3].a < 0.999);
float curvGate = ringValid ? (1.0 - smoothstep(CURV_LO, CURV_HI, curv)) : 0.0;
float tapWindow = lerp(1.3333333, CURV_OPEN_WINDOW, curvGate);
//planar depth prediction
float dzdxF = geo[2].a - centerGeo.a, dzdxB = centerGeo.a - geo[1].a; //E-C, C-W
float dzdyF = geo[3].a - centerGeo.a, dzdyB = centerGeo.a - geo[0].a; //S-C, C-N
float dzdx = abs(dzdxF) < abs(dzdxB) ? dzdxF : dzdxB;
float dzdy = abs(dzdyF) < abs(dzdyB) ? dzdyF : dzdyB;
float gradCap = 6.0 / invDepthTol;
dzdx = clamp(dzdx, -gradCap, gradCap);
dzdy = clamp(dzdy, -gradCap, gradCap);
[unroll] for (int i = 0; i < 4; i++) {
float4 sampleGeo = geo[i];
float planeResid = sampleGeo.a - (centerGeo.a + dzdx * float(offsets[i].x) + dzdy * float(offsets[i].y));
float depthWeight = exp2(-abs(planeResid) * invDepthTolL2); //point-to-plane: slanted floors and gentle kinks pass, depth discontinuities fail
float nAlign = saturate(dot(centerGeo.rgb, sampleGeo.rgb));
float normalWeight = saturate(nAlign * tapWindow - (tapWindow - 1.0)); //angular window
float weight = depthWeight * normalWeight * 2.0; //uniform arm weight
weight = sampleGeo.a >= 0.999 ? 0.0 : weight; //skip skylines
armSum += sampleGeo.rgb * weight;
armWeight += weight;
}
//adaptive center weight to the flicker on small geometry
float armConf = saturate(armWeight * 0.125); //8.0 = four arms x 2.0 max
float centerW = lerp(4.0, MERGE_CENTER_WEIGHT, armConf);
float3 sum = centerGeo.rgb * centerW + armSum;
float totalWeight = centerW + armWeight;
float filteredLen = length(sum);
float3 mergedDir = (filteredLen > EPSILON) ? sum / filteredLen : centerGeo.rgb;
//coherence gate
float coherence = filteredLen / max(totalWeight, EPSILON);
float coherenceGate = smoothstep(COHERENCE_LO, COHERENCE_HI, coherence);
float mergeStrength = max(coherenceGate, curvGate);
float3 filtered = normalize(lerp(centerGeo.rgb, mergedDir, mergeStrength));
return float4(filtered, centerGeo.a); //depth rides through untouched
}
float4 PS_HRAN_A(float4 vp : SV_Position, float2 uv : TEXCOORD) : SV_Target { return ATrousNormalsH(sHRAN_H0, uv, 2); }
float4 PS_HRAN_B(float4 vp : SV_Position, float2 uv : TEXCOORD) : SV_Target { return ATrousNormalsH(sHRAN_HA, uv, 4); }
float4 PS_HRAN_C(float4 vp : SV_Position, float2 uv : TEXCOORD) : SV_Target { return ATrousNormalsH(sHRAN_HB, uv, 8); }
float4 PS_HRAN_Up(float4 vp : SV_Position, float2 uv : TEXCOORD) : SV_Target
{ //joint-bilateral upsample
float4 g = tex2Dlod(sGuideNormals, float4(uv, 0, 0));
if (g.a >= 0.999) return g; //sky/far
//center-relative one-sided guide slopes at FULL res (min-mag guard: silhouette on one side can't poison the other)
float zE = tex2Dlod(sGuideNormals, float4(uv + float2(BUFFER_PIXEL_SIZE.x, 0), 0, 0)).a;
float zW = tex2Dlod(sGuideNormals, float4(uv - float2(BUFFER_PIXEL_SIZE.x, 0), 0, 0)).a;
float zS = tex2Dlod(sGuideNormals, float4(uv + float2(0, BUFFER_PIXEL_SIZE.y), 0, 0)).a;
float zN = tex2Dlod(sGuideNormals, float4(uv - float2(0, BUFFER_PIXEL_SIZE.y), 0, 0)).a;
float dxF = zE - g.a, dxB = g.a - zW;
float dzdx = abs(dxF) < abs(dxB) ? dxF : dxB;
float dyF = zS - g.a, dyB = g.a - zN;
float dzdy = abs(dyF) < abs(dyB) ? dyF : dyB;
float invTol = 1.0 / (g.a * HRAN_TOL_SLOPE + HRAN_TOL_FLOOR); //span ~1-2 full px -> no stride coupling needed
float invTolL2 = invTol * 1.4426950408; //log2(e) prefold
float gradCap = 3.0 / invTol; //cut-poisoned-fit cap, same job as always
dzdx = clamp(dzdx, -gradCap, gradCap);
dzdy = clamp(dzdy, -gradCap, gradCap);
float2 hc = uv * HRAN_SIZE - 0.5;
float2 hb = min(max(floor(hc), 0.0), HRAN_SIZE - 2.0); //border guard: the 2x2 always reads real texels
float2 fr = hc - hb;
float2 frw = smoothstep(0.0, 1.0, fr);
float2 base = (hb + 0.5) * HRAN_PX;
float3 nsum = 0.0; float ws = 0.0;
[unroll] for (int j = 0; j < 2; j++)
[unroll] for (int i = 0; i < 2; i++) {
float4 hg = tex2Dlod(sHRAN_HA, float4(base + float2(i, j) * HRAN_PX, 0, 0));
float2 dFull = 2.0 * (float2(i, j) - fr); //tap offset in FULL-res px (one half-px = two full-px)
float resid = hg.a - (g.a + dzdx * dFull.x + dzdy * dFull.y); //point-to-plane vs the pristine full-res guide
float bi = (i == 0 ? 1.0 - frw.x : frw.x) * (j == 0 ? 1.0 - frw.y : frw.y);
float w = exp2(-abs(resid) * invTolL2) * saturate(saturate(dot(g.rgb, hg.rgb)) * 1.3333333 - 0.3333333) * bi; //75deg window
w = hg.a >= 0.999 ? 0.0 : w;
nsum += hg.rgb * w; ws += w;
}
if (ws < 1e-4) return g; //never blend on the wrong-side, let raw normal through, unsmoothed but correct here
float3 n = nsum / ws; float len = length(n);
float3 outN = (len > EPSILON) ? n / len : g.rgb;
//luma micro-relief
[branch] if (abs(LUMA_DETAIL) > 1e-4)
{
float lodEff = LUMA_DETAIL_LOD + log2(RES_SCALE);
float lodPx = exp2(lodEff);
float2 lr = BUFFER_PIXEL_SIZE * lodPx;
float lE = tex2Dlod(sCurrLuma, float4(uv + float2(lr.x, 0), 0, lodEff)).r;
float lW = tex2Dlod(sCurrLuma, float4(uv - float2(lr.x, 0), 0, lodEff)).r;
float lS = tex2Dlod(sCurrLuma, float4(uv + float2(0, lr.y), 0, lodEff)).r;
float lN = tex2Dlod(sCurrLuma, float4(uv - float2(0, lr.y), 0, lodEff)).r;
float2 lg = float2(lE - lW, lS - lN) * 0.5;
lg = sign(lg) * min(abs(lg), 0.08); //cap: residual hard edges emboss boundedly
outN = normalize(outN + float3(-lg.x, -lg.y, 0.0) * (LUMA_DETAIL * 8.0));
}
return float4(outN, g.a); //full-res depth rides through
}
#endif
#endif
float2 PS_ComputeFlow128(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
if(FRAME_COUNT == 0) return float2(0, 0);
static const int SEARCH_RADIUS = 3;
static const uint mip = 5;
float2 texelSize = BUFFER_PIXEL_SIZE * exp2(mip);
//candidate seeds for the coarsest level for tournament selection
float2 prevSeed = tex2D(sPrevFrameFlow, uv).xy;
float2 zeroSeed = float2(0, 0);
float prevCost = ZMSAD(sCurrLuma, sPrevLuma, uv, uv + prevSeed, texelSize, mip);
float zeroCost = ZMSAD(sCurrLuma, sPrevLuma, uv, uv + zeroSeed, texelSize, mip);
float2 seed = (zeroCost < prevCost) ? zeroSeed : prevSeed; //pick better candidate as seed
float2 bestFlow = seed;
float minCost = ZMSAD(sCurrLuma, sPrevLuma, uv, uv+seed, texelSize, mip);
//search in a grid AROUND the seed
for (int y = -SEARCH_RADIUS; y <= SEARCH_RADIUS; ++y) for (int x = -SEARCH_RADIUS; x <= SEARCH_RADIUS; ++x) {
if (x == 0 && y == 0) continue;
float2 candidateFlow = seed + float2(x, y) * texelSize;
float cost = ZMSAD(sCurrLuma, sPrevLuma, uv, uv + candidateFlow, texelSize, mip);
if (cost < minCost) {
minCost = cost;
bestFlow = candidateFlow;
if (minCost < 0.01) //near-perfect match found
return bestFlow;
}
}
return bestFlow;
}
float2 PS_UpscaleFlow64(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return UpscaleFlow(sFlow128, sCurrLuma, sPrevLuma, uv, BUFFER_PIXEL_SIZE*16.0, 4);
}
float2 PS_MedianPass64(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return Median9(sFlow64A, uv, BUFFER_PIXEL_SIZE*64.0, 6);
}
float2 PS_UpscaleFlow32(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return UpscaleFlow(sFlow64B, sCurrLuma, sPrevLuma, uv, BUFFER_PIXEL_SIZE*8.0, 3);
}
float2 PS_MedianPass32(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return Median9(sFlow32A, uv, BUFFER_PIXEL_SIZE*32.0, 5);
}
float2 PS_UpscaleFlow16(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return UpscaleFlow(sFlow32B, sCurrLuma, sPrevLuma, uv, BUFFER_PIXEL_SIZE*4.0, 2);
}
float2 PS_MedianPass16(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return Median9(sFlow16A, uv, BUFFER_PIXEL_SIZE*16.0, 4);
}
float2 PS_UpscaleFlow8(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return UpscaleFlow(sFlow16B, sCurrLuma, sPrevLuma, uv, BUFFER_PIXEL_SIZE*2.0, 1);
}
float2 PS_MedianPass8A(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return BilateralMedian9(sFlow, uv, BUFFER_PIXEL_SIZE*8.0, 3);
}
float2 PS_MedianPass8B(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return BilateralMedian9(sFlow8, uv, BUFFER_PIXEL_SIZE*8.0, 3);
}
float2 PS_ATrousPassA(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target //stride 1
{
return ATrousFilter(sFlow, uv, 2, 3);
}
float2 PS_ATrousPassB(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target //stride 2
{
float2 flow = ATrousFilter(sFlow8, uv, 4, 1);
//kill sub-pixel noise
float flowPixelMag = length(flow / BUFFER_PIXEL_SIZE);
float gate = saturate(1.0 - pow(1.0 - saturate(saturate(flowPixelMag) - 0.2), 10.0)); //SNAP TO REALITY
return flow*gate;
}
float PS_Confidence(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
if(FRAME_COUNT == 0) return 0.0; //no confidence
float2 flow = tex2D(sFlow, uv).xy;
float2 prevUV = uv + flow; //warp prev frame forward
if(IsOOB(prevUV)) return 0.0;
//look at local contrast for pattern confidence
float sumX = 0, sumX2 = 0, sumY = 0, sumY2 = 0;
float2 lumaTexSize = BUFFER_PIXEL_SIZE * 4.0;
static const float2 offsets[5] = {
float2(0, 1),
float2(-1,0), float2(0, 0), float2(1,0),
float2(0,-1)
};
[unroll] for(int i = 0; i < 5; i++) {
float valCurr = tex2Dlod(sCurrLuma, float4(uv + offsets[i] * lumaTexSize, 0, 2)).r;
float valPrev = tex2Dlod(sPrevLuma, float4(prevUV + offsets[i] * lumaTexSize, 0, 2)).r;
sumX += valCurr; sumX2 += valCurr * valCurr;
sumY += valPrev; sumY2 += valPrev * valPrev;
}
float varCurr = max(0.0, (sumX2 / 5.0) - (sumX / 5.0 * sumX / 5.0));
float varPrev = max(0.0, (sumY2 / 5.0) - (sumY / 5.0 * sumY / 5.0));
float patternConf = 1.0 - saturate(abs(sqrt(varCurr) - sqrt(varPrev)) / (sqrt(varCurr) + 0.01));
//look at neighborhood for flow consistency
float flowMagnitude = length(flow);
float2 flowTexelSize = BUFFER_PIXEL_SIZE * 8.0;
float2 flowN = tex2Dlod(sFlow, float4(uv + float2(0, -flowTexelSize.y), 0, 0)).xy;
float2 flowS = tex2Dlod(sFlow, float4(uv + float2(0, flowTexelSize.y), 0, 0)).xy;
float2 flowE = tex2Dlod(sFlow, float4(uv + float2( flowTexelSize.x, 0), 0, 0)).xy;
float2 flowW = tex2Dlod(sFlow, float4(uv + float2(-flowTexelSize.x, 0), 0, 0)).xy;
float2 avgNeighborFlow = (flowN + flowS + flowE + flowW) * 0.25;
float spatialDiff = distance(flow, avgNeighborFlow);
float spatialThreshold = flowMagnitude * 0.5 + BUFFER_PIXEL_SIZE.x;
float spatialConfidence = saturate(1.0 - (spatialDiff / (spatialThreshold + EPSILON)));
//motion length penalty
float subpixelThreshold = length(BUFFER_PIXEL_SIZE);
float lengthConfidence = (flowMagnitude <= subpixelThreshold) ? 1.0 : rcp((flowMagnitude / subpixelThreshold) * 0.05 + 1.0);
//float panThreshold = BUFFER_PIXEL_SIZE.x * 30.0;
//float lengthConfidence = (flowMagnitude <= panThreshold) ? 1.0 : rcp(((flowMagnitude - panThreshold) / panThreshold) * 0.1 + 1.0);
//current frame final confidence
float currentConf = spatialConfidence * lengthConfidence * patternConf;
//temporal filter
float historyConf = tex2D(sPrevConfidence, prevUV).r;
//DEPRECATED: linear EMA (a=0.15) 15% new + 85% history every frame
//unbiased (settles at the true mean), very stable but distrusts a real drop only as slowly as it trusts a rise
//return lerp(historyConf, currentConf, 0.15); //higher makes it react to changes quickly
//Asymmetric EMA; a=0.5 only on a genuine drop (>0.05 below history) fast distrust, else a reasonable a=0.1
//0.05 deadband keeps calm-region jitter on 0.1; only true occlusion/disocclusion bleeds confidence fast
float alpha = (currentConf < historyConf - 0.05) ? 0.5 : 0.1;
return lerp(historyConf, currentConf, alpha);
}
void PS_StoreFlow(float4 pos : SV_Position, float2 uv : TEXCOORD, out float2 flow : SV_Target0, out float confidence : SV_Target1)
{
flow = tex2D(sFlow, uv).xy;
confidence = tex2D(sConfidence, uv).r;
}
float PS_StoreLuma(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return tex2D(sCurrLuma, uv).r;
}
#if DEBUG_KERNEL
float4 PS_Debug(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float3 sceneColor = GetColor(uv);
switch(DEBUG_VIEW)
{
case 0: {
static const float LINE_PX = 1.5; //divider half-width, px
static const float3 LINE_TINT = float3(0.0, 0.0, 0.0);
static const float2 BOX_HALF = float2(0.16, 0.18); //centre inset half-extents, uv
float2 pixelPos = uv * BUFFER_SCREEN_SIZE;
float2 centrePx = BUFFER_SCREEN_SIZE * 0.5;
float2 boxHalfPx = BOX_HALF * BUFFER_SCREEN_SIZE;
//axis-aligned box distance
float2 dd = abs(pixelPos - centrePx) - boxHalfPx;
float boxSDF = length(max(dd, 0.0)) + min(max(dd.x, dd.y), 0.0);
float3 view;
if (boxSDF < 0.0)
{
float2 boxUV = (uv - (0.5 - BOX_HALF)) / (2.0 * BOX_HALF); //full frame mapped into inset
view = DrawMotionVectors(boxUV).rgb; //centre: motion vectors
}
else
{
float2 quadUV = frac(uv * 2.0); //flow/confidence remap to full [0,1] frame
if (uv.y < 0.5)
view = (uv.x < 0.5)
? tex2Dlod(sNormals, float4(uv, 0, 0)).rgb * 0.5 + 0.5 //TL: normals (spatial, raw uv)
: DepthGradient(tex2Dlod(sDepth, float4(uv, 0, 0)).r, uv); //TR: depth (spatial, raw uv)
else if (uv.x < 0.5)
view = MotionToColor(tex2Dlod(sFlow, float4(quadUV, 0, 0)).xy); //BL: optical flow field
else
{
float confidence = tex2Dlod(sConfidence, float4(quadUV, 0, 0)).x; //BR: motion confidence field
float3 confidenceColor = (confidence < 0.5)
? lerp(float3(1.0, 0.0, 0.0), float3(1.0, 1.0, 0.0), confidence * 2.0)
: lerp(float3(1.0, 1.0, 0.0), float3(0.0, 1.0, 0.0), (confidence - 0.5) * 2.0);
view = lerp(GetColor(quadUV), confidenceColor, 0.9);
}
//black dividers
float dCross = min(abs(pixelPos.x - centrePx.x), abs(pixelPos.y - centrePx.y));
view = lerp(view, LINE_TINT, 1.0 - smoothstep(LINE_PX - 0.9, LINE_PX + 0.9, dCross));
}
//centre inset border
view = lerp(view, LINE_TINT, 1.0 - smoothstep(LINE_PX - 0.9, LINE_PX + 0.9, abs(boxSDF)));
//window labels
// float2 texcoord = uv; //alias: the DrawText macro declares its own internal 'uv'
// float labelMask = 0.0;
// float labelSize = max(BUFFER_HEIGHT * 0.025, 12.0); //label height, px
// int lblNormals[21] = { __R, __e, __c, __o, __n, __s, __t, __r, __u, __c, __t, __e, __d, __Space, __N, __o, __r, __m, __a, __l, __s };
// int lblDepth[16] = { __L, __i, __n, __e, __a, __r, __i, __z, __e, __d, __Space, __D, __e, __p, __t, __h };
// int lblFlow[10] = { __F, __l, __o, __w, __Space, __F, __i, __e, __l, __d };
// int lblConfidence[16] = { __C, __o, __n, __f, __i, __d, __e, __n, __c, __e, __Space, __F, __i, __e, __l, __d };
// int lblVectors[14] = { __M, __o, __t, __i, __o, __n, __Space, __V, __e, __c, __t, __o, __r, __s };
//
// labelMask = 0.0; DrawText_String(float2(BUFFER_WIDTH * 0.25 - 21.0 * labelSize * 0.25, BUFFER_HEIGHT * 0.03), labelSize, 1.0, texcoord, lblNormals, 21, labelMask); view = lerp(view, float3(1.00, 1.00, 1.00), saturate(labelMask)); //TL white
// labelMask = 0.0; DrawText_String(float2(BUFFER_WIDTH * 0.75 - 16.0 * labelSize * 0.25, BUFFER_HEIGHT * 0.03), labelSize, 1.0, texcoord, lblDepth, 16, labelMask); view = lerp(view, float3(0.55, 0.85, 1.00), saturate(labelMask)); //TR blue
// labelMask = 0.0; DrawText_String(float2(BUFFER_WIDTH * 0.25 - 10.0 * labelSize * 0.25, BUFFER_HEIGHT * 0.53), labelSize, 1.0, texcoord, lblFlow, 10, labelMask); view = lerp(view, float3(1.00, 1.00, 1.00), saturate(labelMask)); //BL white
// labelMask = 0.0; DrawText_String(float2(BUFFER_WIDTH * 0.75 - 16.0 * labelSize * 0.25, BUFFER_HEIGHT * 0.53), labelSize, 1.0, texcoord, lblConfidence, 16, labelMask); view = lerp(view, float3(1.00, 1.00, 1.00), saturate(labelMask)); //BR white
// labelMask = 0.0; DrawText_String(float2(BUFFER_WIDTH * 0.50 - 14.0 * labelSize * 0.25, BUFFER_HEIGHT * (0.5 - BOX_HALF.y) + 8.0), labelSize, 1.0, texcoord, lblVectors, 14, labelMask); view = lerp(view, float3(1.00, 1.00, 1.00), saturate(labelMask)); //centre white
//
// view = lerp(view, float3(1.0, 1.0, 1.0), saturate(labelMask)); //white labels
return float4(view, 1.0);
}
case 1: {
float4 gbuffer = tex2D(sNormals, uv);
float3 normal = gbuffer.rgb;
float depth = gbuffer.a;
bool isLeftHalf = uv.x < 0.5;
float4 dbg;
if (isLeftHalf)
dbg = float4(normal * 0.5 + 0.5, 1.0); //left: normals
else
dbg = float4(DepthGradient(depth, uv), 1.0); //right: depth gradient
return dbg;
}
case 2: return float4(MotionToColor(tex2D(sFlow, uv).xy), 1);
case 3: return DrawMotionVectors(uv);
case 4:
{
float confidence = tex2D(sConfidence, uv).x;
float3 confidenceColor;
if (confidence < 0.5)
confidenceColor = lerp(float3(1.0, 0.0, 0.0), float3(1.0, 1.0, 0.0), confidence * 2.0);
else
confidenceColor = lerp(float3(1.0, 1.0, 0.0), float3(0.0, 1.0, 0.0), (confidence - 0.5) * 2.0);
return float4(lerp(sceneColor, confidenceColor, 0.9), 1.0);
}
default: return float4(sceneColor, 1.0);
}
}
#endif
/*----------------.
| :: TECHNIQUE :: |
'----------------*/
technique Lumenite_Kernel <
ui_label = "LUMENITE: Kernel 2.0";
ui_tooltip = "Pre-effect for LumeniteFX shaders.";
>
{
//features
pass { VertexShader = PostProcessVS; PixelShader = PS_PackFeatures; RenderTarget = tCurrLuma; }
//normals
#if IMAGE_SPACE == 0
#if SMOOTH_NORMALS == 0
pass { VertexShader = VS; PixelShader = PS_ReconstructNormals; RenderTarget0 = tNormals; RenderTarget1 = tDepth; }
#else
pass { VertexShader = VS; PixelShader = PS_ReconstructNormals; RenderTarget0 = tGuideNormals; RenderTarget1 = tDepth; }
pass { VertexShader = VS; PixelShader = PS_HRAN_Half; RenderTarget = texHRAN_H0; }
pass { VertexShader = PostProcessVS; PixelShader = PS_HRAN_A; RenderTarget = texHRAN_HA; }
pass { VertexShader = PostProcessVS; PixelShader = PS_HRAN_B; RenderTarget = texHRAN_HB; }
pass { VertexShader = PostProcessVS; PixelShader = PS_HRAN_C; RenderTarget = texHRAN_HA; }
pass { VertexShader = PostProcessVS; PixelShader = PS_HRAN_Up; RenderTarget = tNormals; }
#endif
#endif
//optical flow
pass { VertexShader = PostProcessVS; PixelShader = PS_ComputeFlow128; RenderTarget = tFlow128; }
pass { VertexShader = PostProcessVS; PixelShader = PS_UpscaleFlow64; RenderTarget = tFlow64A; }
pass { VertexShader = PostProcessVS; PixelShader = PS_MedianPass64; RenderTarget = tFlow64B; }
pass { VertexShader = PostProcessVS; PixelShader = PS_UpscaleFlow32; RenderTarget = tFlow32A; }
pass { VertexShader = PostProcessVS; PixelShader = PS_MedianPass32; RenderTarget = tFlow32B; }
pass { VertexShader = PostProcessVS; PixelShader = PS_UpscaleFlow16; RenderTarget = tFlow16A; }
pass { VertexShader = PostProcessVS; PixelShader = PS_MedianPass16; RenderTarget = tFlow16B; }
pass { VertexShader = PostProcessVS; PixelShader = PS_UpscaleFlow8; RenderTarget = tFlow; }
pass { VertexShader = PostProcessVS; PixelShader = PS_MedianPass8A; RenderTarget = tFlow8; }
pass { VertexShader = PostProcessVS; PixelShader = PS_MedianPass8B; RenderTarget = tFlow; }
pass { VertexShader = PostProcessVS; PixelShader = PS_Confidence; RenderTarget = tConfidence; }
pass { VertexShader = PostProcessVS; PixelShader = PS_ATrousPassA; RenderTarget = tFlow8; }
pass { VertexShader = PostProcessVS; PixelShader = PS_ATrousPassB; RenderTarget = tFlow; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StoreFlow; RenderTarget0 = tPrevFrameFlow; RenderTarget1 = tPrevConfidence; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StoreLuma; RenderTarget = tPrevLuma; }
//debug views
#if DEBUG_KERNEL
pass { VertexShader = PostProcessVS; PixelShader = PS_Debug; }
#endif
}
}
@@ -0,0 +1,368 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : lumenite_LSAO.fx
Version : 2026.06.09
Author : Afzaal (Kaidō)
Description: Large-Scale Ray Traced Ambient Occlusion (Screen Space).
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
/*------------------.
| :: DEFINITIONS :: |
'------------------*/
#define FOV 60.0
#define NEAR_PLANE 0.01
#define AO_MAX_MARCH_STEPS 100
/*--------------.
| :: HEADERS :: |
'--------------*/
#include "ReShade.fxh"
#include "./include/lumenite_Projections.fxh"
#include "./include/lumenite_Helpers.fxh"
#include "./include/lumenite_ColorManagement.fxh"
/*---------------.
| :: UNIFORMS :: |
'---------------*/
uniform bool DEBUG_VIEW <
ui_label = "Show AO Mask";
ui_tooltip = "Debug view for the AO. Shows raw AO.";
ui_category = "Ambient Occlusion";
> = 0;
uniform float DEPTH_BOUNDARY <
ui_type = "slider";
ui_min = 0.001; ui_max = 0.999; ui_step = 0.001;
ui_label = "AO Range";
ui_tooltip = "The Z+ range/depth in which the effect is applied.";
ui_category = "Ambient Occlusion";
hidden = false;
> = 0.6;
uniform float DEPTH_FADE_START <
ui_type = "slider";
ui_min = 0.1; ui_max = 1.0; ui_step = 0.01;
ui_label = "Z+ Fade Start (%)";
ui_tooltip = "Z+ fraction where effect starts fading out (relative to AO Range)";
ui_category = "Ambient Occlusion";
hidden = true;
> = 0.75;
uniform float AO_INTENSITY <
ui_type = "drag";
ui_min = 0.0; ui_max = 1.0;
ui_label = "AO Strength";
ui_tooltip = "Controls the intensity of the ambient occlusion effect.";
ui_category = "Ambient Occlusion";
> = 1.0;
/*--------------.
| :: IMPORTS :: |
'--------------*/
namespace Kernel {
texture2D tFlow { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
sampler2D sFlow { Texture = tFlow; MagFilter = POINT; MinFilter = POINT; };
texture2D tConfidence { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
sampler2D sConfidence { Texture = tConfidence; };
texture tNormals { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; MipLevels = 4; };
sampler sNormals { Texture = tNormals; };
texture2D tDepth { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; MipLevels = 4; };
sampler2D sDepth { Texture = tDepth; };
}
namespace LumeniteLSAO {
/*---------------------.
| :: RENDER TARGETS :: |
'---------------------*/
texture tAOTrace { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = R16F; };
sampler sAOTrace { Texture = tAOTrace; AddressU = CLAMP; AddressV = CLAMP; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; };
texture tAO1 { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = RG16F; };
sampler sAO1 { Texture = tAO1; AddressU = CLAMP; AddressV = CLAMP; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; };
texture tAO2 { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = RG16F; };
sampler sAO2 { Texture = tAO2; AddressU = CLAMP; AddressV = CLAMP; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; };
sampler sAO2Linear { Texture = tAO2; AddressU = CLAMP; AddressV = CLAMP; MagFilter = LINEAR; MinFilter = LINEAR; MipFilter = LINEAR; };
texture tPrevAO { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = RG16F; };
sampler sPrevAO { Texture = tPrevAO; AddressU = CLAMP; AddressV = CLAMP; MagFilter = LINEAR; MinFilter = LINEAR; MipFilter = LINEAR; };
//HiZ mipchain
texture tHiZMip0 { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; };
texture tHiZMip1 { Width = BUFFER_WIDTH/2; Height = BUFFER_HEIGHT/2; Format = R16F; };
texture tHiZMip2 { Width = BUFFER_WIDTH/4; Height = BUFFER_HEIGHT/4; Format = R16F; };
texture tHiZMip3 { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
texture tHiZMip4 { Width = BUFFER_WIDTH/16; Height = BUFFER_HEIGHT/16; Format = R16F; };
texture tHiZMip5 { Width = BUFFER_WIDTH/32; Height = BUFFER_HEIGHT/32; Format = R16F; };
sampler sHiZMip0 { Texture = tHiZMip0; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
sampler sHiZMip1 { Texture = tHiZMip1; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
sampler sHiZMip2 { Texture = tHiZMip2; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
sampler sHiZMip3 { Texture = tHiZMip3; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
sampler sHiZMip4 { Texture = tHiZMip4; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
sampler sHiZMip5 { Texture = tHiZMip5; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
/*--------------.
| :: HELPERS :: |
'--------------*/
void BuildOrthonormalBasis(float3 n, out float3 b1, out float3 b2)
{
if (n.z < -0.9999999) {
b1 = float3(0.0, -1.0, 0.0);
b2 = float3(-1.0, 0.0, 0.0);
} else {
float a = rcp(1.0 + n.z);
float b = -n.x * n.y * a;
b1 = float3(mad(-n.x * n.x, a, 1.0), b, -n.x);
b2 = float3(b, mad(-n.y * n.y, a, 1.0), -n.y);
}
}
float3 GenerateHemisphereDirection(float3 normal, float2 rand, float3 tangent, float3 bitangent)
{
float phi = rand.x * 6.28318530718; //2.0*PI as constant
float sinPhi, cosPhi;
sincos(phi, sinPhi, cosPhi);
float cosTheta = sqrt(1.0 - rand.y);
float sinTheta = sqrt(rand.y);
float3 result = normal * cosTheta;
result = mad(bitangent, sinTheta * sinPhi, result);
result = mad(tangent, sinTheta * cosPhi, result);
return result;
}
float CalculateDepthFade(float depth)
{
float fadeStartDepth = DEPTH_BOUNDARY * DEPTH_FADE_START;
float fadeRange = DEPTH_BOUNDARY - fadeStartDepth;
return 1.0 - saturate((depth - fadeStartDepth) / fadeRange);
}
float2 ATrousFilter(sampler SourceSampler, float2 uv, uint dilation, bool adaptiveDilation)
{
float4 gbuffer = tex2D(Kernel::sNormals, uv);
if (gbuffer.a == 0 || gbuffer.a >= DEPTH_BOUNDARY) return float2(1.0, 0.0);
[branch] if (adaptiveDilation) {
float confidence = tex2Dlod(Kernel::sConfidence, float4(uv, 0, 0)).r;
dilation += uint(round((1.0 - confidence) * 2.0)); //scale filter kernel w. motion by up to a factor of 2
}
float2 centerData = tex2Dlod(SourceSampler, float4(uv, 0, 0)).rg;
float variance = max(0.0, centerData.g - (centerData.r * centerData.r)); //Moment - AO^2
variance = max(variance, 0.0001);
float2 sum = centerData;
float totalWeight = 1.0;
for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) {
if (x == 0 && y == 0) continue;
float2 sampleUV = uv + float2(x, y) * dilation * (BUFFER_PIXEL_SIZE * 2.0); //don't forget the x2.0 to properly step half-res grid!
float2 sampleData = tex2Dlod(SourceSampler, float4(sampleUV, 0, 0)).rg;
float4 sampleGeo = tex2Dlod(Kernel::sNormals, float4(sampleUV, 0, 0));
float depthWeight = exp(-abs(gbuffer.a - sampleGeo.a) / (gbuffer.a * 0.02 + 0.001));
float normalWeight = pow(saturate(dot(gbuffer.rgb, sampleGeo.rgb)), 50.0);
float aoDiff = centerData.r - sampleData.r;
float aoWeight = exp(-(aoDiff * aoDiff) / (variance + 0.0001));
float weight = depthWeight * normalWeight * aoWeight;
sum += sampleData * weight;
totalWeight += weight;
}
return sum / (totalWeight + EPSILON);
}
float SamplePrevHiZ(float2 centerUV, sampler srcSampler, int srcMipLvl) {
float2 srcTexelSize = BUFFER_PIXEL_SIZE * pow(2, srcMipLvl);
float2 off[4] = { float2(-0.5, -0.5), float2(0.5, -0.5), float2(-0.5, 0.5), float2(0.5, 0.5) };
float minDepth = 1.0;
[unroll] for(int i=0; i<4; i++)
minDepth = min(minDepth, tex2D(srcSampler, centerUV + off[i] * srcTexelSize).r);
return minDepth;
}
/*--------------.
| :: SHADERS :: |
'--------------*/
float PS_GenerateMip0(VSOUT input) : SV_Target
{
float2 blockOriginUV = floor(input.uv / (BUFFER_PIXEL_SIZE * 2.0)) * (BUFFER_PIXEL_SIZE * 2.0);
float2 uvs[4] = { blockOriginUV + BUFFER_PIXEL_SIZE * float2(0.5, 0.5),
blockOriginUV + BUFFER_PIXEL_SIZE * float2(1.5, 0.5),
blockOriginUV + BUFFER_PIXEL_SIZE * float2(0.5, 1.5),
blockOriginUV + BUFFER_PIXEL_SIZE * float2(1.5, 1.5) };
float d0 = tex2D(Kernel::sDepth, uvs[0]).r;
float d1 = tex2D(Kernel::sDepth, uvs[1]).r;
float d2 = tex2D(Kernel::sDepth, uvs[2]).r;
float d3 = tex2D(Kernel::sDepth, uvs[3]).r;
return min(min(d0, d1), min(d2, d3));
}
float PS_ReduceMip1 (VSOUT input) : SV_Target { return SamplePrevHiZ(input.uv, sHiZMip0, 0); }
float PS_ReduceMip2 (VSOUT input) : SV_Target { return SamplePrevHiZ(input.uv, sHiZMip1, 1); }
float PS_ReduceMip3 (VSOUT input) : SV_Target { return SamplePrevHiZ(input.uv, sHiZMip2, 2); }
float PS_ReduceMip4 (VSOUT input) : SV_Target { return SamplePrevHiZ(input.uv, sHiZMip3, 3); }
float PS_ReduceMip5 (VSOUT input) : SV_Target { return SamplePrevHiZ(input.uv, sHiZMip4, 4); }
float PS_TraceAO(VSOUT input) : SV_Target
{
float4 gbuffer = tex2D(Kernel::sNormals, input.uv);
float3 normal = gbuffer.rgb;
float depth = gbuffer.a;
if (depth == 0 || depth >= DEPTH_BOUNDARY) discard;
float3 startPos = UVToViewSpace(input.uv, depth, input);
float3 tangent, bitangent;
BuildOrthonormalBasis(normal, tangent, bitangent);
float2 noise = GetStratifiedNoise(input.vpos.xy);
float3 rayDir = GenerateHemisphereDirection(normal, noise, tangent, bitangent);
float totalRayLength = 0.7 * depth;
float baseStepSize = totalRayLength / (float)AO_MAX_MARCH_STEPS;
float stepSize = baseStepSize;
float3 currentPos = startPos + rayDir * stepSize;
float occlusion = 0.0;
float t = stepSize;
[loop]
for (int step = 0; step < AO_MAX_MARCH_STEPS; step++) {
if (t >= totalRayLength) break;
float2 hitPos = ViewSpaceToUV(currentPos, input);
if (IsOOB(hitPos)) break;
//select the appropriate Mip Level
float2 ray_screen_velocity = abs(rayDir.xy / currentPos.z) * float2(BUFFER_WIDTH, BUFFER_HEIGHT);
float footprint = max(ray_screen_velocity.x, ray_screen_velocity.y) * max(stepSize / currentPos.z, 1.0);
int mip = clamp(int(log2(max(footprint, 1.0))), 0, 5);
float HiZDepth;
if (mip==5) HiZDepth = tex2Dlod(sHiZMip5, float4(hitPos,0,0)).r;
else if (mip==4) HiZDepth = tex2Dlod(sHiZMip4, float4(hitPos,0,0)).r;
else if (mip==3) HiZDepth = tex2Dlod(sHiZMip3, float4(hitPos,0,0)).r;
else if (mip==2) HiZDepth = tex2Dlod(sHiZMip2, float4(hitPos,0,0)).r;
else if (mip==1) HiZDepth = tex2Dlod(sHiZMip1, float4(hitPos,0,0)).r;
else HiZDepth = tex2Dlod(sHiZMip0, float4(hitPos,0,0)).r;
//skip some empty space
float currentStepSize = stepSize * max(1.0, float(mip) * 0.5); //stepsize mip scaling
if (currentPos.z < HiZDepth && (HiZDepth - currentPos.z) > currentStepSize) {
float leap = max(currentStepSize, (HiZDepth - currentPos.z) * 0.065);
currentPos += rayDir * leap;
t += leap;
continue;
}
//hit test
float sceneDepth = tex2Dlod(Kernel::sDepth, float4(hitPos, 0, 0)).r;
float depthDiff = currentPos.z - sceneDepth;
float maxThickness = currentPos.z * 0.6;
if (depthDiff > (currentPos.z * 0.0001) && depthDiff < maxThickness) {
float3 scenePos = UVToViewSpace(hitPos, sceneDepth, input);
float hitDistance = length(scenePos - startPos);
float normalizedDist = hitDistance / totalRayLength;
occlusion = 1.0 - saturate(depthDiff / maxThickness);
occlusion = occlusion * occlusion;
occlusion = saturate(pow(saturate(1.0 - normalizedDist), 1.2) * occlusion * 1.4);
break;
}
currentPos += rayDir * stepSize;
t += stepSize;
}
float aoFactor = 1.0 - saturate(occlusion * AO_INTENSITY);
return aoFactor;
}
float2 PS_TemporalFilter(VSOUT input) : SV_Target
{
float depth = tex2D(Kernel::sDepth, input.uv).r;
//overwrite noise at boundary with clean White, prevents gaps
if (depth >= DEPTH_BOUNDARY) return float2(1.0, 1.0); //1.0 AO, 1.0 Moment
if (depth == 0) discard;
float ao = tex2D(sAOTrace, input.uv).r;
ao = lerp(1.0, ao, CalculateDepthFade(depth));
float moment = ao * ao;
float2 flow = tex2D(Kernel::sFlow, input.uv).xy;
float confidence = tex2D(Kernel::sConfidence, input.uv).x;
confidence = saturate(confidence + log2(2.0 - confidence) * 0.6); //boost confidence
float2 rawHistory = tex2D(sPrevAO, input.uv + flow).rg; //history stores "1.0 - AO". 0.0 (Black Texture) -> Reads as 1.0 (White)
float prevAO = 1.0 - rawHistory.r;
float prevMoment = 1.0 - rawHistory.g;
float alpha = confidence * 0.98;
ao = lerp(ao, prevAO, alpha);
moment = lerp(moment, prevMoment, alpha);
//max(..., 0.001) to ensure we NEVER write exactly 0.0 again
//this tells the next frame "I contain data"
return float2(max(ao, 0.001), max(moment, 0.001));
}
float2 PS_StoreAO(VSOUT input) : SV_Target
{
//must prevent history collision here
//if we store exactly 0.0 (means White), the next frame's blend pass thinks
//history is empty and resets it, causing shimmer
//so clamp to 0.0001 so the system knows "This is valid history data"
float2 data = tex2D(sAO1, input.uv).rg;
return float2(max(1.0 - data.r, 0.0001), max(1.0 - data.g, 0.0001)); //store inverted
}
float2 PS_ATrousPass1(VSOUT input) : SV_Target { return ATrousFilter(sAO1, input.uv, 2, false); }
float4 PS_ToDisplay(VSOUT input) : SV_Target
{
float depth = tex2D(Kernel::sDepth, input.uv).r;
float ao = ATrousFilter(sAO2Linear, input.uv, 4, true).r; //stable AO mask (fades to 1.0)
if (DEBUG_VIEW) {
#if BUFFER_COLOR_SPACE > 1
return float4(ToOutputColorspace(ao.xxx, true), 1.0);
#else
return float4(ao.xxx, 1.0);
#endif
}
if (depth == 0 || depth >= DEPTH_BOUNDARY) discard;
float3 base = GetLinearColor(input.uv, true);
base *= ao;
return float4(ToOutputColorspace(base, true), 1.0);
}
/*----------------.
| :: TECHNIQUE :: |
'----------------*/
technique Lumenite_LSAO <
ui_label = "LUMENITE: LSAO";
ui_tooltip = "Large-Scale Ray Traced Ambient Occlusion (Screen Space).";
>
{
pass { VertexShader = VS; PixelShader = PS_GenerateMip0; RenderTarget = tHiZMip0; }
pass { VertexShader = VS; PixelShader = PS_ReduceMip1; RenderTarget = tHiZMip1; }
pass { VertexShader = VS; PixelShader = PS_ReduceMip2; RenderTarget = tHiZMip2; }
pass { VertexShader = VS; PixelShader = PS_ReduceMip3; RenderTarget = tHiZMip3; }
pass { VertexShader = VS; PixelShader = PS_ReduceMip4; RenderTarget = tHiZMip4; }
pass { VertexShader = VS; PixelShader = PS_ReduceMip5; RenderTarget = tHiZMip5; }
pass { VertexShader = VS; PixelShader = PS_TraceAO; RenderTarget = tAOTrace; }
pass { VertexShader = VS; PixelShader = PS_TemporalFilter; RenderTarget = tAO1; }
pass { VertexShader = VS; PixelShader = PS_StoreAO; RenderTarget = tPrevAO; }
pass { VertexShader = VS; PixelShader = PS_ATrousPass1; RenderTarget = tAO2; }
pass { VertexShader = VS; PixelShader = PS_ToDisplay; }
}
}
@@ -0,0 +1,403 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : lumenite_QuantAO.fx
Version : 2026.06.09
Author : Afzaal (Kaidō)
Description: Fast Ambient Occlusion (Screen Space).
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
/*------------------.
| :: DEFINITIONS :: |
'------------------*/
#define FOV 60.0
#define NEAR_PLANE 0.01
#define AO_MAX_MARCH_STEPS 48
/*--------------.
| :: HEADERS :: |
'--------------*/
#include "ReShade.fxh"
#include "./include/lumenite_Projections.fxh"
#include "./include/lumenite_Helpers.fxh"
#include "./include/lumenite_ColorManagement.fxh"
/*---------------.
| :: UNIFORMS :: |
'---------------*/
uniform bool DEBUG_VIEW <
ui_label = "Show AO Mask";
ui_tooltip = "Debug view for the AO. Shows raw AO.";
ui_category = "Ambient Occlusion";
> = 0;
uniform float DEPTH_BOUNDARY <
ui_type = "slider";
ui_min = 0.001; ui_max = 0.999; ui_step = 0.001;
ui_label = "AO Range";
ui_tooltip = "The Z+ range/depth in which the effect is applied.";
ui_category = "Ambient Occlusion";
hidden = false;
> = 0.6;
uniform float DEPTH_FADE_START <
ui_type = "slider";
ui_min = 0.1; ui_max = 1.0; ui_step = 0.01;
ui_label = "Z+ Fade Start (%)";
ui_tooltip = "Z+ fraction where effect starts fading out (relative to AO Range)";
ui_category = "Ambient Occlusion";
hidden = true;
> = 0.75;
uniform float AO_INTENSITY <
ui_type = "drag";
ui_min = 0.0; ui_max = 1.0;
ui_label = "AO Strength";
ui_tooltip = "Controls the intensity of the ambient occlusion effect.";
ui_category = "Ambient Occlusion";
> = 1.0;
/*--------------.
| :: IMPORTS :: |
'--------------*/
namespace QuantMotion {
texture2D tFlow { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
sampler2D sFlow { Texture = tFlow; MagFilter = POINT; MinFilter = POINT; };
texture2D tConfidence { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
sampler2D sConfidence { Texture = tConfidence; };
}
namespace LumeniteQuantAO {
/*---------------------.
| :: RENDER TARGETS :: |
'---------------------*/
texture tNormals { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = RGBA16F; };
sampler sNormals { Texture = tNormals; };
texture2D tDepth { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = R16F; };
sampler2D sDepth { Texture = tDepth; };
texture tAOTrace { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = R16F; };
sampler sAOTrace { Texture = tAOTrace; AddressU = CLAMP; AddressV = CLAMP; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; };
texture tAO1 { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = RG16F; };
sampler sAO1 { Texture = tAO1; AddressU = CLAMP; AddressV = CLAMP; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; };
texture tAO2 { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = RG16F; };
sampler sAO2 { Texture = tAO2; AddressU = CLAMP; AddressV = CLAMP; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; };
texture tAO3 { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = RG16F; };
sampler sAO3Linear { Texture = tAO3; AddressU = CLAMP; AddressV = CLAMP; MagFilter = LINEAR; MinFilter = LINEAR; };
texture tPrevAO { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = RG16F; };
sampler sPrevAO { Texture = tPrevAO; AddressU = CLAMP; AddressV = CLAMP; MagFilter = LINEAR; MinFilter = LINEAR; MipFilter = LINEAR; };
//HiZ mipchain
texture tHiZMip0 { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; };
texture tHiZMip1 { Width = BUFFER_WIDTH/2; Height = BUFFER_HEIGHT/2; Format = R16F; };
texture tHiZMip2 { Width = BUFFER_WIDTH/4; Height = BUFFER_HEIGHT/4; Format = R16F; };
texture tHiZMip3 { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
texture tHiZMip4 { Width = BUFFER_WIDTH/16; Height = BUFFER_HEIGHT/16; Format = R16F; };
texture tHiZMip5 { Width = BUFFER_WIDTH/32; Height = BUFFER_HEIGHT/32; Format = R16F; };
sampler sHiZMip0 { Texture = tHiZMip0; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
sampler sHiZMip1 { Texture = tHiZMip1; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
sampler sHiZMip2 { Texture = tHiZMip2; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
sampler sHiZMip3 { Texture = tHiZMip3; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
sampler sHiZMip4 { Texture = tHiZMip4; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
sampler sHiZMip5 { Texture = tHiZMip5; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; };
/*--------------.
| :: HELPERS :: |
'--------------*/
void BuildOrthonormalBasis(float3 n, out float3 b1, out float3 b2)
{
if (n.z < -0.9999999) {
b1 = float3(0.0, -1.0, 0.0);
b2 = float3(-1.0, 0.0, 0.0);
} else {
float a = rcp(1.0 + n.z);
float b = -n.x * n.y * a;
b1 = float3(mad(-n.x * n.x, a, 1.0), b, -n.x);
b2 = float3(b, mad(-n.y * n.y, a, 1.0), -n.y);
}
}
float3 GenerateHemisphereDirection(float3 normal, float2 rand, float3 tangent, float3 bitangent)
{
float phi = rand.x * 6.28318530718; //2.0*PI as constant
float sinPhi, cosPhi;
sincos(phi, sinPhi, cosPhi);
float cosTheta = sqrt(1.0 - rand.y);
float sinTheta = sqrt(rand.y);
float3 result = normal * cosTheta;
result = mad(bitangent, sinTheta * sinPhi, result);
result = mad(tangent, sinTheta * cosPhi, result);
return result;
}
float CalculateDepthFade(float depth)
{
float fadeStartDepth = DEPTH_BOUNDARY * DEPTH_FADE_START;
float fadeRange = DEPTH_BOUNDARY - fadeStartDepth;
return 1.0 - saturate((depth - fadeStartDepth) / fadeRange);
}
float2 ATrousFilter(sampler SourceSampler, float2 uv, uint dilation, bool adaptiveDilation)
{
float4 gbuffer = tex2D(sNormals, uv);
if (gbuffer.a == 0 || gbuffer.a >= DEPTH_BOUNDARY) return float2(1.0, 0.0);
[branch] if (adaptiveDilation) {
float confidence = tex2Dlod(QuantMotion::sConfidence, float4(uv, 0, 0)).r;
dilation += uint(round((1.0 - confidence) * 2.0)); //scale filter kernel w. motion by up to a factor of 2
}
float2 centerData = tex2Dlod(SourceSampler, float4(uv, 0, 0)).rg;
float variance = max(0.0, centerData.g - (centerData.r * centerData.r)); //Moment - AO^2
variance = max(variance, 0.0001);
float2 sum = centerData;
float totalWeight = 1.0;
for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) {
if (x == 0 && y == 0) continue;
float2 sampleUV = uv + float2(x, y) * dilation * (BUFFER_PIXEL_SIZE * 2.0); //don't forget the x2.0 to properly step half-res grid!
float2 sampleData = tex2Dlod(SourceSampler, float4(sampleUV, 0, 0)).rg;
float4 sampleGeo = tex2Dlod(sNormals, float4(sampleUV, 0, 0));
float depthWeight = exp(-abs(gbuffer.a - sampleGeo.a) / (gbuffer.a * 0.02 + 0.001));
float normalWeight = pow(saturate(dot(gbuffer.rgb, sampleGeo.rgb)), 50.0);
float aoDiff = centerData.r - sampleData.r;
float aoWeight = exp(-(aoDiff * aoDiff) / (variance + 0.0001));
float weight = depthWeight * normalWeight * aoWeight;
sum += sampleData * weight;
totalWeight += weight;
}
return sum / (totalWeight + EPSILON);
}
float SamplePrevHiZ(float2 centerUV, sampler srcSampler, int srcMipLvl) {
float2 srcTexelSize = BUFFER_PIXEL_SIZE * pow(2, srcMipLvl);
float2 off[4] = { float2(-0.5, -0.5), float2(0.5, -0.5), float2(-0.5, 0.5), float2(0.5, 0.5) };
float minDepth = 1.0;
[unroll] for(int i=0; i<4; i++)
minDepth = min(minDepth, tex2D(srcSampler, centerUV + off[i] * srcTexelSize).r);
return minDepth;
}
/*--------------.
| :: SHADERS :: |
'--------------*/
void PS_ReconstructNormals(VSOUT input, out float4 gbuffer : SV_Target0, out float depthC : SV_Target1)
{
depthC = GetDepth(input.uv);
const float2 offsetX = float2(BUFFER_PIXEL_SIZE.x, 0);
const float2 offsetY = float2(0, BUFFER_PIXEL_SIZE.y);
float3 pC = UVToViewSpace(input.uv, depthC, input);
float3 pL = UVToViewSpace(input.uv - offsetX, GetDepth(input.uv - offsetX), input);
float3 pR = UVToViewSpace(input.uv + offsetX, GetDepth(input.uv + offsetX), input);
float3 pT = UVToViewSpace(input.uv - offsetY, GetDepth(input.uv - offsetY), input);
float3 pB = UVToViewSpace(input.uv + offsetY, GetDepth(input.uv + offsetY), input);
float3 diffX2 = pR - pC;
float3 diffX1 = pC - pL;
float3 diffY2 = pB - pC;
float3 diffY1 = pC - pT;
float lenSqX2 = dot(diffX2, diffX2);
float lenSqX1 = dot(diffX1, diffX1);
float lenSqY2 = dot(diffY2, diffY2);
float lenSqY1 = dot(diffY1, diffY1);
float3 ddx = lenSqX2 < lenSqX1 ? diffX2 : diffX1;
float3 ddy = lenSqY2 < lenSqY1 ? diffY2 : diffY1;
float3 geoNormal = normalize(cross(ddx, ddy));
gbuffer = float4(geoNormal, depthC);
}
float PS_GenerateMip0(VSOUT input) : SV_Target
{
float2 blockOriginUV = floor(input.uv / (BUFFER_PIXEL_SIZE * 2.0)) * (BUFFER_PIXEL_SIZE * 2.0);
float2 uvs[4] = { blockOriginUV + BUFFER_PIXEL_SIZE * float2(0.5, 0.5),
blockOriginUV + BUFFER_PIXEL_SIZE * float2(1.5, 0.5),
blockOriginUV + BUFFER_PIXEL_SIZE * float2(0.5, 1.5),
blockOriginUV + BUFFER_PIXEL_SIZE * float2(1.5, 1.5) };
float d0 = tex2D(sDepth, uvs[0]).r;
float d1 = tex2D(sDepth, uvs[1]).r;
float d2 = tex2D(sDepth, uvs[2]).r;
float d3 = tex2D(sDepth, uvs[3]).r;
return min(min(d0, d1), min(d2, d3));
}
float PS_ReduceMip1 (VSOUT input) : SV_Target { return SamplePrevHiZ(input.uv, sHiZMip0, 0); }
float PS_ReduceMip2 (VSOUT input) : SV_Target { return SamplePrevHiZ(input.uv, sHiZMip1, 1); }
float PS_ReduceMip3 (VSOUT input) : SV_Target { return SamplePrevHiZ(input.uv, sHiZMip2, 2); }
float PS_ReduceMip4 (VSOUT input) : SV_Target { return SamplePrevHiZ(input.uv, sHiZMip3, 3); }
float PS_ReduceMip5 (VSOUT input) : SV_Target { return SamplePrevHiZ(input.uv, sHiZMip4, 4); }
float PS_TraceAO(VSOUT input) : SV_Target
{
float4 gbuffer = tex2D(sNormals, input.uv);
float3 normal = gbuffer.rgb;
float depth = gbuffer.a;
if (depth == 0 || depth >= DEPTH_BOUNDARY) discard;
float3 startPos = UVToViewSpace(input.uv, depth, input);
float3 tangent, bitangent;
BuildOrthonormalBasis(normal, tangent, bitangent);
float2 noise = GetStratifiedNoise(input.vpos.xy);
float3 rayDir = GenerateHemisphereDirection(normal, noise, tangent, bitangent);
float totalRayLength = 0.7 * depth;
float baseStepSize = totalRayLength / (float)AO_MAX_MARCH_STEPS;
float stepSize = baseStepSize;
float3 currentPos = startPos + rayDir * stepSize;
float occlusion = 0.0;
float t = stepSize;
[loop]
for (int step = 0; step < AO_MAX_MARCH_STEPS; step++) {
if (t >= totalRayLength) break;
float2 hitPos = ViewSpaceToUV(currentPos, input);
if (IsOOB(hitPos)) break;
//select the appropriate Mip Level
float2 ray_screen_velocity = abs(rayDir.xy / currentPos.z) * float2(BUFFER_WIDTH, BUFFER_HEIGHT);
float footprint = max(ray_screen_velocity.x, ray_screen_velocity.y) * max(stepSize / currentPos.z, 1.0);
int mip = clamp(int(log2(max(footprint, 1.0))), 0, 5);
float HiZDepth;
if (mip==5) HiZDepth = tex2Dlod(sHiZMip5, float4(hitPos,0,0)).r;
else if (mip==4) HiZDepth = tex2Dlod(sHiZMip4, float4(hitPos,0,0)).r;
else if (mip==3) HiZDepth = tex2Dlod(sHiZMip3, float4(hitPos,0,0)).r;
else if (mip==2) HiZDepth = tex2Dlod(sHiZMip2, float4(hitPos,0,0)).r;
else if (mip==1) HiZDepth = tex2Dlod(sHiZMip1, float4(hitPos,0,0)).r;
else HiZDepth = tex2Dlod(sHiZMip0, float4(hitPos,0,0)).r;
//skip some empty space
float currentStepSize = stepSize * max(1.0, float(mip) * 0.5); //stepsize mip scaling
if (currentPos.z < HiZDepth && (HiZDepth - currentPos.z) > currentStepSize) {
float leap = max(currentStepSize, (HiZDepth - currentPos.z) * 0.065);
currentPos += rayDir * leap;
t += leap;
continue;
}
//hit test
float sceneDepth = tex2Dlod(sDepth, float4(hitPos, 0, 0)).r;
float depthDiff = currentPos.z - sceneDepth;
float maxThickness = currentPos.z * 0.6;
if (depthDiff > (currentPos.z * 0.0001) && depthDiff < maxThickness) {
float3 scenePos = UVToViewSpace(hitPos, sceneDepth, input);
float hitDistance = length(scenePos - startPos);
float normalizedDist = hitDistance / totalRayLength;
occlusion = 1.0 - saturate(depthDiff / maxThickness);
occlusion = occlusion * occlusion;
occlusion = saturate(pow(saturate(1.0 - normalizedDist), 1.2) * occlusion * 1.4);
break;
}
currentPos += rayDir * stepSize;
t += stepSize;
}
float aoFactor = 1.0 - saturate(occlusion * AO_INTENSITY);
return aoFactor;
}
float2 PS_TemporalFilter(VSOUT input) : SV_Target
{
float depth = tex2D(sDepth, input.uv).r;
//overwrite noise at boundary with clean White, prevents gaps
if (depth >= DEPTH_BOUNDARY) return float2(1.0, 1.0); //1.0 AO, 1.0 Moment
if (depth == 0) discard;
float ao = tex2D(sAOTrace, input.uv).r;
ao = lerp(1.0, ao, CalculateDepthFade(depth));
float moment = ao * ao;
float2 flow = tex2D(QuantMotion::sFlow, input.uv).xy;
float confidence = tex2D(QuantMotion::sConfidence, input.uv).x;
confidence = saturate(confidence + log2(2.0 - confidence) * 0.55); //boost confidence
float2 rawHistory = tex2D(sPrevAO, input.uv + flow).rg; //history stores "1.0 - AO". 0.0 (Black Texture) -> Reads as 1.0 (White)
float prevAO = 1.0 - rawHistory.r;
float prevMoment = 1.0 - rawHistory.g;
float alpha = confidence * 0.98;
ao = lerp(ao, prevAO, alpha);
moment = lerp(moment, prevMoment, alpha);
//max(..., 0.001) to ensure we NEVER write exactly 0.0 again
//this tells the next frame "I contain data"
return float2(max(ao, 0.001), max(moment, 0.001));
}
float2 PS_StoreAO(VSOUT input) : SV_Target
{
//must prevent history collision here
//if we store exactly 0.0 (means White), the next frame's blend pass thinks
//history is empty and resets it, causing shimmer
//so clamp to 0.0001 so the system knows "This is valid history data"
float2 data = tex2D(sAO1, input.uv).rg;
return float2(max(1.0 - data.r, 0.0001), max(1.0 - data.g, 0.0001)); //store inverted
}
float2 PS_ATrousPass1(VSOUT input) : SV_Target { return ATrousFilter(sAO1, input.uv, 2, false); }
float2 PS_ATrousPass2(VSOUT input) : SV_Target { return ATrousFilter(sAO2, input.uv, 4, true); }
float4 PS_ToDisplay(VSOUT input) : SV_Target
{
float depth = tex2D(sDepth, input.uv).r;
float ao = tex2D(sAO3Linear, input.uv).r;
if (DEBUG_VIEW) {
#if BUFFER_COLOR_SPACE > 1
return float4(ToOutputColorspace(ao.xxx, true), 1.0);
#else
return float4(ao.xxx, 1.0);
#endif
}
if (depth == 0 || depth >= DEPTH_BOUNDARY) discard;
float3 base = GetLinearColor(input.uv, true);
base *= ao;
return float4(ToOutputColorspace(base, true), 1.0);
}
/*----------------.
| :: TECHNIQUE :: |
'----------------*/
technique Lumenite_QuantAO <
ui_label = "LUMENITE: QuantAO";
ui_tooltip = "Fast Ambient Occlusion (Screen Space).";
>
{
pass { VertexShader = VS; PixelShader = PS_ReconstructNormals; RenderTarget0 = tNormals; RenderTarget1 = tDepth; }
pass { VertexShader = VS; PixelShader = PS_GenerateMip0; RenderTarget = tHiZMip0; }
pass { VertexShader = VS; PixelShader = PS_ReduceMip1; RenderTarget = tHiZMip1; }
pass { VertexShader = VS; PixelShader = PS_ReduceMip2; RenderTarget = tHiZMip2; }
pass { VertexShader = VS; PixelShader = PS_ReduceMip3; RenderTarget = tHiZMip3; }
pass { VertexShader = VS; PixelShader = PS_ReduceMip4; RenderTarget = tHiZMip4; }
pass { VertexShader = VS; PixelShader = PS_ReduceMip5; RenderTarget = tHiZMip5; }
pass { VertexShader = VS; PixelShader = PS_TraceAO; RenderTarget = tAOTrace; }
pass { VertexShader = VS; PixelShader = PS_TemporalFilter; RenderTarget = tAO1; }
pass { VertexShader = VS; PixelShader = PS_StoreAO; RenderTarget = tPrevAO; }
pass { VertexShader = VS; PixelShader = PS_ATrousPass1; RenderTarget = tAO2; }
pass { VertexShader = VS; PixelShader = PS_ATrousPass2; RenderTarget = tAO3; }
pass { VertexShader = VS; PixelShader = PS_ToDisplay; }
}
}
@@ -0,0 +1,444 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : QuantMotion.fx
Version : 2026.06.16
Author : Afzaal (Kaidō)
Description: Superfast motion vectors for low-end hardware.
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
/*------------------.
| :: DEFINITIONS :: |
'------------------*/
#define EPSILON 1e-6
#ifndef DEBUG_FLOW
#define DEBUG_FLOW 0
#endif
/*--------------.
| :: HEADERS :: |
'--------------*/
#include "ReShade.fxh"
/*---------------.
| :: UNIFORMS :: |
'---------------*/
uniform uint FRAME_COUNT < source = "framecount"; >;
namespace QuantMotion {
/*---------------------.
| :: RENDER TARGETS :: |
'---------------------*/
texture2D tFlow { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
sampler2D sFlow { Texture = tFlow; MagFilter = POINT; MinFilter = POINT; };
texture2D tConfidence { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
sampler2D sConfidence { Texture = tConfidence; };
texture2D tCurrLuma { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; MipLevels = 8; };
sampler2D sCurrLuma { Texture = tCurrLuma; MagFilter = LINEAR; MinFilter = LINEAR; MipFilter = LINEAR; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tPrevLuma { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; MipLevels = 8; };
sampler2D sPrevLuma { Texture = tPrevLuma; MagFilter = LINEAR; MinFilter = LINEAR; MipFilter = LINEAR; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow128 { Width = BUFFER_WIDTH/128; Height = BUFFER_HEIGHT/128; Format = RG16F; };
sampler2D sFlow128 { Texture = tFlow128; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow64A { Width = BUFFER_WIDTH/64; Height = BUFFER_HEIGHT/64; Format = RG16F; };
sampler2D sFlow64A { Texture = tFlow64A; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow64B { Width = BUFFER_WIDTH/64; Height = BUFFER_HEIGHT/64; Format = RG16F; };
sampler2D sFlow64B { Texture = tFlow64B; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow32A { Width = BUFFER_WIDTH/32; Height = BUFFER_HEIGHT/32; Format = RG16F; };
sampler2D sFlow32A { Texture = tFlow32A; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow32B { Width = BUFFER_WIDTH/32; Height = BUFFER_HEIGHT/32; Format = RG16F; };
sampler2D sFlow32B { Texture = tFlow32B; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow16A { Width = BUFFER_WIDTH/16; Height = BUFFER_HEIGHT/16; Format = RG16F; };
sampler2D sFlow16A { Texture = tFlow16A; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow16B { Width = BUFFER_WIDTH/16; Height = BUFFER_HEIGHT/16; Format = RG16F; };
sampler2D sFlow16B { Texture = tFlow16B; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tFlow8 { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
sampler2D sFlow8 { Texture = tFlow8; MagFilter = POINT; MinFilter = POINT; AddressU = CLAMP; AddressV = CLAMP; AddressW = CLAMP; };
texture2D tPrevFrameFlow { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
sampler2D sPrevFrameFlow { Texture = tPrevFrameFlow; MagFilter = POINT; MinFilter = POINT; };
texture2D tPrevConfidence { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
sampler2D sPrevConfidence { Texture = tPrevConfidence; };
/*--------------.
| :: HELPERS :: |
'--------------*/
bool IsOOB(float2 uv) {
return any(uv < 0.0) || any(uv > 1.0);
}
float3 GetColor(float2 uv)
{
return tex2Dlod(ReShade::BackBuffer, float4(uv, 0, 0)).rgb;
}
float3 MotionToColor(float2 motion)
{
float angle = atan2(-motion.y, -motion.x) / 6.283 + 0.5;
float rawLength = length(motion) / (15.0 * BUFFER_PIXEL_SIZE.x);
float compressed = rawLength / (1.0 + rawLength * 1.4); //asymptotic squash
float boosted = pow(compressed, 0.5); //lift shadows
float magnitude = saturate(lerp(compressed, boosted, saturate(rawLength * 3.0)));
float3 hsv = float3(angle, 1, magnitude);
float4 K = float4(1, 2/3.0, 1/3.0, 3);
float3 p = abs(frac(hsv.xxx + K.xyz) * 6 - K.www);
return hsv.z * lerp(K.xxx, clamp(p - K.xxx, 0, 1), hsv.y) + 0.1;
}
float ZMSAD(sampler2D currLumaSrc, sampler2D prevLumaSrc, float2 posA, float2 posB, float2 texelSize, uint mip)
{
static const int2 offsets[9] = {
int2(0, 3),
int2(0, 1),
int2(-3,0), int2(-1,0), int2(0, 0), int2(1,0), int2(3,0),
int2(0,-1),
int2(0,-3)
};
//gather samples and calculate the mean for each patch
float samplesA[9], samplesB[9];
float meanA = 0.0, meanB = 0.0;
[unroll] for(int i = 0; i < 9; i++) {
float2 offset = float2(offsets[i]) * texelSize;
samplesA[i] = tex2Dlod(currLumaSrc, float4(posA + offset, 0, mip)).r;
samplesB[i] = tex2Dlod(prevLumaSrc, float4(posB + offset, 0, mip)).r;
meanA += samplesA[i];
meanB += samplesB[i];
}
meanA /= 9.0;
meanB /= 9.0;
//SAD on the normalized samples
float err = 0.0;
[unroll] for(int i = 0; i < 9; i++)
err += abs((samplesA[i] - meanA) - (samplesB[i] - meanB));
return ((err / 9.0) + EPSILON);
}
float2 Median9(sampler2D flowSrc, float2 uv, float2 texelSize, uint mip)
{
float2 v[9];
int idx = 0;
[unroll] for(int dy = -1; dy <= 1; dy++) for(int dx = -1; dx <= 1; dx++)
v[idx++] = tex2Dlod(flowSrc, float4(uv + float2(dx, dy) * texelSize, 0, mip)).xy;
//bubble sort ensures the Median lands in v[4], only needs 5 passes
//indices 4,5,6,7,8 contain the 5 largest items, so v[4] is the median
[unroll] for(int k = 0; k < 5; k++) for(int i = 0; i < 8 - k; i++) { //checks decrease as right side gets sorted
float2 a = v[i];
float2 b = v[i+1];
v[i] = min(a, b);
v[i+1] = max(a, b);
}
return v[4];
}
float2 BilateralMedian9(sampler2D flowSrc, float2 uv, float2 texelSize, uint mip)
{
static const int2 DENSE_3X3[9] = {
int2(-1,-1), int2(0,-1), int2(1,-1),
int2(-1, 0), int2(0, 0), int2(1, 0),
int2(-1, 1), int2(0, 1), int2(1, 1)
};
float lumaC = tex2Dlod(sCurrLuma, float4(uv, 0, 0)).x;
float lumaW = tex2Dlod(sCurrLuma, float4(uv + float2(-1.0, 0.0) * texelSize, 0, 0)).x;
float lumaE = tex2Dlod(sCurrLuma, float4(uv + float2( 1.0, 0.0) * texelSize, 0, 0)).x;
float lumaN = tex2Dlod(sCurrLuma, float4(uv + float2( 0.0,-1.0) * texelSize, 0, 0)).x;
float lumaS = tex2Dlod(sCurrLuma, float4(uv + float2( 0.0, 1.0) * texelSize, 0, 0)).x;
//central-difference gradient, wider baseline than quad ddx/ddy, derived from real samples
float dxLuma = (lumaE - lumaW) * 0.5;
float dyLuma = (lumaS - lumaN) * 0.5;
float2 v[9];
uint validCount = 0;
[unroll] for (int i = 0; i < 9; i++) {
int2 off = DENSE_3X3[i];
float2 sampleUV = uv + float2(off) * texelSize;
//cardinals + center use sampled luma; diagonals get linear prediction
float sampleLuma = lumaC; //covers (0,0)
if (off.x == -1 && off.y == 0) sampleLuma = lumaW;
else if (off.x == 1 && off.y == 0) sampleLuma = lumaE;
else if (off.x == 0 && off.y == -1) sampleLuma = lumaN;
else if (off.x == 0 && off.y == 1) sampleLuma = lumaS;
else if (off.x != 0 && off.y != 0) sampleLuma = lumaC + float(off.x) * dxLuma + float(off.y) * dyLuma;
bool isValid = abs(lumaC - sampleLuma) <= 0.05;
v[i] = isValid ? tex2Dlod(flowSrc, float4(sampleUV, 0, mip)).xy : float2(1e38, 1e38);
validCount += uint(isValid);
}
if(validCount < 3u) return v[4];
//right-to-left bubble: smallest reaches v[0] per pass; after 5 passes, v[0..4] sorted ascending
[unroll] for(int k = 0; k < 5; k++) for(int j = 7; j >= k; j--) {
float2 a = v[j];
float2 b = v[j+1];
v[j] = min(a, b);
v[j+1] = max(a, b);
}
uint medianIdx = validCount / 2u;
float2 result = v[1]; //fallback for validCount == 3 (medianIdx 1)
if (medianIdx == 2u) result = v[2];
if (medianIdx == 3u) result = v[3];
if (medianIdx == 4u) result = v[4];
return result;
}
float2 ATrousFilter(sampler2D motionSrc, float2 uv, uint dilation, uint mip)
{
static const int2 offsets[8] = { int2(-1,-1), int2(0,-1), int2(1,-1),
int2(-1, 0), int2(1, 0),
int2(-1, 1), int2(0, 1), int2(1, 1) };
float2 centerFlow = tex2Dlod(motionSrc, float4(uv, 0, 0)).xy;
float centerConf = max(tex2Dlod(sConfidence, float4(uv, 0, 0)).r, 0.01); //0.01 floor prevents NaN if conf hits 0
float2 sum = centerFlow * centerConf;
float totalWeight = centerConf;
[unroll] for (int i = 0; i < 8; i++) {
float2 sampleUV = uv + float2(offsets[i]) * dilation * BUFFER_PIXEL_SIZE * 8.0; //*8 = stride of flow grid
float2 sampleFlow = tex2Dlod(motionSrc, float4(sampleUV, 0, 0)).xy;
float2 flowDelta = (sampleFlow - centerFlow) / BUFFER_PIXEL_SIZE * 8.0;
float flowWeight = exp(-dot(flowDelta, flowDelta) * 0.125);
float weight = flowWeight;
sum += sampleFlow * weight;
totalWeight += weight;
}
return sum / (totalWeight + EPSILON);
}
float2 UpscaleFlow(sampler2D coarseSrc, sampler2D currLumaSrc, sampler2D prevLumaSrc, float2 uv, float2 texelSize, uint mip)
{
if(FRAME_COUNT == 0) return float2(0, 0);
float2 coarseTexelSize = rcp(float2(tex2Dsize(coarseSrc, 0)));
//pool candidates for tournament selection. order matters here
float2 candidates[6];
candidates[0] = tex2D(coarseSrc, uv).xy ;
candidates[1] = tex2D(coarseSrc, uv + float2(0, -coarseTexelSize.y)).xy ;
candidates[2] = tex2D(coarseSrc, uv + float2(0, coarseTexelSize.y)).xy ;
candidates[3] = tex2D(coarseSrc, uv - float2(coarseTexelSize.x, 0)).xy ;
candidates[4] = tex2D(coarseSrc, uv + float2(coarseTexelSize.x, 0)).xy ;
candidates[5] = tex2D(sPrevFrameFlow, uv).xy;
float minCost = 1e6;
float2 prediction = candidates[0];
[loop] for (int i = 0; i < 6; i++) {
float cost = ZMSAD(currLumaSrc, prevLumaSrc, uv, uv + candidates[i], texelSize, mip);
if (cost < minCost) {
minCost = cost;
prediction = candidates[i];
}
}
//refinement with parabolic fitting
float costLeft = ZMSAD(currLumaSrc, prevLumaSrc, uv, uv + prediction - float2(texelSize.x, 0), texelSize, mip);
float costRight = ZMSAD(currLumaSrc, prevLumaSrc, uv, uv + prediction + float2(texelSize.x, 0), texelSize, mip);
float costDown = ZMSAD(currLumaSrc, prevLumaSrc, uv, uv + prediction - float2(0, texelSize.y), texelSize, mip);
float costUp = ZMSAD(currLumaSrc, prevLumaSrc, uv, uv + prediction + float2(0, texelSize.y), texelSize, mip);
//sub-pixel offset (parabolic fitting)
float2 subpixelOffset;
subpixelOffset.x = (costLeft - costRight) / (4.0 * (costLeft + costRight - 2.0 * minCost) + EPSILON); //EPSILON for flat surface handling
subpixelOffset.y = (costDown - costUp) / (4.0 * (costDown + costUp - 2.0 * minCost) + EPSILON);
//clamp offset to a reasonable range
subpixelOffset = clamp(subpixelOffset, -0.5, 0.5);
return (prediction+subpixelOffset*texelSize);
}
/*--------------.
| :: SHADERS :: |
'--------------*/
float PS_PackFeatures(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
float luma = dot(GetColor(uv), float3(0.2126, 0.7152, 0.0722));
return luma * rcp(1.0 + luma);
}
float2 PS_ComputeFlow128(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
if(FRAME_COUNT == 0) return float2(0, 0);
static const int SEARCH_RADIUS = 3;
static const uint mip = 5;
float2 texelSize = BUFFER_PIXEL_SIZE * exp2(mip);
//candidate seeds for the coarsest level for tournament selection
float2 prevSeed = tex2D(sPrevFrameFlow, uv).xy;
float2 zeroSeed = float2(0, 0);
float prevCost = ZMSAD(sCurrLuma, sPrevLuma, uv, uv + prevSeed, texelSize, mip);
float zeroCost = ZMSAD(sCurrLuma, sPrevLuma, uv, uv + zeroSeed, texelSize, mip);
float2 seed = (zeroCost < prevCost) ? zeroSeed : prevSeed; //pick better candidate as seed
float2 bestFlow = seed;
float minCost = ZMSAD(sCurrLuma, sPrevLuma, uv, uv+seed, texelSize, mip);
//search in a grid AROUND the seed
for (int y = -SEARCH_RADIUS; y <= SEARCH_RADIUS; ++y) for (int x = -SEARCH_RADIUS; x <= SEARCH_RADIUS; ++x) {
if (x == 0 && y == 0) continue;
float2 candidateFlow = seed + float2(x, y) * texelSize;
float cost = ZMSAD(sCurrLuma, sPrevLuma, uv, uv + candidateFlow, texelSize, mip);
if (cost < minCost) {
minCost = cost;
bestFlow = candidateFlow;
if (minCost < 0.01) //near-perfect match found
return bestFlow;
}
}
return bestFlow;
}
float2 PS_UpscaleFlow64(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return UpscaleFlow(sFlow128, sCurrLuma, sPrevLuma, uv, BUFFER_PIXEL_SIZE*16.0, 4);
}
float2 PS_MedianPass64(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return Median9(sFlow64A, uv, BUFFER_PIXEL_SIZE*64.0, 6);
}
float2 PS_UpscaleFlow32(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return UpscaleFlow(sFlow64B, sCurrLuma, sPrevLuma, uv, BUFFER_PIXEL_SIZE*8.0, 3);
}
float2 PS_MedianPass32(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return Median9(sFlow32A, uv, BUFFER_PIXEL_SIZE*32.0, 5);
}
float2 PS_UpscaleFlow16(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return UpscaleFlow(sFlow32B, sCurrLuma, sPrevLuma, uv, BUFFER_PIXEL_SIZE*4.0, 2);
}
float2 PS_MedianPass16(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return Median9(sFlow16A, uv, BUFFER_PIXEL_SIZE*16.0, 4);
}
float2 PS_UpscaleFlow8(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return UpscaleFlow(sFlow16B, sCurrLuma, sPrevLuma, uv, BUFFER_PIXEL_SIZE*2.0, 1);
}
float2 PS_MedianPass8(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return BilateralMedian9(sFlow8, uv, BUFFER_PIXEL_SIZE*8.0, 3);
}
float2 PS_ATrousPassA(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target //stride 1
{
return ATrousFilter(sFlow, uv, 2, 3);
}
float2 PS_ATrousPassB(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target //stride 2
{
float2 flow = ATrousFilter(sFlow8, uv, 4, 1);
//kill sub-pixel noise
float flowPixelMag = length(flow / BUFFER_PIXEL_SIZE);
float gate = saturate(1.0 - pow(1.0 - saturate(saturate(flowPixelMag) - 0.2), 10.0)); //SNAP TO REALITY
return flow*gate;
}
float PS_Confidence(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
if(FRAME_COUNT == 0) return 0.0; //no confidence
float2 flow = tex2D(sFlow, uv).xy;
float2 prevUV = uv + flow; //warp prev frame forward
if(IsOOB(prevUV)) return 0.0;
float currLuma = tex2Dlod(sCurrLuma, float4(uv, 0, 3)).r;
float prevLuma = tex2Dlod(sPrevLuma, float4(prevUV, 0, 3)).r;
float lumaError = abs(currLuma - prevLuma);
if(lumaError > 0.1) return 0.0; //no confidence
float subpixelThreshold = length(BUFFER_PIXEL_SIZE);
float flowMagnitude = length(flow);
if (flowMagnitude <= subpixelThreshold) return 0.9; //if flow is subpixel, high confidence
float motionPenalty = flowMagnitude / subpixelThreshold;
float lengthConfidence = rcp(motionPenalty * 0.07 + 1.0);
float photometricConfidence = exp(-lumaError * 8.0 * lengthConfidence);
//current frame final confidence
float currentConf = lengthConfidence * photometricConfidence;
//temporal filter
float historyConf = tex2D(sPrevConfidence, prevUV).r;
float alpha = (currentConf < historyConf - 0.05) ? 0.5 : 0.1; //drop fast (kill speckles promptly), regain slowly (stay stable)
return lerp(historyConf, currentConf, alpha);
}
void PS_StoreFlow(float4 pos : SV_Position, float2 uv : TEXCOORD, out float2 flow : SV_Target0, out float confidence : SV_Target1)
{
flow = tex2D(sFlow, uv).xy;
confidence = tex2D(sConfidence, uv).r;
}
float PS_StoreLuma(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return tex2D(sCurrLuma, uv).r;
}
#if DEBUG_FLOW
float4 PS_Debug(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target
{
return float4(MotionToColor(tex2D(sFlow, uv).xy), 1);
}
#endif
/*----------------.
| :: TECHNIQUE :: |
'----------------*/
technique Lumenite_QuantMotion <
ui_label = "LUMENITE: QuantMotion";
ui_tooltip = "Superfast motion vectors for ReShade.";
>
{
//optical flow
pass { VertexShader = PostProcessVS; PixelShader = PS_PackFeatures; RenderTarget = tCurrLuma; }
pass { VertexShader = PostProcessVS; PixelShader = PS_ComputeFlow128; RenderTarget = tFlow128; }
pass { VertexShader = PostProcessVS; PixelShader = PS_UpscaleFlow64; RenderTarget = tFlow64A; }
pass { VertexShader = PostProcessVS; PixelShader = PS_MedianPass64; RenderTarget = tFlow64B; }
pass { VertexShader = PostProcessVS; PixelShader = PS_UpscaleFlow32; RenderTarget = tFlow32A; }
pass { VertexShader = PostProcessVS; PixelShader = PS_MedianPass32; RenderTarget = tFlow32B; }
pass { VertexShader = PostProcessVS; PixelShader = PS_UpscaleFlow16; RenderTarget = tFlow16A; }
pass { VertexShader = PostProcessVS; PixelShader = PS_MedianPass16; RenderTarget = tFlow16B; }
pass { VertexShader = PostProcessVS; PixelShader = PS_UpscaleFlow8; RenderTarget = tFlow8; }
pass { VertexShader = PostProcessVS; PixelShader = PS_MedianPass8; RenderTarget = tFlow; }
pass { VertexShader = PostProcessVS; PixelShader = PS_Confidence; RenderTarget = tConfidence; }
pass { VertexShader = PostProcessVS; PixelShader = PS_ATrousPassA; RenderTarget = tFlow8; }
pass { VertexShader = PostProcessVS; PixelShader = PS_ATrousPassB; RenderTarget = tFlow; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StoreFlow; RenderTarget0 = tPrevFrameFlow; RenderTarget1 = tPrevConfidence; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StoreLuma; RenderTarget = tPrevLuma; }
//debug views
#if DEBUG_FLOW
pass { VertexShader = PostProcessVS; PixelShader = PS_Debug; }
#endif
}
}
@@ -0,0 +1,300 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : lumenite_RTAO.fx
Version : 2026.05.30
Author : Afzaal (Kaidō)
Description: Ray Traced Ambient Occlusion (Screen Space).
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
/*------------------.
| :: DEFINITIONS :: |
'------------------*/
#define FOV 60.0
#define NEAR_PLANE 0.01
#define INITIAL_STEP_SCALE 0.9
#define STEP_GROWTH_FACTOR 1.2
#define AO_MAX_MARCH_STEPS 15
/*--------------.
| :: HEADERS :: |
'--------------*/
#include "ReShade.fxh"
#include "./include/lumenite_Projections.fxh"
#include "./include/lumenite_Helpers.fxh"
#include "./include/lumenite_ColorManagement.fxh"
/*---------------.
| :: UNIFORMS :: |
'---------------*/
uniform bool DEBUG_VIEW <
ui_label = "Show AO Mask";
ui_tooltip = "Debug view for the AO. Shows raw AO.";
ui_category = "Ambient Occlusion";
> = 0;
uniform float DEPTH_BOUNDARY <
ui_type = "slider";
ui_min = 0.001; ui_max = 0.999; ui_step = 0.001;
ui_label = "AO Range";
ui_tooltip = "The Z+ range/depth in which the effect is applied.";
ui_category = "Ambient Occlusion";
hidden = false;
> = 0.6;
uniform float DEPTH_FADE_START <
ui_type = "slider";
ui_min = 0.1; ui_max = 1.0; ui_step = 0.01;
ui_label = "Z+ Fade Start (%)";
ui_tooltip = "Z+ fraction where effect starts fading out (relative to AO Range)";
ui_category = "Ambient Occlusion";
hidden = true;
> = 0.75;
uniform float AO_INTENSITY <
ui_type = "drag";
ui_min = 0.0; ui_max = 1.0;
ui_label = "AO Strength";
ui_tooltip = "Controls the intensity of the ambient occlusion effect.";
ui_category = "Ambient Occlusion";
> = 1.0;
//deprecated
// uniform int USER_GUIDE <
// ui_type = "radio";
// ui_category = "";
// ui_label = " ";
// ui_text = "RESOLUTION_SCALING:\n0: Renders AO at full-resolution.\n1: Renders AO at half-resolution.";
// >;
/*--------------.
| :: IMPORTS :: |
'--------------*/
namespace Kernel {
texture2D tFlow { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
sampler2D sFlow { Texture = tFlow; MagFilter = POINT; MinFilter = POINT; };
texture2D tConfidence { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
sampler2D sConfidence { Texture = tConfidence; };
texture tNormals { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; MipLevels = 4; };
sampler sNormals { Texture = tNormals; };
texture2D tDepth { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; MipLevels = 4; };
sampler2D sDepth { Texture = tDepth; };
}
namespace LumeniteRTAO {
/*---------------------.
| :: RENDER TARGETS :: |
'---------------------*/
texture tAOTrace { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = R16F; };
sampler sAOTrace { Texture = tAOTrace; AddressU = CLAMP; AddressV = CLAMP; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; };
texture tAO1 { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = RG16F; };
sampler sAO1 { Texture = tAO1; AddressU = CLAMP; AddressV = CLAMP; MagFilter = POINT; MinFilter = POINT; MipFilter = POINT; };
sampler sAO1Linear { Texture = tAO1; AddressU = CLAMP; AddressV = CLAMP; MagFilter = LINEAR; MinFilter = LINEAR; MipFilter = LINEAR; };
texture tPrevAO { Width = BUFFER_WIDTH / 2; Height = BUFFER_HEIGHT / 2; Format = RG16F; };
sampler sPrevAO { Texture = tPrevAO; AddressU = CLAMP; AddressV = CLAMP; MagFilter = LINEAR; MinFilter = LINEAR; MipFilter = LINEAR; };
/*--------------.
| :: HELPERS :: |
'--------------*/
void BuildOrthonormalBasis(float3 n, out float3 b1, out float3 b2)
{
if (n.z < -0.9999999) {
b1 = float3(0.0, -1.0, 0.0);
b2 = float3(-1.0, 0.0, 0.0);
} else {
float a = rcp(1.0 + n.z);
float b = -n.x * n.y * a;
b1 = float3(mad(-n.x * n.x, a, 1.0), b, -n.x);
b2 = float3(b, mad(-n.y * n.y, a, 1.0), -n.y);
}
}
float3 GenerateHemisphereDirection(float3 normal, float2 rand, float3 tangent, float3 bitangent)
{
float phi = rand.x * 6.28318530718; //2.0*PI as constant
float sinPhi, cosPhi;
sincos(phi, sinPhi, cosPhi);
float cosTheta = sqrt(1.0 - rand.y);
float sinTheta = sqrt(rand.y);
float3 result = normal * cosTheta;
result = mad(bitangent, sinTheta * sinPhi, result);
result = mad(tangent, sinTheta * cosPhi, result);
return result;
}
float CalculateDepthFade(float depth)
{
float fadeStartDepth = DEPTH_BOUNDARY * DEPTH_FADE_START;
float fadeRange = DEPTH_BOUNDARY - fadeStartDepth;
return 1.0 - saturate((depth - fadeStartDepth) / fadeRange);
}
float2 ATrousFilter(sampler SourceSampler, float2 uv, uint dilation)
{
float4 gbuffer = tex2D(Kernel::sNormals, uv);
if (gbuffer.a == 0 || gbuffer.a >= DEPTH_BOUNDARY) return float2(1.0, 0.0);
float confidence = tex2Dlod(Kernel::sConfidence, float4(uv, 0, 0)).r;
dilation += uint(round((1.0 - confidence))); //scale filter radius with motion
float2 centerData = tex2Dlod(SourceSampler, float4(uv, 0, 0)).rg;
float variance = max(0.0, centerData.g - (centerData.r * centerData.r)); //Moment - AO^2
variance = max(variance, 0.0001);
float2 sum = centerData;
float totalWeight = 1.0;
for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) {
if (x == 0 && y == 0) continue;
float2 sampleUV = uv + float2(x, y) * dilation * (BUFFER_PIXEL_SIZE * 2.0); //don't forget the x2.0 to properly step half-res grid!
float2 sampleData = tex2Dlod(SourceSampler, float4(sampleUV, 0, 0)).rg;
float4 sampleGeo = tex2Dlod(Kernel::sNormals, float4(sampleUV, 0, 0));
float depthWeight = exp(-abs(gbuffer.a - sampleGeo.a) / (gbuffer.a * 0.02 + 0.001));
float normalWeight = pow(saturate(dot(gbuffer.rgb, sampleGeo.rgb)), 50.0);
float aoDiff = centerData.r - sampleData.r;
float aoWeight = exp(-(aoDiff * aoDiff) / (variance + 0.0001));
float weight = depthWeight * normalWeight * aoWeight;
sum += sampleData * weight;
totalWeight += weight;
}
return sum / (totalWeight + EPSILON);
}
/*--------------.
| :: SHADERS :: |
'--------------*/
float PS_TraceAO(VSOUT input) : SV_Target
{
//deprecated
// if (CHECKERBOARD_RENDERING) {
// #if RESOLUTION_SCALING
// if(CheckerboardSkip(uint2(input.vpos.xy), 2.0)) discard;
// #else
// if(CheckerboardSkip(uint2(input.vpos.xy), 1.0)) discard;
// #endif
// }
float4 gbuffer = tex2D(Kernel::sNormals, input.uv);
float3 normal = gbuffer.rgb;
float depth = gbuffer.a;
if (depth == 0 || depth >= DEPTH_BOUNDARY) discard;
float3 startPos = UVToViewSpace(input.uv, depth, input);
float3 tangent, bitangent;
BuildOrthonormalBasis(normal, tangent, bitangent);
float2 noise = GetStratifiedNoise(input.vpos.xy);
float3 rayDir = GenerateHemisphereDirection(normal, noise, tangent, bitangent);
float invDepth = rcp(depth);
float totalRayLength = 0.02 * depth;
float initialStepScale = INITIAL_STEP_SCALE * rcp((float)AO_MAX_MARCH_STEPS);
float stepSize = totalRayLength * initialStepScale;
float3 rayPos = mad(rayDir, stepSize * 0.5, startPos);
rayPos += normal * depth * 0.0005; //push ray slightly OUTWARD along the normal; clears staircase artifacts
float occlusion = 0.0;
[loop]
for (int step = 0; step < AO_MAX_MARCH_STEPS; step++) {
float2 sampleUV = ViewSpaceToUV(rayPos, input);
float sceneDepth = GetDepth(sampleUV);
float depthDiff = rayPos.z - sceneDepth;
[branch]
if (depthDiff > 0.0 && depthDiff < rayPos.z) {
float3 scenePos = UVToViewSpace(sampleUV, sceneDepth, input);
float hitDistance = length(scenePos - startPos);
float normalizedDistance = hitDistance * invDepth;
occlusion = exp(-normalizedDistance * 15.0);
break;
}
stepSize *= STEP_GROWTH_FACTOR;
rayPos = mad(rayDir, stepSize, rayPos);
}
float aoFactor = 1.0 - saturate(occlusion * AO_INTENSITY);
return aoFactor;
}
float2 PS_TemporalFilter(VSOUT input) : SV_Target
{
float depth = tex2D(Kernel::sDepth, input.uv).r;
//overwrite noise at boundary with clean White, prevents gaps
if (depth >= DEPTH_BOUNDARY) return float2(1.0, 1.0); //1.0 AO, 1.0 Moment
if (depth == 0) discard;
float ao = tex2D(sAOTrace, input.uv).r;
ao = lerp(1.0, ao, CalculateDepthFade(depth));
float moment = ao * ao;
float2 flow = tex2D(Kernel::sFlow, input.uv).xy;
float confidence = tex2D(Kernel::sConfidence, input.uv).x;
confidence = saturate(confidence + log2(2.0 - confidence) * 0.6); //boost confidence
float2 rawHistory = tex2D(sPrevAO, input.uv + flow).rg; //history stores "1.0 - AO". 0.0 (Black Texture) -> Reads as 1.0 (White)
float prevAO = 1.0 - rawHistory.r;
float prevMoment = 1.0 - rawHistory.g;
float alpha = confidence * 0.98;
ao = lerp(ao, prevAO, alpha);
moment = lerp(moment, prevMoment, alpha);
//max(..., 0.001) to ensure we NEVER write exactly 0.0 again
//this tells the next frame "I contain data"
return float2(max(ao, 0.001), max(moment, 0.001));
}
float2 PS_StoreAO(VSOUT input) : SV_Target
{
//must prevent history collision here
//if we store exactly 0.0 (means White), the next frame's blend pass thinks
//history is empty and resets it, causing shimmer
//so clamp to 0.0001 so the system knows "This is valid history data"
float2 data = tex2D(sAO1, input.uv).rg;
return float2(max(1.0 - data.r, 0.0001), max(1.0 - data.g, 0.0001)); //store inverted
}
float4 PS_ToDisplay(VSOUT input) : SV_Target
{
float depth = tex2D(Kernel::sDepth, input.uv).r;
float ao = ATrousFilter(sAO1Linear, input.uv, 2).r; //stable AO mask (fades to 1.0)
if (DEBUG_VIEW) {
#if BUFFER_COLOR_SPACE > 1
return float4(ToOutputColorspace(ao.xxx, true), 1.0);
#else
return float4(ao.xxx, 1.0);
#endif
}
if (depth == 0 || depth >= DEPTH_BOUNDARY) discard;
float3 base = GetLinearColor(input.uv, true);
base *= ao;
return float4(ToOutputColorspace(base, true), 1.0);
}
/*----------------.
| :: TECHNIQUE :: |
'----------------*/
technique Lumenite_RTAO <
ui_label = "LUMENITE: RTAO";
ui_tooltip = "Ray Traced Ambient Occlusion (Screen Space).";
>
{
pass { VertexShader = VS; PixelShader = PS_TraceAO; RenderTarget = tAOTrace; }
pass { VertexShader = VS; PixelShader = PS_TemporalFilter; RenderTarget = tAO1; }
pass { VertexShader = VS; PixelShader = PS_StoreAO; RenderTarget = tPrevAO; }
pass { VertexShader = VS; PixelShader = PS_ToDisplay; }
}
}
@@ -0,0 +1,360 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : lumenite_SSSR.fx
Version : 2026.09.06
Author : Afzaal (Kaidō)
Description: Stochastic Screen Space Reflections.
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
/*------------------.
| :: DEFINITIONS :: |
'------------------*/
#define FOV 70.0
#define NEAR_PLANE 0.5
#define RAY_LENGTH_SCALE 9.0
#define RAY_ORIGIN_BIAS -0.0004
/*--------------.
| :: HEADERS :: |
'--------------*/
#include "ReShade.fxh"
#include "./include/lumenite_Projections.fxh"
#include "./include/lumenite_Helpers.fxh"
#include "./include/lumenite_ColorManagement.fxh"
/*---------------.
| :: UNIFORMS :: |
'---------------*/
uniform bool SMOOTH_SHADING <
ui_label = "Smooth Shading";
ui_tooltip = "Slightly smoothens the raw normals. Turn OFF if SMOOTH_NORMALS is enabled in Kernel.";
> = 1;
uniform float DEPTH_BOUNDARY <
ui_type = "slider";
ui_min = 0.001; ui_max = 0.999; ui_step = 0.001;
ui_label = "SSSR Range";
ui_tooltip = "The Z+ range/depth in which the effect is applied.";
ui_category = "";
hidden = false;
> = 0.85;
uniform float DEPTH_FADE_START <
ui_type = "slider";
ui_min = 0.1; ui_max = 1.0; ui_step = 0.01;
ui_label = "Z+ Fade Start (%)";
ui_tooltip = "Z+ fraction where effect starts fading out (relative to Z+ boundary)";
ui_category = "";
hidden = true;
> = 0.75;
uniform int MAX_STEPS <
ui_type = "drag";
ui_min = 1; ui_max = 32; ui_step = 1;
ui_label = "Ray Resolution";
ui_category = "";
ui_tooltip = "";
> = 32;
uniform int BINARY_SEARCH_STEPS <
ui_type = "drag";
ui_min = 1; ui_max = 8; ui_step = 1;
ui_label = "Hit Refinement";
ui_category = "";
ui_tooltip = "";
> = 4;
uniform float F0 <
ui_type = "drag";
ui_min = 0.0; ui_max = 2.0; ui_step = 0.001;
ui_label = "Base Reflectivity (F0)";
ui_category = "";
ui_tooltip = "";
> = 1.0;
uniform float ROUGHNESS <
ui_type = "drag";
ui_min = 0.0; ui_max = 0.3; ui_step = 0.001;
ui_label = "Roughness";
ui_category = "";
ui_tooltip = "";
> = 0.1;
uniform float BUMP_SCALE <
ui_type = "drag";
ui_min = 0.0; ui_max = 1.0; ui_step = 0.001;
ui_label = "Bump Detail";
ui_tooltip = "Scale of the extracted bump details. Lower = finer bumps.";
> = 0.5;
uniform float TAIL_FEATHERING <
ui_type = "drag";
ui_min = 0.0; ui_max = 5.0; ui_step = 0.001;
ui_label = "Tail Feathering";
ui_category = "";
ui_tooltip = "";
> = 0.0;
/*--------------.
| :: IMPORTS :: |
'--------------*/
namespace Kernel {
texture2D tFlow { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
sampler2D sFlow { Texture = tFlow; MagFilter = POINT; MinFilter = POINT; };
texture2D tConfidence { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
sampler2D sConfidence { Texture = tConfidence; };
texture tNormals { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; MipLevels = 4; };
sampler sNormals { Texture = tNormals; };
texture2D tDepth { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; MipLevels = 4; };
sampler2D sDepth { Texture = tDepth; };
}
namespace LumeniteSSSR {
/*---------------------.
| :: RENDER TARGETS :: |
'---------------------*/
texture tSpec1 { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; };
sampler sSpec1 { Texture = tSpec1; AddressU = CLAMP; AddressV = CLAMP; };
texture tSpec2 { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; };
sampler sSpec2 { Texture = tSpec2; AddressU = CLAMP; AddressV = CLAMP; };
texture tPrevSpec { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; };
sampler sPrevSpec { Texture = tPrevSpec; AddressU = CLAMP; AddressV = CLAMP; };
/*--------------.
| :: HELPERS :: |
'--------------*/
float CalculateDepthFade(float depth)
{
float fadeStartDepth = DEPTH_BOUNDARY * DEPTH_FADE_START;
float fadeRange = DEPTH_BOUNDARY - fadeStartDepth;
return 1.0 - saturate((depth - fadeStartDepth) / fadeRange);
}
float3 CalculateSmoothNormal(float2 uv, float4 gbuffer, int dilation, sampler SrcSampler)
{
float3 normal = gbuffer.rgb;
float depth = gbuffer.a;
float3 normalSum = normal;
float weightSum = 1.0;
[unroll] for(int dy = -4; dy <= 4; dy++) for (int dx = -4; dx <= 4; dx++) {
float2 sampleUV = uv + float2(dx, dy) * ReShade::PixelSize * dilation;
float4 neighborData = tex2Dlod(SrcSampler, float4(sampleUV, 0, 0));
float depthDiff = abs(neighborData.a - depth);
float normalDot = max(dot(normal, neighborData.rgb), 0.0);
float weight = exp(-depthDiff * 300.0) * pow(normalDot, 20.0);
normalSum += neighborData.rgb * weight;
weightSum += weight;
}
return normalize(normalSum / weightSum);
}
float3 GetBackBuffer(float2 uv)
{
return tex2Dlod(ReShade::BackBuffer, float4(uv,0,0)).rgb;
}
float3 CalculateBumpyNormal(float2 uv, float3 geoNormal)
{
float2 texelSize = BUFFER_PIXEL_SIZE * BUMP_SCALE;
float3 lumaWeights = float3(0.299, 0.587, 0.114);
//use gamma space intentionally
float lumaCenter = dot(GetBackBuffer(uv), lumaWeights);
float lumaRight = dot(GetBackBuffer(uv + float2(texelSize.x, 0.0)), lumaWeights);
float lumaBottom = dot(GetBackBuffer(uv + float2(0.0, texelSize.y)), lumaWeights);
//luma gradients
float dx = (lumaRight - lumaCenter) * 2.5;
float dy = (lumaBottom - lumaCenter) * 2.5;
//orthogonal tangent basis around macro geometry normal
float3 up = abs(geoNormal.z) < 0.999 ? float3(0.0, 0.0, 1.0) : float3(1.0, 0.0, 0.0);
float3 tangent = normalize(cross(up, geoNormal));
float3 bitangent = cross(geoNormal, tangent);
//2D bump gradient to 3D tangent-space normal
float3 bumpVec = normalize(float3(-dx, -dy, 1.0));
return normalize(tangent * bumpVec.x + bitangent * bumpVec.y + geoNormal * bumpVec.z);
}
/*--------------.
| :: SHADERS :: |
'--------------*/
float4 PS_TraceSpecular(VSOUT input) : SV_Target
{
float4 gbuffer = tex2D(Kernel::sNormals, input.uv);
float3 normal = gbuffer.rgb;
float depth = gbuffer.a;
if (depth <= 0.0 || depth > DEPTH_BOUNDARY) return float4(0, 0, 0, 1);
//process normals
if (SMOOTH_SHADING) normal = CalculateSmoothNormal(input.uv, gbuffer, 3, Kernel::sNormals);
if (BUMP_SCALE > 0.0) normal = CalculateBumpyNormal(input.uv, normal);
float3 StartPos = UVToViewSpace(input.uv, depth, input);
float3 viewDir = normalize(-StartPos);
float dynamicRayLengthNormalized = min(RAY_LENGTH_SCALE * depth, 1.0-depth);
float stepSize = dynamicRayLengthNormalized / float(MAX_STEPS);
float3 mirrorDir = reflect(-viewDir, normal);
if (dot(mirrorDir, mirrorDir) < 0.001) { //mirror reflection validation chck
return float4(0, 0, 0, 1);
}
float2 noise = GetStratifiedNoise(input.vpos.xy);
float3 jitterN = normalize(normal + float3((noise * 2.0 - 1.0) * ROUGHNESS * 0.2, 0.0));
float3 rayDir = reflect(-viewDir, jitterN);
if (dot(rayDir, normal) < 0.0) rayDir = mirrorDir; //prevent jitter from pushing ray inside the geometry
float biasedOffset = RAY_ORIGIN_BIAS + (depth * RAY_ORIGIN_BIAS * 0.01); //intentional -ve origin bias
float3 biasedStartPos = StartPos - (normal * biasedOffset); //deliberately pushes the ray slightly into the floor, makes it immediately collide with the floor's depth, killing "joined reflections"
float t = stepSize * noise.x;
float3 spec = float3(0.0, 0.0, 0.0);
bool hitFound = false;
float distanceRatio = 0.0;
float2 finalUV = 0.0;
for (int i = 0; i < MAX_STEPS; i++)
{
if (t >= dynamicRayLengthNormalized)
break;
float3 currentPos = biasedStartPos + rayDir * t;
float2 hitUV = ViewSpaceToUV(currentPos, input);
if (IsOOB(hitUV))
break;
float sceneDepth = tex2Dlod(Kernel::sDepth, float4(hitUV, 0, 0)).r;
if (sceneDepth > DEPTH_BOUNDARY) {
t += stepSize;
continue;
}
float3 scenePos = UVToViewSpace(hitUV, sceneDepth, input);
float depthDiff = currentPos.z - scenePos.z;
if (depthDiff > 0.0) //passed behind surface
{
float gateThreshold = dynamicRayLengthNormalized * 0.1; //initially, a broad thickness check
float extraThickness = (t > gateThreshold) ? 0.01 : 0.0; //if t is past the threshold, add extra thickness
float dynamicThickness = (currentPos.z * 0.05) + extraThickness;
if (depthDiff < dynamicThickness)
{
//binary search refinement
float binarySearchT = t;
float binarySearchStep = stepSize;
float3 binarySearchCurrentPos = currentPos;
float2 binarySearchUV = hitUV;
float3 binarySearchScenePos = scenePos;
for (int j = 0; j < BINARY_SEARCH_STEPS; j++) {
binarySearchStep *= 0.5;
binarySearchT += (binarySearchCurrentPos.z > binarySearchScenePos.z) ? -binarySearchStep : binarySearchStep; //move backwards if behind the surface, otherwise forwards
binarySearchCurrentPos = biasedStartPos + rayDir * binarySearchT;
binarySearchUV = ViewSpaceToUV(binarySearchCurrentPos, input);
float binarySearchSceneDepth = tex2Dlod(Kernel::sDepth, float4(binarySearchUV, 0, 0)).r;
binarySearchScenePos = UVToViewSpace(binarySearchUV, binarySearchSceneDepth, input);
}
float finalDepthDiff = binarySearchCurrentPos.z - binarySearchScenePos.z;
if (abs(finalDepthDiff) < (binarySearchCurrentPos.z * 0.01 + 0.01)) { //tighter thickness tolerance on the final refined hit to discard empty space behind thin grass
hitFound = true;
distanceRatio = binarySearchT / dynamicRayLengthNormalized;
finalUV = binarySearchUV;
break;
}
}
}
t += stepSize * noise.y;
}
if (hitFound) {
float3 hitColor = GetLinearColor(finalUV, false);
float2 edgeFadeUV = abs(finalUV * 2.0 - 1.0);
float edgeFade = saturate(1.0 - max(edgeFadeUV.x, edgeFadeUV.y));
edgeFade = smoothstep(0.0, 0.05, edgeFade);
float maxDistFade = pow(saturate(1.0 - distanceRatio), TAIL_FEATHERING + EPSILON);
spec = hitColor * maxDistFade * edgeFade;
}
return float4(spec, 1.0);
}
float4 PS_TemporalBlend(VSOUT input) : SV_Target
{
float depth = tex2D(Kernel::sDepth, input.uv).r;
if (depth >= DEPTH_BOUNDARY) return float4(0, 0, 0, 0);
float3 spec = tex2D(sSpec1, input.uv).rgb;
float2 flow = tex2D(Kernel::sFlow, input.uv).xy;
float confidence = tex2D(Kernel::sConfidence, input.uv).x;
confidence = saturate(confidence + log2(2.0 - confidence) * 0.5);
float3 prevSpec = tex2D(sPrevSpec, input.uv + flow).rgb;
float historyMax = max(prevSpec.r, max(prevSpec.g, prevSpec.b));
float blendWeight = (historyMax < 0.00001) ? 0.0 : (confidence * 0.98);
float3 blended = lerp(spec, prevSpec, blendWeight);
return float4(blended, 1.0);
}
float4 PS_StoreHistory(VSOUT input) : SV_Target
{
float depth = tex2D(Kernel::sDepth, input.uv).r;
if (depth >= DEPTH_BOUNDARY) return float4(0, 0, 0, 0); //if past boundary, store 0.0 to 'clear' history for next frame
return float4(max(tex2D(sSpec2, input.uv).rgb, 0.0001), 1.0); //clamp to 0.0001 so it knows 'valid hist data', prevents shimmer at depth boundary edges
}
float4 PS_ToDisplay(VSOUT input) : SV_Target
{
float3 base = GetLinearColor(input.uv, false);
float4 gbuffer = tex2D(Kernel::sNormals, input.uv);
float3 normal = gbuffer.rgb;
float depth = gbuffer.a;
float3 surfacePos = UVToViewSpace(input.uv, depth, input);
float depthFade = CalculateDepthFade(depth);
float3 viewDir = normalize(-surfacePos);
float NdotV = saturate(dot(normal, viewDir));
float fresnel = F0 + (1.0 - F0) * pow(1.0 - NdotV, 5.0); //schlick's approximation
float3 spec = tex2D(sSpec2, input.uv).rgb;
spec *= depthFade;
spec *= fresnel;
float reflectionMask = saturate(length(spec) + fresnel * 0.5);
float3 conservationBase = base * (1.0 - reflectionMask * 0.7 * depthFade);
return float4(ToOutputColorspace(conservationBase + spec, false), 1.0);
}
/*----------------.
| :: TECHNIQUE :: |
'----------------*/
technique LUMENITE_SSSR <
ui_label = "LUMENITE: SSSR";
ui_tooltip = "Stochastic Screen Space Reflections.";
>
{
pass { VertexShader = VS; PixelShader = PS_TraceSpecular; RenderTarget = tSpec1; }
pass { VertexShader = VS; PixelShader = PS_TemporalBlend; RenderTarget = tSpec2; }
pass { VertexShader = VS; PixelShader = PS_ToDisplay; }
pass { VertexShader = VS; PixelShader = PS_StoreHistory; RenderTarget = tPrevSpec; }
}
}
@@ -0,0 +1,525 @@
/*
========================================================================
Copyright (c) Afzaal. All rights reserved.
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.
========================================================================
GitHub : https://github.com/umar-afzaal/LumeniteFX
Discord : https://discord.gg/deXJrW2dx6
Filename : lumenite_TRAA.fx
Version : 2026.07.28
Author : Afzaal (Kaidō)
Description: Temporal Reprojection Anti-Aliasing
License : AGNYA License (https://github.com/nvb-uy/AGNYA-License)
========================================================================
*/
/*------------------.
| :: DEFINITIONS :: |
'------------------*/
#ifndef ENABLE_DLAA
#define ENABLE_DLAA 1
#endif
/*--------------.
| :: HEADERS :: |
'--------------*/
#include "ReShade.fxh"
#include "./include/lumenite_ColorManagement.fxh"
#include "./include/lumenite_Helpers.fxh"
/*---------------.
| :: UNIFORMS :: |
'---------------*/
uniform int SHOW_STATUS <
ui_type = "radio";
ui_label = " ";
#if ENABLE_DLAA
ui_text = "DLAA Prepass: Enabled.";
#else
ui_text = "DLAA Prepass: Disabled.";
#endif
>;
#if ENABLE_DLAA
uniform bool DEBUG_EDGES <
ui_label = "Show Edge Mask";
ui_tooltip = "Paints the detected edge mask over black background.";
> = false;
uniform int EDGE_MODE <
ui_type = "combo";
ui_label = "Edge Detection";
ui_items = "Luma\0Geometric\0";
ui_tooltip = "Luma: shading and texture edges as well; the classic DLAA mask.\n"
"Geometric: silhouettes only, ignores flat UI.";
> = 0;
#endif
uniform float HISTORY_BLEND <
ui_type = "slider";
ui_min = 0.0; ui_max = 1.0; ui_step = 0.01;
ui_label = "Temporal Blend";
hidden = false;
> = 0.9;
uniform float SHARP_STRENGTH <
ui_type = "drag";
ui_min = 0; ui_max = 2.0; ui_step = 0.05;
ui_label = "Adaptive Sharpen";
hidden = false;
> = 1.0;
uniform float MAX_SHARP_DIFF <
ui_type = "drag";
ui_min = 0.05; ui_max = 0.25; ui_step = 0.01;
ui_label = "Sharpen Guard";
ui_tooltip = "Higher = more aggressive sharpening allowed.\nLower = tighter anti-ringing clamp.";
hidden = true;
> = 0.1;
uniform float HFI_INTENSITY <
ui_type = "drag";
ui_min = 0.0; ui_max = 0.1; ui_step = 0.001;
ui_label = "High-Frequency Injection";
ui_tooltip = "Re-injects detail lost during Temporal blend.";
> = 0.01;
/*--------------.
| :: IMPORTS :: |
'--------------*/
namespace Kernel {
texture2D tFlow { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = RG16F; };
sampler2D sFlow { Texture = tFlow; MagFilter = POINT; MinFilter = POINT; };
texture2D tConfidence { Width = BUFFER_WIDTH/8; Height = BUFFER_HEIGHT/8; Format = R16F; };
sampler2D sConfidence { Texture = tConfidence; };
texture tNormals { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; MipLevels = 4; };
sampler sNormals { Texture = tNormals; };
texture2D tDepth { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = R16F; MipLevels = 4; };
sampler2D sDepth { Texture = tDepth; };
}
namespace LumeniteTRAA {
/*---------------------.
| :: RENDER TARGETS :: |
'---------------------*/
#if ENABLE_DLAA
texture tDLAAPreFilter { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; };
sampler sDLAAPreFilter { Texture = tDLAAPreFilter; MinFilter = LINEAR; MagFilter = LINEAR; MipFilter = LINEAR; };
texture tDLAAPrePass { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; };
sampler sDLAAPrePass { Texture = tDLAAPrePass; MagFilter = POINT; MinFilter = POINT; };
#endif
texture tCurrHistory { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; };
sampler sCurrHistory { Texture = tCurrHistory; MagFilter = LINEAR; MinFilter = LINEAR; MipFilter = LINEAR; };
texture tPrevHistory { Width = BUFFER_WIDTH; Height = BUFFER_HEIGHT; Format = RGBA16F; };
sampler sPrevHistory { Texture = tPrevHistory; MagFilter = LINEAR; MinFilter = LINEAR; MipFilter = LINEAR; };
/*--------------.
| :: HELPERS :: |
'--------------*/
//5-Tap 2D Catmull-Rom Filter (Brian Karis / Unreal Engine)
float3 SampleCatmullRom5Tap(sampler tex, float2 uv) {
float2 pos = uv * float2(BUFFER_WIDTH, BUFFER_HEIGHT);
float2 centerPos = floor(pos - 0.5) + 0.5;
float2 f = pos - centerPos;
//1D Catmull-Rom weights
float2 f2 = f * f;
float2 f3 = f2 * f;
float2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f));
float2 w1 = 1.0 + f2 * (-2.5 + 1.5 * f);
float2 w2 = f * (0.5 + f * (2.0 - 1.5 * f));
float2 w3 = f2 * (-0.5 + 0.5 * f);
//group the inner positive lobes (w1, w2) for bilinear hardware
float2 w12 = w1 + w2;
float2 offset12 = w2 / (w12 + 0.00001); // Prevent div by zero
//5-tap texture fetch in a cross pattern
float2 texCoord0 = (centerPos - float2(1.0, 0.0) + float2(0.0, offset12.y)) * BUFFER_PIXEL_SIZE; //left
float2 texCoord1 = (centerPos + float2(2.0, 0.0) + float2(0.0, offset12.y)) * BUFFER_PIXEL_SIZE; //right
float2 texCoord2 = (centerPos + float2(offset12.x, -1.0)) * BUFFER_PIXEL_SIZE; //top
float2 texCoord3 = (centerPos + float2(offset12.x, 2.0)) * BUFFER_PIXEL_SIZE; //bottom
float2 texCoord4 = (centerPos + offset12) * BUFFER_PIXEL_SIZE; //center
//final 2D weights for the 5 taps
float weight0 = w0.x * w12.y; //left
float weight1 = w3.x * w12.y; //right
float weight2 = w12.x * w0.y; //top
float weight3 = w12.x * w3.y; //bottom
float weight4 = w12.x * w12.y; //center
//normalize weights because we dropped the 4 corner taps (sum would be slightly < 1.0)
float weightSum = weight0 + weight1 + weight2 + weight3 + weight4;
weightSum = max(weightSum, 0.0001);
weight0 /= weightSum;
weight1 /= weightSum;
weight2 /= weightSum;
weight3 /= weightSum;
weight4 /= weightSum;
//sample w. hw bilinear filtering (offsets take care of the interpolation)
float3 color0 = tex2Dlod(tex, float4(texCoord0, 0, 0)).rgb;
float3 color1 = tex2Dlod(tex, float4(texCoord1, 0, 0)).rgb;
float3 color2 = tex2Dlod(tex, float4(texCoord2, 0, 0)).rgb;
float3 color3 = tex2Dlod(tex, float4(texCoord3, 0, 0)).rgb;
float3 color4 = tex2Dlod(tex, float4(texCoord4, 0, 0)).rgb;
float3 result = color0 * weight0 + color1 * weight1 + color2 * weight2 + color3 * weight3 + color4 * weight4;
//anti-ringing clamp
float3 minColor = min(min(min(color0, color1), min(color2, color3)), color4);
float3 maxColor = max(max(max(color0, color1), max(color2, color3)), color4);
return clamp(result, minColor, maxColor);
}
//if ray misses the bounding box (tEnter > tExit), returning t = 1.0 is the safe fallback
float3 YCoCgLineBoxClip(float3 historyYCoCg, float3 meanYCoCg, float3 colorMin, float3 colorMax) {
float3 rayDir = meanYCoCg - historyYCoCg;
rayDir = abs(rayDir) < 0.0001 ? float3(0.0001, 0.0001, 0.0001) : rayDir; //avoid div by zero
//compute t for intersection with min and max bounds per-channel
float3 tMin = (colorMin - historyYCoCg) / rayDir;
float3 tMax = (colorMax - historyYCoCg) / rayDir;
float3 t1 = min(tMin, tMax);
float3 t2 = max(tMin, tMax);
tMin = t1;
tMax = t2;
//entry and exit points for ray-box intersection
float tEnter = max(max(tMin.x, tMin.y), tMin.z);
float tExit = min(min(tMax.x, tMax.y), tMax.z);
//if ray misses the box; fallback to 1.0 (mean) to discard history
//else, clamp the entry point to [0, 1] to clip exactly at the box edge
float t = tEnter > tExit ? 1.0 : clamp(tEnter, 0.0, 1.0);
return historyYCoCg + rayDir * t;
}
/*--------------.
| :: SHADERS :: |
'--------------*/
#if ENABLE_DLAA
float4 PS_DLAAPreFilter(float4 vpos : SV_Position, float2 uv : TexCoord) : SV_Target {
float3 center = sqrt(max(GetLinearColor(uv, false), 0.0));
float edge;
if (!EDGE_MODE) {
//luma edge in perceptual space; the extra sqrt fattens the mask
float2 px = float2(BUFFER_PIXEL_SIZE.x, 0.0);
float2 py = float2(0.0, BUFFER_PIXEL_SIZE.y);
float3 left = sqrt(max(GetLinearColor(uv - px, false), 0.0));
float3 right = sqrt(max(GetLinearColor(uv + px, false), 0.0));
float3 top = sqrt(max(GetLinearColor(uv - py, false), 0.0));
float3 bottom = sqrt(max(GetLinearColor(uv + py, false), 0.0));
float3 edges = 4.0 * abs((left + right + top + bottom) - 4.0 * center);
edge = GetLuminance(sqrt(max(edges, 0.0))); //recursive gamma compression: do another sqrt(), fattens the edge mask
} else {
float4 s0 = tex2Dlod(Kernel::sNormals, float4(uv + BUFFER_PIXEL_SIZE * float2(-1,-1), 0, 0));
float4 s1 = tex2Dlod(Kernel::sNormals, float4(uv + BUFFER_PIXEL_SIZE * float2( 0,-1), 0, 0));
float4 s2 = tex2Dlod(Kernel::sNormals, float4(uv + BUFFER_PIXEL_SIZE * float2( 1,-1), 0, 0));
float4 s3 = tex2Dlod(Kernel::sNormals, float4(uv + BUFFER_PIXEL_SIZE * float2(-1, 0), 0, 0));
float4 s4 = tex2Dlod(Kernel::sNormals, float4(uv, 0, 0));
float4 s5 = tex2Dlod(Kernel::sNormals, float4(uv + BUFFER_PIXEL_SIZE * float2( 1, 0), 0, 0));
float4 s6 = tex2Dlod(Kernel::sNormals, float4(uv + BUFFER_PIXEL_SIZE * float2(-1, 1), 0, 0));
float4 s7 = tex2Dlod(Kernel::sNormals, float4(uv + BUFFER_PIXEL_SIZE * float2( 0, 1), 0, 0));
float4 s8 = tex2Dlod(Kernel::sNormals, float4(uv + BUFFER_PIXEL_SIZE * float2( 1, 1), 0, 0));
//3x3 depth Sobel
float dC = s4.a;
float sxD = -s0.a + s2.a - 2.0 * s3.a + 2.0 * s5.a - s6.a + s8.a;
float syD = -s0.a - 2.0 * s1.a - s2.a + s6.a + 2.0 * s7.a + s8.a;
float depthEdge = saturate(sqrt(sxD * sxD + syD * syD) / (dC + 1e-5));
//3x3 normal Sobel
float3 sxN = -s0.xyz + s2.xyz - 2.0 * s3.xyz + 2.0 * s5.xyz - s6.xyz + s8.xyz;
float3 syN = -s0.xyz - 2.0 * s1.xyz - s2.xyz + s6.xyz + 2.0 * s7.xyz + s8.xyz;
float normalEdge = saturate(length(sxN) + length(syN));
edge = max(depthEdge, normalEdge);
}
return float4(center, edge);
}
#define SAMPLE_G(uv, dx, dy) tex2Dlod(sDLAAPreFilter, float4((uv) + float2(dx, dy) * BUFFER_PIXEL_SIZE, 0, 0))
float4 PS_DLAA(float4 vpos : SV_Position, float2 uv : TexCoord) : SV_Target {
float4 center = SAMPLE_G(uv, 0.0, 0.0);
float4 left01 = SAMPLE_G(uv, -1.5, 0.0);
float4 right01 = SAMPLE_G(uv, 1.5, 0.0);
float4 top01 = SAMPLE_G(uv, 0.0, -1.5);
float4 bottom01 = SAMPLE_G(uv, 0.0, 1.5);
//flat-region early exit
float localEdges = max(center.a, max(max(left01.a, right01.a), max(top01.a, bottom01.a)));
if (localEdges < 0.05) return float4(center.xyz * center.xyz, 1.0);
float4 wH = 2.0 * (left01 + right01);
float4 wV = 2.0 * (top01 + bottom01);
float4 edgeH = abs(wH - 4.0 * center) / 4.0;
float4 edgeV = abs(wV - 4.0 * center) / 4.0;
float4 blurredH = (wH + 2.0 * center) / 6.0;
float4 blurredV = (wV + 2.0 * center) / 6.0;
float edgeHLum = GetLuminance(edgeH.xyz);
float edgeVLum = GetLuminance(edgeV.xyz);
float blurredHLum = GetLuminance(blurredH.xyz);
float blurredVLum = GetLuminance(blurredV.xyz);
const float kLambda = 3.0;
const float kEpsilon = 0.1;
float edgeMaskH = saturate((kLambda * edgeHLum - kEpsilon) / (blurredVLum + 1e-5));
float edgeMaskV = saturate((kLambda * edgeVLum - kEpsilon) / (blurredHLum + 1e-5));
float gate = (!EDGE_MODE) ? 1.0 : center.a;
edgeMaskH *= gate;
edgeMaskV *= gate;
float4 clr = center;
clr = lerp(clr, blurredH, edgeMaskV);
clr = lerp(clr, blurredV, edgeMaskH * 0.5);
//skip unnecessary work on long-edges
if (localEdges > 0.5) {
float4 h0 = right01;
float4 h1 = SAMPLE_G(uv, 3.5, 0.0);
float4 h2 = SAMPLE_G(uv, 5.5, 0.0);
float4 h3 = SAMPLE_G(uv, 7.5, 0.0);
float4 h4 = left01;
float4 h5 = SAMPLE_G(uv, -3.5, 0.0);
float4 h6 = SAMPLE_G(uv, -5.5, 0.0);
float4 h7 = SAMPLE_G(uv, -7.5, 0.0);
float4 v0 = bottom01;
float4 v1 = SAMPLE_G(uv, 0.0, 3.5);
float4 v2 = SAMPLE_G(uv, 0.0, 5.5);
float4 v3 = SAMPLE_G(uv, 0.0, 7.5);
float4 v4 = top01;
float4 v5 = SAMPLE_G(uv, 0.0, -3.5);
float4 v6 = SAMPLE_G(uv, 0.0, -5.5);
float4 v7 = SAMPLE_G(uv, 0.0, -7.5);
float longEdgeMaskH = (h0.a + h1.a + h2.a + h3.a + h4.a + h5.a + h6.a + h7.a) / 8.0;
float longEdgeMaskV = (v0.a + v1.a + v2.a + v3.a + v4.a + v5.a + v6.a + v7.a) / 8.0;
longEdgeMaskH = saturate(longEdgeMaskH * 2.0 - 1.0);
longEdgeMaskV = saturate(longEdgeMaskV * 2.0 - 1.0);
if (abs(longEdgeMaskH - longEdgeMaskV) > 0.2) {
float4 left = SAMPLE_G(uv, -1.0, 0.0);
float4 right = SAMPLE_G(uv, 1.0, 0.0);
float4 top = SAMPLE_G(uv, 0.0, -1.0);
float4 bottom = SAMPLE_G(uv, 0.0, 1.0);
float4 longBlurredH = (h0 + h1 + h2 + h3 + h4 + h5 + h6 + h7) / 8.0;
float4 longBlurredV = (v0 + v1 + v2 + v3 + v4 + v5 + v6 + v7) / 8.0;
float lbHLum = GetLuminance(longBlurredH.xyz);
float lbVLum = GetLuminance(longBlurredV.xyz);
float centerLum = GetLuminance(center.xyz);
float leftLum = GetLuminance(left.xyz);
float rightLum = GetLuminance(right.xyz);
float topLum = GetLuminance(top.xyz);
float bottomLum = GetLuminance(bottom.xyz);
float4 clrV = center;
float4 clrH = center;
float hx = saturate(0.0 + (lbHLum - topLum) / (centerLum - topLum + 1e-6));
float hy = saturate(1.0 + (lbHLum - centerLum) / (centerLum - bottomLum + 1e-6));
float vx = saturate(0.0 + (lbVLum - leftLum) / (centerLum - leftLum + 1e-6));
float vy = saturate(1.0 + (lbVLum - centerLum) / (centerLum - rightLum + 1e-6));
float4 vhxy = float4(vx, vy, hx, hy);
vhxy.x = (vhxy.x == 0.0) ? 1.0 : vhxy.x;
vhxy.y = (vhxy.y == 0.0) ? 1.0 : vhxy.y;
vhxy.z = (vhxy.z == 0.0) ? 1.0 : vhxy.z;
vhxy.w = (vhxy.w == 0.0) ? 1.0 : vhxy.w;
clrV = lerp(left, clrV, vhxy.x);
clrV = lerp(right, clrV, vhxy.y);
clrH = lerp(top, clrH, vhxy.z);
clrH = lerp(bottom, clrH, vhxy.w);
clr = lerp(clr, clrV, longEdgeMaskV);
clr = lerp(clr, clrH, longEdgeMaskH);
}
}
//highlight protection
float4 r0 = SAMPLE_G(uv, -1.5, -1.5);
float4 r1 = SAMPLE_G(uv, 1.5, -1.5);
float4 r2 = SAMPLE_G(uv, -1.5, 1.5);
float4 r3 = SAMPLE_G(uv, 1.5, 1.5);
float4 r = (4.0 * (r0 + r1 + r2 + r3) + center + top01 + bottom01 + left01 + right01) / 25.0;
float mask = saturate(r.a * 3.0 - 2.0);
clr = lerp(clr, center, mask);
return float4(clr.xyz * clr.xyz, 1.0); //store linear color here!
}
#endif
float4 PS_TRAA(float4 vpos : SV_Position, float2 texcoord : TexCoord) : SV_Target {
//3x3 neighborhood from DLAA prepass
static const float2 offsets[9] = {
float2(-1, -1), float2(0, -1), float2(1, -1),
float2(-1, 0) , float2(0, 0) , float2(1, 0),
float2(-1, 1) , float2(0, 1) , float2(1, 1)
};
float3 samples[9];
float3 samplesYCoCg[9];
float3 meanYCoCg = float3(0, 0, 0);
for (int i = 0; i < 9; i++) {
float2 samplePos = texcoord + BUFFER_PIXEL_SIZE * offsets[i];
#if ENABLE_DLAA
samples[i] = tex2Dlod(sDLAAPrePass, float4(samplePos, 0, 0)).rgb;
#else
samples[i] = GetLinearColor(samplePos, false);
#endif
samplesYCoCg[i] = linearToYCoCg(samples[i]);
meanYCoCg += samplesYCoCg[i];
}
meanYCoCg /= 9.0;
//standard deviation per channel
float3 stddev = float3(0, 0, 0);
for (int i = 0; i < 9; i++) {
float3 diff = samplesYCoCg[i] - meanYCoCg;
stddev += diff * diff;
}
stddev = sqrt(stddev / 9.0);
//variance-scaled bounding box in YCoCg
float3 colorMin = meanYCoCg - stddev * 1.25;
float3 colorMax = meanYCoCg + stddev * 1.25;
float2 flow = tex2D(Kernel::sFlow, texcoord).xy;
float confidence = tex2D(Kernel::sConfidence, texcoord).x;
confidence = saturate(confidence + 0.11 * 4.0 * confidence * (1.0 - confidence));
float2 historyUV = texcoord + flow;
historyUV = clamp(historyUV, BUFFER_PIXEL_SIZE, 1.0 - BUFFER_PIXEL_SIZE);
float3 historyRGB = SampleCatmullRom5Tap(sPrevHistory, historyUV);
float3 historyYCoCg = linearToYCoCg(historyRGB);
//clip history to current neighborhood bounds via line-box intersection
float3 clippedHistoryYCoCg = YCoCgLineBoxClip(historyYCoCg, meanYCoCg, colorMin, colorMax);
//re-inject current pixel's detail into clipped history
float3 centerYCoCg = samplesYCoCg[4]; //blend against the center pixel (index 4 of the 3x3 grid)
float3 injectedHistory = clippedHistoryYCoCg + (centerYCoCg - meanYCoCg) * HFI_INTENSITY;
//blend clipped history with current in YCoCg space
float blendVal = min(0.98, HISTORY_BLEND);
float3 blendedYCoCg = lerp(centerYCoCg, injectedHistory, confidence * blendVal);
float3 output = YCoCgToLinear(blendedYCoCg);
return float4(output, 1.0);
}
float4 PS_ToDisplay(float4 vpos : SV_Position, float2 texcoord : TexCoord) : SV_Target {
#if ENABLE_DLAA
if (DEBUG_EDGES) {
float edgeDbg = tex2D(sDLAAPreFilter, texcoord).a;
static const float3 edgeTint = float3(0.125, 0.698, 0.667) * float3(0.125, 0.698, 0.667); //target color squared so lands on the real hue
return float4(ToOutputColorspace(edgeTint * saturate(edgeDbg), false), 1.0);
}
#endif
float3 c = tex2D(sCurrHistory, texcoord).rgb;
float3 sharpened = c;
if (SHARP_STRENGTH > 0) {
float2 off = BUFFER_PIXEL_SIZE * 0.5;
float3 ne = tex2D(sCurrHistory, texcoord + float2( off.x, off.y)).rgb;
float3 sw = tex2D(sCurrHistory, texcoord + float2(-off.x, -off.y)).rgb;
float3 se = tex2D(sCurrHistory, texcoord + float2( off.x, -off.y)).rgb;
float3 nw = tex2D(sCurrHistory, texcoord + float2(-off.x, off.y)).rgb;
//bounds for the neighborhood
float3 local_min = min(min(min(ne, nw), min(se, sw)), c);
float3 local_max = max(max(max(ne, nw), max(se, sw)), c);
//high-pass
float3 diag_max = max(max(ne, nw), max(se, sw));
float3 diag_min = min(min(ne, nw), min(se, sw));
float3 diff_rgb = 2.0 * c + (ne + nw + se + sw) - 3.0 * (diag_max + diag_min);
static const float3 luma_weight = float3(0.2126, 0.7152, 0.0722);
float luma_c = dot(c, luma_weight);
float luma_diff = dot(diff_rgb, luma_weight);
//rational limit
float max_allowed = MAX_SHARP_DIFF * (luma_c + 0.1);
luma_diff = luma_diff / (rcp(SHARP_STRENGTH) + abs(luma_diff) / max(max_allowed, 0.001));
//lower epsilon (0.005) for more dark-area detail
float ratio = (luma_c + luma_diff) / max(luma_c, 0.005);
//allow up to 3x brightness for extreme highlights
ratio = clamp(ratio, 0.3, 3.0);
sharpened = c * ratio;
//anti-ringing
//instead of clamping strictly to min/max, we allow a 20% overshoot
//perceived "sharpness" while capping fireflies
float3 overshoot_min = local_min * 0.8;
float3 overshoot_max = local_max * 1.2;
sharpened = clamp(sharpened, overshoot_min, overshoot_max);
}
return float4(ToOutputColorspace(sharpened, false), 1.0);
}
float4 PS_StoreHistory(float4 vpos : SV_Position, float2 texcoord : TexCoord) : SV_Target {
float3 taaResult = tex2D(sCurrHistory, texcoord).rgb;
return float4(taaResult, 1.0);
}
/*----------------.
| :: TECHNIQUE :: |
'----------------*/
technique Lumenite_TRAA <
ui_label = "LUMENITE: TRAA";
ui_tooltip = "Temporal Reprojection Anti-Aliasing.";
>
{
#if ENABLE_DLAA
pass { VertexShader = PostProcessVS; PixelShader = PS_DLAAPreFilter; RenderTarget = tDLAAPreFilter; }
pass { VertexShader = PostProcessVS; PixelShader = PS_DLAA; RenderTarget = tDLAAPrePass; } //spatial filter
#endif
pass { VertexShader = PostProcessVS; PixelShader = PS_TRAA; RenderTarget = tCurrHistory; } //temporal filter
pass { VertexShader = PostProcessVS; PixelShader = PS_ToDisplay; }
pass { VertexShader = PostProcessVS; PixelShader = PS_StoreHistory; RenderTarget = tPrevHistory; }
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 B