#version 430

// layout (location=0) in vec3 vertexPosition;

out vec2 uv;

out float br;

uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
uniform mat4 projectionInvMatrix;
uniform float g_windowWidth;
uniform float g_windowHeight;

uniform float g_time;

uniform float size = 32.0;
uniform float rot;

vec2 rot2(vec2 p, float a) {
  vec2 r = p;
  r.x = cos(a)*p.x - sin(a)*p.y;
  r.y = sin(a)*p.x + cos(a)*p.y;
  return r;
}

float zn = 0.0;
float zf = 1.0;


layout(binding=0, offset=0) uniform atomic_uint ac;

vec4 CalcEyeFromWindow(in vec3 windowSpace) {
    vec3 ndcPos;
    vec4 viewport = vec4(0.0, 0.0, g_windowWidth, g_windowHeight);
    ndcPos.xy = ((2.0 * windowSpace.xy) - (2.0 * viewport.xy)) / (viewport.zw) - 1;
    ndcPos.z = (2.0 * windowSpace.z - zn - zf) / (zf - zn);
    vec4 clipPos;
    clipPos.w = projectionMatrix[3][2]/(ndcPos.z-(projectionMatrix[2][2]/projectionMatrix[2][3]));
    clipPos.xyz = ndcPos * clipPos.w;
    return projectionInvMatrix * clipPos;
}


void main() {
  vec4 vp = vec4(0.0);

  float id = float(gl_VertexID);

  float id3 = fract(id/3.0)*3.0; // index of the vertex in a triangle 0,1,2
  float idv = floor((id/3.0-fract(id/3.0))+0.5); // triangle index 0,1,2,3,...
  float idv2 = fract(idv/2.0)*2.0; // every second triangle 0 and 1
  float idq = floor((id/6.0-fract(id/6.0))+0.5); // quad index 0,1,2,3,...

  if (idv2 < 0.5) {
      if (id3 < 0.50) {
          vp = vec4(0.0, 0.0, 0.0, 1.0);
      } else if (id3 < 1.5) {
          vp = vec4(1.0, 0.0, 0.0, 1.0);
      } else if (id3 < 2.5) {
          vp = vec4(0.0, 1.0, 0.0, 1.0);
      }
  } else {
      if (id3 < 0.50) {
          vp = vec4(1.0, 0.0, 0.0, 1.0);
      } else if (id3 < 1.5) {
          vp = vec4(1.0, 1.0, 0.0, 1.0);
      } else if (id3 < 2.5) {
          vp = vec4(0.0, 1.0, 0.0, 1.0);
      }
  }
  vp.xy -= vec2(0.50);
  vp.xyz *= 2.0;
  vp.y *= 16.0/9.0;
  vp.x *= size/1280.0;
  vp.x *= 2.0;
  vp.y *= size/1280.0*1.03;

  float perRow = floor(1280.0/size)+0.0;

 // vp.xz = rotateXY2(vp.xz, rot);

  float px = fract(idq/(perRow))+0.5/perRow;
  float py = (floor(idq/(perRow))+0.5)/(floor(720.0/size)+0.0);

  vp.x += (px-0.50)*2.0;
  vp.y += (py-0.50)*2.0;


  uv = vp.xy*0.5+vec2(0.5);

  //vp *= 0.0;

  vp.z = 0.50;

  vec3 vpc;
  vpc.x = (px-0.50)*2.0;
  vpc.y = (py-0.50)*2.0;
  vpc.z = vp.z;

  vp.xy = (vp.xy+vec2(1.0))*0.5;
  vp.xy *= vec2(g_windowWidth, g_windowHeight);

  vpc.xy = (vpc.xy+vec2(1.0))*0.5;
  vpc.xy *= vec2(g_windowWidth, g_windowHeight);


  vec4 vp3d = CalcEyeFromWindow(vp.xyz);
  vec4 vp3dc = CalcEyeFromWindow(vpc.xyz);

  vp3d.xz = rot2(vp3d.xz-vp3dc.xz, rot)+vp3dc.xz;

  vp = projectionMatrix*vec4(vp3d.xyz, 1.0);

//  vp = vp3d;

  vp /= vp.w;

 // vp.x += idv*0.11;
 // vp.x += sin(idq*0.1);
 // vp.y += cos(idq*0.112);

 // uint counter = atomicCounterIncrement(ac);

 // br = float(counter)*0.0001;
  br = 1.0;

  gl_Position = vp;
 // uv = vec2(0.0);
}
