#version 430

in vec2 uv;

layout(location = 0) out vec4 frag;

uniform float g_time;


layout(binding=0, rgba32i) uniform iimage2D mesherTriangles;
layout(binding=1, rgba32f) uniform image2D mesherVertPos;
layout(binding=2, rgba32f) uniform image2D mesherTriNorm;
layout(binding=3, rgba32i) uniform iimage2D mesherTriAdjLeft;
layout(binding=4, rgba32i) uniform iimage2D mesherTriAdjRight;
layout(binding=5, rgba32f) uniform image2D mesherVertNorm;
layout(binding=6, r32i) uniform iimage2D mesherVertPriTri;

uniform float div = 1.0;


ivec2 getTrip(int idt) {
    ivec2 triBufSize = imageSize(mesherTriangles);
    ivec2 trip;
    trip.y = idt/triBufSize.x;
    trip.x = idt-trip.y*triBufSize.x;
   // trip.y = 0;
    return trip;
}

void main() {
    ivec2 uvs = ivec2(gl_FragCoord.xy);

    vec4 screen = vec4(0.0);

    ivec2 triBufSize = imageSize(mesherTriangles);

    int divi = int(div);

    int pid = uvs.x+uvs.y*triBufSize.x;

    if (pid > (divi+1)*(divi+1)) {
        discard; return;
    }


    vec3 norm = vec3(0.0);

    int idt = imageLoad(mesherVertPriTri, uvs).x;
    int idTri = idt;
    int vi = pid;
    norm = imageLoad(mesherTriNorm, getTrip(idTri)).xyz;

    bool lookRight = false;

    ivec4 adj = ivec4(0);
    int i = 0;

    while (true) {
      if (lookRight) {
          adj = imageLoad(mesherTriAdjRight, getTrip(idTri));
      } else {
          adj = imageLoad(mesherTriAdjLeft, getTrip(idTri));
      }
      ivec4 triVerts = imageLoad(mesherTriangles, getTrip(idTri));
      if (triVerts.x == vi) {
          idTri = adj.x;
      } else if (triVerts.y == vi) {
          idTri = adj.y;
      } else if (triVerts.z == vi) {
          idTri = adj.z;
      } else {
          idTri = -1;
          break;
      }
      i++;
      if (idTri == -1 && !lookRight) {
          lookRight = true;
          idTri = idt;
          continue;
      }
      if (i>16 || (idTri == idt) || (idTri == -1)) break;
      norm += imageLoad(mesherTriNorm, getTrip(idTri)).xyz;
    }

    norm = normalize(norm);

    imageStore(mesherVertNorm, uvs, vec4(norm, 0.0));


    discard;

    screen.a = 1.0;
    frag = screen;


}
