#version 420 core
// UNIFORM BLOCK

#define WELL_GL_PATCH_SIZE  16

layout(vertices = WELL_GL_PATCH_SIZE) out;


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

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

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

float
CalcTessSizeVertical(vec3 cPosIn, float rRadius)
{
  float
    rDist = gl_ModelViewProjectionMatrix[0][3] * cPosIn.x +
            gl_ModelViewProjectionMatrix[1][3] * cPosIn.y + 
            gl_ModelViewProjectionMatrix[2][3] * cPosIn.z + 
            gl_ModelViewProjectionMatrix[3][3];

  float
    rPixelUnit = projInfoY * -rDist;

  float rPixels = rRadius / rPixelUnit;

  if (rPixels < 1.0) rPixels = 1.0;
  else if (rPixels > float(WELL_GL_PATCH_SIZE - 1)) rPixels = float(WELL_GL_PATCH_SIZE - 1);
 
  return rPixels;
}

void main(void)
{
  if (gl_InvocationID == 0)
  {
      // vertical tesselation
    float
      rRadius = length((outpos_CS_in[WELL_GL_PATCH_SIZE - 1].xyz - outpos_CS_in[0].xyz) / cSceneScale);

    float
      rTessSizeVertical = CalcTessSizeVertical(outpos_CS_in[WELL_GL_PATCH_SIZE / 2].xyz, rRadius);

    gl_TessLevelOuter[0] = rTessSizeVertical;
    gl_TessLevelOuter[2] = rTessSizeVertical;
    gl_TessLevelInner[1] = rTessSizeVertical;

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

  outpos_ES_in[gl_InvocationID] = outpos_CS_in[gl_InvocationID];
  outAziIncl_ES_in[gl_InvocationID] = outAziIncl_CS_in[gl_InvocationID];
}
