#version 330 core

in vec2 UV;
in vec3 normal;
in vec2 speed;
in vec4 pos;
in vec3 origpos;

//...
in vec4 oldprojected;
in vec4 newprojected;

// Values that stay constant for the whole mesh.
uniform sampler2D myTextureSampler;

// output
layout(location = 0) out vec4 color;
layout(location = 1) out vec4 oNormal;
layout(location = 2) out vec4 speedcolor;
layout(location = 3) out vec4 position;


const vec3 dirlight = normalize(vec3(-1.0, -1.0, -1.0));

vec3 getSpeedColor() {
    vec2 delta = newprojected.xy/newprojected.w - oldprojected.xy/oldprojected.w;
    return vec3(5.0 * (delta - 0.0),0.0);
}

void main(){
	// ToDo: taika
	float r = length(normal);
	float x = acos(normal.z / r) / 3.141;
	float y = atan(normal.y / normal.x) / (3.141 / 2.0) + 0.5;
	vec2 lut = vec2(0.0);

	if ((abs(normal.x) > abs(normal.y)) && (abs(normal.x) > abs(normal.z))) {
		lut = (normal.yz + vec2(1.0)) / abs(normal.x) / 2.0;
	}
	else if ((abs(normal.y) > abs(normal.x)) && (abs(normal.y) > abs(normal.z))) {
		lut = (normal.xz + vec2(1.0)) / abs(normal.y) / 2.0;
	}
	else {
		lut = (normal.xy + vec2(1.0)) / abs(normal.z) / 2.0;
	}

	float normalfactor = max(dot(normal, dirlight), 0.2) + 0.2 * max(dot(normal, normalize(pos.xyz)), 0.0);
	//normalfactor = 1.0 + 0.2 * normalfactor;
	//color = vec4(texture( myTextureSampler, vec2(x, y) ).xyz * normalfactor, 1.0);
	color = texture( myTextureSampler, vec2(x, y) );
	color = texture( myTextureSampler, lut );
	color = normalfactor * color + (1.0 - normalfactor) * vec4(vec3(0.2), 1.0);
	vec4 origcolorr = color;

	// Procedural approach
	//float possum = dot(origpos, vec3(1.0));
	////float possum = origpos.x + origpos.y + origpos.z;
	//const float modulos = 4.0;
	//color = vec4(normalfactor * vec3(mod(possum, modulos) > modulos / 2.0), 1.0) * color;
	//if (mod(possum, modulos) <= modulos / 2.0) {
	//	color = vec4(0.75 * origcolorr.xyz, 1.0);
	//}

	//color = 0.5 * (color + texture(myTextureSampler, UV));
	oNormal = vec4(normal, 1.0);
    speedcolor = vec4(getSpeedColor(), 1.0);
    position = pos;
}
