//  Copyright © 2013  B. Clausius <barcc@gmx.de>
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

uniform sampler2D tex;
varying vec4 position;
varying vec3 color;
varying vec2 texcoord;
varying vec3 normal;
const vec3 pointlight = vec3(0., 0., 0.);
// diffuse+ambient+specular is the maxintensity
const float diffuse = 1.4;
const float ambient = .3;
const float shininess = 50.;
const float attenuation = 0.001;
const vec3 specular = vec3(5., 4.5, 3.) * .5;
const vec3 invgamma = vec3(1./2.2);

void main()
{
    // mix color and image
    vec4 col_tex = texture2D(tex, texcoord);
    vec3 col_face = mix(color.rgb, col_tex.rgb, col_tex.a);
    
    vec3 norm = normalize(normal);
    vec3 lightvector = pointlight - position.xyz;
    vec3 dirtolight = normalize(lightvector);
    float cos_angle = dot(norm, dirtolight);
    cos_angle = clamp(cos_angle, 0, 1);
    
    // attenuation
    float light_distance_sqr = dot(lightvector, lightvector);
    float attenfactor = 1. / (1.0 + attenuation * light_distance_sqr);
    
    // combine color components
    vec3 col = ambient * col_face;
    col += specular * attenfactor * pow(cos_angle, shininess);
    col += diffuse * col_face * cos_angle;
    
    gl_FragColor = vec4(pow(col, invgamma), 1.);
}

