#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 mesherVertNorm;
layout(binding=3, r32i) uniform iimage2D mesherVertTriCounts;
layout(binding=4, r32i) uniform iimage2D mesherVertTriOfs;
layout(binding=5, r32i) uniform iimage2D mesherVertTriMap;

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;

    int trc = imageLoad(mesherVertTriCounts, uvs).x;
    int tro = imageLoad(mesherVertTriOfs, getTrip(pid+1)).x;

    vec3 n = vec3(0.0);

    trc = min(trc, 8);

  //  int tri = imageLoad(mesherVertTriMap, getTrip(tro+0)).x;

    for (int i=0; i<trc; i++) {
        int tri = imageLoad(mesherVertTriMap, getTrip(tro+i)).x;
     //   ivec4 tvids = imageLoad(mesherTriangles, getTrip(tri));
        ivec4 tvids = imageLoad(mesherTriangles, getTrip(pid));

        vec3 va = imageLoad(mesherVertPos, getTrip(tvids.x)).xyz;
        vec3 vb = imageLoad(mesherVertPos, getTrip(tvids.y)).xyz;
        vec3 vc = imageLoad(mesherVertPos, getTrip(tvids.z)).xyz;

        vec3 d1 = vb-va;
        vec3 d2 = vc-va;

        n += cross(d1,d2);

       // n = vec3(tvids.xyz);
    }

    n = normalize(n);
/*
    if (trc == 3) {
        n = vec3(1.0, 0.0, 0.0);
    } else {
        n = vec3(0.0, 1.0, 0.0);
    }
    n = vec3(tro)/5000000.0;
*/
  //  n = vec3(tri)*0.0000001;

    ivec4 tvids = imageLoad(mesherTriangles, getTrip(pid));

 //   n = vec3(tvids.xyz)/1000000.0;

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

//    while (true) {

//        if ((tia == -1) || (tia==tid)) break;
//    }

    discard;

    screen.a = 1.0;
    frag = screen;


}
