#version 420 core
// UNIFORM BLOCK

#define USE_COLOR_PROP BOOL_COLOR_PROP

#define WELL_GL_PATCH_SIZE  3

layout(vertices = WELL_GL_PATCH_SIZE) out;

in vec4 outpos_CS_in[];
in vec2 outAziIncl_CS_in[];

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

out vec4 outpos_ES_in[];
out vec2 outAziIncl_ES_in[];

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

float
CalcTessSizeHorizontal(vec4 cPosRadius)
{
  float
    rOuterRadius = cRadiusScale.w;

  // REPLACE VIEWDEPEDENT TESSELATION SIZE

  float
    rDist = gl_ModelViewProjectionMatrix[0][3] * cPosRadius.x +
            gl_ModelViewProjectionMatrix[1][3] * cPosRadius.y + 
            gl_ModelViewProjectionMatrix[2][3] * cPosRadius.z + 
            gl_ModelViewProjectionMatrix[3][3];

 if (rDist < 0.0) return 512.0;

  float
    rPixelUnit = projInfoY * -rDist;

  float rPixels = rOuterRadius / rPixelUnit;
  rPixels *= 4.0;

  if (rPixels < 4.0) rPixels = 4.0;
  else if (rPixels > 512.0) rPixels = 512.0;

  return rPixels;
}

void main(void)
{
    if (gl_InvocationID == 0)
    {
      // horizontal tesselation
      float
        rTess = CalcTessSizeHorizontal(outpos_CS_in[1]);

      gl_TessLevelOuter[0] = 3;
      gl_TessLevelOuter[1] = rTess;
    }

    outpos_ES_in[gl_InvocationID] = outpos_CS_in[gl_InvocationID];
    outAziIncl_ES_in[gl_InvocationID] = outAziIncl_CS_in[gl_InvocationID];
#if USE_COLOR_PROP
    outProp_ES_in[gl_InvocationID] = outProp_CS_in[gl_InvocationID];
#endif
}
