#version 430
#define PI 3.1415926535897932
uniform mat4 cam_mat;
uniform sampler2D skytex;
uniform ivec2 light_screensize;

out vec4 out_Color;

void main(void)
{
	//modified viewdir_from_screenpos
	mat4 invmat = inverse(cam_mat);
	vec2 screenpos = gl_FragCoord.xy / vec2(light_screensize/2) - 1;
	vec4 origin = invmat * vec4(screenpos, 0.0, 1.0);
	vec4 lookat = invmat * vec4(screenpos, 1.0, 1.0);
	origin = origin/origin.w;
	lookat = lookat/lookat.w;
	vec3 viewdir = normalize((lookat - origin).xyz);

	//calculate sky coordinate
	vec2 skycoord = vec2(	atan(viewdir.y, viewdir.x) 	/ (2*PI)	+ 0.5,
							-asin(viewdir.z) 			/ PI 		+ 0.5);
	//texture lookups
	vec2 skyGradX = dFdx(skycoord);
	vec2 skyGradY = dFdy(skycoord);
	if(length(skyGradX) > 0.99) skyGradX = vec2(0.0);
	if(length(skyGradY) > 0.99) skyGradY = vec2(0.0);
	vec4 skycolor = textureGrad(skytex, skycoord, skyGradX, skyGradY);
	out_Color = skycolor;
}
