
layout(location = 0, index = 0) out vec4 out_color0;

uniform samplerCube cubetex;
uniform vec4 resolution;
uniform vec4 viewwidth;

const float aspect = 2.35; //TODO: input?
const float pi = 3.1415926536;

/*
mat4 rotmat( float angle_rad, vec3 rotvec )
{
	mat4 ret;
	float c = cos( angle_rad );
	float s = sin( angle_rad );
	float t = 1.0 - c;

	ret[0].x = t*rotvec[0]*rotvec[0] + c;
	ret[0].y = t*rotvec[0]*rotvec[1] - s*rotvec[2];
	ret[0].z = t*rotvec[0]*rotvec[2] + s*rotvec[1];
	ret[0].w = 0.0;

	ret[1].x = t*rotvec[0]*rotvec[1] + s*rotvec[2];
	ret[1].y = t*rotvec[1]*rotvec[1] + c;
	ret[1].z = t*rotvec[1]*rotvec[2] - s*rotvec[0];
	ret[1].w = 0.0;

	ret[2].x = t*rotvec[0]*rotvec[2] - s*rotvec[1];
	ret[2].y = t*rotvec[1]*rotvec[2] + s*rotvec[0];
	ret[2].z = t*rotvec[2]*rotvec[2] + c;
	ret[2].w = 0.0;

	ret[3].x = 0.0;
	ret[3].y = 0.0;
	ret[3].z = 0.0;
	ret[3].w = 1.0;

	return ret;
}
vec3 fisheye0( vec2 uv, float m )
{
	vec2 ctrvec = vec2(0.5)-uv;
	ctrvec.x *= aspect;
	float rot = length(ctrvec) * m; //TODO: fov_y directly?
	rot = pow(rot, 0.75 );
	vec3 rotvec = vec3( 0, -ctrvec.x, ctrvec.y );
	const vec4 fwd = vec4(-1,0,0,0);
	vec3 dir = (rotmat(rot, rotvec) * fwd).xyz;

	return dir;
}


vec3 fisheye1( vec2 uv, float m)
{
	uv = uv * 2.0 - 1.0;
	uv.y *= aspect;
	uv *= 6.0 * m;

	vec3 dir = vec3( uv.x, uv.y, sqrt(1.0-dot(uv.xy,uv.xy) ) );

	float l = length(dir);
	dir /= l;

	return dir;
	//return (l<1.01) ? dir : vec3(0,0,0);
}
*/

vec3 fisheye2( vec2 uv, float m)
{
	uv = uv * 2.0 - 1.0;
	uv.y /= aspect;
	uv *= m;

	vec3 dir = vec3( uv.x, uv.y, 1.0-dot(uv.xy,uv.xy) );
	dir = vec3( -dir.z, dir.y, -dir.x );

	float l = length(dir);
	dir /= l;

	return dir;
	//return (l<1.01) ? dir : vec3(0,0,0);
}


void main()
{
	vec2 uv = gl_FragCoord.xy * resolution.zw;
	vec3 dir = fisheye2( uv, viewwidth.x );
	vec4 cubemap_sample = texture( cubetex, dir );
	out_color0 = vec4( cubemap_sample );
}
