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

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

    int tid = pid;

    ivec4 tvids = imageLoad(mesherTriangles, uvs);

    int triOfs, triCount=0;

    triOfs = imageLoad(mesherVertTriOfs, getTrip(tvids.x+1)).x;
    triCount = imageAtomicAdd(mesherVertTriCounts, getTrip(tvids.x), 1);
    imageStore(mesherVertTriMap, getTrip(triOfs+triCount), ivec4(tid));

    triOfs = imageLoad(mesherVertTriOfs, getTrip(tvids.y+1)).x;
    triCount = imageAtomicAdd(mesherVertTriCounts, getTrip(tvids.y), 1);
    imageStore(mesherVertTriMap, getTrip(triOfs+triCount), ivec4(tid));

    triOfs = imageLoad(mesherVertTriOfs, getTrip(tvids.z+1)).x;
    triCount = imageAtomicAdd(mesherVertTriCounts, getTrip(tvids.z), 1);
    imageStore(mesherVertTriMap, getTrip(triOfs+triCount), ivec4(tid));

    discard;

    screen.a = 1.0;
    frag = screen;


}
