#version 330

uniform vec4 BaseColor;
uniform vec3 CameraPos;
uniform int HasEnvMap;
uniform float EnvMapRotate;

uniform sampler2D EnvMapSampler;

in vec3 VSWorldPos;
in vec3 VSNormal;
in vec2 VSTexCoord;

out vec4 OutColor;

float PI = 3.141592653589793;
vec3 saturate(vec3 v) { return clamp(v, 0, 1); }
float atan2(float y, float x) { return x == 0.0 ? sign(y)*PI/2 : atan(y, x); }


vec2 dirToUV(vec3 dir)
{
	return vec2(
		atan2(dir.z, dir.x) / (PI*2),
		acos(dir.y) / PI);
}

vec2 envmapUV(vec3 dir)
{
	return dirToUV(dir) + vec2(EnvMapRotate, 0.0);
}

vec4 LINEARtoSRGB(vec4 srgbIn, bool is_srgb)
{
	if(is_srgb){
		vec3 linOut = pow(abs(srgbIn.xyz),vec3(1.0/2.2,1.0/2.2,1.0/2.2));
		return vec4(linOut,srgbIn.w);
	}else{
		return srgbIn;
	}
}

void main(void)
{
	vec3 V = normalize(CameraPos - VSWorldPos);
	vec3 col = LINEARtoSRGB(texture(EnvMapSampler, envmapUV(-V)) * BaseColor, HasEnvMap == 2).xyz;
	OutColor = vec4(saturate(col), 1.0);
}

