/***********************************************/
/*           Copyright (c) 2025 Belmu          */
/*             All Rights Reserved             */
/***********************************************/

layout (local_size_x = 8, local_size_y = 4, local_size_z = 1) in;

const vec2 workGroupsRender = vec2(1.0, 1.0);

layout (rgba32f) uniform image2D colorimg1;

#include "/settings.glsl"
#include "/include/common.glsl"

void main() {
    ivec2 fragCoords = ivec2(gl_GlobalInvocationID.xy);
    if (fragCoords.x > viewWidth || fragCoords.y > viewHeight) return;

    vec4 radianceOut = texelFetch(MAIN_BUFFER, fragCoords, 0);

    #if DEBUG_ALBEDO == 0 && DEBUG_NORMALS == 0 && DEBUG_HIT_POSITION == 0

        vec4 history  = texelFetch(RADIANCE_HISTORY_BUFFER, fragCoords, 0);
             history *= float(hideGUI);

        radianceOut.a = history.a + 1;

        float weight = saturate(1.0 / max(radianceOut.a, 1.0));

        #if CHECKERBOARD_RENDERING == 1
            ivec2 coords   = ivec2(fragCoords / int(viewWidth * 0.1));
            bool canRender = (coords.x + coords.y & 1) == (frameCounter & 1);
            
            weight *= float(canRender);
        #endif

        radianceOut.rgb = mix(history.rgb, radianceOut.rgb, weight);

    #endif

    imageStore(colorimg1, ivec2(gl_GlobalInvocationID.xy), radianceOut);
}
