/*
 * fragment shader for heightmap rendering
 *
 * calculates the pixel color by using the given detail textures
 * and the information in the heightmap-texture, which texture has which opacity
 *
 * written by:
 * christian moellinger <ch.moellinger@gmail.com>
 * 01/2011
 */

#version 330 core
precision highp float;

uniform sampler2D detailTexture1;
uniform sampler2D detailTexture2;
uniform sampler2D detailTexture1_normal;
uniform sampler2D detailTexture1_bump;
uniform sampler2D detailTexture2_normal;
uniform sampler2D detailTexture2_bump;
uniform sampler2D baseTexture;
uniform sampler2D heightmap;
uniform sampler2D shadowmap;

uniform mat4 Camera_ProjectionMatrix;
uniform mat4 Camera_TransformMatrix;
uniform mat4 Camera_TempTransformMatrix;
uniform mat4 Model_TransformMatrix;
uniform mat3 NormalMatrix;

out vec4 FragColor;
in vec2 texcoords;
in vec3 my_ObjPosition;
in float fog;
in vec3 my_Normal;
in vec3 my_LightDir;
in vec3 my_EyeDir;
in mat3 NormalMatrix2;
in vec4 my_WorldPosition;
in vec2 my_ShadowMapCoords;

float factor_detail1 = texture(heightmap, texcoords).g;
float factor_detail2 = texture(heightmap, texcoords).b;

vec4 detail1 = texture(detailTexture1, texcoords * 20);
vec4 detail2 = texture(detailTexture2, texcoords * 20);

vec4 light_value = vec4(0.1, 0.1, 0.1, 1.0);

//these things should set per uniforms
float MaterialShininess = 100.0;
float att = 1.0;

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);
//end

const float invRadius = 0.1;



const float scale = 0.007;

void doPhong()
{
    vec3 N = normalize(NormalMatrix2 * normalize(my_Normal));

    vec3 L = normalize(my_LightDir);

    float lambertTerm = dot(N,L);

    if(lambertTerm > 0.0)
    {
	    light_value += Light0Diffuse * MaterialDiffuse * lambertTerm * att;

	    vec3 E = normalize(my_EyeDir);
	    vec3 R = reflect(-L, N);

	    float specular = pow(max(dot(R, E), 0.0), MaterialShininess);

	    light_value += Light0Specular * MaterialSpecular * specular * att;
    }

    FragColor = vec4((1.0 - fog) * vec3(factor_detail1 * detail1 + factor_detail2 * detail2) * light_value.rgb, -my_ObjPosition.y * 10);
}

void main()
{


    float light = 1.0;
    vec4 shadowcoords_f = Camera_ProjectionMatrix * Camera_TempTransformMatrix * Model_TransformMatrix * vec4(my_ObjPosition, 1.0);
    vec2 shadowcoords = (shadowcoords_f / shadowcoords_f.w).xy;
    shadowcoords += 1.0;
    shadowcoords *= 0.5;


    float ShadowMapValue = texture(shadowmap, shadowcoords).r;

    float ComparedZ = shadowcoords_f.z / shadowcoords_f.w;

    if (ComparedZ > ShadowMapValue)
	light = 0.2;
    else
	light = 1.0;

    doPhong();
}

