##start
##vertex

#version 150
#extension GL_ARB_explicit_attrib_location : enable


layout(location=0) in vec3 in_Position;
layout(location=1) in vec3 in_Normal;
layout(location=2) in vec2 in_Tc;

uniform mat4 modelViewProjectionMatrix;


uniform vec3 sunDir;
uniform sampler2D diffuseTex;


out vec4 color;
out vec4 n;
out vec4 wpos;
out vec2 tex;

void main()
{

   color = vec4(1,0.1,0.1,1);


   n = vec4(in_Normal,0);

   wpos =  vec4(in_Position,0);
   gl_Position = modelViewProjectionMatrix*vec4(in_Position,1) ;
   tex = in_Tc;


}



##end

##start
##geometry
#version 150
#extension GL_EXT_geometry_shader4 : enable

layout(triangles) in;
in vec4[3] n;
in vec4[3] wpos;
in vec2[3] tex;

layout(triangle_strip, max_vertices = 3) out;

out vec4 normal;
out vec2 tc;

void main() {
    vec4 averageNormal = vec4(0,0,0,0);
//  for(int i = 0; i <  gl_VerticesIn; i++) {
//      averageNormal += n[i]; //flat shading
//  }
  averageNormal+=n[0];
  averageNormal+=n[2];
averageNormal = normalize(averageNormal);

//float left = dot( cross( vec3(averageNormal),vec3(wpos[0]-wpos[2])),vec3(n[1]));
  vec2[3] tc2;
  //if(left<0){

  if(wpos[0].y==wpos[1].y){
      //top and bottom
      if(wpos[0].z<wpos[1].z){
            //left,right,front and back
            tc2[0] = vec2(0.5,0);
            tc2[1] = vec2(0.5,1);
            tc2[2] = vec2(1,1);
        }else{
            tc2[0] = vec2(1,1);
            tc2[1] = vec2(1,0);
            tc2[2] = vec2(0.5,0);
        }
  }
  const float epsilon = 0.0001;
  const float size = 1.0/6.0;

  float offset = tex[1].y*size;

 // int id = (int)tex[1].y;
  bool bot = false;
    switch(int(tex[1].y)){
        case 2: offset=0;break;
        case 1: offset=0;bot=true;break;

        case 3: offset=1;break;
        case 5: offset=1;bot=true;break;

        case 7: offset=2;break;
        case 4: offset=2;bot=true;break;

        case 6: offset=3;break;
        case 0: offset=3;bot=true;break;
        }

    if(tex[0].x == tex[1].x  ){
        offset = (tex[1].x == 2)? 4:5;
        bot = (tex[1].y == 6 || tex[1].y == 0) ? false:true;
    }

    offset = offset*size;

  //else if(wpos[0].y<wpos[1].y){


  if( !bot){
      //left,right,front and back
      tc2[0] = vec2(offset+epsilon,0);
      tc2[1] = vec2(offset+epsilon,1);
      tc2[2] = vec2(offset+size-epsilon,1);
  }else{
      tc2[0] = vec2(offset+size-epsilon,1);
      tc2[1] = vec2(offset+size-epsilon,0);
      tc2[2] = vec2(offset+epsilon,0);
  }


  for(int i = 0; i <  gl_VerticesIn; i++) {
    gl_Position = gl_PositionIn[i];
    tc = tc2[i];
    normal = averageNormal;
    //normal = n[i];
    EmitVertex();
  }
  EndPrimitive();
}


##end

##start
##fragment

#version 150 core

in vec4 color;
in vec4 normal;
in vec2 tc;

out vec4 out_color;

uniform vec3 sunDir;
uniform vec4 sunColor;


uniform sampler2D diffuseTex;

void main(void)
{
     out_color = texture(diffuseTex,tc);
}


##end
