#version 330

uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;


layout (points) in;
layout (triangle_strip, max_vertices = 4) out;
//layout (points, max_vertices = 1) out;

in vec3 patchMin[];
in vec3 patchMax[];
in vec3 patchNormal[];
in vec3 patchColor[];

out vec3 fragmentNormal; 
out vec3 fragmentColor; 

void main ()
{
  fragmentNormal = patchNormal[0];
  fragmentColor  = patchColor[0];

  vec3 normalInViewSpace = (modelViewMatrix*vec4(fragmentNormal,0)).xyz;

  if(normalInViewSpace.z < -0.5) // just don't draw quads from back size; 
    return;

  vec3 v0 = patchMin[0];
  vec3 v2 = patchMax[0];

  vec3 dirX, dirY;
  float patchSizeX, patchSizeY;

  if(abs(fragmentNormal.x) > 1.0e-6)
  {
    dirX = vec3(0.0,0.0,1.0);
	dirY = vec3(0.0,1.0,0.0);

	patchSizeX = abs(v2.z - v0.z);
	patchSizeY = abs(v2.y - v0.y);
  }
  else if(abs(fragmentNormal.y) > 1.0e-6)
  {
    dirX = vec3(1.0,0.0,0.0);
	dirY = vec3(0.0,0.0,1.0);

	patchSizeX = abs(v2.x - v0.x);
	patchSizeY = abs(v2.z - v0.z);
  }
  else if(abs(fragmentNormal.z) > 1.0e-6)
  {
    dirX = vec3(1.0,0.0,0.0);
	dirY = vec3(0.0,1.0,0.0);

	patchSizeX = abs(v2.x - v0.x);
	patchSizeY = abs(v2.y - v0.y);
  }

  vec3 v1 = v0 + dirX*patchSizeX;
  vec3 v3 = v0 + dirY*patchSizeY;

  gl_Position = projectionMatrix*(modelViewMatrix*vec4(v0,1));
  EmitVertex();

  gl_Position = projectionMatrix*(modelViewMatrix*vec4(v1,1));
  EmitVertex();

  gl_Position = projectionMatrix*(modelViewMatrix*vec4(v3,1));
  EmitVertex();

  gl_Position = projectionMatrix*(modelViewMatrix*vec4(v2,1));
  EmitVertex();

  EndPrimitive();
  

  //gl_Position = projectionMatrix*(modelViewMatrix*vec4(0.5*patchMin[0] + patchMax[0]*0.5,1));
  //EmitVertex();
  //EndPrimitive();

}

