/*
 * fragment shader for parallax lighting
 *
 *
 * written by:
 * christian moellinger <ch.moellinger@gmail.com>
 * 11/2010
 */

#version 330 core

out vec4 out_Color;
in vec3 my_Texcoord;
in vec3 my_LightDir;
in vec3 my_EyeDir;

uniform sampler2D color_texture;
uniform sampler2D normal_texture;
uniform sampler2D height_texture;

const float invRadius = 0.1;

const vec4 Light0Ambient = vec4(0.0);
const vec4 Light0Diffuse = vec4(0.8);
const vec4 Light0Specular = vec4(1.0);

const vec4 MaterialAmbient = vec4(1.0);
const vec4 MaterialDiffuse = vec4(1.0);
const vec4 MaterialSpecular = vec4(1.0);

const float scale = 0.014;

void main(void)
{
    float distSqr = dot(my_LightDir, my_LightDir);

    float att = 1.0;//clamp(1.0 - invRadius * sqrt(distSqr), 0.0, 1.0);

    vec3 lVec = my_LightDir * inversesqrt(distSqr);

    vec3 vVec = normalize(my_EyeDir);
    vec3 vVec2 = vVec;
    vVec2.x = -vVec2.x;	//dont know why this is needed - maybe a bug in viewvector calculation?

    float height = texture(height_texture, my_Texcoord.st).r;
    float offset = scale * (2.0 * height - 1.0);

    vec2 texcoord_offset = (offset * vVec2.xy);// / vVec2.z;

    vec4 bump_value = texture(normal_texture, my_Texcoord.st + texcoord_offset);
    vec4 texture_value = texture(color_texture, my_Texcoord.st + texcoord_offset);

    vec4 base = texture_value;

    vec3 bump = normalize(bump_value.rgb * 2.0 - 1.0);

    vec4 vAmbient = Light0Ambient * MaterialAmbient;

    float diffuse = max( dot(lVec, bump), 0.0 );

    vec4 vDiffuse = Light0Diffuse * MaterialDiffuse * diffuse;

    float specular = pow(clamp(dot(reflect(-lVec, bump), vVec), 0.0, 1.0), 10.0);

    vec4 vSpecular = Light0Specular * MaterialSpecular * specular;

    vec4 light_value = (vAmbient*base + vDiffuse*base + vSpecular) * att;

    out_Color = light_value * texture_value;
}
