// **************************************
// DOME FLAT TO SHAE for WINGS RX
// **************************************
// DOME_flat2hapeping for 2D contents anywhere in the dome
// places 2D image as pseudo 3D layer in dome
// (C) 2018 VIOSO GmbH
// version 1.1 (bf)
// date: 05.11.2018


 const float c_PI   = 3.141592653589793238462643383279502884197169399375105820974944592308;
 const float c_PIH  = c_PI/2.0;
 const float c_2PI  = 2.0*c_PI;
 const float c_G2R  = c_PI/180.0;
 const float c_G2RH = c_G2R/2.0;
 const vec4 c_BgColor = vec4( 0, 0, 0, 0);

//@implements: sampler2D
struct DOME_flat2hape {

	sampler2D sampler;
    
    //@ label: "Aspect X", editor: range,  min: 0, max: 300, range_min: 0, range_max: 3000, range_default: 16
	float ratiox;
	//@ label: "Aspect Y", editor: range,  min: 0, max: 300, range_min: 0, range_max: 3000, range_default: 9
	float ratioy;    
	//@ label: "Azimuth/Position", editor: range,  min: 0, max: 360, range_min: 0, range_max: 360, range_default: 270
	float azimuth;
	//@ label: "Elevation/Height", editor: range,  min: 0, max: 360, range_min: 0, range_max: 360, range_default: 40
	float elevation;
	//@ label: "Field of view", editor: range,  min: 0, max: 360, range_min: 0, range_max: 360, range_default: 50
	float fov;
	
	
};


vec2 DomeMasterUV(vec4 vT,vec2 vPos,float d, float azimuthb)
{
	vec4 vA;
	float f,u,v;

	f=mod( vT.x + 180.0, 360.0);
	vT.x=(f<0.0)? f + 180.0 : f - 180.0;
	
	f=atan( vPos.y, vPos.x )/c_PI;
	u=(1.0 + f)/2.0;
	v=(azimuthb>0.5)? ( c_PIH - acos(d) )/c_PIH : d;

	vA.zw=vec2( vT.w*vT.z/360.0, vT.z/90.0);
	vA.xy=vec2( (1.0 + vT.x/180.0 - vA.z)/2.0, vT.y/90.0 - vA.w/2.0 );
	
	f=( u - vA.x )/vA.z;
	v=( v - vA.y )/vA.w;
	if(f<0.0)
		f=( 1.0 + u - vA.x )/vA.z;
	else if(f>=1.0)
		f=( u - 1.0 - vA.x )/vA.z;
		
	return vec2( f, v);
}



vec4 texture(DOME_flat2hape s, vec2 tex_coords)

{
	
	
	vec2 pos = tex_coords;
	
	
	vec2 vR,vP,vO,vDM;
	float u,v,c,ss,sX,sY,r;
	vec2 vPos=vec2( 2.0*(pos.x - 0.5), 2.0*(pos.y - 0.5) );
	float d=length(vPos);

	//vO=float2( 0.5, 0.5 );
	
	//sX=-1.0;
	//sY= 0.5;
	
	//texContent.GetDimensions( u, v);
	r= s.ratiox/s.ratioy;

	u=sin(s.elevation*c_G2R);
	sY=s.fov/90.0;
	sX=-sY*r;
	vO.x=u - sY/2.0;
	vO.y=-sX/2.0;
	
	c=cos(-s.azimuth*c_G2R);
	ss=sin(-s.azimuth*c_G2R);
	vP.x=c*vPos.x - ss*vPos.y;
	vP.y=ss*vPos.x + c*vPos.y;
	
	vDM=DomeMasterUV( vec4 (0,s.elevation,s.fov,r), vP, d, s.azimuth);

		vR=vP-vO;
	u=vR.y/sX;
	v=vR.x/sY;
	
	v=(1.0 - vP.x)*v + vP.x*vDM.y;
	
	v= 1.0-v;
		
	u= 1.0-u;
return ( (d>1) || (u<0) || (u>=1) || (v<0) || (v>=1) )? (s.elevation>0.5)?  c_BgColor : c_BgColor : texture( s.sampler, vec2( u, v) );
	
	
	
	
	
	
	
} 