in  vec4 dir;
out vec4 fragColor;
uniform vec4 camera; // xyz- camera origin(LY)  , w - 1/rad(LY)
uniform sampler2D tex0;
#define  iChannel0 tex0

bool RSI(in vec3 ro,in vec3 rd,out vec2 res)
{
  float b = dot(ro,rd);
  float c = dot(ro,ro) - 1.0;
  float d = b*b - c;

  if(d <= 0.0) return false;
  d = sqrt(d);
  res.x=(-b - d);
  res.y=(-b + d);
  return true;
}

vec4 castray( in vec3 ro, vec3 rd)
{
  const float PI=3.14159265358979;
  vec2 t;
  if (!RSI(ro,rd,t)) discard;
  float a=(t.y-t.x)*.5;
  vec3 p=ro+rd*t.x;
  float lon=atan(p.y,p.x);
  float lat=PI/2.-atan(length(p.xy),p.z);
  float x=.5+lon*.5/PI;
  float y=.5+lat/PI;
  vec3 col=texture( iChannel0,vec2(x,y)).rgb;
  return vec4(col,a*a*.2);
}

void main( )
{
  vec3 ro  =  camera.xyz*camera.w;
  vec3 rd  =  normalize(dir.xyz-camera.xyz);
  vec4 col =  castray(ro,rd);
  fragColor = vec4( col.rgb*(col.a*dir.w),0.0 );
}
