diff options
author | Clément Foucault <foucault.clem@gmail.com> | 2019-12-02 03:40:58 +0300 |
---|---|---|
committer | Clément Foucault <foucault.clem@gmail.com> | 2019-12-02 15:15:52 +0300 |
commit | 9516921c05bd9fee5c94942eb8e38f47ba7e4351 (patch) | |
tree | da007fc17bc6a02f849dae2e8f76f5ab304fe4dc /source/blender/draw/intern/shaders | |
parent | 1f6c3699a836d485ed37f443cd0fcd19e978dbb6 (diff) |
Overlay Engine: Refactor & Cleanup
This is the unification of all overlays into one overlay engine as described in T65347.
I went over all the code making it more future proof with less hacks and removing old / not relevent parts.
Goals / Acheivements:
- Remove internal shader usage (only drw shaders)
- Remove viewportSize and viewportSizeInv and put them in gloabl ubo
- Fixed some drawing issues: Missing probe option and Missing Alt+B clipping of some shader
- Remove old (legacy) shaders dependancy (not using view UBO).
- Less shader variation (less compilation time at first load and less patching needed for vulkan)
- removed some geom shaders when I could
- Remove static e_data (except shaders storage where it is OK)
- Clear the way to fix some anoying limitations (dithered transparency, background image compositing etc...)
- Wireframe drawing now uses the same batching capabilities as workbench & eevee (indirect drawing).
- Reduced complexity, removed ~3000 Lines of code in draw (also removed a lot of unused shader in GPU).
- Post AA to avoid complexity and cost of MSAA.
Remaining issues:
- ~~Armature edits, overlay toggles, (... others?) are not refreshing viewport after AA is complete~~
- FXAA is not the best for wires, maybe investigate SMAA
- Maybe do something more temporally stable for AA.
- ~~Paint overlays are not working with AA.~~
- ~~infront objects are difficult to select.~~
- ~~the infront wires sometimes goes through they solid counterpart (missing clear maybe?) (toggle overlays on-off when using infront+wireframe overlay in solid shading)~~
Note: I made some decision to change slightly the appearance of some objects to simplify their drawing. Namely the empty arrows end (which is now hollow/wire) and distance points of the cameras/spots being done by lines.
Reviewed By: jbakker
Differential Revision: https://developer.blender.org/D6296
Diffstat (limited to 'source/blender/draw/intern/shaders')
8 files changed, 2933 insertions, 0 deletions
diff --git a/source/blender/draw/intern/shaders/common_colormanagement_lib.glsl b/source/blender/draw/intern/shaders/common_colormanagement_lib.glsl new file mode 100644 index 00000000000..45f711296f3 --- /dev/null +++ b/source/blender/draw/intern/shaders/common_colormanagement_lib.glsl @@ -0,0 +1,30 @@ +float linearrgb_to_srgb(float c) +{ + if (c < 0.0031308) { + return (c < 0.0) ? 0.0 : c * 12.92; + } + else { + return 1.055 * pow(c, 1.0 / 2.4) - 0.055; + } +} + +vec4 texture_read_as_linearrgb(sampler2D tex, bool premultiplied, vec2 co) +{ + /* By convention image textures return scene linear colors, but + * overlays still assume srgb. */ + vec4 color = texture(tex, co); + /* Unpremultiply if stored multiplied, since straight alpha is expected by shaders. */ + if (premultiplied && !(color.a == 0.0 || color.a == 1.0)) { + color.rgb = color.rgb / color.a; + } + return color; +} + +vec4 texture_read_as_srgb(sampler2D tex, bool premultiplied, vec2 co) +{ + vec4 color = texture_read_as_linearrgb(tex, premultiplied, co); + color.r = linearrgb_to_srgb(color.r); + color.g = linearrgb_to_srgb(color.g); + color.b = linearrgb_to_srgb(color.b); + return color; +} diff --git a/source/blender/draw/intern/shaders/common_fullscreen_vert.glsl b/source/blender/draw/intern/shaders/common_fullscreen_vert.glsl new file mode 100644 index 00000000000..8a7fb97d98c --- /dev/null +++ b/source/blender/draw/intern/shaders/common_fullscreen_vert.glsl @@ -0,0 +1,11 @@ + +out vec4 uvcoordsvar; + +void main() +{ + int v = gl_VertexID % 3; + float x = -1.0 + float((v & 1) << 2); + float y = -1.0 + float((v & 2) << 1); + gl_Position = vec4(x, y, 1.0, 1.0); + uvcoordsvar = vec4((gl_Position.xy + 1.0) * 0.5, 0.0, 0.0); +} diff --git a/source/blender/draw/intern/shaders/common_fxaa_lib.glsl b/source/blender/draw/intern/shaders/common_fxaa_lib.glsl new file mode 100644 index 00000000000..9eaba00988d --- /dev/null +++ b/source/blender/draw/intern/shaders/common_fxaa_lib.glsl @@ -0,0 +1,884 @@ +//---------------------------------------------------------------------------------- +// File: es3-kepler\FXAA/FXAA3_11.h +// SDK Version: v3.00 +// Email: gameworks@nvidia.com +// Site: http://developer.nvidia.com/ +// +// Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of NVIDIA CORPORATION nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +//---------------------------------------------------------------------------------- + +/* BLENDER MODIFICATIONS: + * + * - (#B1#) Compute luma on the fly using BT. 709 luma function + * - (#B2#) main function instead of #include, due to lack of + * ARB_shading_language_include in 3.3 + * - (#B3#) version and extension directives + * - removed "FXAA Console" algorithm support and shader parameters + * - removed HLSL support shims + * - (#B4#) change luma sampling to compute, not use A channel + * (this also removes GATHER4_ALPHA support) + * - removed all the console shaders (only remaining algorithm is "FXAA PC + * Quality") + * + * Note that this file doesn't follow the coding style guidelines. + */ + +/*============================================================================ + FXAA QUALITY - TUNING KNOBS +------------------------------------------------------------------------------ +NOTE the other tuning knobs are now in the shader function inputs! +============================================================================*/ +#ifndef FXAA_QUALITY__PRESET +// +// Choose the quality preset. +// This needs to be compiled into the shader as it effects code. +// Best option to include multiple presets is to +// in each shader define the preset, then include this file. +// +// OPTIONS +// ----------------------------------------------------------------------- +// 10 to 15 - default medium dither (10=fastest, 15=highest quality) +// 20 to 29 - less dither, more expensive (20=fastest, 29=highest quality) +// 39 - no dither, very expensive +// +// NOTES +// ----------------------------------------------------------------------- +// 12 = slightly faster then FXAA 3.9 and higher edge quality (default) +// 13 = about same speed as FXAA 3.9 and better than 12 +// 23 = closest to FXAA 3.9 visually and performance wise +// _ = the lowest digit is directly related to performance +// _ = the highest digit is directly related to style +// +# define FXAA_QUALITY__PRESET 12 +#endif + +/*============================================================================ + + FXAA QUALITY - PRESETS + +============================================================================*/ + +/*============================================================================ + FXAA QUALITY - MEDIUM DITHER PRESETS +============================================================================*/ +#if (FXAA_QUALITY__PRESET == 10) +# define FXAA_QUALITY__PS 3 +# define FXAA_QUALITY__P0 1.5 +# define FXAA_QUALITY__P1 3.0 +# define FXAA_QUALITY__P2 12.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 11) +# define FXAA_QUALITY__PS 4 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 3.0 +# define FXAA_QUALITY__P3 12.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 12) +# define FXAA_QUALITY__PS 5 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 4.0 +# define FXAA_QUALITY__P4 12.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 13) +# define FXAA_QUALITY__PS 6 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 4.0 +# define FXAA_QUALITY__P5 12.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 14) +# define FXAA_QUALITY__PS 7 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 4.0 +# define FXAA_QUALITY__P6 12.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 15) +# define FXAA_QUALITY__PS 8 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 4.0 +# define FXAA_QUALITY__P7 12.0 +#endif + +/*============================================================================ + FXAA QUALITY - LOW DITHER PRESETS +============================================================================*/ +#if (FXAA_QUALITY__PRESET == 20) +# define FXAA_QUALITY__PS 3 +# define FXAA_QUALITY__P0 1.5 +# define FXAA_QUALITY__P1 2.0 +# define FXAA_QUALITY__P2 8.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 21) +# define FXAA_QUALITY__PS 4 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 8.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 22) +# define FXAA_QUALITY__PS 5 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 8.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 23) +# define FXAA_QUALITY__PS 6 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 8.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 24) +# define FXAA_QUALITY__PS 7 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 3.0 +# define FXAA_QUALITY__P6 8.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 25) +# define FXAA_QUALITY__PS 8 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 4.0 +# define FXAA_QUALITY__P7 8.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 26) +# define FXAA_QUALITY__PS 9 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 2.0 +# define FXAA_QUALITY__P7 4.0 +# define FXAA_QUALITY__P8 8.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 27) +# define FXAA_QUALITY__PS 10 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 2.0 +# define FXAA_QUALITY__P7 2.0 +# define FXAA_QUALITY__P8 4.0 +# define FXAA_QUALITY__P9 8.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 28) +# define FXAA_QUALITY__PS 11 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 2.0 +# define FXAA_QUALITY__P7 2.0 +# define FXAA_QUALITY__P8 2.0 +# define FXAA_QUALITY__P9 4.0 +# define FXAA_QUALITY__P10 8.0 +#endif +/*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PRESET == 29) +# define FXAA_QUALITY__PS 12 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.5 +# define FXAA_QUALITY__P2 2.0 +# define FXAA_QUALITY__P3 2.0 +# define FXAA_QUALITY__P4 2.0 +# define FXAA_QUALITY__P5 2.0 +# define FXAA_QUALITY__P6 2.0 +# define FXAA_QUALITY__P7 2.0 +# define FXAA_QUALITY__P8 2.0 +# define FXAA_QUALITY__P9 2.0 +# define FXAA_QUALITY__P10 4.0 +# define FXAA_QUALITY__P11 8.0 +#endif + +/*============================================================================ + FXAA QUALITY - EXTREME QUALITY +============================================================================*/ +#if (FXAA_QUALITY__PRESET == 39) +# define FXAA_QUALITY__PS 12 +# define FXAA_QUALITY__P0 1.0 +# define FXAA_QUALITY__P1 1.0 +# define FXAA_QUALITY__P2 1.0 +# define FXAA_QUALITY__P3 1.0 +# define FXAA_QUALITY__P4 1.0 +# define FXAA_QUALITY__P5 1.5 +# define FXAA_QUALITY__P6 2.0 +# define FXAA_QUALITY__P7 2.0 +# define FXAA_QUALITY__P8 2.0 +# define FXAA_QUALITY__P9 2.0 +# define FXAA_QUALITY__P10 4.0 +# define FXAA_QUALITY__P11 8.0 +#endif + +#define FxaaSat(x) clamp(x, 0.0, 1.0) + +#ifdef FXAA_ALPHA + +# define FxaaTexTop(t, p) textureLod(t, p, 0.0).aaaa +# define FxaaTexOff(t, p, o, r) textureLodOffset(t, p, 0.0, o).aaaa +# define FxaaLuma(rgba) rgba.a + +#else + +# define FxaaTexTop(t, p) textureLod(t, p, 0.0) +# define FxaaTexOff(t, p, o, r) textureLodOffset(t, p, 0.0, o) + +/* (#B1#) */ +float FxaaLuma(vec4 rgba) +{ + // note: sqrt because the sampled colors are in a linear colorspace! + // this approximates a perceptual conversion, which is good enough for the + // algorithm + return sqrt(dot(rgba.rgb, vec3(0.2126, 0.7152, 0.0722))); +} + +#endif + +/*============================================================================ + + FXAA3 QUALITY - PC + +============================================================================*/ +/*--------------------------------------------------------------------------*/ +vec4 FxaaPixelShader( + // + // Use noperspective interpolation here (turn off perspective interpolation). + // {xy} = center of pixel + vec2 pos, + // + // Input color texture. + // {rgb_} = color in linear or perceptual color space + sampler2D tex, + // + // Only used on FXAA Quality. + // This must be from a constant/uniform. + // {x_} = 1.0/screenWidthInPixels + // {_y} = 1.0/screenHeightInPixels + vec2 fxaaQualityRcpFrame, + // + // Only used on FXAA Quality. + // This used to be the FXAA_QUALITY__SUBPIX define. + // It is here now to allow easier tuning. + // Choose the amount of sub-pixel aliasing removal. + // This can effect sharpness. + // 1.00 - upper limit (softer) + // 0.75 - default amount of filtering + // 0.50 - lower limit (sharper, less sub-pixel aliasing removal) + // 0.25 - almost off + // 0.00 - completely off + float fxaaQualitySubpix, + // + // Only used on FXAA Quality. + // This used to be the FXAA_QUALITY__EDGE_THRESHOLD define. + // It is here now to allow easier tuning. + // The minimum amount of local contrast required to apply algorithm. + // 0.333 - too little (faster) + // 0.250 - low quality + // 0.166 - default + // 0.125 - high quality + // 0.063 - overkill (slower) + float fxaaQualityEdgeThreshold, + // + // Only used on FXAA Quality. + // This used to be the FXAA_QUALITY__EDGE_THRESHOLD_MIN define. + // It is here now to allow easier tuning. + // Trims the algorithm from processing darks. + // 0.0833 - upper limit (default, the start of visible unfiltered edges) + // 0.0625 - high quality (faster) + // 0.0312 - visible limit (slower) + float fxaaQualityEdgeThresholdMin) +{ + /*--------------------------------------------------------------------------*/ + vec2 posM; + posM.x = pos.x; + posM.y = pos.y; + vec4 rgbyM = FxaaTexTop(tex, posM); + float lumaM = FxaaLuma(rgbyM); // (#B4#) + float lumaS = FxaaLuma(FxaaTexOff(tex, posM, ivec2(0, 1), fxaaQualityRcpFrame.xy)); + float lumaE = FxaaLuma(FxaaTexOff(tex, posM, ivec2(1, 0), fxaaQualityRcpFrame.xy)); + float lumaN = FxaaLuma(FxaaTexOff(tex, posM, ivec2(0, -1), fxaaQualityRcpFrame.xy)); + float lumaW = FxaaLuma(FxaaTexOff(tex, posM, ivec2(-1, 0), fxaaQualityRcpFrame.xy)); + /*--------------------------------------------------------------------------*/ + float maxSM = max(lumaS, lumaM); + float minSM = min(lumaS, lumaM); + float maxESM = max(lumaE, maxSM); + float minESM = min(lumaE, minSM); + float maxWN = max(lumaN, lumaW); + float minWN = min(lumaN, lumaW); + float rangeMax = max(maxWN, maxESM); + float rangeMin = min(minWN, minESM); + float rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold; + float range = rangeMax - rangeMin; + float rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled); + bool earlyExit = range < rangeMaxClamped; + /*--------------------------------------------------------------------------*/ + if (earlyExit) { + return rgbyM; + } + /*--------------------------------------------------------------------------*/ + float lumaNW = FxaaLuma(FxaaTexOff(tex, posM, ivec2(-1, -1), fxaaQualityRcpFrame.xy)); + float lumaSE = FxaaLuma(FxaaTexOff(tex, posM, ivec2(1, 1), fxaaQualityRcpFrame.xy)); + float lumaNE = FxaaLuma(FxaaTexOff(tex, posM, ivec2(1, -1), fxaaQualityRcpFrame.xy)); + float lumaSW = FxaaLuma(FxaaTexOff(tex, posM, ivec2(-1, 1), fxaaQualityRcpFrame.xy)); + /*--------------------------------------------------------------------------*/ + float lumaNS = lumaN + lumaS; + float lumaWE = lumaW + lumaE; + float subpixRcpRange = 1.0 / range; + float subpixNSWE = lumaNS + lumaWE; + float edgeHorz1 = (-2.0 * lumaM) + lumaNS; + float edgeVert1 = (-2.0 * lumaM) + lumaWE; + /*--------------------------------------------------------------------------*/ + float lumaNESE = lumaNE + lumaSE; + float lumaNWNE = lumaNW + lumaNE; + float edgeHorz2 = (-2.0 * lumaE) + lumaNESE; + float edgeVert2 = (-2.0 * lumaN) + lumaNWNE; + /*--------------------------------------------------------------------------*/ + float lumaNWSW = lumaNW + lumaSW; + float lumaSWSE = lumaSW + lumaSE; + float edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2); + float edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2); + float edgeHorz3 = (-2.0 * lumaW) + lumaNWSW; + float edgeVert3 = (-2.0 * lumaS) + lumaSWSE; + float edgeHorz = abs(edgeHorz3) + edgeHorz4; + float edgeVert = abs(edgeVert3) + edgeVert4; + /*--------------------------------------------------------------------------*/ + float subpixNWSWNESE = lumaNWSW + lumaNESE; + float lengthSign = fxaaQualityRcpFrame.x; + bool horzSpan = edgeHorz >= edgeVert; + float subpixA = subpixNSWE * 2.0 + subpixNWSWNESE; + /*--------------------------------------------------------------------------*/ + if (!horzSpan) { + lumaN = lumaW; + } + if (!horzSpan) { + lumaS = lumaE; + } + if (horzSpan) { + lengthSign = fxaaQualityRcpFrame.y; + } + float subpixB = (subpixA * (1.0 / 12.0)) - lumaM; + /*--------------------------------------------------------------------------*/ + float gradientN = lumaN - lumaM; + float gradientS = lumaS - lumaM; + float lumaNN = lumaN + lumaM; + float lumaSS = lumaS + lumaM; + bool pairN = abs(gradientN) >= abs(gradientS); + float gradient = max(abs(gradientN), abs(gradientS)); + if (pairN) { + lengthSign = -lengthSign; + } + float subpixC = FxaaSat(abs(subpixB) * subpixRcpRange); + /*--------------------------------------------------------------------------*/ + vec2 posB; + posB.x = posM.x; + posB.y = posM.y; + vec2 offNP; + offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x; + offNP.y = (horzSpan) ? 0.0 : fxaaQualityRcpFrame.y; + if (!horzSpan) { + posB.x += lengthSign * 0.5; + } + if (horzSpan) { + posB.y += lengthSign * 0.5; + } + /*--------------------------------------------------------------------------*/ + vec2 posN; + posN.x = posB.x - offNP.x * FXAA_QUALITY__P0; + posN.y = posB.y - offNP.y * FXAA_QUALITY__P0; + vec2 posP; + posP.x = posB.x + offNP.x * FXAA_QUALITY__P0; + posP.y = posB.y + offNP.y * FXAA_QUALITY__P0; + float subpixD = ((-2.0) * subpixC) + 3.0; + float lumaEndN = FxaaLuma(FxaaTexTop(tex, posN)); + float subpixE = subpixC * subpixC; + float lumaEndP = FxaaLuma(FxaaTexTop(tex, posP)); + /*--------------------------------------------------------------------------*/ + if (!pairN) { + lumaNN = lumaSS; + } + float gradientScaled = gradient * 1.0 / 4.0; + float lumaMM = lumaM - lumaNN * 0.5; + float subpixF = subpixD * subpixE; + bool lumaMLTZero = lumaMM < 0.0; + /*--------------------------------------------------------------------------*/ + lumaEndN -= lumaNN * 0.5; + lumaEndP -= lumaNN * 0.5; + bool doneN = abs(lumaEndN) >= gradientScaled; + bool doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P1; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P1; + } + bool doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P1; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P1; + } + /*--------------------------------------------------------------------------*/ + if (doneNP) { + if (!doneN) { + lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + } + if (!doneP) { + lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + } + if (!doneN) { + lumaEndN = lumaEndN - lumaNN * 0.5; + } + if (!doneP) { + lumaEndP = lumaEndP - lumaNN * 0.5; + } + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P2; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P2; + } + doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P2; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P2; + } + /*--------------------------------------------------------------------------*/ +#if (FXAA_QUALITY__PS > 3) + if (doneNP) { + if (!doneN) { + lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + } + if (!doneP) { + lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + } + if (!doneN) { + lumaEndN = lumaEndN - lumaNN * 0.5; + } + if (!doneP) { + lumaEndP = lumaEndP - lumaNN * 0.5; + } + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P3; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P3; + } + doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P3; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P3; + } + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 4) + if (doneNP) { + if (!doneN) { + lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + } + if (!doneP) { + lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + } + if (!doneN) { + lumaEndN = lumaEndN - lumaNN * 0.5; + } + if (!doneP) { + lumaEndP = lumaEndP - lumaNN * 0.5; + } + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P4; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P4; + } + doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P4; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P4; + } + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 5) + if (doneNP) { + if (!doneN) { + lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + } + if (!doneP) { + lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + } + if (!doneN) { + lumaEndN = lumaEndN - lumaNN * 0.5; + } + if (!doneP) { + lumaEndP = lumaEndP - lumaNN * 0.5; + } + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P5; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P5; + } + doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P5; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P5; + } + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 6) + if (doneNP) { + if (!doneN) { + lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + } + if (!doneP) { + lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + } + if (!doneN) { + lumaEndN = lumaEndN - lumaNN * 0.5; + } + if (!doneP) { + lumaEndP = lumaEndP - lumaNN * 0.5; + } + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P6; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P6; + } + doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P6; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P6; + } + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 7) + if (doneNP) { + if (!doneN) { + lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + } + if (!doneP) { + lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + } + if (!doneN) { + lumaEndN = lumaEndN - lumaNN * 0.5; + } + if (!doneP) { + lumaEndP = lumaEndP - lumaNN * 0.5; + } + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P7; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P7; + } + doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P7; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P7; + } + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 8) + if (doneNP) { + if (!doneN) { + lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + } + if (!doneP) { + lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + } + if (!doneN) { + lumaEndN = lumaEndN - lumaNN * 0.5; + } + if (!doneP) { + lumaEndP = lumaEndP - lumaNN * 0.5; + } + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P8; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P8; + } + doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P8; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P8; + } + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 9) + if (doneNP) { + if (!doneN) { + lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + } + if (!doneP) { + lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + } + if (!doneN) { + lumaEndN = lumaEndN - lumaNN * 0.5; + } + if (!doneP) { + lumaEndP = lumaEndP - lumaNN * 0.5; + } + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P9; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P9; + } + doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P9; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P9; + } + /*--------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 10) + if (doneNP) { + if (!doneN) { + lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + } + if (!doneP) { + lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + } + if (!doneN) { + lumaEndN = lumaEndN - lumaNN * 0.5; + } + if (!doneP) { + lumaEndP = lumaEndP - lumaNN * 0.5; + } + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P10; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P10; + } + doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P10; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P10; + } + /*-------------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 11) + if (doneNP) { + if (!doneN) { + lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + } + if (!doneP) { + lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + } + if (!doneN) { + lumaEndN = lumaEndN - lumaNN * 0.5; + } + if (!doneP) { + lumaEndP = lumaEndP - lumaNN * 0.5; + } + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P11; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P11; + } + doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P11; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P11; + } + /*-----------------------------------------------------------------------*/ +# if (FXAA_QUALITY__PS > 12) + if (doneNP) { + if (!doneN) { + lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy)); + } + if (!doneP) { + lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy)); + } + if (!doneN) { + lumaEndN = lumaEndN - lumaNN * 0.5; + } + if (!doneP) { + lumaEndP = lumaEndP - lumaNN * 0.5; + } + doneN = abs(lumaEndN) >= gradientScaled; + doneP = abs(lumaEndP) >= gradientScaled; + if (!doneN) { + posN.x -= offNP.x * FXAA_QUALITY__P12; + } + if (!doneN) { + posN.y -= offNP.y * FXAA_QUALITY__P12; + } + doneNP = (!doneN) || (!doneP); + if (!doneP) { + posP.x += offNP.x * FXAA_QUALITY__P12; + } + if (!doneP) { + posP.y += offNP.y * FXAA_QUALITY__P12; + } + /*-----------------------------------------------------------------------*/ + } +# endif + /*-------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +# endif + /*--------------------------------------------------------------------------*/ + } +#endif + /*--------------------------------------------------------------------------*/ + } + /*--------------------------------------------------------------------------*/ + float dstN = posM.x - posN.x; + float dstP = posP.x - posM.x; + if (!horzSpan) { + dstN = posM.y - posN.y; + } + if (!horzSpan) { + dstP = posP.y - posM.y; + } + /*--------------------------------------------------------------------------*/ + bool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero; + float spanLength = (dstP + dstN); + bool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero; + float spanLengthRcp = 1.0 / spanLength; + /*--------------------------------------------------------------------------*/ + bool directionN = dstN < dstP; + float dst = min(dstN, dstP); + bool goodSpan = directionN ? goodSpanN : goodSpanP; + float subpixG = subpixF * subpixF; + float pixelOffset = (dst * (-spanLengthRcp)) + 0.5; + float subpixH = subpixG * fxaaQualitySubpix; + /*--------------------------------------------------------------------------*/ + float pixelOffsetGood = goodSpan ? pixelOffset : 0.0; + float pixelOffsetSubpix = max(pixelOffsetGood, subpixH); + if (!horzSpan) { + posM.x += pixelOffsetSubpix * lengthSign; + } + if (horzSpan) { + posM.y += pixelOffsetSubpix * lengthSign; + } + return FxaaTexTop(tex, posM); +} +/*==========================================================================*/ diff --git a/source/blender/draw/intern/shaders/common_globals_lib.glsl b/source/blender/draw/intern/shaders/common_globals_lib.glsl new file mode 100644 index 00000000000..151932a3b47 --- /dev/null +++ b/source/blender/draw/intern/shaders/common_globals_lib.glsl @@ -0,0 +1,108 @@ +#define COMMON_GLOBALS_LIB + +/* keep in sync with GlobalsUboStorage */ +layout(std140) uniform globalsBlock +{ + vec4 colorWire; + vec4 colorWireEdit; + vec4 colorActive; + vec4 colorSelect; + vec4 colorDupliSelect; + vec4 colorDupli; + vec4 colorLibrarySelect; + vec4 colorLibrary; + vec4 colorTransform; + vec4 colorLight; + vec4 colorSpeaker; + vec4 colorCamera; + vec4 colorCameraPath; + vec4 colorEmpty; + vec4 colorVertex; + vec4 colorVertexSelect; + vec4 colorVertexUnreferenced; + vec4 colorVertexMissingData; + vec4 colorEditMeshActive; + vec4 colorEdgeSelect; + vec4 colorEdgeSeam; + vec4 colorEdgeSharp; + vec4 colorEdgeCrease; + vec4 colorEdgeBWeight; + vec4 colorEdgeFaceSelect; + vec4 colorEdgeFreestyle; + vec4 colorFace; + vec4 colorFaceSelect; + vec4 colorFaceFreestyle; + vec4 colorNormal; + vec4 colorVNormal; + vec4 colorLNormal; + vec4 colorFaceDot; + vec4 colorSkinRoot; + vec4 colorDeselect; + vec4 colorOutline; + vec4 colorLightNoAlpha; + + vec4 colorBackground; + vec4 colorEditMeshMiddle; + + vec4 colorHandleFree; + vec4 colorHandleAuto; + vec4 colorHandleVect; + vec4 colorHandleAlign; + vec4 colorHandleAutoclamp; + vec4 colorHandleSelFree; + vec4 colorHandleSelAuto; + vec4 colorHandleSelVect; + vec4 colorHandleSelAlign; + vec4 colorHandleSelAutoclamp; + vec4 colorNurbUline; + vec4 colorNurbVline; + vec4 colorNurbSelUline; + vec4 colorNurbSelVline; + vec4 colorActiveSpline; + + vec4 colorBonePose; + + vec4 colorCurrentFrame; + + vec4 colorGrid; + vec4 colorGridEmphasise; + vec4 colorGridAxisX; + vec4 colorGridAxisY; + vec4 colorGridAxisZ; + + vec4 screenVecs[2]; + vec4 sizeViewport; /* Inverted size in zw. */ + + float sizePixel; /* This one is for dpi scalling */ + float pixelFac; /* To use with mul_project_m4_v3_zfac() */ + float sizeObjectCenter; + float sizeLightCenter; + float sizeLightCircle; + float sizeLightCircleShadow; + float sizeVertex; + float sizeEdge; + float sizeEdgeFix; + float sizeFaceDot; + + float pad_globalsBlock; +}; + +#define sizeViewportInv (sizeViewport.zw) + +/* data[0] (1st byte flags) */ +#define FACE_ACTIVE (1 << 0) +#define FACE_SELECTED (1 << 1) +#define FACE_FREESTYLE (1 << 2) +#define VERT_UV_SELECT (1 << 3) +#define VERT_UV_PINNED (1 << 4) +#define EDGE_UV_SELECT (1 << 5) +#define FACE_UV_ACTIVE (1 << 6) +#define FACE_UV_SELECT (1 << 7) +/* data[1] (2st byte flags) */ +#define VERT_ACTIVE (1 << 0) +#define VERT_SELECTED (1 << 1) +#define EDGE_ACTIVE (1 << 2) +#define EDGE_SELECTED (1 << 3) +#define EDGE_SEAM (1 << 4) +#define EDGE_SHARP (1 << 5) +#define EDGE_FREESTYLE (1 << 6) diff --git a/source/blender/draw/intern/shaders/common_hair_lib.glsl b/source/blender/draw/intern/shaders/common_hair_lib.glsl new file mode 100644 index 00000000000..cbcdc947bc7 --- /dev/null +++ b/source/blender/draw/intern/shaders/common_hair_lib.glsl @@ -0,0 +1,206 @@ +/** + * Library to create hairs dynamically from control points. + * This is less bandwidth intensive than fetching the vertex attributes + * but does more ALU work per vertex. This also reduces the amount + * of data the CPU has to precompute and transfer for each update. + */ + +/** + * hairStrandsRes: Number of points per hair strand. + * 2 - no subdivision + * 3+ - 1 or more interpolated points per hair. + */ +uniform int hairStrandsRes = 8; + +/** + * hairThicknessRes : Subdiv around the hair. + * 1 - Wire Hair: Only one pixel thick, independent of view distance. + * 2 - Polystrip Hair: Correct width, flat if camera is parallel. + * 3+ - Cylinder Hair: Massive calculation but potentially perfect. Still need proper support. + */ +uniform int hairThicknessRes = 1; + +/* Hair thickness shape. */ +uniform float hairRadRoot = 0.01; +uniform float hairRadTip = 0.0; +uniform float hairRadShape = 0.5; +uniform bool hairCloseTip = true; + +uniform mat4 hairDupliMatrix; + +/* -- Per control points -- */ +uniform samplerBuffer hairPointBuffer; /* RGBA32F */ +#define point_position xyz +#define point_time w /* Position along the hair length */ + +/* -- Per strands data -- */ +uniform usamplerBuffer hairStrandBuffer; /* R32UI */ +uniform usamplerBuffer hairStrandSegBuffer; /* R16UI */ + +/* Not used, use one buffer per uv layer */ +// uniform samplerBuffer hairUVBuffer; /* RG32F */ +// uniform samplerBuffer hairColBuffer; /* RGBA16 linear color */ + +/* -- Subdivision stage -- */ +/** + * We use a transform feedback to preprocess the strands and add more subdivision to it. + * For the moment these are simple smooth interpolation but one could hope to see the full + * children particle modifiers being evaluated at this stage. + * + * If no more subdivision is needed, we can skip this step. + */ + +#ifdef HAIR_PHASE_SUBDIV +int hair_get_base_id(float local_time, int strand_segments, out float interp_time) +{ + float time_per_strand_seg = 1.0 / float(strand_segments); + + float ratio = local_time / time_per_strand_seg; + interp_time = fract(ratio); + + return int(ratio); +} + +void hair_get_interp_attrs( + out vec4 data0, out vec4 data1, out vec4 data2, out vec4 data3, out float interp_time) +{ + float local_time = float(gl_VertexID % hairStrandsRes) / float(hairStrandsRes - 1); + + int hair_id = gl_VertexID / hairStrandsRes; + int strand_offset = int(texelFetch(hairStrandBuffer, hair_id).x); + int strand_segments = int(texelFetch(hairStrandSegBuffer, hair_id).x); + + int id = hair_get_base_id(local_time, strand_segments, interp_time); + + int ofs_id = id + strand_offset; + + data0 = texelFetch(hairPointBuffer, ofs_id - 1); + data1 = texelFetch(hairPointBuffer, ofs_id); + data2 = texelFetch(hairPointBuffer, ofs_id + 1); + data3 = texelFetch(hairPointBuffer, ofs_id + 2); + + if (id <= 0) { + /* root points. Need to reconstruct previous data. */ + data0 = data1 * 2.0 - data2; + } + if (id + 1 >= strand_segments) { + /* tip points. Need to reconstruct next data. */ + data3 = data2 * 2.0 - data1; + } +} +#endif + +/* -- Drawing stage -- */ +/** + * For final drawing, the vertex index and the number of vertex per segment + */ + +#ifndef HAIR_PHASE_SUBDIV +int hair_get_strand_id(void) +{ + return gl_VertexID / (hairStrandsRes * hairThicknessRes); +} + +int hair_get_base_id(void) +{ + return gl_VertexID / hairThicknessRes; +} + +/* Copied from cycles. */ +float hair_shaperadius(float shape, float root, float tip, float time) +{ + float radius = 1.0 - time; + + if (shape < 0.0) { + radius = pow(radius, 1.0 + shape); + } + else { + radius = pow(radius, 1.0 / (1.0 - shape)); + } + + if (hairCloseTip && (time > 0.99)) { + return 0.0; + } + + return (radius * (root - tip)) + tip; +} + +# ifdef OS_MAC +in float dummy; +# endif + +void hair_get_pos_tan_binor_time(bool is_persp, + mat4 invmodel_mat, + vec3 camera_pos, + vec3 camera_z, + out vec3 wpos, + out vec3 wtan, + out vec3 wbinor, + out float time, + out float thickness, + out float thick_time) +{ + int id = hair_get_base_id(); + vec4 data = texelFetch(hairPointBuffer, id); + wpos = data.point_position; + time = data.point_time; + +# ifdef OS_MAC + /* Generate a dummy read to avoid the driver bug with shaders having no + * vertex reads on macOS (T60171) */ + wpos.y += dummy * 0.0; +# endif + + if (time == 0.0) { + /* Hair root */ + wtan = texelFetch(hairPointBuffer, id + 1).point_position - wpos; + } + else { + wtan = wpos - texelFetch(hairPointBuffer, id - 1).point_position; + } + + wpos = (hairDupliMatrix * vec4(wpos, 1.0)).xyz; + wtan = -normalize(mat3(hairDupliMatrix) * wtan); + + vec3 camera_vec = (is_persp) ? camera_pos - wpos : camera_z; + wbinor = normalize(cross(camera_vec, wtan)); + + thickness = hair_shaperadius(hairRadShape, hairRadRoot, hairRadTip, time); + + if (hairThicknessRes > 1) { + thick_time = float(gl_VertexID % hairThicknessRes) / float(hairThicknessRes - 1); + thick_time = thickness * (thick_time * 2.0 - 1.0); + + /* Take object scale into account. + * NOTE: This only works fine with uniform scaling. */ + float scale = 1.0 / length(mat3(invmodel_mat) * wbinor); + + wpos += wbinor * thick_time * scale; + } +} + +vec2 hair_get_customdata_vec2(const samplerBuffer cd_buf) +{ + int id = hair_get_strand_id(); + return texelFetch(cd_buf, id).rg; +} + +vec3 hair_get_customdata_vec3(const samplerBuffer cd_buf) +{ + int id = hair_get_strand_id(); + return texelFetch(cd_buf, id).rgb; +} + +vec4 hair_get_customdata_vec4(const samplerBuffer cd_buf) +{ + int id = hair_get_strand_id(); + return texelFetch(cd_buf, id).rgba; +} + +vec3 hair_get_strand_pos(void) +{ + int id = hair_get_strand_id() * hairStrandsRes; + return texelFetch(hairPointBuffer, id).point_position; +} + +#endif diff --git a/source/blender/draw/intern/shaders/common_hair_refine_vert.glsl b/source/blender/draw/intern/shaders/common_hair_refine_vert.glsl new file mode 100644 index 00000000000..3f5e3f8226f --- /dev/null +++ b/source/blender/draw/intern/shaders/common_hair_refine_vert.glsl @@ -0,0 +1,71 @@ + +/* To be compiled with common_hair_lib.glsl */ + +out vec4 finalColor; + +vec4 get_weights_cardinal(float t) +{ + float t2 = t * t; + float t3 = t2 * t; +#if defined(CARDINAL) + float fc = 0.71; +#else /* defined(CATMULL_ROM) */ + float fc = 0.5; +#endif + + vec4 weights; + /* GLSL Optimized version of key_curve_position_weights() */ + float fct = t * fc; + float fct2 = t2 * fc; + float fct3 = t3 * fc; + weights.x = (fct2 * 2.0 - fct3) - fct; + weights.y = (t3 * 2.0 - fct3) + (-t2 * 3.0 + fct2) + 1.0; + weights.z = (-t3 * 2.0 + fct3) + (t2 * 3.0 - (2.0 * fct2)) + fct; + weights.w = fct3 - fct2; + return weights; +} + +/* TODO(fclem): This one is buggy, find why. (it's not the optimization!!) */ +vec4 get_weights_bspline(float t) +{ + float t2 = t * t; + float t3 = t2 * t; + + vec4 weights; + /* GLSL Optimized version of key_curve_position_weights() */ + weights.xz = vec2(-0.16666666, -0.5) * t3 + (0.5 * t2 + 0.5 * vec2(-t, t) + 0.16666666); + weights.y = (0.5 * t3 - t2 + 0.66666666); + weights.w = (0.16666666 * t3); + return weights; +} + +vec4 interp_data(vec4 v0, vec4 v1, vec4 v2, vec4 v3, vec4 w) +{ + return v0 * w.x + v1 * w.y + v2 * w.z + v3 * w.w; +} + +#ifdef TF_WORKAROUND +uniform int targetWidth; +uniform int targetHeight; +uniform int idOffset; +#endif + +void main(void) +{ + float interp_time; + vec4 data0, data1, data2, data3; + hair_get_interp_attrs(data0, data1, data2, data3, interp_time); + + vec4 weights = get_weights_cardinal(interp_time); + finalColor = interp_data(data0, data1, data2, data3, weights); + +#ifdef TF_WORKAROUND + int id = gl_VertexID - idOffset; + gl_Position.x = ((float(id % targetWidth) + 0.5) / float(targetWidth)) * 2.0 - 1.0; + gl_Position.y = ((float(id / targetWidth) + 0.5) / float(targetHeight)) * 2.0 - 1.0; + gl_Position.z = 0.0; + gl_Position.w = 1.0; + + gl_PointSize = 1.0; +#endif +} diff --git a/source/blender/draw/intern/shaders/common_smaa_lib.glsl b/source/blender/draw/intern/shaders/common_smaa_lib.glsl new file mode 100644 index 00000000000..09b573d4bb5 --- /dev/null +++ b/source/blender/draw/intern/shaders/common_smaa_lib.glsl @@ -0,0 +1,1436 @@ +/** + * Copyright (C) 2013 Jorge Jimenez (jorge@iryoku.com) + * Copyright (C) 2013 Jose I. Echevarria (joseignacioechevarria@gmail.com) + * Copyright (C) 2013 Belen Masia (bmasia@unizar.es) + * Copyright (C) 2013 Fernando Navarro (fernandn@microsoft.com) + * Copyright (C) 2013 Diego Gutierrez (diegog@unizar.es) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * 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. As clarification, there + * is no requirement that the copyright notice and permission be included in + * binary distributions 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. + */ + +/** + * _______ ___ ___ ___ ___ + * / || \/ | / \ / \ + * | (---- | \ / | / ^ \ / ^ \ + * \ \ | |\/| | / /_\ \ / /_\ \ + * ----) | | | | | / _____ \ / _____ \ + * |_______/ |__| |__| /__/ \__\ /__/ \__\ + * + * E N H A N C E D + * S U B P I X E L M O R P H O L O G I C A L A N T I A L I A S I N G + * + * http://www.iryoku.com/smaa/ + * + * Hi, welcome aboard! + * + * Here you'll find instructions to get the shader up and running as fast as + * possible. + * + * IMPORTANTE NOTICE: when updating, remember to update both this file and the + * precomputed textures! They may change from version to version. + * + * The shader has three passes, chained together as follows: + * + * |input|------------------� + * v | + * [ SMAA*EdgeDetection ] | + * v | + * |edgesTex| | + * v | + * [ SMAABlendingWeightCalculation ] | + * v | + * |blendTex| | + * v | + * [ SMAANeighborhoodBlending ] <------� + * v + * |output| + * + * Note that each [pass] has its own vertex and pixel shader. Remember to use + * oversized triangles instead of quads to avoid overshading along the + * diagonal. + * + * You've three edge detection methods to choose from: luma, color or depth. + * They represent different quality/performance and anti-aliasing/sharpness + * tradeoffs, so our recommendation is for you to choose the one that best + * suits your particular scenario: + * + * - Depth edge detection is usually the fastest but it may miss some edges. + * + * - Luma edge detection is usually more expensive than depth edge detection, + * but catches visible edges that depth edge detection can miss. + * + * - Color edge detection is usually the most expensive one but catches + * chroma-only edges. + * + * For quickstarters: just use luma edge detection. + * + * The general advice is to not rush the integration process and ensure each + * step is done correctly (don't try to integrate SMAA T2x with predicated edge + * detection from the start!). Ok then, let's go! + * + * 1. The first step is to create two RGBA temporal render targets for holding + * |edgesTex| and |blendTex|. + * + * In DX10 or DX11, you can use a RG render target for the edges texture. + * In the case of NVIDIA GPUs, using RG render targets seems to actually be + * slower. + * + * On the Xbox 360, you can use the same render target for resolving both + * |edgesTex| and |blendTex|, as they aren't needed simultaneously. + * + * 2. Both temporal render targets |edgesTex| and |blendTex| must be cleared + * each frame. Do not forget to clear the alpha channel! + * + * 3. The next step is loading the two supporting precalculated textures, + * 'areaTex' and 'searchTex'. You'll find them in the 'Textures' folder as + * C++ headers, and also as regular DDS files. They'll be needed for the + * 'SMAABlendingWeightCalculation' pass. + * + * If you use the C++ headers, be sure to load them in the format specified + * inside of them. + * + * You can also compress 'areaTex' and 'searchTex' using BC5 and BC4 + * respectively, if you have that option in your content processor pipeline. + * When compressing then, you get a non-perceptible quality decrease, and a + * marginal performance increase. + * + * 4. All samplers must be set to linear filtering and clamp. + * + * After you get the technique working, remember that 64-bit inputs have + * half-rate linear filtering on GCN. + * + * If SMAA is applied to 64-bit color buffers, switching to point filtering + * when accesing them will increase the performance. Search for + * 'SMAASamplePoint' to see which textures may benefit from point + * filtering, and where (which is basically the color input in the edge + * detection and resolve passes). + * + * 5. All texture reads and buffer writes must be non-sRGB, with the exception + * of the input read and the output write in + * 'SMAANeighborhoodBlending' (and only in this pass!). If sRGB reads in + * this last pass are not possible, the technique will work anyway, but + * will perform antialiasing in gamma space. + * + * IMPORTANT: for best results the input read for the color/luma edge + * detection should *NOT* be sRGB. + * + * 6. Before including SMAA.h you'll have to setup the render target metrics, + * the target and any optional configuration defines. Optionally you can + * use a preset. + * + * You have the following targets available: + * SMAA_HLSL_3 + * SMAA_HLSL_4 + * SMAA_HLSL_4_1 + * SMAA_GLSL_3 * + * SMAA_GLSL_4 * + * + * * (See SMAA_INCLUDE_VS and SMAA_INCLUDE_PS below). + * + * And four presets: + * SMAA_PRESET_LOW (%60 of the quality) + * SMAA_PRESET_MEDIUM (%80 of the quality) + * SMAA_PRESET_HIGH (%95 of the quality) + * SMAA_PRESET_ULTRA (%99 of the quality) + * + * For example: + * #define SMAA_RT_METRICS float4(1.0 / 1280.0, 1.0 / 720.0, 1280.0, 720.0) + * #define SMAA_HLSL_4 + * #define SMAA_PRESET_HIGH + * #include "SMAA.h" + * + * Note that SMAA_RT_METRICS doesn't need to be a macro, it can be a + * uniform variable. The code is designed to minimize the impact of not + * using a constant value, but it is still better to hardcode it. + * + * Depending on how you encoded 'areaTex' and 'searchTex', you may have to + * add (and customize) the following defines before including SMAA.h: + * #define SMAA_AREATEX_SELECT(sample) sample.rg + * #define SMAA_SEARCHTEX_SELECT(sample) sample.r + * + * If your engine is already using porting macros, you can define + * SMAA_CUSTOM_SL, and define the porting functions by yourself. + * + * 7. Then, you'll have to setup the passes as indicated in the scheme above. + * You can take a look into SMAA.fx, to see how we did it for our demo. + * Checkout the function wrappers, you may want to copy-paste them! + * + * 8. It's recommended to validate the produced |edgesTex| and |blendTex|. + * You can use a screenshot from your engine to compare the |edgesTex| + * and |blendTex| produced inside of the engine with the results obtained + * with the reference demo. + * + * 9. After you get the last pass to work, it's time to optimize. You'll have + * to initialize a stencil buffer in the first pass (discard is already in + * the code), then mask execution by using it the second pass. The last + * pass should be executed in all pixels. + * + * + * After this point you can choose to enable predicated thresholding, + * temporal supersampling and motion blur integration: + * + * a) If you want to use predicated thresholding, take a look into + * SMAA_PREDICATION; you'll need to pass an extra texture in the edge + * detection pass. + * + * b) If you want to enable temporal supersampling (SMAA T2x): + * + * 1. The first step is to render using subpixel jitters. I won't go into + * detail, but it's as simple as moving each vertex position in the + * vertex shader, you can check how we do it in our DX10 demo. + * + * 2. Then, you must setup the temporal resolve. You may want to take a look + * into SMAAResolve for resolving 2x modes. After you get it working, you'll + * probably see ghosting everywhere. But fear not, you can enable the + * CryENGINE temporal reprojection by setting the SMAA_REPROJECTION macro. + * Check out SMAA_DECODE_VELOCITY if your velocity buffer is encoded. + * + * 3. The next step is to apply SMAA to each subpixel jittered frame, just as + * done for 1x. + * + * 4. At this point you should already have something usable, but for best + * results the proper area textures must be set depending on current jitter. + * For this, the parameter 'subsampleIndices' of + * 'SMAABlendingWeightCalculationPS' must be set as follows, for our T2x + * mode: + * + * @SUBSAMPLE_INDICES + * + * | S# | Camera Jitter | subsampleIndices | + * +----+------------------+---------------------+ + * | 0 | ( 0.25, -0.25) | float4(1, 1, 1, 0) | + * | 1 | (-0.25, 0.25) | float4(2, 2, 2, 0) | + * + * These jitter positions assume a bottom-to-top y axis. S# stands for the + * sample number. + * + * More information about temporal supersampling here: + * http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf + * + * c) If you want to enable spatial multisampling (SMAA S2x): + * + * 1. The scene must be rendered using MSAA 2x. The MSAA 2x buffer must be + * created with: + * - DX10: see below (*) + * - DX10.1: D3D10_STANDARD_MULTISAMPLE_PATTERN or + * - DX11: D3D11_STANDARD_MULTISAMPLE_PATTERN + * + * This allows to ensure that the subsample order matches the table in + * @SUBSAMPLE_INDICES. + * + * (*) In the case of DX10, we refer the reader to: + * - SMAA::detectMSAAOrder and + * - SMAA::msaaReorder + * + * These functions allow to match the standard multisample patterns by + * detecting the subsample order for a specific GPU, and reordering + * them appropriately. + * + * 2. A shader must be run to output each subsample into a separate buffer + * (DX10 is required). You can use SMAASeparate for this purpose, or just do + * it in an existing pass (for example, in the tone mapping pass, which has + * the advantage of feeding tone mapped subsamples to SMAA, which will yield + * better results). + * + * 3. The full SMAA 1x pipeline must be run for each separated buffer, storing + * the results in the final buffer. The second run should alpha blend with + * the existing final buffer using a blending factor of 0.5. + * 'subsampleIndices' must be adjusted as in the SMAA T2x case (see point + * b). + * + * d) If you want to enable temporal supersampling on top of SMAA S2x + * (which actually is SMAA 4x): + * + * 1. SMAA 4x consists on temporally jittering SMAA S2x, so the first step is + * to calculate SMAA S2x for current frame. In this case, 'subsampleIndices' + * must be set as follows: + * + * | F# | S# | Camera Jitter | Net Jitter | subsampleIndices | + * +----+----+--------------------+-------------------+----------------------+ + * | 0 | 0 | ( 0.125, 0.125) | ( 0.375, -0.125) | float4(5, 3, 1, 3) | + * | 0 | 1 | ( 0.125, 0.125) | (-0.125, 0.375) | float4(4, 6, 2, 3) | + * +----+----+--------------------+-------------------+----------------------+ + * | 1 | 2 | (-0.125, -0.125) | ( 0.125, -0.375) | float4(3, 5, 1, 4) | + * | 1 | 3 | (-0.125, -0.125) | (-0.375, 0.125) | float4(6, 4, 2, 4) | + * + * These jitter positions assume a bottom-to-top y axis. F# stands for the + * frame number. S# stands for the sample number. + * + * 2. After calculating SMAA S2x for current frame (with the new subsample + * indices), previous frame must be reprojected as in SMAA T2x mode (see + * point b). + * + * e) If motion blur is used, you may want to do the edge detection pass + * together with motion blur. This has two advantages: + * + * 1. Pixels under heavy motion can be omitted from the edge detection process. + * For these pixels we can just store "no edge", as motion blur will take + * care of them. + * 2. The center pixel tap is reused. + * + * Note that in this case depth testing should be used instead of stenciling, + * as we have to write all the pixels in the motion blur pass. + * + * That's it! + */ + +//----------------------------------------------------------------------------- +// SMAA Presets + +/** + * Note that if you use one of these presets, the following configuration + * macros will be ignored if set in the "Configurable Defines" section. + */ + +#if defined(SMAA_PRESET_LOW) +# define SMAA_THRESHOLD 0.15 +# define SMAA_MAX_SEARCH_STEPS 4 +# define SMAA_DISABLE_DIAG_DETECTION +# define SMAA_DISABLE_CORNER_DETECTION +#elif defined(SMAA_PRESET_MEDIUM) +# define SMAA_THRESHOLD 0.1 +# define SMAA_MAX_SEARCH_STEPS 8 +# define SMAA_DISABLE_DIAG_DETECTION +# define SMAA_DISABLE_CORNER_DETECTION +#elif defined(SMAA_PRESET_HIGH) +# define SMAA_THRESHOLD 0.1 +# define SMAA_MAX_SEARCH_STEPS 16 +# define SMAA_MAX_SEARCH_STEPS_DIAG 8 +# define SMAA_CORNER_ROUNDING 25 +#elif defined(SMAA_PRESET_ULTRA) +# define SMAA_THRESHOLD 0.05 +# define SMAA_MAX_SEARCH_STEPS 32 +# define SMAA_MAX_SEARCH_STEPS_DIAG 16 +# define SMAA_CORNER_ROUNDING 25 +#endif + +//----------------------------------------------------------------------------- +// Configurable Defines + +/** + * SMAA_THRESHOLD specifies the threshold or sensitivity to edges. + * Lowering this value you will be able to detect more edges at the expense of + * performance. + * + * Range: [0, 0.5] + * 0.1 is a reasonable value, and allows to catch most visible edges. + * 0.05 is a rather overkill value, that allows to catch 'em all. + * + * If temporal supersampling is used, 0.2 could be a reasonable value, as low + * contrast edges are properly filtered by just 2x. + */ +#ifndef SMAA_THRESHOLD +# define SMAA_THRESHOLD 0.1 +#endif + +/** + * SMAA_DEPTH_THRESHOLD specifies the threshold for depth edge detection. + * + * Range: depends on the depth range of the scene. + */ +#ifndef SMAA_DEPTH_THRESHOLD +# define SMAA_DEPTH_THRESHOLD (0.1 * SMAA_THRESHOLD) +#endif + +/** + * SMAA_MAX_SEARCH_STEPS specifies the maximum steps performed in the + * horizontal/vertical pattern searches, at each side of the pixel. + * + * In number of pixels, it's actually the double. So the maximum line length + * perfectly handled by, for example 16, is 64 (by perfectly, we meant that + * longer lines won't look as good, but still antialiased). + * + * Range: [0, 112] + */ +#ifndef SMAA_MAX_SEARCH_STEPS +# define SMAA_MAX_SEARCH_STEPS 16 +#endif + +/** + * SMAA_MAX_SEARCH_STEPS_DIAG specifies the maximum steps performed in the + * diagonal pattern searches, at each side of the pixel. In this case we jump + * one pixel at time, instead of two. + * + * Range: [0, 20] + * + * On high-end machines it is cheap (between a 0.8x and 0.9x slower for 16 + * steps), but it can have a significant impact on older machines. + * + * Define SMAA_DISABLE_DIAG_DETECTION to disable diagonal processing. + */ +#ifndef SMAA_MAX_SEARCH_STEPS_DIAG +# define SMAA_MAX_SEARCH_STEPS_DIAG 8 +#endif + +/** + * SMAA_CORNER_ROUNDING specifies how much sharp corners will be rounded. + * + * Range: [0, 100] + * + * Define SMAA_DISABLE_CORNER_DETECTION to disable corner processing. + */ +#ifndef SMAA_CORNER_ROUNDING +# define SMAA_CORNER_ROUNDING 25 +#endif + +/** + * If there is an neighbor edge that has SMAA_LOCAL_CONTRAST_FACTOR times + * bigger contrast than current edge, current edge will be discarded. + * + * This allows to eliminate spurious crossing edges, and is based on the fact + * that, if there is too much contrast in a direction, that will hide + * perceptually contrast in the other neighbors. + */ +#ifndef SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR +# define SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR 2.0 +#endif + +/** + * Predicated thresholding allows to better preserve texture details and to + * improve performance, by decreasing the number of detected edges using an + * additional buffer like the light accumulation buffer, object ids or even the + * depth buffer (the depth buffer usage may be limited to indoor or short range + * scenes). + * + * It locally decreases the luma or color threshold if an edge is found in an + * additional buffer (so the global threshold can be higher). + * + * This method was developed by Playstation EDGE MLAA team, and used in + * Killzone 3, by using the light accumulation buffer. More information here: + * http://iryoku.com/aacourse/downloads/06-MLAA-on-PS3.pptx + */ +#ifndef SMAA_PREDICATION +# define SMAA_PREDICATION 0 +#endif + +/** + * Threshold to be used in the additional predication buffer. + * + * Range: depends on the input, so you'll have to find the magic number that + * works for you. + */ +#ifndef SMAA_PREDICATION_THRESHOLD +# define SMAA_PREDICATION_THRESHOLD 0.01 +#endif + +/** + * How much to scale the global threshold used for luma or color edge + * detection when using predication. + * + * Range: [1, 5] + */ +#ifndef SMAA_PREDICATION_SCALE +# define SMAA_PREDICATION_SCALE 2.0 +#endif + +/** + * How much to locally decrease the threshold. + * + * Range: [0, 1] + */ +#ifndef SMAA_PREDICATION_STRENGTH +# define SMAA_PREDICATION_STRENGTH 0.4 +#endif + +/** + * Temporal reprojection allows to remove ghosting artifacts when using + * temporal supersampling. We use the CryEngine 3 method which also introduces + * velocity weighting. This feature is of extreme importance for totally + * removing ghosting. More information here: + * http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf + * + * Note that you'll need to setup a velocity buffer for enabling reprojection. + * For static geometry, saving the previous depth buffer is a viable + * alternative. + */ +#ifndef SMAA_REPROJECTION +# define SMAA_REPROJECTION 0 +#endif + +/** + * SMAA_REPROJECTION_WEIGHT_SCALE controls the velocity weighting. It allows to + * remove ghosting trails behind the moving object, which are not removed by + * just using reprojection. Using low values will exhibit ghosting, while using + * high values will disable temporal supersampling under motion. + * + * Behind the scenes, velocity weighting removes temporal supersampling when + * the velocity of the subsamples differs (meaning they are different objects). + * + * Range: [0, 80] + */ +#ifndef SMAA_REPROJECTION_WEIGHT_SCALE +# define SMAA_REPROJECTION_WEIGHT_SCALE 30.0 +#endif + +/** + * On some compilers, discard cannot be used in vertex shaders. Thus, they need + * to be compiled separately. + */ +#ifndef SMAA_INCLUDE_VS +# define SMAA_INCLUDE_VS 1 +#endif +#ifndef SMAA_INCLUDE_PS +# define SMAA_INCLUDE_PS 1 +#endif + +//----------------------------------------------------------------------------- +// Texture Access Defines + +#ifndef SMAA_AREATEX_SELECT +# if defined(SMAA_HLSL_3) +# define SMAA_AREATEX_SELECT(sample) sample.ra +# else +# define SMAA_AREATEX_SELECT(sample) sample.rg +# endif +#endif + +#ifndef SMAA_SEARCHTEX_SELECT +# define SMAA_SEARCHTEX_SELECT(sample) sample.r +#endif + +#ifndef SMAA_DECODE_VELOCITY +# define SMAA_DECODE_VELOCITY(sample) sample.rg +#endif + +//----------------------------------------------------------------------------- +// Non-Configurable Defines + +#define SMAA_AREATEX_MAX_DISTANCE 16 +#define SMAA_AREATEX_MAX_DISTANCE_DIAG 20 +#define SMAA_AREATEX_PIXEL_SIZE (1.0 / float2(160.0, 560.0)) +#define SMAA_AREATEX_SUBTEX_SIZE (1.0 / 7.0) +#define SMAA_SEARCHTEX_SIZE float2(66.0, 33.0) +#define SMAA_SEARCHTEX_PACKED_SIZE float2(64.0, 16.0) +#define SMAA_CORNER_ROUNDING_NORM (float(SMAA_CORNER_ROUNDING) / 100.0) + +//----------------------------------------------------------------------------- +// Porting Functions + +#if defined(SMAA_HLSL_3) +# define SMAATexture2D(tex) sampler2D tex +# define SMAATexturePass2D(tex) tex +# define SMAASampleLevelZero(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0)) +# define SMAASampleLevelZeroPoint(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0)) +# define SMAASampleLevelZeroOffset(tex, coord, offset) \ + tex2Dlod(tex, float4(coord + offset * SMAA_RT_METRICS.xy, 0.0, 0.0)) +# define SMAASample(tex, coord) tex2D(tex, coord) +# define SMAASamplePoint(tex, coord) tex2D(tex, coord) +# define SMAASampleOffset(tex, coord, offset) tex2D(tex, coord + offset * SMAA_RT_METRICS.xy) +# define SMAA_FLATTEN [flatten] +# define SMAA_BRANCH [branch] +#endif +#if defined(SMAA_HLSL_4) || defined(SMAA_HLSL_4_1) +SamplerState LinearSampler +{ + Filter = MIN_MAG_LINEAR_MIP_POINT; + AddressU = Clamp; + AddressV = Clamp; +}; +SamplerState PointSampler +{ + Filter = MIN_MAG_MIP_POINT; + AddressU = Clamp; + AddressV = Clamp; +}; +# define SMAATexture2D(tex) Texture2D tex +# define SMAATexturePass2D(tex) tex +# define SMAASampleLevelZero(tex, coord) tex.SampleLevel(LinearSampler, coord, 0) +# define SMAASampleLevelZeroPoint(tex, coord) tex.SampleLevel(PointSampler, coord, 0) +# define SMAASampleLevelZeroOffset(tex, coord, offset) \ + tex.SampleLevel(LinearSampler, coord, 0, offset) +# define SMAASample(tex, coord) tex.Sample(LinearSampler, coord) +# define SMAASamplePoint(tex, coord) tex.Sample(PointSampler, coord) +# define SMAASampleOffset(tex, coord, offset) tex.Sample(LinearSampler, coord, offset) +# define SMAA_FLATTEN [flatten] +# define SMAA_BRANCH [branch] +# define SMAATexture2DMS2(tex) Texture2DMS<float4, 2> tex +# define SMAALoad(tex, pos, sample) tex.Load(pos, sample) +# if defined(SMAA_HLSL_4_1) +# define SMAAGather(tex, coord) tex.Gather(LinearSampler, coord, 0) +# endif +#endif +#if defined(SMAA_GLSL_3) || defined(SMAA_GLSL_4) +# define SMAATexture2D(tex) sampler2D tex +# define SMAATexturePass2D(tex) tex +# define SMAASampleLevelZero(tex, coord) textureLod(tex, coord, 0.0) +# define SMAASampleLevelZeroPoint(tex, coord) textureLod(tex, coord, 0.0) +# define SMAASampleLevelZeroOffset(tex, coord, offset) textureLodOffset(tex, coord, 0.0, offset) +# define SMAASample(tex, coord) texture(tex, coord) +# define SMAASamplePoint(tex, coord) texture(tex, coord) +# define SMAASampleOffset(tex, coord, offset) texture(tex, coord, offset) +# define SMAA_FLATTEN +# define SMAA_BRANCH +# define lerp(a, b, t) mix(a, b, t) +# define saturate(a) clamp(a, 0.0, 1.0) +# if defined(SMAA_GLSL_4) +# define mad(a, b, c) fma(a, b, c) +# define SMAAGather(tex, coord) textureGather(tex, coord) +# else +# define mad(a, b, c) (a * b + c) +# endif +# define float2 vec2 +# define float3 vec3 +# define float4 vec4 +# define int2 ivec2 +# define int3 ivec3 +# define int4 ivec4 +# define bool2 bvec2 +# define bool3 bvec3 +# define bool4 bvec4 +#endif + +#if !defined(SMAA_HLSL_3) && !defined(SMAA_HLSL_4) && !defined(SMAA_HLSL_4_1) && \ + !defined(SMAA_GLSL_3) && !defined(SMAA_GLSL_4) && !defined(SMAA_CUSTOM_SL) +# error you must define the shading language: SMAA_HLSL_*, SMAA_GLSL_* or SMAA_CUSTOM_SL +#endif + +//----------------------------------------------------------------------------- +// Misc functions + +/** + * Gathers current pixel, and the top-left neighbors. + */ +float3 SMAAGatherNeighbours(float2 texcoord, float4 offset[3], SMAATexture2D(tex)) +{ +#ifdef SMAAGather + return SMAAGather(tex, texcoord + SMAA_RT_METRICS.xy * float2(-0.5, -0.5)).grb; +#else + float P = SMAASamplePoint(tex, texcoord).r; + float Pleft = SMAASamplePoint(tex, offset[0].xy).r; + float Ptop = SMAASamplePoint(tex, offset[0].zw).r; + return float3(P, Pleft, Ptop); +#endif +} + +/** + * Adjusts the threshold by means of predication. + */ +float2 SMAACalculatePredicatedThreshold(float2 texcoord, + float4 offset[3], + SMAATexture2D(predicationTex)) +{ + float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(predicationTex)); + float2 delta = abs(neighbours.xx - neighbours.yz); + float2 edges = step(SMAA_PREDICATION_THRESHOLD, delta); + return SMAA_PREDICATION_SCALE * SMAA_THRESHOLD * (1.0 - SMAA_PREDICATION_STRENGTH * edges); +} + +/** + * Conditional move: + */ +void SMAAMovc(bool2 cond, inout float2 variable, float2 value) +{ + SMAA_FLATTEN if (cond.x) variable.x = value.x; + SMAA_FLATTEN if (cond.y) variable.y = value.y; +} + +void SMAAMovc(bool4 cond, inout float4 variable, float4 value) +{ + SMAAMovc(cond.xy, variable.xy, value.xy); + SMAAMovc(cond.zw, variable.zw, value.zw); +} + +#if SMAA_INCLUDE_VS +//----------------------------------------------------------------------------- +// Vertex Shaders + +/** + * Edge Detection Vertex Shader + */ +void SMAAEdgeDetectionVS(float2 texcoord, out float4 offset[3]) +{ + offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-1.0, 0.0, 0.0, -1.0), texcoord.xyxy); + offset[1] = mad(SMAA_RT_METRICS.xyxy, float4(1.0, 0.0, 0.0, 1.0), texcoord.xyxy); + offset[2] = mad(SMAA_RT_METRICS.xyxy, float4(-2.0, 0.0, 0.0, -2.0), texcoord.xyxy); +} + +/** + * Blend Weight Calculation Vertex Shader + */ +void SMAABlendingWeightCalculationVS(float2 texcoord, out float2 pixcoord, out float4 offset[3]) +{ + pixcoord = texcoord * SMAA_RT_METRICS.zw; + + // We will use these offsets for the searches later on (see @PSEUDO_GATHER4): + offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-0.25, -0.125, 1.25, -0.125), texcoord.xyxy); + offset[1] = mad(SMAA_RT_METRICS.xyxy, float4(-0.125, -0.25, -0.125, 1.25), texcoord.xyxy); + + // And these for the searches, they indicate the ends of the loops: + offset[2] = mad(SMAA_RT_METRICS.xxyy, + float4(-2.0, 2.0, -2.0, 2.0) * float(SMAA_MAX_SEARCH_STEPS), + float4(offset[0].xz, offset[1].yw)); +} + +/** + * Neighborhood Blending Vertex Shader + */ +void SMAANeighborhoodBlendingVS(float2 texcoord, out float4 offset) +{ + offset = mad(SMAA_RT_METRICS.xyxy, float4(1.0, 0.0, 0.0, 1.0), texcoord.xyxy); +} +#endif // SMAA_INCLUDE_VS + +#if SMAA_INCLUDE_PS +//----------------------------------------------------------------------------- +// Edge Detection Pixel Shaders (First Pass) + +/** + * Luma Edge Detection + * + * IMPORTANT NOTICE: luma edge detection requires gamma-corrected colors, and + * thus 'colorTex' should be a non-sRGB texture. + */ +float2 SMAALumaEdgeDetectionPS(float2 texcoord, + float4 offset[3], + SMAATexture2D(colorTex) +# if SMAA_PREDICATION + , + SMAATexture2D(predicationTex) +# endif +) +{ +// Calculate the threshold: +# if SMAA_PREDICATION + float2 threshold = SMAACalculatePredicatedThreshold( + texcoord, offset, SMAATexturePass2D(predicationTex)); +# else + float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD); +# endif + + // Calculate lumas: + float4 weights = float4(0.2126 * 0.5, 0.7152 * 0.5, 0.0722 * 0.5, 0.5); + float L = dot(SMAASamplePoint(colorTex, texcoord).rgba, weights); + + float Lleft = dot(SMAASamplePoint(colorTex, offset[0].xy).rgba, weights); + float Ltop = dot(SMAASamplePoint(colorTex, offset[0].zw).rgba, weights); + + // We do the usual threshold: + float4 delta; + delta.xy = abs(L - float2(Lleft, Ltop)); + float2 edges = step(threshold, delta.xy); + + // Then discard if there is no edge: + if (dot(edges, float2(1.0, 1.0)) == 0.0) + discard; + + // Calculate right and bottom deltas: + float Lright = dot(SMAASamplePoint(colorTex, offset[1].xy).rgba, weights); + float Lbottom = dot(SMAASamplePoint(colorTex, offset[1].zw).rgba, weights); + delta.zw = abs(L - float2(Lright, Lbottom)); + + // Calculate the maximum delta in the direct neighborhood: + float2 maxDelta = max(delta.xy, delta.zw); + + // Calculate left-left and top-top deltas: + float Lleftleft = dot(SMAASamplePoint(colorTex, offset[2].xy).rgba, weights); + float Ltoptop = dot(SMAASamplePoint(colorTex, offset[2].zw).rgba, weights); + delta.zw = abs(float2(Lleft, Ltop) - float2(Lleftleft, Ltoptop)); + + // Calculate the final maximum delta: + maxDelta = max(maxDelta.xy, delta.zw); + float finalDelta = max(maxDelta.x, maxDelta.y); + + // Local contrast adaptation: +# if !defined(SHADER_API_OPENGL) + edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy); +# endif + + return edges; +} + +/** + * Color Edge Detection + * + * IMPORTANT NOTICE: color edge detection requires gamma-corrected colors, and + * thus 'colorTex' should be a non-sRGB texture. + */ +float2 SMAAColorEdgeDetectionPS(float2 texcoord, + float4 offset[3], + SMAATexture2D(colorTex) +# if SMAA_PREDICATION + , + SMAATexture2D(predicationTex) +# endif +) +{ +// Calculate the threshold: +# if SMAA_PREDICATION + float2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, predicationTex); +# else + float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD); +# endif + + // Calculate color deltas: + float4 delta; + float3 C = SMAASamplePoint(colorTex, texcoord).rgb; + + float3 Cleft = SMAASamplePoint(colorTex, offset[0].xy).rgb; + float3 t = abs(C - Cleft); + delta.x = max(max(t.r, t.g), t.b); + + float3 Ctop = SMAASamplePoint(colorTex, offset[0].zw).rgb; + t = abs(C - Ctop); + delta.y = max(max(t.r, t.g), t.b); + + // We do the usual threshold: + float2 edges = step(threshold, delta.xy); + + // Then discard if there is no edge: + if (dot(edges, float2(1.0, 1.0)) == 0.0) + discard; + + // Calculate right and bottom deltas: + float3 Cright = SMAASamplePoint(colorTex, offset[1].xy).rgb; + t = abs(C - Cright); + delta.z = max(max(t.r, t.g), t.b); + + float3 Cbottom = SMAASamplePoint(colorTex, offset[1].zw).rgb; + t = abs(C - Cbottom); + delta.w = max(max(t.r, t.g), t.b); + + // Calculate the maximum delta in the direct neighborhood: + float2 maxDelta = max(delta.xy, delta.zw); + + // Calculate left-left and top-top deltas: + float3 Cleftleft = SMAASamplePoint(colorTex, offset[2].xy).rgb; + t = abs(C - Cleftleft); + delta.z = max(max(t.r, t.g), t.b); + + float3 Ctoptop = SMAASamplePoint(colorTex, offset[2].zw).rgb; + t = abs(C - Ctoptop); + delta.w = max(max(t.r, t.g), t.b); + + // Calculate the final maximum delta: + maxDelta = max(maxDelta.xy, delta.zw); + float finalDelta = max(maxDelta.x, maxDelta.y); + + // Local contrast adaptation: +# if !defined(SHADER_API_OPENGL) + edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy); +# endif + + return edges; +} + +/** + * Depth Edge Detection + */ +float2 SMAADepthEdgeDetectionPS(float2 texcoord, float4 offset[3], SMAATexture2D(depthTex)) +{ + float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(depthTex)); + float2 delta = abs(neighbours.xx - float2(neighbours.y, neighbours.z)); + float2 edges = step(SMAA_DEPTH_THRESHOLD, delta); + + if (dot(edges, float2(1.0, 1.0)) == 0.0) + discard; + + return edges; +} + +//----------------------------------------------------------------------------- +// Diagonal Search Functions + +# if !defined(SMAA_DISABLE_DIAG_DETECTION) + +/** + * Allows to decode two binary values from a bilinear-filtered access. + */ +float2 SMAADecodeDiagBilinearAccess(float2 e) +{ + // Bilinear access for fetching 'e' have a 0.25 offset, and we are + // interested in the R and G edges: + // + // +---G---+-------+ + // | x o R x | + // +-------+-------+ + // + // Then, if one of these edge is enabled: + // Red: (0.75 * X + 0.25 * 1) => 0.25 or 1.0 + // Green: (0.75 * 1 + 0.25 * X) => 0.75 or 1.0 + // + // This function will unpack the values (mad + mul + round): + // wolframalpha.com: round(x * abs(5 * x - 5 * 0.75)) plot 0 to 1 + e.r = e.r * abs(5.0 * e.r - 5.0 * 0.75); + return round(e); +} + +float4 SMAADecodeDiagBilinearAccess(float4 e) +{ + e.rb = e.rb * abs(5.0 * e.rb - 5.0 * 0.75); + return round(e); +} + +/** + * These functions allows to perform diagonal pattern searches. + */ +float2 SMAASearchDiag1(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e) +{ + float4 coord = float4(texcoord, -1.0, 1.0); + float3 t = float3(SMAA_RT_METRICS.xy, 1.0); + while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) && coord.w > 0.9) { + coord.xyz = mad(t, float3(dir, 1.0), coord.xyz); + e = SMAASampleLevelZero(edgesTex, coord.xy).rg; + coord.w = dot(e, float2(0.5, 0.5)); + } + return coord.zw; +} + +float2 SMAASearchDiag2(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e) +{ + float4 coord = float4(texcoord, -1.0, 1.0); + coord.x += 0.25 * SMAA_RT_METRICS.x; // See @SearchDiag2Optimization + float3 t = float3(SMAA_RT_METRICS.xy, 1.0); + while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) && coord.w > 0.9) { + coord.xyz = mad(t, float3(dir, 1.0), coord.xyz); + + // @SearchDiag2Optimization + // Fetch both edges at once using bilinear filtering: + e = SMAASampleLevelZero(edgesTex, coord.xy).rg; + e = SMAADecodeDiagBilinearAccess(e); + + // Non-optimized version: + // e.g = SMAASampleLevelZero(edgesTex, coord.xy).g; + // e.r = SMAASampleLevelZeroOffset(edgesTex, coord.xy, int2(1, 0)).r; + + coord.w = dot(e, float2(0.5, 0.5)); + } + return coord.zw; +} + +/** + * Similar to SMAAArea, this calculates the area corresponding to a certain + * diagonal distance and crossing edges 'e'. + */ +float2 SMAAAreaDiag(SMAATexture2D(areaTex), float2 dist, float2 e, float offset) +{ + float2 texcoord = mad( + float2(SMAA_AREATEX_MAX_DISTANCE_DIAG, SMAA_AREATEX_MAX_DISTANCE_DIAG), e, dist); + + // We do a scale and bias for mapping to texel space: + texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE); + + // Diagonal areas are on the second half of the texture: + texcoord.x += 0.5; + + // Move to proper place, according to the subpixel offset: + texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset; + + // Do it! + return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord)); +} + +/** + * This searches for diagonal patterns and returns the corresponding weights. + */ +float2 SMAACalculateDiagWeights(SMAATexture2D(edgesTex), + SMAATexture2D(areaTex), + float2 texcoord, + float2 e, + float4 subsampleIndices) +{ + float2 weights = float2(0.0, 0.0); + + // Search for the line ends: + float4 d; + float2 end; + if (e.r > 0.0) { + d.xz = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, 1.0), end); + d.x += float(end.y > 0.9); + } + else + d.xz = float2(0.0, 0.0); + d.yw = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, -1.0), end); + + SMAA_BRANCH + if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3 + // Fetch the crossing edges: + float4 coords = mad( + float4(-d.x + 0.25, d.x, d.y, -d.y - 0.25), SMAA_RT_METRICS.xyxy, texcoord.xyxy); + float4 c; + c.xy = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).rg; + c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2(1, 0)).rg; + c.yxwz = SMAADecodeDiagBilinearAccess(c.xyzw); + + // Non-optimized version: + // float4 coords = mad(float4(-d.x, d.x, d.y, -d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy); + // float4 c; + // c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).g; + // c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2( 0, 0)).r; + // c.z = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).g; + // c.w = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, -1)).r; + + // Merge crossing edges at each side into a single value: + float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw); + + // Remove the crossing edge if we didn't found the end of the line: + SMAAMovc(bool2(step(0.9, d.zw)), cc, float2(0.0, 0.0)); + + // Fetch the areas for this line: + weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.z); + } + + // Search for the line ends: + d.xz = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, -1.0), end); + if (SMAASampleLevelZeroOffset(edgesTex, texcoord, int2(1, 0)).r > 0.0) { + d.yw = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, 1.0), end); + d.y += float(end.y > 0.9); + } + else + d.yw = float2(0.0, 0.0); + + SMAA_BRANCH + if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3 + // Fetch the crossing edges: + float4 coords = mad(float4(-d.x, -d.x, d.y, d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy); + float4 c; + c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).g; + c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(0, -1)).r; + c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2(1, 0)).gr; + float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw); + + // Remove the crossing edge if we didn't found the end of the line: + SMAAMovc(bool2(step(0.9, d.zw)), cc, float2(0.0, 0.0)); + + // Fetch the areas for this line: + weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.w).gr; + } + + return weights; +} +# endif + +//----------------------------------------------------------------------------- +// Horizontal/Vertical Search Functions + +/** + * This allows to determine how much length should we add in the last step + * of the searches. It takes the bilinearly interpolated edge (see + * @PSEUDO_GATHER4), and adds 0, 1 or 2, depending on which edges and + * crossing edges are active. + */ +float SMAASearchLength(SMAATexture2D(searchTex), float2 e, float offset) +{ + // The texture is flipped vertically, with left and right cases taking half + // of the space horizontally: + float2 scale = SMAA_SEARCHTEX_SIZE * float2(0.5, -1.0); + float2 bias = SMAA_SEARCHTEX_SIZE * float2(offset, 1.0); + + // Scale and bias to access texel centers: + scale += float2(-1.0, 1.0); + bias += float2(0.5, -0.5); + + // Convert from pixel coordinates to texcoords: + // (We use SMAA_SEARCHTEX_PACKED_SIZE because the texture is cropped) + scale *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE; + bias *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE; + + // Lookup the search texture: + return SMAA_SEARCHTEX_SELECT(SMAASampleLevelZero(searchTex, mad(scale, e, bias))); +} + +/** + * Horizontal/vertical search functions for the 2nd pass. + */ +float SMAASearchXLeft(SMAATexture2D(edgesTex), + SMAATexture2D(searchTex), + float2 texcoord, + float end) +{ + /** + * @PSEUDO_GATHER4 + * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to + * sample between edge, thus fetching four edges in a row. + * Sampling with different offsets in each direction allows to disambiguate + * which edges are active from the four fetched ones. + */ + float2 e = float2(0.0, 1.0); + while (texcoord.x > end && e.g > 0.8281 && // Is there some edge not activated? + e.r == 0.0) { // Or is there a crossing edge that breaks the line? + e = SMAASampleLevelZero(edgesTex, texcoord).rg; + texcoord = mad(-float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord); + } + + float offset = mad( + -(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0), 3.25); + return mad(SMAA_RT_METRICS.x, offset, texcoord.x); + + // Non-optimized version: + // We correct the previous (-0.25, -0.125) offset we applied: + // texcoord.x += 0.25 * SMAA_RT_METRICS.x; + + // The searches are bias by 1, so adjust the coords accordingly: + // texcoord.x += SMAA_RT_METRICS.x; + + // Disambiguate the length added by the last step: + // texcoord.x += 2.0 * SMAA_RT_METRICS.x; // Undo last step + // texcoord.x -= SMAA_RT_METRICS.x * (255.0 / 127.0) * + // SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0); return mad(SMAA_RT_METRICS.x, offset, + // texcoord.x); +} + +float SMAASearchXRight(SMAATexture2D(edgesTex), + SMAATexture2D(searchTex), + float2 texcoord, + float end) +{ + float2 e = float2(0.0, 1.0); + while (texcoord.x < end && e.g > 0.8281 && // Is there some edge not activated? + e.r == 0.0) { // Or is there a crossing edge that breaks the line? + e = SMAASampleLevelZero(edgesTex, texcoord).rg; + texcoord = mad(float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord); + } + float offset = mad( + -(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.5), 3.25); + return mad(-SMAA_RT_METRICS.x, offset, texcoord.x); +} + +float SMAASearchYUp(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) +{ + float2 e = float2(1.0, 0.0); + while (texcoord.y > end && e.r > 0.8281 && // Is there some edge not activated? + e.g == 0.0) { // Or is there a crossing edge that breaks the line? + e = SMAASampleLevelZero(edgesTex, texcoord).rg; + texcoord = mad(-float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord); + } + float offset = mad( + -(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.0), 3.25); + return mad(SMAA_RT_METRICS.y, offset, texcoord.y); +} + +float SMAASearchYDown(SMAATexture2D(edgesTex), + SMAATexture2D(searchTex), + float2 texcoord, + float end) +{ + float2 e = float2(1.0, 0.0); + while (texcoord.y < end && e.r > 0.8281 && // Is there some edge not activated? + e.g == 0.0) { // Or is there a crossing edge that breaks the line? + e = SMAASampleLevelZero(edgesTex, texcoord).rg; + texcoord = mad(float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord); + } + float offset = mad( + -(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.5), 3.25); + return mad(-SMAA_RT_METRICS.y, offset, texcoord.y); +} + +/** + * Ok, we have the distance and both crossing edges. So, what are the areas + * at each side of current edge? + */ +float2 SMAAArea(SMAATexture2D(areaTex), float2 dist, float e1, float e2, float offset) +{ + // Rounding prevents precision errors of bilinear filtering: + float2 texcoord = mad(float2(SMAA_AREATEX_MAX_DISTANCE, SMAA_AREATEX_MAX_DISTANCE), + round(4.0 * float2(e1, e2)), + dist); + + // We do a scale and bias for mapping to texel space: + texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE); + + // Move to proper place, according to the subpixel offset: + texcoord.y = mad(SMAA_AREATEX_SUBTEX_SIZE, offset, texcoord.y); + + // Do it! + return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord)); +} + +//----------------------------------------------------------------------------- +// Corner Detection Functions + +void SMAADetectHorizontalCornerPattern(SMAATexture2D(edgesTex), + inout float2 weights, + float4 texcoord, + float2 d) +{ +# if !defined(SMAA_DISABLE_CORNER_DETECTION) + float2 leftRight = step(d.xy, d.yx); + float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight; + + rounding /= leftRight.x + leftRight.y; // Reduce blending for pixels in the center of a line. + + float2 factor = float2(1.0, 1.0); + factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, 1)).r; + factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, 1)).r; + factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, -2)).r; + factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, -2)).r; + + weights *= saturate(factor); +# endif +} + +void SMAADetectVerticalCornerPattern(SMAATexture2D(edgesTex), + inout float2 weights, + float4 texcoord, + float2 d) +{ +# if !defined(SMAA_DISABLE_CORNER_DETECTION) + float2 leftRight = step(d.xy, d.yx); + float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight; + + rounding /= leftRight.x + leftRight.y; + + float2 factor = float2(1.0, 1.0); + factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(1, 0)).g; + factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, 1)).g; + factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(-2, 0)).g; + factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(-2, 1)).g; + + weights *= saturate(factor); +# endif +} + +//----------------------------------------------------------------------------- +// Blending Weight Calculation Pixel Shader (Second Pass) + +float4 SMAABlendingWeightCalculationPS(float2 texcoord, + float2 pixcoord, + float4 offset[3], + SMAATexture2D(edgesTex), + SMAATexture2D(areaTex), + SMAATexture2D(searchTex), + float4 subsampleIndices) +{ // Just pass zero for SMAA 1x, see @SUBSAMPLE_INDICES. + float4 weights = float4(0.0, 0.0, 0.0, 0.0); + + float2 e = SMAASample(edgesTex, texcoord).rg; + + SMAA_BRANCH + if (e.g > 0.0) { // Edge at north +# if !defined(SMAA_DISABLE_DIAG_DETECTION) + // Diagonals have both north and west edges, so searching for them in + // one of the boundaries is enough. + weights.rg = SMAACalculateDiagWeights( + SMAATexturePass2D(edgesTex), SMAATexturePass2D(areaTex), texcoord, e, subsampleIndices); + + // We give priority to diagonals, so if we find a diagonal we skip + // horizontal/vertical processing. + SMAA_BRANCH + if (weights.r == -weights.g) { // weights.r + weights.g == 0.0 +# endif + + float2 d; + + // Find the distance to the left: + float3 coords; + coords.x = SMAASearchXLeft( + SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].xy, offset[2].x); + coords.y = + offset[1].y; // offset[1].y = texcoord.y - 0.25 * SMAA_RT_METRICS.y (@CROSSING_OFFSET) + d.x = coords.x; + + // Now fetch the left crossing edges, two at a time using bilinear + // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to + // discern what value each edge has: + float e1 = SMAASampleLevelZero(edgesTex, coords.xy).r; + + // Find the distance to the right: + coords.z = SMAASearchXRight( + SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].zw, offset[2].y); + d.y = coords.z; + + // We want the distances to be in pixel units (doing this here allow to + // better interleave arithmetic and memory accesses): + d = abs(round(mad(SMAA_RT_METRICS.zz, d, -pixcoord.xx))); + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + float2 sqrt_d = sqrt(d); + + // Fetch the right crossing edges: + float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.zy, int2(1, 0)).r; + + // Ok, we know how this pattern looks like, now it is time for getting + // the actual area: + weights.rg = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.y); + + // Fix corners: + coords.y = texcoord.y; + SMAADetectHorizontalCornerPattern(SMAATexturePass2D(edgesTex), weights.rg, coords.xyzy, d); + +# if !defined(SMAA_DISABLE_DIAG_DETECTION) + } + else + e.r = 0.0; // Skip vertical processing. +# endif + } + + SMAA_BRANCH + if (e.r > 0.0) { // Edge at west + float2 d; + + // Find the distance to the top: + float3 coords; + coords.y = SMAASearchYUp( + SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].xy, offset[2].z); + coords.x = offset[0].x; // offset[1].x = texcoord.x - 0.25 * SMAA_RT_METRICS.x; + d.x = coords.y; + + // Fetch the top crossing edges: + float e1 = SMAASampleLevelZero(edgesTex, coords.xy).g; + + // Find the distance to the bottom: + coords.z = SMAASearchYDown( + SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].zw, offset[2].w); + d.y = coords.z; + + // We want the distances to be in pixel units: + d = abs(round(mad(SMAA_RT_METRICS.ww, d, -pixcoord.yy))); + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + float2 sqrt_d = sqrt(d); + + // Fetch the bottom crossing edges: + float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.xz, int2(0, 1)).g; + + // Get the area for this direction: + weights.ba = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.x); + + // Fix corners: + coords.x = texcoord.x; + SMAADetectVerticalCornerPattern(SMAATexturePass2D(edgesTex), weights.ba, coords.xyxz, d); + } + + return weights; +} + +//----------------------------------------------------------------------------- +// Neighborhood Blending Pixel Shader (Third Pass) + +float4 SMAANeighborhoodBlendingPS(float2 texcoord, + float4 offset, + SMAATexture2D(colorTex), + SMAATexture2D(blendTex) +# if SMAA_REPROJECTION + , + SMAATexture2D(velocityTex) +# endif +) +{ + // Fetch the blending weights for current pixel: + float4 a; + a.x = SMAASample(blendTex, offset.xy).a; // Right + a.y = SMAASample(blendTex, offset.zw).g; // Top + a.wz = SMAASample(blendTex, texcoord).xz; // Bottom / Left + + // Is there any blending weight with a value greater than 0.0? + SMAA_BRANCH + if (dot(a, float4(1.0, 1.0, 1.0, 1.0)) < 1e-5) { + float4 color = SMAASampleLevelZero(colorTex, texcoord); + +# if SMAA_REPROJECTION + float2 velocity = SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, texcoord)); + + // Pack velocity into the alpha channel: + color.a = sqrt(5.0 * length(velocity)); +# endif + + return color; + } + else { + bool h = max(a.x, a.z) > max(a.y, a.w); // max(horizontal) > max(vertical) + + // Calculate the blending offsets: + float4 blendingOffset = float4(0.0, a.y, 0.0, a.w); + float2 blendingWeight = a.yw; + SMAAMovc(bool4(h, h, h, h), blendingOffset, float4(a.x, 0.0, a.z, 0.0)); + SMAAMovc(bool2(h, h), blendingWeight, a.xz); + blendingWeight /= dot(blendingWeight, float2(1.0, 1.0)); + + // Calculate the texture coordinates: + float4 blendingCoord = mad( + blendingOffset, float4(SMAA_RT_METRICS.xy, -SMAA_RT_METRICS.xy), texcoord.xyxy); + + // We exploit bilinear filtering to mix current pixel with the chosen + // neighbor: + float4 color = blendingWeight.x * SMAASampleLevelZero(colorTex, blendingCoord.xy); + color += blendingWeight.y * SMAASampleLevelZero(colorTex, blendingCoord.zw); + +# if SMAA_REPROJECTION + // Antialias velocity for proper reprojection in a later stage: + float2 velocity = blendingWeight.x * + SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.xy)); + velocity += blendingWeight.y * + SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.zw)); + + // Pack velocity into the alpha channel: + color.a = sqrt(5.0 * length(velocity)); +# endif + + return color; + } +} + +//----------------------------------------------------------------------------- +// Temporal Resolve Pixel Shader (Optional Pass) + +float4 SMAAResolvePS(float2 texcoord, + SMAATexture2D(currentColorTex), + SMAATexture2D(previousColorTex) +# if SMAA_REPROJECTION + , + SMAATexture2D(velocityTex) +# endif +) +{ +# if SMAA_REPROJECTION + // Velocity is assumed to be calculated for motion blur, so we need to + // inverse it for reprojection: + float2 velocity = -SMAA_DECODE_VELOCITY(SMAASamplePoint(velocityTex, texcoord).rg); + + // Fetch current pixel: + float4 current = SMAASamplePoint(currentColorTex, texcoord); + + // Reproject current coordinates and fetch previous pixel: + float4 previous = SMAASamplePoint(previousColorTex, texcoord + velocity); + + // Attenuate the previous pixel if the velocity is different: + float delta = abs(current.a * current.a - previous.a * previous.a) / 5.0; + float weight = 0.5 * saturate(1.0 - sqrt(delta) * SMAA_REPROJECTION_WEIGHT_SCALE); + + // Blend the pixels according to the calculated weight: + return lerp(current, previous, weight); +# else + // Just blend the pixels: + float4 current = SMAASamplePoint(currentColorTex, texcoord); + float4 previous = SMAASamplePoint(previousColorTex, texcoord); + return lerp(current, previous, 0.5); +# endif +} + +//----------------------------------------------------------------------------- +// Separate Multisamples Pixel Shader (Optional Pass) + +# ifdef SMAALoad +void SMAASeparatePS(float4 position, + float2 texcoord, + out float4 target0, + out float4 target1, + SMAATexture2DMS2(colorTexMS)) +{ + int2 pos = int2(position.xy); + target0 = SMAALoad(colorTexMS, pos, 0); + target1 = SMAALoad(colorTexMS, pos, 1); +} +# endif + +//----------------------------------------------------------------------------- +#endif // SMAA_INCLUDE_PS diff --git a/source/blender/draw/intern/shaders/common_view_lib.glsl b/source/blender/draw/intern/shaders/common_view_lib.glsl new file mode 100644 index 00000000000..1a28a307163 --- /dev/null +++ b/source/blender/draw/intern/shaders/common_view_lib.glsl @@ -0,0 +1,187 @@ +#define COMMON_VIEW_LIB +#define DRW_RESOURCE_CHUNK_LEN 512 + +/* keep in sync with DRWManager.view_data */ +layout(std140) uniform viewBlock +{ + /* Same order as DRWViewportMatrixType */ + mat4 ViewProjectionMatrix; + mat4 ViewProjectionMatrixInverse; + mat4 ViewMatrix; + mat4 ViewMatrixInverse; + mat4 ProjectionMatrix; + mat4 ProjectionMatrixInverse; + + vec4 clipPlanes[6]; + + /* TODO move it elsewhere. */ + vec4 CameraTexCoFactors; +}; + +#ifdef world_clip_planes_calc_clip_distance +# undef world_clip_planes_calc_clip_distance +# define world_clip_planes_calc_clip_distance(p) \ + _world_clip_planes_calc_clip_distance(p, clipPlanes) +#endif + +#ifdef COMMON_GLOBALS_LIB +float mul_project_m4_v3_zfac(in vec3 co) +{ + return pixelFac * ((ViewProjectionMatrix[0][3] * co.x) + (ViewProjectionMatrix[1][3] * co.y) + + (ViewProjectionMatrix[2][3] * co.z) + ViewProjectionMatrix[3][3]); +} +#endif + +/* Not the right place but need to be common to all overlay's. + * TODO Split to an overlay lib. */ +mat4 extract_matrix_packed_data(mat4 mat, out vec4 dataA, out vec4 dataB) +{ + const float div = 1.0 / 255.0; + int a = int(mat[0][3]); + int b = int(mat[1][3]); + int c = int(mat[2][3]); + int d = int(mat[3][3]); + dataA = vec4(a & 0xFF, a >> 8, b & 0xFF, b >> 8) * div; + dataB = vec4(c & 0xFF, c >> 8, d & 0xFF, d >> 8) * div; + mat[0][3] = mat[1][3] = mat[2][3] = 0.0; + mat[3][3] = 1.0; + return mat; +} + +/* Same here, Not the right place but need to be common to all overlay's. + * TODO Split to an overlay lib. */ +/* edge_start and edge_pos needs to be in the range [0..sizeViewport]. */ +vec4 pack_line_data(vec2 frag_co, vec2 edge_start, vec2 edge_pos) +{ + vec2 edge = edge_start - edge_pos; + float len = length(edge); + if (len > 0.0) { + edge /= len; + vec2 perp = vec2(-edge.y, edge.x); + float dist = dot(perp, frag_co - edge_start); + /* Add 0.1 to diffenrentiate with cleared pixels. */ + return vec4(perp * 0.5 + 0.5, dist * 0.25 + 0.5 + 0.1, 0.0); + } + else { + /* Default line if the origin is perfectly aligned with a pixel. */ + return vec4(1.0, 0.0, 0.5 + 0.1, 0.0); + } +} + +uniform int resourceChunk; + +#ifdef GPU_VERTEX_SHADER +# ifdef GL_ARB_shader_draw_parameters +# define baseInstance gl_BaseInstanceARB +# else /* no ARB_shader_draw_parameters */ +uniform int baseInstance; +# endif + +# if defined(IN_PLACE_INSTANCES) || defined(INSTANCED_ATTRIB) +/* When drawing instances of an object at the same position. */ +# define instanceId 0 +# elif defined(GPU_DEPRECATED_AMD_DRIVER) +/* A driver bug make it so that when using an attribute with GL_INT_2_10_10_10_REV as format, + * the gl_InstanceID is incremented by the 2 bit component of the attrib. + * Ignore gl_InstanceID then. */ +# define instanceId 0 +# else +# define instanceId gl_InstanceID +# endif + +# define resource_id (baseInstance + instanceId) + +/* Use this to declare and pass the value if + * the fragment shader uses the resource_id. */ +# define RESOURCE_ID_VARYING flat out int resourceIDFrag; +# define RESOURCE_ID_VARYING_GEOM flat out int resourceIDGeom; +# define PASS_RESOURCE_ID resourceIDFrag = resource_id; +# define PASS_RESOURCE_ID_GEOM resourceIDGeom = resource_id; +#endif + +/* If used in a fragment / geometry shader, we pass + * resource_id as varying. */ +#ifdef GPU_GEOMETRY_SHADER +# define RESOURCE_ID_VARYING \ + flat out int resourceIDFrag; \ + flat in int resourceIDGeom[]; + +# define resource_id resourceIDGeom +# define PASS_RESOURCE_ID(i) resourceIDFrag = resource_id[i]; +#endif + +#ifdef GPU_FRAGMENT_SHADER +flat in int resourceIDFrag; +# define resource_id resourceIDFrag +#endif + +#if !defined(GPU_INTEL) && !defined(GPU_DEPRECATED_AMD_DRIVER) && !defined(OS_MAC) && \ + !defined(INSTANCED_ATTRIB) +struct ObjectMatrices { + mat4 drw_modelMatrix; + mat4 drw_modelMatrixInverse; +}; + +layout(std140) uniform modelBlock +{ + ObjectMatrices drw_matrices[DRW_RESOURCE_CHUNK_LEN]; +}; + +# define ModelMatrix (drw_matrices[resource_id].drw_modelMatrix) +# define ModelMatrixInverse (drw_matrices[resource_id].drw_modelMatrixInverse) + +#else /* GPU_INTEL */ +/* Intel GPU seems to suffer performance impact when the model matrix is in UBO storage. + * So for now we just force using the legacy path. */ +/* Note that this is also a workaround of a problem on osx (amd or nvidia) + * and older amd driver on windows. */ +uniform mat4 ModelMatrix; +uniform mat4 ModelMatrixInverse; +#endif + +#define resource_handle (resourceChunk * DRW_RESOURCE_CHUNK_LEN + resource_id) + +/** Transform shortcuts. */ +/* Rule of thumb: Try to reuse world positions and normals because converting though viewspace + * will always be decomposed in at least 2 matrix operation. */ + +/** + * Some clarification: + * Usually Normal matrix is transpose(inverse(ViewMatrix * ModelMatrix)) + * + * But since it is slow to multiply matrices we decompose it. Decomposing + * inversion and transposition both invert the product order leaving us with + * the same original order: + * transpose(ViewMatrixInverse) * transpose(ModelMatrixInverse) + * + * Knowing that the view matrix is orthogonal, the transpose is also the inverse. + * Note: This is only valid because we are only using the mat3 of the ViewMatrixInverse. + * ViewMatrix * transpose(ModelMatrixInverse) + **/ +#define normal_object_to_view(n) (mat3(ViewMatrix) * (transpose(mat3(ModelMatrixInverse)) * n)) +#define normal_object_to_world(n) (transpose(mat3(ModelMatrixInverse)) * n) +#define normal_world_to_object(n) (transpose(mat3(ModelMatrix)) * n) +#define normal_world_to_view(n) (mat3(ViewMatrix) * n) + +#define point_object_to_ndc(p) (ViewProjectionMatrix * vec4((ModelMatrix * vec4(p, 1.0)).xyz, 1.0)) +#define point_object_to_view(p) ((ViewMatrix * vec4((ModelMatrix * vec4(p, 1.0)).xyz, 1.0)).xyz) +#define point_object_to_world(p) ((ModelMatrix * vec4(p, 1.0)).xyz) +#define point_view_to_ndc(p) (ProjectionMatrix * vec4(p, 1.0)) +#define point_view_to_object(p) ((ModelMatrixInverse * (ViewMatrixInverse * vec4(p, 1.0))).xyz) +#define point_view_to_world(p) ((ViewMatrixInverse * vec4(p, 1.0)).xyz) +#define point_world_to_ndc(p) (ViewProjectionMatrix * vec4(p, 1.0)) +#define point_world_to_object(p) ((ModelMatrixInverse * vec4(p, 1.0)).xyz) +#define point_world_to_view(p) ((ViewMatrix * vec4(p, 1.0)).xyz) + +/* Due to some shader compiler bug, we somewhat need to access gl_VertexID + * to make vertex shaders work. even if it's actually dead code. */ +#ifdef GPU_INTEL +# define GPU_INTEL_VERTEX_SHADER_WORKAROUND gl_Position.x = float(gl_VertexID); +#else +# define GPU_INTEL_VERTEX_SHADER_WORKAROUND +#endif + +#define DRW_BASE_SELECTED (1 << 1) +#define DRW_BASE_FROM_DUPLI (1 << 2) +#define DRW_BASE_FROM_SET (1 << 3) +#define DRW_BASE_ACTIVE (1 << 4) |