DeferredCombine.fsh 1.57 KB
Newer Older
Dario Seyb's avatar
Dario Seyb committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#version 330

uniform sampler2D uSamplerColor;
uniform sampler2D uSamplerNormal;
uniform sampler2D uSamplerPosition;
uniform sampler2D uSamplerDepth;

uniform vec3 uLightPosition;
uniform vec4 uLightColor;

uniform float uNear;
uniform float uFar;

uniform mat4 uViewProjectionInverseMatrix;

in vec2 vTexCoord;

out vec4 oColor;

vec3 unpackNormal(vec4 norm) {
  return (norm.xyz * 2) - vec3(1, 1, 1);
}

float linearizeDepth(float depth) {
  return  (2.0 * uNear) / (uFar + uNear - depth * (uFar - uNear));  // convert to linear values
}

vec3 unpackWorldPosition(float depth) {
    vec4 clipSpaceLocation;
    clipSpaceLocation.xy = vTexCoord * 2.0f - 1.0f;
    clipSpaceLocation.z = depth* 2.0f - 1.0f;;
    clipSpaceLocation.w = 1.0f;
    vec4 homogenousLocation = uViewProjectionInverseMatrix * clipSpaceLocation;
    return homogenousLocation.xyz / homogenousLocation.w;
}

void main()
{
    vec4 color  = texture(uSamplerColor, vTexCoord);
    vec3 normal = unpackNormal(texture(uSamplerNormal, vTexCoord));
    vec3 position = texture(uSamplerPosition, vTexCoord).xyz;
    
    float depth = texture(uSamplerDepth, vTexCoord).r;
    
    if(depth == 1) discard;
    
    vec3 worldPosition = unpackWorldPosition(depth);
    
    vec3 lightDir = uLightPosition - worldPosition;
    float lightDistance = length(lightDir);
    lightDir /= lightDistance;
    
    float diffuseFactor = dot(lightDir, normal) * uLightColor.a/lightDistance;
    if(diffuseFactor < 0) diffuseFactor = 0;
    
    vec3 diffuseColor =  diffuseFactor * uLightColor.rgb * color.rgb;
    
    oColor = vec4(diffuseColor, 1);
}