

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

uniform sampler2D tex0;

in vec2 texcoord0_nm;

//TODO: input
float BarrelPower = 1.125f;

//note: http://glsl.heroku.com/e#3290.7
// copied from Little Grasshopper
// Given a vec2 in [-1,+1], generate a texture coord in [0,+1]
vec2 barrel_distortion( vec2 p )
{
    float theta  = atan(p.y, p.x);
    float radius = length(p);
    radius = pow(radius, BarrelPower);
    p.x = radius * cos(theta);
    p.y = radius * sin(theta);

    return 0.5f * ( p + 1.0f );
}

void main( void )
{
	vec2 uv = texcoord0_nm;
	vec2 pos = barrel_distortion( 2 * uv - 1 );

	//note: refit to screen
	vec2 oversiz = barrel_distortion( vec2(1,1) ); 	//TODO: cpu side
	pos = 2 * pos - 1;
	pos = pos / (oversiz*oversiz);
	pos = 0.5f * pos + 0.5f;

	float n = 1.0f / 8.0f;
	vec2 pm =  mod( pos, n);
	vec3 clr_a = vec3(pos - pm, 0.5f);
	vec3 clr_b = vec3(0.5f, pos-pm);

	vec3 clr = mix(clr_a, clr_b, 0.5f);

	vec2 outside = step( vec2(0.5f), abs(pos.xy-0.5f) );
	float os = clamp( dot( outside, outside ), 0, 1 );

	vec4 texcol = texture( tex0, pos );

	//outcol0 = vec4( clr, 1.0f );
	//return;

	outcol0 = texcol;

	outcol0.r += os;
}


// void main( void )
// {
	// float aspect = resolution.x / resolution.y;
	// vec2 unipos = ( gl_FragCoord.xy / resolution ); 
	// vec2 pos = unipos * 2.0f - 1.0f;
	// pos *= aspect;
	// pos = barrel_distortion(pos);
	
	// float n = 1.0f / 8.0f;
	// vec2 pm =  mod( pos, n);

	// vec3 clr_a = vec3(pos - pm, 0.5f);
	// vec3 clr_b = vec3(0.5f, pos-pm);

	// vec3 clr = mix(clr_a, clr_b, 0.5f);

	// outcol0 = vec4( clr, 1.0f );
// }
