//--------------------------------------------------------------------------------------
// File: FinalPass.hlsl
//
// The PSs for doing tone-mapping based on the input luminance, used in CS path of 
// HDRToneMappingCS11 sample
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------

struct QuadVS_Output
{
    float4 Pos : SV_POSITION;              
    float2 Tex : TEXCOORD0;
};

Texture2D<float4> tex : register( t0 );
StructuredBuffer<float> lum : register( t1 );
Texture2D<float4> bloom : register( t2 );

SamplerState PointSampler : register (s0);
SamplerState LinearSampler : register (s1);


static const float  MIDDLE_GRAY = 0.5f;
static const float  LUM_WHITE = 1.5f;
static const float FUDGE = 0.001;
// The per-color weighting to be used for luminance calculations in RGB order.
static const float3 LUMINANCE_VECTOR  = float3(0.2125f, 0.7154f, 0.0721f);

// The per-color weighting to be used for blue shift under low light.
static const float3 BLUE_SHIFT_VECTOR = float3(1.05f, 0.97f, 1.27f); 

cbuffer cbPS : register( b0 )
{
    float4    g_param;   
};

float4 toneMap(float4 inColour, float lum)
{	
	// Initial luminence scaling (equation 2)
    inColour.rgb *= MIDDLE_GRAY / (FUDGE + lum);

	// Control white out (equation 4 nom)
    inColour.rgb *= (1.0 + inColour.rgb / LUM_WHITE);

	// Final mapping (equation 4 denom)
	inColour.rgb /= (1.0 + inColour.rgb);
	
	return inColour;
}

float4 HDRFragmentShader( QuadVS_Output Input ) : SV_TARGET
{
/*    float4 vColor = tex.Sample( PointSampler, Input.Tex );
    float fLum = lum[0]*g_param.x*2;
    float3 vBloom = bloom.Sample( LinearSampler, Input.Tex );
	vBloom = 0.0f;

    // Tone mapping
    vColor.rgb *= MIDDLE_GRAY / (fLum + 0.001f);
    vColor.rgb *= (1.0f + vColor/LUM_WHITE);
    vColor.rgb /= (1.0f + vColor);
    
    vColor.rgb += 0.6f * vBloom;
    vColor.a = 1.0f;
    return vColor;*/
	
	// Get main scene colour
    float4 vColor = tex.Sample( PointSampler, Input.Tex );

	// Get luminence value
	float fLum = lum[0]*g_param.x;

	// Define a linear blending from -1.5 to 2.6 (log scale) which
	// determines the lerp amount for blue shift
    float fBlueShiftCoefficient = 1.0f - (fLum + 1.5)/4.1;
    fBlueShiftCoefficient = saturate(fBlueShiftCoefficient);

	// Lerp between current color and blue, desaturated copy
    float3 vRodColor = dot( (float3)vColor, LUMINANCE_VECTOR ) * BLUE_SHIFT_VECTOR;
    vColor.rgb = lerp( (float3)vColor, vRodColor, fBlueShiftCoefficient );

	// tone map this
	float4 toneMappedSceneCol = toneMap(vColor, fLum);
	
	// Get bloom colour
    float4 bloom = float4(0.0, 0.0, 0.0, 0.0);//tex2D(inBloom, uv);

	// Add scene & bloom
	return float4(toneMappedSceneCol.rgb + bloom.rgb, 1.0f);
}