#type vertex
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoords;

out VS_OUT {
    vec3 FragPos;
    vec3 Normal;
    vec2 TexCoords;
    vec2 TexCoordsEnvMap;  // Sphere mapping env map
} vs_out;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    vs_out.FragPos = vec3(model * vec4(aPos, 1.0));
    vs_out.TexCoords = aTexCoords;
    vs_out.Normal = vec3(model * vec4(aNormal, 1.0));


    // Calc Env. map
    vec3 u = vec3(view * model * vec4(aPos, 1.0));
    vec3 n = vec3(model * vec4(aNormal, 1.0));
    vec3 r = reflect( u, n );
    float m = 2.0 * sqrt( r.x*r.x + r.y*r.y + (r.z+1.0)*(r.z+1.0) );
    vs_out.TexCoordsEnvMap.s = (r.x/m + 0.5);
    vs_out.TexCoordsEnvMap.t = (r.y/m + 0.5);

    gl_Position = projection * view * model * vec4(aPos, 1.0);
}

#type fragment
#version 330 core
layout (location = 0) out vec4 FragColor;
layout (location = 1) out vec4 brightColor;

in VS_OUT {
vec3 FragPos;
vec3 Normal;
vec2 TexCoords;
vec2 TexCoordsEnvMap;
} fs_in;

uniform vec3 lightPos;
uniform vec3 lightCol;

uniform vec3 viewPos;
uniform float ambientStrenght; // Recommended 0.1

uniform sampler2D texture_diffuse1;
uniform vec3 cameraPos;
uniform float envMapImpact;
uniform sampler2D environment;

void main()
{    
//vec3 objectColor = texture(texture_diffuse1, fs_in.TexCoords).rgb;
vec3 objectColor = vec3(1,0.2,0.2);

// ambient
vec3 ambient = ambientStrenght * objectColor;

// diffuse
vec3 norm = normalize(fs_in.Normal);
vec3 lightDir = normalize(lightPos - fs_in.FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * lightCol;

vec3 result = (ambient + diffuse) * objectColor;
//FragColor = vec4(result, 1.0);

// With cubeMaps (not supported by the engine yet...)
//vec3 incident = normalize(fs_in.FragPos - cameraPos);
//vec3 reflection = reflect(incident, norm);
//FragColor = vec4(texture(environment, reflection.xy).rgb, 1.0);
vec4 color = vec4(result + envMapImpact*texture(environment, fs_in.TexCoordsEnvMap).rgb, 1.0);
float brightness = dot(color.xyz, vec3(0.5, 0, 0));//vec3(0.1126, 0.1152, 0.0722));

FragColor = color;

if(brightness > 1)
    brightColor = color;
else
    brightColor = vec4(0.0, 0.0, 0.0, 1.0);
}