#version 420 core
// UNIFORM BLOCK

#define USE_COLOR_PROP BOOL_COLOR_PROP
#define WELL_LOG_NO_VALUE (1e19)

layout(quads, equal_spacing, cw) in;

uniform vec4 cRadiusScale;
uniform vec3 cSceneScale;
uniform float proj33;
uniform float proj1length;

in vec4 outpos_ES_in[];
in vec2 outAziIncl_ES_in[];

in vec3 outVecX_ES_in[];
in vec3 outVecY_ES_in[];
in vec3 outVecZ_ES_in[];

#if USE_COLOR_PROP
in float outProp_ES_in[];
out float rLogValueTransferFunction;
#endif

out float rTexU;

out vec3 N;
out vec3 vObjPos;

out float rDiscard;

#define REAL_PI_F 3.14159265

void main()
{
  vec3
    cCurrVertex = outpos_ES_in[0].xyz;

  vec2
    cAziIncl = outAziIncl_ES_in[0];

#if USE_COLOR_PROP
  rLogValueTransferFunction = outProp_ES_in[0];
#endif

  rDiscard = 1.0;

  // are we at novalue?
  if (outpos_ES_in[0].w > WELL_LOG_NO_VALUE)
  {
    rDiscard = 0.0;
  }

  mat3 
    cMat;

  cMat[0] = outVecX_ES_in[0];
  cMat[1] = outVecY_ES_in[0];
  cMat[2] = outVecZ_ES_in[0];

  float
    rPhi = gl_TessCoord.x * 2.0 * REAL_PI_F,   // 0 <= phi <= 2pi
    rTheta = gl_TessCoord.y * REAL_PI_F; // 0 <= theta <= pi

  float
    rX = sin(rTheta) * cos(rPhi),
    rY = sin(rTheta) * sin(rPhi),
    rZ = cos(rTheta);

  vec3
    cLocalSpherePos = vec3(rX, rY, rZ);

  //2DLOG code will be replace here
  // calculate sphere pos based on glTess

  vec3 cPos = cMat * cLocalSpherePos * vec3(cRadiusScale.w);
  cPos *= cSceneScale;
  cPos += cCurrVertex.xyz;

  vObjPos = (gl_ModelViewMatrix* vec4(cPos , 1.0)).xyz;

  // Normal on ellipsoid
  N = cLocalSpherePos;
  
  N.x /= length(vec3(cMat[0].x, cMat[1].x, cMat[2].x));
  N.y /= length(vec3(cMat[0].y, cMat[1].y, cMat[2].y));
  N.z /= length(vec3(cMat[0].z, cMat[1].z, cMat[2].z));

  cMat[0] = normalize(cMat[0]);
  cMat[1] = normalize(cMat[1]);
  cMat[2] = normalize(cMat[2]);

  N = cMat * N;

  N = (gl_ModelViewMatrix * vec4(N , 0.0)).xyz;

  gl_Position = gl_ModelViewProjectionMatrix * vec4(cPos, 1.0);

  // CLIPPLANE CODE


}
