//=============================================================================
//// Shader uses position and texture
//=============================================================================

SamplerState samPoint
{
    Filter = MIN_MAG_MIP_POINT;
    AddressU = Mirror;
    AddressV = Mirror;
};

SamplerState samLin
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Mirror;
    AddressV = Mirror;
};

Texture2D gTexture;
Texture2D gHighlightTexture;

float gThreshold = 0.98f;
float gIntensity = 0.675f;

/// Create Depth Stencil State (ENABLE DEPTH WRITING)
DepthStencilState stencilState
{
    DepthEnable = true;
};
/// Create Rasterizer State (Backface culling) 
RasterizerState backCulling
{
    CullMode = BACK;
};

//IN/OUT STRUCTS
//--------------
struct VS_INPUT
{
    float3 Position : POSITION;
    float2 TexCoord : TEXCOORD0;

};

struct PS_INPUT
{
    float4 Position : SV_POSITION;
    float2 TexCoord : TEXCOORD1;
};


//VERTEX SHADER
//-------------
PS_INPUT VS(VS_INPUT input)
{
    PS_INPUT output = (PS_INPUT) 0;
    output.Position = float4(input.Position.xy, 0, 1);
    output.TexCoord = input.TexCoord;
    
    return output;
}

//PIXEL SHADER
//------------
float4 PS_BrightFilter(PS_INPUT input) : SV_Target
{
    float3 color = gTexture.Sample(samPoint, input.TexCoord);
    float brightness = (0.3f * color.r) + (0.59f * color.g) + (0.11f * color.b);
    return float4(color.rgb * brightness * brightness * brightness, 1);
}

float4 PS_BrightFilterCutOff(PS_INPUT input) :SV_Target
{
    float3 color = gTexture.Sample(samPoint, input.TexCoord);
    float brightness = (0.3f * color.r) + (0.59f * color.g) + (0.11f * color.b);
    //if(brightness > gThreshold)
    if(color.r > gThreshold || color.g > gThreshold || color.b > gThreshold)
        return float4(color.rgb, 1);
    else
        return float4(0, 0, 0, 1);

}

float4 PS_CombineBloom(PS_INPUT input) : SV_Target
{
    float4 scene = gTexture.Sample(samPoint, input.TexCoord);
    float4 highlight = gHighlightTexture.Sample(samLin, input.TexCoord);
    
    // make color go towards white if it's really intense
    float3 sceneColor = (scene + highlight * gIntensity).rgb;
    //float3 colorOffset = clamp(sceneColor - 1, 0, 100000);
    //sceneColor += max(max(colorOffset.r, colorOffset.g), colorOffset.b);
    return float4(sceneColor.rgb, 1);
}


//TECHNIQUE
//---------
technique11 BrightFilter
{
    pass P0
    {
        SetVertexShader(CompileShader(vs_4_0, VS()));
        SetGeometryShader(NULL);
        SetPixelShader(CompileShader(ps_4_0, PS_BrightFilterCutOff()));

        SetRasterizerState(backCulling);
        SetDepthStencilState(stencilState, 0);
    }
}

technique11 CombineBloom
{
    pass P0
    {
        SetVertexShader(CompileShader(vs_4_0, VS()));
        SetGeometryShader(NULL);
        SetPixelShader(CompileShader(ps_4_0, PS_CombineBloom()));

        SetRasterizerState(backCulling);
        SetDepthStencilState(stencilState, 0);
    }
}
