/**
 * Copyright (C) 2013 Stellar Jockeys.
 * All Rights Reserved.
 *
 * NOTICE: All information contained herein is, and remains the property of
 * Stellar Jockeys and its suppliers, if any.  The intellectual and technical
 * concepts contained herein are proprietary to Stellar Jockeys and its suppliers.
 * Dissemination of this information or reproduction of this material is
 * strictly forbidden unless prior written permission is obtained from
 * Stellar Jockeys.
 *
 * @file fragdeferred.glsl
 * @author Harry Hsiao
 * @date 01/22/2013
 */
#ifndef FRAGDEFERRED_GLSL
#define FRAGDEFERRED_GLSL

#ifndef FRAGCOLORSHIFT_GLSL
#error fragcolorshift.glsl should also be included
#endif

#ifndef CONVERSIONS_GLSL
#error conversions.glsl should also be included
#endif

#ifndef CONSTANTS_GLSL
#error constants.glsl should also be included
#endif

#ifndef FRAGMATERIAL_GLSL
#error fragmaterial.glsl should also be included
#endif

#ifndef FRAGNORMAL_GLSL
#error fragnormal.glsl should also be included
#endif

void main()
{
    float depth = texture2D(uDepth, vTextureCoord).r;

    if (depth < (1.0 / 255.0))
    {
        discard;
    }

    gl_FragDepth = AdjustedDepth(gl_FragCoord.z, depth, uDepthConversion);

    vec2 tapDelta = uTapDelta;
    float mirrored = clamp(floor(dFdx(vTextureCoord.x)), -1.0, 0.0) * 2.0 + 1.0;
    tapDelta.x *= mirrored;

#ifdef LOW_GRAPHICS
    vec3 normal = DeriveNormalLow(vTextureCoord, depth, tapDelta, PPD_SRC, uDepth);
#else
    vec3 normal = DeriveNormal(vTextureCoord, depth, tapDelta, PPD_SRC, uDepth);
#endif

    vec4 normalColor = vec4(NormalToColor(normal), 1.0);
    gl_FragData[2] = normalColor;

    vec4 color = texture2D(uTexture, vTextureCoord);
    color = ShiftColor(vColorShift, color);

#ifdef CAMO_EFFECT
    vec3 up = vec3(0.36, 0.48, 0.80);
    up *= step(0.0, vOpacitySweep) * 2.0 - 1.0;
    float margin = 0.125;
    float upper = abs(vOpacitySweep) * (2.0 + margin) - 1.0;
    float opacity_progress = clamp((upper - dot(normal, up)) / margin, 0.0, 1.0);
    float opacity = mix(vOpacity, 1.0, opacity_progress);
    float normalizedOpacity = clamp((opacity - uOpacityMinimum) / (1.0 - uOpacityMinimum), 0.0, 1.0);
    color.a *= opacity;

    float chromaticAberration = mix(uOpacityChromaticAberration, 0.0, normalizedOpacity);
    float diffuseDimming = 1.0 - mix(uOpacityDiffuseDimming, 0.0, normalizedOpacity);
    color.rgb = mix(color.rgb, normalColor.rgb, chromaticAberration);
    color.rgb *= diffuseDimming;

    gl_FragData[1] = vMaterial * vec4(normalizedOpacity, normalizedOpacity, 1.0, 1.0);
#else
    gl_FragData[1] = vMaterial;
#endif

    gl_FragData[0] = color;
}

#endif
