From 7160882bd21be2a8b5724e4d17f4eca1804e314e Mon Sep 17 00:00:00 2001 From: Azaezel Date: Sat, 8 Dec 2018 01:41:06 -0600 Subject: [PATCH] gl conversion WIP. general notes: mSamplerNames[#]/samplerNames[#] entry explicitly corresponds to the order of definition GL side. shifted the colorbuffer slot over to S1 in keeping with the gbuffer layout for consistency completed converts: brdf, lighting, torque. nonvisually verified convert: vectorlight noncompiling due to tripping on deferredUncondition: reflectionprobe --- .../client/lighting/advanced/shaders.cs | 21 +- .../Full/game/shaders/common/gl/brdf.glsl | 98 ++++++ .../Full/game/shaders/common/gl/lighting.glsl | 332 ++++++++---------- .../Full/game/shaders/common/gl/torque.glsl | 2 + .../advanced/gl/reflectionProbeP.glsl | 150 ++------ .../lighting/advanced/gl/vectorLightP.glsl | 204 ++++------- .../lighting/advanced/reflectionProbeP.hlsl | 4 +- 7 files changed, 372 insertions(+), 439 deletions(-) create mode 100644 Templates/Full/game/shaders/common/gl/brdf.glsl diff --git a/Templates/Full/game/core/scripts/client/lighting/advanced/shaders.cs b/Templates/Full/game/core/scripts/client/lighting/advanced/shaders.cs index 72a1bdccd..54c0f5dbd 100644 --- a/Templates/Full/game/core/scripts/client/lighting/advanced/shaders.cs +++ b/Templates/Full/game/core/scripts/client/lighting/advanced/shaders.cs @@ -287,10 +287,11 @@ new ShaderData( ReflectionProbeShader ) OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/reflectionProbeP.glsl"; samplerNames[0] = "$deferredBuffer"; - samplerNames[1] = "$matInfoBuffer"; - samplerNames[2] = "$cubeMap"; - samplerNames[3] = "$irradianceCubemap"; - samplerNames[4] = "$BRDFTexture"; + samplerNames[1] = "$colorBuffer"; + samplerNames[2] = "$matInfoBuffer"; + samplerNames[3] = "$cubeMap"; + samplerNames[4] = "$irradianceCubemap"; + samplerNames[5] = "$BRDFTexture"; pixVersion = 3.0; }; @@ -318,12 +319,14 @@ new GFXStateBlockData( AL_ProbeState ) samplersDefined = true; samplerStates[0] = SamplerClampPoint; // G-buffer mSamplerNames[0] = "deferredBuffer"; - samplerStates[1] = SamplerClampLinear; // Shadow Map (Do not use linear, these are perspective projections) - mSamplerNames[1] = "matInfoBuffer"; + samplerStates[1] = SamplerClampLinear; + mSamplerNames[1] = "colorBuffer"; + samplerStates[2] = SamplerClampLinear; + mSamplerNames[2] = "matInfoBuffer"; - mSamplerNames[2] = "cubeMap"; - mSamplerNames[3] = "irradianceCubemap"; - mSamplerNames[4] = "BRDFTexture"; + mSamplerNames[3] = "cubeMap"; + mSamplerNames[4] = "irradianceCubemap"; + mSamplerNames[5] = "BRDFTexture"; cullDefined = true; cullMode = GFXCullCW; diff --git a/Templates/Full/game/shaders/common/gl/brdf.glsl b/Templates/Full/game/shaders/common/gl/brdf.glsl new file mode 100644 index 000000000..2b9709dab --- /dev/null +++ b/Templates/Full/game/shaders/common/gl/brdf.glsl @@ -0,0 +1,98 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2018 GarageGames, LLC +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. +//----------------------------------------------------------------------------- + +#ifndef BRDF_HLSL +#define BRDF_HLSL + +#include "./torque.glsl" + +// BRDF from Frostbite presentation: +// Moving Frostbite to Physically Based Rendering +// S“ebastien Lagarde - Electronic Arts Frostbite +// Charles de Rousiers - Electronic Arts Frostbite +// SIGGRAPH 2014 + +vec3 F_Schlick(in vec3 f0, in float f90, in float u) +{ + return f0 + (f90 - f0) * pow(1.f - u, 5.f); +} + +vec3 F_Fresnel(vec3 SpecularColor, float VoH) +{ + vec3 SpecularColorSqrt = sqrt(min(SpecularColor, vec3(0.99, 0.99, 0.99))); + vec3 n = (1 + SpecularColorSqrt) / (1 - SpecularColorSqrt); + vec3 g = sqrt(n*n + VoH*VoH - 1); + return 0.5 * sqr((g - VoH) / (g + VoH)) * (1 + sqr(((g + VoH)*VoH - 1) / ((g - VoH)*VoH + 1))); +} + +vec3 FresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness) +{ + vec3 ret = vec3(0.0, 0.0, 0.0); + float powTheta = pow(1.0 - cosTheta, 5.0); + float invRough = float(1.0 - roughness); + + ret.x = F0.x + (max(invRough, F0.x) - F0.x) * powTheta; + ret.y = F0.y + (max(invRough, F0.y) - F0.y) * powTheta; + ret.z = F0.z + (max(invRough, F0.z) - F0.z) * powTheta; + + return ret; +} + +float Fr_DisneyDiffuse(float NdotV, float NdotL, float LdotH, float linearRoughness) +{ + float energyBias = lerp(0, 0.5, linearRoughness); + float energyFactor = lerp(1.0, 1.0 / 1.51, linearRoughness); + float fd90 = energyBias + 2.0 * LdotH*LdotH * linearRoughness; + vec3 f0 = vec3(1.0f, 1.0f, 1.0f); + float lightScatter = F_Schlick(f0, fd90, NdotL).r; + float viewScatter = F_Schlick(f0, fd90, NdotV).r; + + return lightScatter * viewScatter * energyFactor; +} + +float V_SmithGGXCorrelated(float NdotL, float NdotV, float alphaG2) +{ + // Original formulation of G_SmithGGX Correlated + // lambda_v = (-1 + sqrt(alphaG2 * (1 - NdotL2) / NdotL2 + 1)) * 0.5f; + // lambda_l = (-1 + sqrt(alphaG2 * (1 - NdotV2) / NdotV2 + 1)) * 0.5f; + // G_SmithGGXCorrelated = 1 / (1 + lambda_v + lambda_l); + // V_SmithGGXCorrelated = G_SmithGGXCorrelated / (4.0f * NdotL * NdotV); + + + // This is the optimized version + //float alphaG2 = alphaG * alphaG; + + // Caution: the "NdotL *" and "NdotV *" are explicitely inversed , this is not a mistake. + float Lambda_GGXV = NdotL * sqrt((-NdotV * alphaG2 + NdotV) * NdotV + alphaG2); + float Lambda_GGXL = NdotV * sqrt((-NdotL * alphaG2 + NdotL) * NdotL + alphaG2); + + return 0.5f / (Lambda_GGXV + Lambda_GGXL); +} + +float D_GGX(float NdotH, float m2) +{ + // Divide by PI is apply later + //float m2 = m * m; + float f = (NdotH * m2 - NdotH) * NdotH + 1; + return m2 / (f * f); +} + +#endif diff --git a/Templates/Full/game/shaders/common/gl/lighting.glsl b/Templates/Full/game/shaders/common/gl/lighting.glsl index da24d2028..7556545ca 100644 --- a/Templates/Full/game/shaders/common/gl/lighting.glsl +++ b/Templates/Full/game/shaders/common/gl/lighting.glsl @@ -21,7 +21,7 @@ //----------------------------------------------------------------------------- #include "./torque.glsl" - +#include "./brdf.glsl" #ifndef TORQUE_SHADERGEN // These are the uniforms used by most lighting shaders. @@ -44,132 +44,21 @@ uniform vec4 albedo; #endif // !TORQUE_SHADERGEN - -vec3 F_schlick( in vec3 f0, in vec3 f90, in float u ) +vec3 getDistanceVectorToPlane( vec3 origin, vec3 direction, vec4 plane ) { - // - // F( v, h ) = F0 + ( 1.0 - F0 ) * pow( 1.0f - HdotV, 5.0f ) - // - // - // where - // - // F0 = BaseColor * nDotL - // - // Dielectric materials always have a range of 0.02 < F0 < 0.05 , use a stock value of 0.04 ( roughly plastics ) - // + float denum = dot( plane.xyz, direction.xyz ); + float num = dot( plane, vec4( origin, 1.0 ) ); + float t = -num / denum; - return f0 + ( f90 - f0 ) * pow( 1.0f - u , 5.0f ); + return direction.xyz * t; } -float Fr_DisneyDiffuse ( float NdotV , float NdotL , float LdotH , float linearRoughness ) +vec3 getDistanceVectorToPlane( float negFarPlaneDotEye, vec3 direction, vec4 plane ) { - float energyBias = mix (0 , 0.5 , linearRoughness ); - float energyFactor = mix (1.0 , 1.0 / 1.51 , linearRoughness ); - float fd90 = energyBias + 2.0 * LdotH * LdotH * linearRoughness ; - vec3 f0 = vec3 ( 1.0f , 1.0f , 1.0f ); - float lightScatter = F_schlick( f0 , vec3(fd90), NdotL ).r; - float viewScatter = F_schlick(f0 , vec3(fd90), NdotV ).r; + float denum = dot( plane.xyz, direction.xyz ); + float t = negFarPlaneDotEye / denum; - return lightScatter * viewScatter * energyFactor ; -} - -float SmithGGX( float NdotL, float NdotV, float alpha ) -{ - // - // G( L, V, h ) = G( L ) G( V ) - // - // nDotL - // G( L ) = _________________________ - // nDotL ( 1 - k ) + k - // - // - // NdotV - // G( V ) = _________________________ - // NdotV ( 1 - k ) + k - // - // - // pow( ( Roughness + 1 ), 2) - // , Where k = __________________________ ( unreal 4 ) - // 8 - // - - float alphaSqr = alpha * alpha; - - //float GGX_V = NdotL * sqrt ( ( - NdotV * alphaSqr + NdotV ) * NdotV + alphaSqr ); - //float GGX_L = NdotV * sqrt ( ( - NdotL * alphaSqr + NdotL ) * NdotL + alphaSqr ); - - float GGX_V = NdotL + sqrt ( ( - NdotV * alphaSqr + NdotV ) * NdotV + alphaSqr ); - float GGX_L = NdotV + sqrt ( ( - NdotL * alphaSqr + NdotL ) * NdotL + alphaSqr ); - - return 1.0/( GGX_V + GGX_L ); - //return 0.5f / ( GGX_V + GGX_L ); -} - -float D_GGX( float NdotH , float alpha ) -{ - // - // or GGX ( disney / unreal 4 ) - // - // alpha = pow( roughness, 2 ); - // - // pow( alpha, 2 ) - // D( h ) = ________________________________________________________________ - // PI pow( pow( NdotH , 2 ) ( pow( alpha, 2 ) - 1 ) + 1 ), 2 ) - // - - float alphaSqr = alpha*alpha; - float f = ( NdotH * alphaSqr - NdotH ) * NdotH + 1; - return alphaSqr / ( M_PI_F * (f * f) ); -} - -vec4 EvalBDRF( vec3 baseColor, vec3 lightColor, vec3 toLight, vec3 position, vec3 normal, float roughness, float metallic ) -{ - // - // Microfacet Specular Cook-Torrance - // - // D( h ) F( v, h ) G( l, v, h ) - // f( l, v ) = ____________________________ - // 4 ( dot( n, l ) dot( n, v ) - // - // - - vec3 L = normalize( toLight ); - vec3 V = normalize( -position ); - vec3 H = normalize( L + V ); - vec3 N = normal; - - float NdotV = abs( dot( N, V ) ) + 1e-5f; - float NdotH = saturate( dot( N, H ) ); - float NdotL = saturate( dot( N, L ) ); - float LdotH = saturate( dot( L, H ) ); - - float VdotH = saturate( dot( V, H ) ); - - if ( NdotL == 0 ) - return vec4( 0.0f, 0.0f, 0.0f, 0.0f ); - - float alpha = roughness; - float visLinAlpha = alpha * alpha; - - vec3 f0 = baseColor; - float metal = metallic; - - vec3 F_conductor= F_schlick( f0, vec3( 1.0, 1.0, 1.0 ), VdotH ); - vec3 F_dielec = F_schlick( vec3( 0.04, 0.04, 0.04 ), vec3( 1.0, 1.0, 1.0 ), VdotH ); - float Vis = SmithGGX( NdotL, NdotV, visLinAlpha ); - float D = D_GGX( NdotH, visLinAlpha ); - - vec3 Fr_dielec = D * F_dielec * Vis; - vec3 Fr_conductor = D * F_conductor * Vis; - - vec3 Fd = vec3(Fr_DisneyDiffuse( NdotV , NdotL , LdotH , visLinAlpha ) / M_PI_F); - vec3 specular = ( 1.0f - metal ) * Fr_dielec + metal * Fr_conductor; - vec3 diffuse = ( 1.0f - metal ) * Fd * f0; - - vec3 ret = ( diffuse + specular + lightColor) * vec3(NdotL); - - float FR = saturate(length(specular)); - return vec4(ret,FR); + return direction.xyz * t; } void compute4Lights( vec3 wsView, @@ -194,81 +83,152 @@ void compute4Lights( vec3 wsView, out vec4 outDiffuse, out vec4 outSpecular ) { - // NOTE: The light positions and spotlight directions - // are stored in SoA order, so inLightPos[0] is the - // x coord for all 4 lights... inLightPos[1] is y... etc. - // - // This is the key to fully utilizing the vector units and - // saving a huge amount of instructions. - // - // For example this change saved more than 10 instructions - // over a simple for loop for each light. - - int i; + outDiffuse = vec4(0,0,0,0); + outSpecular = vec4(0,0,0,0); +} - vec4 lightVectors[3]; - for ( i = 0; i < 3; i++ ) - lightVectors[i] = wsPosition[i] - inLightPos[i]; +struct Surface +{ + vec3 P; // world space position + vec3 N; // world space normal + vec3 V; // world space view vector + vec4 baseColor; // base color [0 -> 1] (rgba) + float metalness; // metalness [0:dielectric -> 1:metal] + float roughness; // roughness: [0:smooth -> 1:rough] (linear) + float roughness_brdf; // roughness remapped from linear to BRDF + float depth; // depth: [0:near -> 1:far] (linear) + float ao; // ambient occlusion [0 -> 1] + float matFlag; // material flag - use getFlag to retreive + float NdotV; // cos(angle between normal and view vector) + vec3 f0; // fresnel value (rgb) + vec3 albedo; // diffuse light absorbtion value (rgb) + vec3 R; // reflection vector + vec3 F; // fresnel term computed from f0, N and V + void Update(); +}; - // Accumulate the dot product between the light - // vector and the normal. - // - // The normal is negated because it faces away from - // the surface and the light faces towards the - // surface... this keeps us from needing to flip - // the light vector direction which complicates - // the spot light calculations. - // - // We normalize the result a little later. - // - vec4 nDotL = vec4(0); - for ( i = 0; i < 3; i++ ) - nDotL += lightVectors[i] * -wsNormal[i]; - - vec4 squareDists = vec4(0); - for ( i = 0; i < 3; i++ ) - squareDists += lightVectors[i] * lightVectors[i]; - half4 correction = half4(inversesqrt( squareDists )); - nDotL = saturate( nDotL * correction ); +void Surface::Update() +{ + NdotV = abs(dot(N, V)) + 1e-5f; // avoid artifact - // First calculate a simple point light linear - // attenuation factor. - // - // If this is a directional light the inverse - // radius should be greater than the distance - // causing the attenuation to have no affect. - // - vec4 atten = saturate( 1.0 - ( squareDists * inLightInvRadiusSq ) ); + albedo = baseColor.rgb * (1.0 - metalness); + f0 = lerp(vec3(0.04), baseColor.rgb, metalness); + R = -reflect(V, N); + float f90 = saturate(50.0 * dot(f0, vec3(0.33,0.33,0.33))); + F = F_Schlick(f0, f90, NdotV); +} + +Surface createSurface(vec4 gbuffer0, sampler2D gbufferTex1, sampler2D gbufferTex2, in vec2 uv, in vec3 wsEyePos, in vec3 wsEyeRay, in mat4 invView) +{ + Surface surface;// = Surface(); - #ifndef TORQUE_BL_NOSPOTLIGHT + vec4 gbuffer1 = texture(gbufferTex1, uv); + vec4 gbuffer2 = texture(gbufferTex2, uv); + surface.depth = gbuffer0.a; + surface.P = wsEyePos + wsEyeRay * surface.depth; + surface.N = tMul(invView, vec4(gbuffer0.xyz,0)).xyz; //TODO move t3d to use WS normals + surface.V = normalize(wsEyePos - surface.P); + surface.baseColor = gbuffer1; + const float minRoughness=1e-4; + surface.roughness = clamp(1.0 - gbuffer2.b, minRoughness, 1.0); //t3d uses smoothness, so we convert to roughness. + surface.roughness_brdf = surface.roughness * surface.roughness; + surface.metalness = gbuffer2.a; + surface.ao = gbuffer2.g; + surface.matFlag = gbuffer2.r; + surface.Update(); + return surface; +} - // The spotlight attenuation factor. This is really - // fast for what it does... 6 instructions for 4 spots. +struct SurfaceToLight +{ + vec3 L; // surface to light vector + vec3 Lu; // un-normalized surface to light vector + vec3 H; // half-vector between view vector and light vector + float NdotL; // cos(angle between N and L) + float HdotV; // cos(angle between H and V) = HdotL = cos(angle between H and L) + float NdotH; // cos(angle between N and H) - vec4 spotAtten = vec4(0); - for ( i = 0; i < 3; i++ ) - spotAtten += lightVectors[i] * inLightSpotDir[i]; +}; - vec4 cosAngle = ( spotAtten * correction ) - inLightSpotAngle; - atten *= saturate( cosAngle * inLightSpotFalloff ); +SurfaceToLight createSurfaceToLight(in Surface surface, in vec3 L) +{ + SurfaceToLight surfaceToLight;// = SurfaceToLight(); + surfaceToLight.Lu = L; + surfaceToLight.L = normalize(L); + surfaceToLight.H = normalize(surface.V + surfaceToLight.L); + surfaceToLight.NdotL = saturate(dot(surfaceToLight.L, surface.N)); + surfaceToLight.HdotV = saturate(dot(surfaceToLight.H, surface.V)); + surfaceToLight.NdotH = saturate(dot(surfaceToLight.H, surface.N)); + return surfaceToLight; +} - #endif +vec3 BRDF_GetSpecular(in Surface surface, in SurfaceToLight surfaceToLight) +{ + float f90 = saturate(50.0 * dot(surface.f0, vec3(0.33,0.33,0.33))); + vec3 F = F_Schlick(surface.f0, f90, surfaceToLight.HdotV); + float Vis = V_SmithGGXCorrelated(surface.NdotV, surfaceToLight.NdotL, surface.roughness_brdf); + float D = D_GGX(surfaceToLight.NdotH, surface.roughness_brdf); + vec3 Fr = D * F * Vis / M_PI_F; + return Fr; +} - // Get the final light intensity. - vec4 intensity = nDotL * atten; - - // Combine the light colors for output. - vec4 lightColor = vec4(0); - for ( i = 0; i < 4; i++ ) - lightColor += intensity[i] * inLightColor[i]; - - vec3 toLight = vec3(0); - for ( i = 0; i < 3; i++ ) - toLight += lightVectors[i].rgb; - - outDiffuse = vec4(albedo.rgb*(1.0-metalness),albedo.a); - outSpecular = EvalBDRF( vec3( 1.0, 1.0, 1.0 ), lightColor.rgb, toLight, wsPosition, wsNormal, smoothness, metalness ); +vec3 BRDF_GetDiffuse(in Surface surface, in SurfaceToLight surfaceToLight) +{ + //getting some banding with disney method, using lambert instead - todo futher testing + float Fd = 1.0 / M_PI_F; + //energy conservation - remove this if reverting back to disney method + vec3 kD = vec3(1.0) - surface.F; + kD *= 1.0 - surface.metalness; + vec3 diffuse = kD * surface.baseColor.rgb * Fd; + return diffuse; +} + +//attenuations functions from "moving frostbite to pbr paper" +//https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf +float smoothDistanceAtt ( float squaredDistance , float invSqrAttRadius ) +{ + float factor = squaredDistance * invSqrAttRadius ; + float smoothFactor = saturate (1.0f - factor * factor ); + return sqr(smoothFactor); +} + +float getDistanceAtt( vec3 unormalizedLightVector , float invSqrAttRadius ) +{ + float sqrDist = dot ( unormalizedLightVector , unormalizedLightVector ); + float attenuation = 1.0 / (max ( sqrDist , 0.01*0.01) ); + attenuation *= smoothDistanceAtt ( sqrDist , invSqrAttRadius ); + return attenuation; +} + + float getSpotAngleAtt( vec3 normalizedLightVector , vec3 lightDir , vec2 lightSpotParams ) + { + float cd = dot ( lightDir , normalizedLightVector ); + float attenuation = saturate ( ( cd - lightSpotParams.x ) / lightSpotParams.y ); + // smooth the transition + return sqr(attenuation); +} + +vec3 getDirectionalLight(in Surface surface, in SurfaceToLight surfaceToLight, vec3 lightColor, float lightIntensity, float shadow) +{ + vec3 factor = lightColor * max(surfaceToLight.NdotL, 0) * shadow * lightIntensity; + vec3 diffuse = BRDF_GetDiffuse(surface,surfaceToLight) * factor; + vec3 spec = BRDF_GetSpecular(surface,surfaceToLight) * factor; + + vec3 final = max(vec3(0.0f), diffuse + spec * surface.ao); + return final; +} + +vec3 getPunctualLight(in Surface surface, in SurfaceToLight surfaceToLight, vec3 lightColor, float lightIntensity, float radius, float shadow) +{ + float attenuation = getDistanceAtt(surfaceToLight.Lu, radius); + vec3 factor = lightColor * max(surfaceToLight.NdotL, 0) * shadow * lightIntensity * attenuation; + + vec3 diffuse = BRDF_GetDiffuse(surface,surfaceToLight) * factor; + vec3 spec = BRDF_GetSpecular(surface,surfaceToLight) * factor; + + vec3 final = max(vec3(0.0f), diffuse + spec * surface.ao * surface.F); + return final; } float G1V(float dotNV, float k) diff --git a/Templates/Full/game/shaders/common/gl/torque.glsl b/Templates/Full/game/shaders/common/gl/torque.glsl index e2f86c9b3..7461d57c8 100644 --- a/Templates/Full/game/shaders/common/gl/torque.glsl +++ b/Templates/Full/game/shaders/common/gl/torque.glsl @@ -383,4 +383,6 @@ vec3 getCubeDir(int face, vec2 uv) return normalize(dir); } + +#define sqr(a) ((a)*(a)) #endif // _TORQUE_GLSL_ diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/reflectionProbeP.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/reflectionProbeP.glsl index fda00f328..42c084ed7 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/reflectionProbeP.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/reflectionProbeP.glsl @@ -2,10 +2,9 @@ #include "shadergen:/autogenConditioners.h" #include "farFrustumQuad.glsl" -#include "lightingUtils.glsl" #include "../../../gl/lighting.glsl" #include "../../../gl/torque.glsl" -#line 8 +#line 7 in vec4 pos; in vec4 wsEyeDir; @@ -13,6 +12,7 @@ in vec4 ssPos; in vec4 vsEyeDir; uniform sampler2D deferredBuffer; +uniform sampler2D colorBuffer; uniform sampler2D matInfoBuffer; uniform samplerCube cubeMap; uniform samplerCube irradianceCubemap; @@ -28,7 +28,8 @@ uniform vec4 vsFarPlane; uniform float radius; uniform vec2 attenuation; -uniform mat4x4 invViewMat; +uniform mat4 worldToObj; +uniform mat4 cameraToWorld; uniform vec3 eyePosWorld; uniform vec3 bbMin; @@ -53,24 +54,7 @@ vec3 boxProject(vec3 wsPosition, vec3 reflectDir, vec3 boxWSPos, vec3 boxMin, ve return posonbox - boxWSPos; } -vec3 iblBoxDiffuse(vec3 normal, - vec3 wsPos, - samplerCube irradianceCube, - vec3 boxPos, - vec3 boxMin, - vec3 boxMax) -{ - // Irradiance (Diffuse) - vec3 cubeN = normalize(normal); - vec3 irradiance = texture(irradianceCube, cubeN).xyz; - - return irradiance; -} - -vec3 iblBoxSpecular(vec3 normal, - vec3 wsPos, - float roughness, - vec3 surfToEye, +vec3 iblBoxSpecular(vec3 normal, vec3 wsPos, float roughness, vec3 surfToEye, sampler2D brdfTexture, samplerCube radianceCube, vec3 boxPos, @@ -80,7 +64,7 @@ vec3 iblBoxSpecular(vec3 normal, float ndotv = clamp(dot(normal, surfToEye), 0.0, 1.0); // BRDF - vec2 brdf = texture(brdfTexture, vec2(roughness, ndotv)).xy; + vec2 brdf = textureLod(brdfTexture, vec2(roughness, ndotv),0).xy; // Radiance (Specular) float maxmip = pow(cubeMips+1,2); @@ -94,123 +78,65 @@ vec3 iblBoxSpecular(vec3 normal, return radiance; } -float defineSphereSpaceInfluence(vec3 centroidPosVS, float rad, vec2 atten, vec3 surfPosVS, vec3 norm) -{ - // Build light vec, get length, clip pixel if needed - vec3 lightVec = centroidPosVS - surfPosVS; - float lenLightV = length( lightVec ); - if (( rad - lenLightV )<0) - return -1; - - // Get the attenuated falloff. - float attn = attenuate( vec4(1,1,1,1), atten, lenLightV ); - if ((attn - 1e-6)<0) - return -1; - - // Normalize lightVec - lightVec = lightVec /= lenLightV; - - // If we can do dynamic branching then avoid wasting - // fillrate on pixels that are backfacing to the light. - float nDotL = abs(dot( lightVec, norm )); - - return saturate( nDotL * attn ); -} - float defineBoxSpaceInfluence(vec3 surfPosWS, vec3 probePos, float radius, float atten) { - vec3 surfPosLS = mul( worldToObj, vec4(surfPosWS,1.0)).xyz; + vec3 surfPosLS = tMul( worldToObj, vec4(surfPosWS,1.0)).xyz; vec3 boxMinLS = probePos-(vec3(1,1,1)*radius); vec3 boxMaxLS = probePos+(vec3(1,1,1)*radius); - float boxOuterRange = length(lsBoxMax - lsBoxMin); + float boxOuterRange = length(boxMaxLS - boxMinLS); float boxInnerRange = boxOuterRange / atten; vec3 localDir = vec3(abs(surfPosLS.x), abs(surfPosLS.y), abs(surfPosLS.z)); localDir = (localDir - boxInnerRange) / (boxOuterRange - boxInnerRange); - float influenceVal = max(localDir.x, max(localDir.y, localDir.z)) * -1; - - return influenceVal; + return max(localDir.x, max(localDir.y, localDir.z)) * -1; } - -float defineDepthInfluence(vec3 probePosWS, vec3 surfPosWS, samplerCube radianceCube) -{ - //TODO properly: filter out pixels projected uppon by probes behind walls by looking up the depth stored in the probes cubemap alpha - //and comparing legths - vec3 probeToSurf = probePosWS-surfPosWS; - - float depthRef = texture(cubeMap, -probeToSurf,0).a*radius; - float dist = length( probeToSurf ); - - return depthRef-dist; -} - out vec4 OUT_col; -out vec4 OUT_col1; void main() { // Compute scene UV - vec3 ssPos = ssPos.xyz / ssPos.w; + vec2 uvScene = getUVFromSSPos( ssPos.xyz/ssPos.w, rtParams0 ); - vec2 uvScene = getUVFromSSPos( ssPos, rtParams0 ); - - // Matinfo flags - vec4 matInfo = texture( matInfoBuffer, uvScene ); - - // Sample/unpack the normal/z data - vec4 deferredSample = deferredUncondition( deferredBuffer, uvScene ); - vec3 normal = deferredSample.rgb; - float depth = deferredSample.a; - if (depth>0.9999) - { - OUT_col = vec4(0.0); - OUT_col1 = vec4(0.0); - return; - } - - // Need world-space normal. - vec3 wsNormal = tMul(vec4(normal, 1), invViewMat).rgb; - - vec3 eyeRay = getDistanceVectorToPlane( -vsFarPlane.w, vsEyeDir.xyz, vsFarPlane ); - vec3 viewSpacePos = eyeRay * depth; - - vec3 wsEyeRay = tMul(vec4(eyeRay, 1), invViewMat).rgb; - - // Use eye ray to get ws pos - vec3 worldPos = vec3(eyePosWorld + wsEyeRay * depth); - + //eye ray WS/LS + vec3 vsEyeRay = getDistanceVectorToPlane( -vsFarPlane.w, vsEyeDir.xyz, vsFarPlane ); + vec3 wsEyeRay = tMul(cameraToWorld, vec4(vsEyeRay, 0)).xyz; + + //unpack normal and linear depth + vec4 normDepth = deferredUncondition(deferredBuffer, uvScene); + + //create surface + Surface surface = createSurface( normDepth, colorBuffer, matInfoBuffer, + uvScene, eyePosWorld, wsEyeRay, cameraToWorld); float blendVal = 1.0; - - //clip bounds and (TODO properly: set falloff) if(useSphereMode>0) { - blendVal = defineSphereSpaceInfluence(probeLSPos, radius, attenuation, viewSpacePos, normal); + vec3 L = probeWSPos - surface.P; + blendVal = 1.0-length(L)/radius; + clip(blendVal); } else { float tempAttenVal = 3.5; - blendVal = defineBoxSpaceInfluence(worldPos, probeWSPos, radius, tempAttenVal); - } - if (blendVal<0) - { - OUT_col = vec4(0.0); - OUT_col1 = vec4(0.0); - return; + blendVal = defineBoxSpaceInfluence(surface.P, probeWSPos, radius, tempAttenVal); + clip(blendVal); + float compression = 0.05; + blendVal=(1.0-compression)+blendVal*compression; } - - //flip me on to have probes filter by depth - //clip(defineDepthInfluence(probeWSPos, worldPos, cubeMap)); - - //render into the bound space defined above - vec3 surfToEye = normalize(worldPos.xyz-eyePosWorld.xyz); - OUT_col = vec4(iblBoxDiffuse(wsNormal, worldPos, irradianceCubemap, probeWSPos, bbMin, bbMax), blendVal); - OUT_col1 = vec4(iblBoxSpecular(wsNormal, worldPos, 1.0 - matInfo.b, surfToEye, BRDFTexture, cubeMap, probeWSPos, bbMin, bbMax), blendVal); + vec3 surfToEye = normalize(surface.P - eyePosWorld); + vec3 irradiance = textureLod(irradianceCubemap, surface.N,0).xyz; + vec3 specular = iblBoxSpecular(surface.N, surface.P, surface.roughness, surfToEye, BRDFTexture, cubeMap, probeWSPos, bbMin, bbMax); + vec3 F = FresnelSchlickRoughness(surface.NdotV, surface.f0, surface.roughness); + specular *= F; + //energy conservation + vec3 kD = vec3(1.0) - F; + kD *= 1.0 - surface.metalness; + //final diffuse color + vec3 diffuse = kD * irradiance * surface.baseColor.rgb; - OUT_col *= matInfo.g; - OUT_col1 *= matInfo.g; + OUT_col = vec4(diffuse + specular * surface.ao, blendVal); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl b/Templates/Full/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl index d23a9d3fb..d46fa7c33 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl @@ -25,7 +25,6 @@ #include "farFrustumQuad.glsl" #include "../../../gl/torque.glsl" #include "../../../gl/lighting.glsl" -#include "lightingUtils.glsl" #include "../../shadowMap/shadowMapIO_GLSL.h" #include "softShadow.glsl" @@ -34,6 +33,7 @@ in vec2 uv0; in vec3 wsEyeRay; in vec3 vsEyeRay; +uniform sampler2D deferredBuffer; uniform sampler2D shadowMap; uniform sampler2D dynamicShadowMap; @@ -42,68 +42,68 @@ uniform sampler2D ssaoMask ; uniform vec4 rtParams3; #endif -uniform sampler2D deferredBuffer; -uniform sampler2D lightBuffer; uniform sampler2D colorBuffer; uniform sampler2D matInfoBuffer; +uniform float lightBrightness; uniform vec3 lightDirection; uniform vec4 lightColor; -uniform float lightBrightness; uniform vec4 lightAmbient; + +uniform float shadowSoftness; uniform vec3 eyePosWorld; -uniform mat4x4 eyeMat; + uniform vec4 atlasXOffset; uniform vec4 atlasYOffset; -uniform vec2 atlasScale; uniform vec4 zNearFarInvNearFar; uniform vec4 lightMapParams; -uniform vec2 fadeStartLength; +uniform vec4 farPlaneScalePSSM; uniform vec4 overDarkPSSM; -uniform float shadowSoftness; - + +uniform vec2 fadeStartLength; +uniform vec2 atlasScale; + +uniform mat4 eyeMat; +uniform mat4 cameraToWorld; + //static shadowMap -uniform mat4x4 worldToLightProj; +uniform mat4 worldToLightProj; uniform vec4 scaleX; uniform vec4 scaleY; uniform vec4 offsetX; uniform vec4 offsetY; -uniform vec4 farPlaneScalePSSM; //dynamic shadowMap -uniform mat4x4 dynamicWorldToLightProj; +uniform mat4 dynamicWorldToLightProj; uniform vec4 dynamicScaleX; uniform vec4 dynamicScaleY; uniform vec4 dynamicOffsetX; uniform vec4 dynamicOffsetY; uniform vec4 dynamicFarPlaneScalePSSM; -vec4 AL_VectorLightShadowCast( sampler2D _sourceshadowMap, +vec4 AL_VectorLightShadowCast( sampler2D _sourceShadowMap, vec2 _texCoord, mat4 _worldToLightProj, - vec4 _worldPos, - vec4 _scaleX, vec4 _scaleY, - vec4 _offsetX, vec4 _offsetY, + vec3 _worldPos, + vec4 _scaleX, + vec4 _scaleY, + vec4 _offsetX, + vec4 _offsetY, vec4 _farPlaneScalePSSM, - vec4 _atlasXOffset, vec4 _atlasYOffset, - vec2 _atlasScale, - float _shadowSoftness, - float _dotNL , - vec4 _overDarkPSSM -) + float _dotNL) { // Compute shadow map coordinate - vec4 pxlPosLightProj = tMul(_worldToLightProj, _worldPos); + vec4 pxlPosLightProj = tMul(_worldToLightProj, vec4(_worldPos,1)); vec2 baseShadowCoord = pxlPosLightProj.xy / pxlPosLightProj.w; - // Distance to light, in shadowMap space + // Distance to light, in shadowmap space float distToLight = pxlPosLightProj.z / pxlPosLightProj.w; // Figure out which split to sample from. Basically, we compute the shadowMap sample coord // for all of the splits and then check if its valid. - vec4 shadowCoordX = vec4( baseShadowCoord.x ); - vec4 shadowCoordY = vec4( baseShadowCoord.y ); - vec4 farPlaneDists = vec4( distToLight ); + vec4 shadowCoordX = baseShadowCoord.xxxx; + vec4 shadowCoordY = baseShadowCoord.yyyy; + vec4 farPlaneDists = distToLight.xxxx; shadowCoordX *= _scaleX; shadowCoordY *= _scaleY; shadowCoordX += _offsetX; @@ -132,10 +132,10 @@ vec4 AL_VectorLightShadowCast( sampler2D _sourceshadowMap, else finalMask = vec4(0, 0, 0, 1); - vec3 debugColor = vec3(0); + vec3 debugColor = vec3(0,0,0); #ifdef NO_SHADOW - debugColor = vec3(1.0); + debugColor = vec3(1.0,1.0,1.0); #endif #ifdef PSSM_DEBUG_RENDER @@ -164,7 +164,7 @@ vec4 AL_VectorLightShadowCast( sampler2D _sourceshadowMap, shadowCoord = baseShadowCoord * finalScale; shadowCoord += finalOffset; - // Convert to _texCoord space + // Convert to texcoord space shadowCoord = 0.5 * shadowCoord + vec2(0.5, 0.5); shadowCoord.y = 1.0f - shadowCoord.y; @@ -181,132 +181,76 @@ vec4 AL_VectorLightShadowCast( sampler2D _sourceshadowMap, distToLight *= farPlaneScale; return vec4(debugColor, - softShadow_filter( _sourceshadowMap, - _texCoord, - shadowCoord, - farPlaneScale * _shadowSoftness, - distToLight, - _dotNL, - dot( finalMask, _overDarkPSSM ) ) ); + softShadow_filter( _sourceShadowMap, + _texCoord, + shadowCoord, + farPlaneScale * _shadowSoftness, + distToLight, + _dotNL, + dot( finalMask, _overDarkPSSM ) ) ); } out vec4 OUT_col; -out vec4 OUT_col1; void main() { - // Matinfo flags - float4 matInfo = texture( matInfoBuffer, uv0 ); + //unpack normal and linear depth + vec4 normDepth = TORQUE_DEFERRED_UNCONDITION(deferredBuffer, uv0); + + //create surface + Surface surface = createSurface( normDepth, colorBuffer, matInfoBuffer, + uv0, eyePosWorld, wsEyeRay, cameraToWorld); - vec4 colorSample = texture( colorBuffer, uv0 ); - vec3 subsurface = vec3(0.0,0.0,0.0); - if (getFlag( matInfo.r, 1 )) + //early out if emissive + if (getFlag(surface.matFlag, 0)) { - subsurface = colorSample.rgb; - if (colorSample.r>colorSample.g) - subsurface = vec3(0.772549, 0.337255, 0.262745); - else - subsurface = vec3(0.337255, 0.772549, 0.262745); + return 0.0.xxxx; } - // Sample/unpack the normal/z data - vec4 deferredSample = deferredUncondition( deferredBuffer, uv0 ); - vec3 normal = deferredSample.rgb; - float depth = deferredSample.a; + //create surface to light + SurfaceToLight surfaceToLight = createSurfaceToLight(surface, -lightDirection); - // Use eye ray to get ws pos - vec4 worldPos = vec4(eyePosWorld + wsEyeRay * depth, 1.0f); - - // Get the light attenuation. - float dotNL = dot(-lightDirection, normal); - - #ifdef PSSM_DEBUG_RENDER - vec3 debugColor = vec3(0); - #endif + //light color might be changed by PSSM_DEBUG_RENDER + vec3 lightingColor = lightColor.rgb; #ifdef NO_SHADOW - - // Fully unshadowed. - float shadowed = 1.0; - - #ifdef PSSM_DEBUG_RENDER - debugColor = vec3(1.0); - #endif - + float shadow = 1.0; #else - vec4 static_shadowed_colors = AL_VectorLightShadowCast( shadowMap, - uv0.xy, - worldToLightProj, - worldPos, - scaleX, scaleY, - offsetX, offsetY, - farPlaneScalePSSM, - atlasXOffset, atlasYOffset, - atlasScale, - shadowSoftness, - dotNL, - overDarkPSSM); - vec4 dynamic_shadowed_colors = AL_VectorLightShadowCast( dynamicShadowMap, - uv0.xy, - dynamicWorldToLightProj, - worldPos, - dynamicScaleX, dynamicScaleY, - dynamicOffsetX, dynamicOffsetY, - dynamicFarPlaneScalePSSM, - atlasXOffset, atlasYOffset, - atlasScale, - shadowSoftness, - dotNL, - overDarkPSSM); + // Fade out the shadow at the end of the range. + vec4 zDist = (zNearFarInvNearFar.x + zNearFarInvNearFar.y * surface.depth); + float fadeOutAmt = ( zDist.x - fadeStartLength.x ) * fadeStartLength.y; + + vec4 static_shadowed_colors = AL_VectorLightShadowCast( TORQUE_SAMPLER2D_MAKEARG(shadowMap), uv0.xy, worldToLightProj, surface.P, scaleX, scaleY, offsetX, offsetY, + farPlaneScalePSSM, surfaceToLight.NdotL); + + vec4 dynamic_shadowed_colors = AL_VectorLightShadowCast( TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), uv0.xy, dynamicWorldToLightProj, surface.P, dynamicScaleX, + dynamicScaleY, dynamicOffsetX, dynamicOffsetY, dynamicFarPlaneScalePSSM, surfaceToLight.NdotL); + float static_shadowed = static_shadowed_colors.a; float dynamic_shadowed = dynamic_shadowed_colors.a; #ifdef PSSM_DEBUG_RENDER - debugColor = static_shadowed_colors.rgb*0.5+dynamic_shadowed_colors.rgb*0.5; + lightingColor = static_shadowed_colors.rgb*0.5+dynamic_shadowed_colors.rgb*0.5; #endif - // Fade out the shadow at the end of the range. - vec4 zDist = vec4(zNearFarInvNearFar.x + zNearFarInvNearFar.y * depth); - float fadeOutAmt = ( zDist.x - fadeStartLength.x ) * fadeStartLength.y; - - static_shadowed = mix( static_shadowed, 1.0, saturate( fadeOutAmt ) ); - dynamic_shadowed = mix( dynamic_shadowed, 1.0, saturate( fadeOutAmt ) ); + static_shadowed = lerp( static_shadowed, 1.0, saturate( fadeOutAmt ) ); + dynamic_shadowed = lerp( dynamic_shadowed, 1.0, saturate( fadeOutAmt ) ); - // temp for debugging. uncomment one or the other. - //float shadowed = static_shadowed; - //float shadowed = dynamic_shadowed; - float shadowed = min(static_shadowed, dynamic_shadowed)*matInfo.g; + float shadow = min(static_shadowed, dynamic_shadowed); #ifdef PSSM_DEBUG_RENDER if ( fadeOutAmt > 1.0 ) - debugColor = vec3(1.0); + lightingColor = 1.0; #endif - #endif // !NO_SHADOW + #endif //NO_SHADOW + // Sample the AO texture. + #ifdef USE_SSAO_MASK + surface.ao *= 1.0 - TORQUE_TEX2D( ssaoMask, viewportCoordToRenderTarget( uv0.xy, rtParams3 ) ).r; + #endif - vec3 l = normalize(-lightDirection); - vec3 v = normalize(eyePosWorld - worldPos.xyz); + //get directional light contribution + vec3 lighting = getDirectionalLight(surface, surfaceToLight, lightingColor.rgb, lightBrightness, shadow); - vec3 h = normalize(v + l); - float dotNLa = clamp(dot(normal, l), 0.0, 1.0); - float dotNVa = clamp(dot(normal, v), 0.0, 1.0); - float dotNHa = clamp(dot(normal, h), 0.0, 1.0); - float dotHVa = clamp(dot(normal, v), 0.0, 1.0); - float dotLHa = clamp(dot(l, h), 0.0, 1.0); - - float roughness = 1.0001-matInfo.b; - float metalness = matInfo.a; - - //diffuse - //float dotNL = clamp(dot(normal,l), 0.0, 1.0); - float disDiff = Fr_DisneyDiffuse(dotNVa, dotNLa, dotLHa, roughness); - vec3 diffuse = vec3(disDiff, disDiff, disDiff) / M_PI_F;// alternative: (lightColor * dotNL) / Pi; - //specular - vec3 specular = directSpecular(normal, v, l, roughness, 1.0) * lightColor.rgb; - - float finalShadowed = shadowed; - -//output - OUT_col = float4(diffuse * (lightBrightness)*dotNLa*shadowed,1.0); - OUT_col1 = float4(specular * (lightBrightness)*dotNLa*shadowed,1.0); + return vec4(lighting, 0); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/reflectionProbeP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/reflectionProbeP.hlsl index b6e838de9..9af29fa91 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/reflectionProbeP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/reflectionProbeP.hlsl @@ -13,8 +13,8 @@ struct ConvexConnectP }; TORQUE_UNIFORM_SAMPLER2D(deferredBuffer, 0); -TORQUE_UNIFORM_SAMPLER2D(matInfoBuffer, 1); -TORQUE_UNIFORM_SAMPLER2D(colorBuffer, 2); +TORQUE_UNIFORM_SAMPLER2D(colorBuffer, 1); +TORQUE_UNIFORM_SAMPLER2D(matInfoBuffer, 2); TORQUE_UNIFORM_SAMPLERCUBE(cubeMap, 3); TORQUE_UNIFORM_SAMPLERCUBE(irradianceCubemap, 4); TORQUE_UNIFORM_SAMPLER2D(BRDFTexture, 5);