// =========================================
// FISH EYE CHROMATIC ABERRATION
// =========================================

float4 TESR_FishEyeCA_fFisheyeZoom;
float4 TESR_FishEyeCA_fFisheyeDistortion;
float4 TESR_FishEyeCA_fFisheyeDistortionCubic;
float4 TESR_FishEyeCA_fFisheyeColorshift;

sampler2D TESR_RenderedBuffer : register(s0) = sampler_state {
	AddressU  = CLAMP;
	AddressV  = CLAMP;
	MinFilter = LINEAR;
	MagFilter = LINEAR;
	MipFilter = NONE;
};

struct VSOUT {
	float4 vertPos : POSITION;
	float2 UVCoord : TEXCOORD0;
};

struct VSIN {
	float4 vertPos : POSITION0;
	float2 UVCoord : TEXCOORD0;
};

VSOUT FrameVS(VSIN IN) {
	VSOUT OUT = (VSOUT)0.0f;
	OUT.vertPos = IN.vertPos;
	OUT.UVCoord = IN.UVCoord;
	return (OUT);
}

float4 PS_FISHEYE_CA( VSOUT IN, float2 texcoord : TEXCOORD0 ) : COLOR {

//     TESR_FishEyeCA_fFisheyeZoom.r = 0.5;
//     TESR_FishEyeCA_fFisheyeDistortion.r = 0.15; 
//     TESR_FishEyeCA_fFisheyeDistortionCubic.r = 0.15;  
//     TESR_FishEyeCA_fFisheyeColorshift.r = -0.03; 
     
      

	float4 coord = 0.0;
	coord.xy = texcoord.xy;
	coord.w = 0.0;
	float4 color = 0.0.xxxx;
	float3 eta = float3( 1.0 + TESR_FishEyeCA_fFisheyeColorshift.r * 0.9, 1.0 + TESR_FishEyeCA_fFisheyeColorshift.r * 0.6, 1.0 + TESR_FishEyeCA_fFisheyeColorshift.r * 0.3 );
	float2 center;
	center.x = coord.x - 0.5;
	center.y = coord.y - 0.5;
	float LensZoom = 1.0 / TESR_FishEyeCA_fFisheyeZoom.r;
	float r2 = ( texcoord.x - 0.5 ) * ( texcoord.x - 0.5 ) + ( texcoord.y - 0.5 ) * ( texcoord.y - 0.5 );     
	float f = 0;
	if ( TESR_FishEyeCA_fFisheyeDistortionCubic.r == 0.0 ) {
		f = 1 + r2 * TESR_FishEyeCA_fFisheyeDistortion.r;
	} else {
        f = 1 + r2 * ( TESR_FishEyeCA_fFisheyeDistortion.r + TESR_FishEyeCA_fFisheyeDistortionCubic.r * sqrt( r2 ));
	};
	float x = f * LensZoom * ( coord.x - 0.5 ) + 0.5;
	float y = f * LensZoom * ( coord.y - 0.5 ) + 0.5;
	float2 rCoords = ( f * eta.r ) * LensZoom * ( center.xy * 0.5 ) + 0.5;
	float2 gCoords = ( f * eta.g ) * LensZoom * ( center.xy * 0.5 ) + 0.5;
	float2 bCoords = ( f * eta.b ) * LensZoom * ( center.xy * 0.5 ) + 0.5;
	color.x = tex2D( TESR_RenderedBuffer, rCoords ).r;
	color.y = tex2D( TESR_RenderedBuffer, gCoords ).g;
	color.z = tex2D( TESR_RenderedBuffer, bCoords ).b;

	return color;
}

technique {
	pass {
		VertexShader = compile vs_3_0 FrameVS();
		PixelShader = compile ps_3_0 PS_FISHEYE_CA();
	}
}