//
// Copyright (C) 2012 ANSYS, Inc. and its subsidiaries.  All Rights Reserved.
//
// Sub and average the colors and output.
//
// Author: vpatel
//

uniform sampler2D FragAccumTex;
uniform sampler2D FragCountTex;
uniform sampler2D BackgroundTex;

// This is the average color, which works reasonably well.
// gl_FragColor.xyz = (fragCount <= 0.0) ? BackgroundColor.xyz : fragSum.xyz/fragCount;

#pragma include("lib/RenderPass/OutputFragment.frag.glsl")

void main(void)
{
    FRAGDATA frag = InitFragData();

    vec4 fragSum = texture2D(FragAccumTex, gl_TexCoord[0].xy);
    float fragCount = texture2D(FragCountTex, gl_TexCoord[0].xy).a;
    vec4 backgroundColor = texture2D(BackgroundTex, gl_TexCoord[0].xy);

    if (fragCount != 0.0)
    {
        vec4 average = vec4(fragSum.rgb / fragSum.a, fragSum.a / fragCount);
        float t = pow(1.0 - average.a, fragCount);
        vec4 color = vec4((average.rgb * (1.0 - t)) + (backgroundColor.xyz * t), 1.0);

        SetColor( frag, color );
    }
    else
    {
        SetColor( frag, backgroundColor );
    }

    OutputFragment( frag );
}
