#version 430

in vec2 uv;

layout(location = 0) out vec4 frag;

uniform float g_time;


uniform float dispSmooth = 0.0;

layout(binding=0, rgba32f) uniform image2D pardexPos;
layout(binding=1, r32i) uniform iimage2D pardexBucketCounts;
//layout(binding=2, rgba32f) uniform image2D pardexBucketCountsRGB;


uniform float div = 1.0;

uniform float scaleX = 100.0;
uniform float scaleY = 100.0;
uniform float scaleZ = 30.0;

uniform float partNum = 0.0;


uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;


ivec2 getTrip(int idt) {
    ivec2 triBufSize = imageSize(pardexBucketCounts);
    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(pardexPos)/2;

    int divi = int(div);
    int pid = uvs.x+uvs.y*triBufSize.x;

    if (pid >= partNum) { discard; return; }


    vec4 vp = imageLoad(pardexPos, uvs);

    vp = viewMatrix*vec4(vp.xyz, 1.0);

  //  vp = projectionMatrix*vp;
  //  vp.xyz /= vp.w;

    float minZ = 0.0;
    float maxZ = 1200.0;

    float dz = 1.0-(-vp.z-minZ)/(maxZ-minZ);

    dz = clamp(dz, 0.0, 1.0);
    dz *= (1024.0*1024-1.0);

    dz = clamp(dz, 0.0, 1024.0*1024.0-1.0);

    ivec2 db = getTrip(int(dz));
    int bc = imageAtomicAdd(pardexBucketCounts, db, 1);

 //   imageStore(pardexBucketCountsRGB, db, vec4(bc+1)*0.5);
//    imageStore(pardexBucketCountsRGB, db, vec4(0.75));

    discard;

    screen.a = 1.0;
    frag = screen;


}
