#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=1, offset=0) uniform atomic_uint ac;

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-1;

    if (pid < 0) {
        discard;
        return;
    }

    ivec2 trip = getTrip(pid);

    int triCount = imageLoad(mesherVertTriCounts, trip).x;
    triCount = min(triCount, 16);
    //int triOfs = imageAtomicAdd(mesherVertTriOfs, ivec2(0, 0), triCount).x;
    //imageStore(mesherVertTriOfs, uvs, ivec4(triOfs));
    imageStore(mesherVertTriOfs, uvs, ivec4(pid*8));

    discard;

    screen.a = 1.0;
    frag = screen;


}
