#version 330

uniform float time;
uniform sampler2D ourTexture;
uniform float texture_level;
uniform int lighting;
uniform int has_uvs;
uniform int has_normals;

out vec4 FragColor;
flat in int vID;
in vec2 texCoord;
in vec3 position;
in vec3 normal;


float rand(float n)
{
	return fract(sin(n) * 43758.5453123);
}

void main()
{
	vec3 triangle_color = vec3(rand(float(vID + int(time))), rand(float(vID + int(time))), rand(float(vID + int(time)))) * (1 - texture_level);
	vec3 texture_color;
	if (has_uvs > 0) {
		texture_color = texture_level * texture(ourTexture, vec2(texCoord.x, 1.- texCoord.y)).rgb;
	}
	else {
		texture_color = texture_level * texture(ourTexture, position.yz).rgb;
		if (abs(position.x) < 0.077) {
			texture_color = texture_level * texture(ourTexture, position.xy).rgb;
		}
	}
	vec3 color = triangle_color + texture_color;
	if (has_normals > 0 && lighting == 1) {
		vec3 n = normalize(vec3(10. * cos(time), 10., 10. * sin(time)) - position);
		float ambient = 0.2;
		float phong = max(0., dot(n, normalize(normal)));
		float specular = pow(max(dot(reflect(n, normalize(normal)), normalize(vec3(0, 0, -2) - position)), 0.), 10.);
		color = color * (ambient + (1. - ambient) * phong) + vec3(1.) * specular;
	}
	FragColor = vec4(color, 1.);
}
