#include "../DeathScreen.hls"
#include "../MipLevels.hls"
#include "../FogOfWar/FogOfWar_PS.hls"
#include "../Transition/Transition.hls"

// Diffuse map
sampler DIFFUSE_MAP :           register (s0);
sampler NOISE_TEXTURE : register (s2);
sampler ALT_DIFFUSE_TEXTURE : register(s3);
sampler SCROLL_DIRECTION_MASK_TEXTURE : register(s4);
float4 MaskInfo; // xy = scale  z = bias   w = pow
float4 DebugColor;
float TIME;

#if EMISSIVE
// Funky emissive map which contains diffuse/emissive slider and team color mask
sampler EMISSIVE_MAP :          register (s1);
#endif

// Shadow map
sampler	SHADOW_MAP	:			register (s5);

#ifdef MOD2X_COLORMAP
sampler COLORMAP    : register (s8);
#endif
#ifdef FOG_PIXELSHADER_BLEND
sampler FOGLIGHTING : register(s9);
#endif

// Highlight the character when selected
float4 kGrassFade : register(c23);

// Ambient color
float4  AMBIENT_COLOR  :        register(c21);

// Self illumination value
float3 SELF_ILLUMINATION : register(c24);

float4 DEPTH_SCALE_OFFSET : register(c25);

float4 CAMERA_POSITION : register(c26);

float4 OUTLINE_MOD : register(c27);

#include "../ShadowMap/pcf1.hls"

struct FRAGMENT
{
    float4  m_Color0 : COLOR0;
#ifdef MRT_SUPPORTED
    float4  m_Color1 : COLOR1;
#endif
};


///////////////////////////////////////////////////////////////////////////////////////
///
///
///
///////////////////////////////////////////////////////////////////////////////////////
FRAGMENT
    main
    (
    #if defined(FOG_PIXELSHADER_BLEND)
        float4  uv1 :           TEXCOORD0, 
    #else
        float2  uv1 :           TEXCOORD0, 
    #endif
        float4  Pos1 :          TEXCOORD1,
        float4  in_texcoord4 :  TEXCOORD2,
#ifndef DISABLE_SHADOWS
        float3  uvSM :          TEXCOORD3, 
#endif
#if  SEPARATE_ALPHA_UV
        float2  alphaUV:        TEXCOORD4,
#endif
        float2  vTexOutNonScroll : TEXCOORD5,
        float4  sunColor :      COLOR0,
        float4  envColor :      COLOR1
    )
{    
    // Incident sun light
#ifndef USE_LIGHT_GRID
        float4 incidentSunLight = sunColor;

    #ifndef DISABLE_SHADOWS
        // Modulate the incident sun light by the shadow
        int shadowSamples = 1;
        
        float shadowMask = saturate(SampleShadowMap(SHADOW_MAP, uvSM)+0.4f);
        incidentSunLight *= shadowMask;
    #endif

        // Sum the incident sun light with contributions from environmental and ambient
        float4 incidentLight = incidentSunLight + envColor * 4 + AMBIENT_COLOR;
#else
    float4 incidentLight = envColor;
#endif

// Read the diffuse texture
float4 baseDiffuse = tex2D(DIFFUSE_MAP, vTexOutNonScroll.xy);
float baseDiffuseAlpha = baseDiffuse.a;
baseDiffuse.a = 1.0f;

//Read the Bottom Layer Texture
float4 scrollMask = tex2D(SCROLL_DIRECTION_MASK_TEXTURE, vTexOutNonScroll.xy);
float4 noiseDiffuse = tex2D(NOISE_TEXTURE, uv1.xy * MaskInfo.xy);
float4 mask1Scroll = tex2D(NOISE_TEXTURE, in_texcoord4.zw * MaskInfo.xy);
float4 mask2Scroll = tex2D(NOISE_TEXTURE, (-1 *in_texcoord4.zw) * MaskInfo.xy);
//Read the Top Layer Texture
float4 topDiffuse = tex2D(ALT_DIFFUSE_TEXTURE, vTexOutNonScroll.xy);
//blend the base and the bottom diffuse textures while respecting if the bottom texture has it's own alpha
float4 baseBlend = lerp(baseDiffuse, DebugColor, clamp(baseDiffuseAlpha, 0.0f,1.0f));

#if EMISSIVE
    // Read emissive texture which contains emissive/diffuse factor
    #if EMISSIVE_USES_SECOND_LAYER
        float4 texelEmissive = tex2D(EMISSIVE_MAP, in_texcoord4.zw);
        // if we're using emissive from the 2nd layer, we also need to
        // mask it via the alpha channel of the diffuse.
        texelEmissive *= (1.0f - baseDiffuseAlpha);
    #else
        float4 texelEmissive = tex2D(EMISSIVE_MAP, uv1.xy);
    #endif

    float emissiveFactor = texelEmissive.g;                 /// Amount of color which is emissive
    float diffuseFactor = saturate(1.f - emissiveFactor);   /// Amount of color which is diffuse
#else
    float emissiveFactor = 1.0f;
    float diffuseFactor = 0.0f;
#endif

    //final color from diffuse pass BASIC
    //baseDiffuse.rgb = lerp(baseDiffuse, DebugColor, bottomDiffuse.b, MaskInfo.z,0.2,0.4));   
    //baseDiffuse.rgb = DebugColor * noiseDiffuse.b * scrollMask.r;
    //baseDiffuse.rgb = lerp(baseDiffuse, DebugColor, saturate(noiseDiffuse.g)*scrollMask.r);
    //baseDiffuse = lerp(baseDiffuse, DebugColor, saturate(mask1Scroll.g)*scrollMask.g);
    //baseDiffuse = lerp(baseDiffuse, DebugColor, saturate(mask2Scroll.g)*scrollMask.b);

    baseDiffuse.rgb = lerp(baseDiffuse, topDiffuse, saturate(noiseDiffuse.r)*scrollMask.r);
    baseDiffuse = lerp(baseDiffuse, topDiffuse, saturate(mask1Scroll.r)*scrollMask.g);
    baseDiffuse = lerp(baseDiffuse, topDiffuse, saturate(mask2Scroll.r)*scrollMask.b);

#if SEPARATE_ALPHA_UV
    baseDiffuse.a = tex2D(DIFFUSE_MAP, alphaUV).a;
#endif

#if defined(FULLBRIGHT) //handle the fullbright debug visualization.
    float4 lighting = 1.0f;
#elif defined(USE_LIGHT_GRID)
    //lighting
    #if defined(SHOW_LIGHTING)
        float lightScale = 1.0f;
    #else
        float lightScale = 4.0f * sunColor.b;
    #endif
    float4 lighting = saturate(diffuseFactor * incidentLight * lightScale + emissiveFactor + sunColor.a*float4(SELF_ILLUMINATION, 0.f));
#else
    float4 lighting = saturate(diffuseFactor * incidentLight + emissiveFactor + float4(SELF_ILLUMINATION, 0.f));
#endif

    // Compute albedo color using a combination of diffuse and emissive values
    float4 albedoColor = baseDiffuse * lighting;

    // Calculate final color
    float4 finalColor = saturate(albedoColor);
    finalColor.a = baseDiffuse.a;

    finalColor = ApplyTransition(finalColor, lighting.rgb, vTexOutNonScroll.xy);
    finalColor.a *=  kGrassFade.a; // apply any global alpha factor (e.g., the fading associated with being in the grass)

#if !defined(DISABLE_FOW) && !defined(FULLBRIGHT)
    float4 fowFactors = GetFogOfWarFactors(in_texcoord4.xy);
    finalColor.rgb = lerp(fowFactors.rgb, finalColor.rgb, fowFactors.a);
#endif

//Note: if texture transition is enabled then too many instructions are used if combined with height fog.
//So fog is disabled during texture transitions.
#if defined(FOG_PIXELSHADER_BLEND) && !defined(FULLBRIGHT)
    //modify the fog color based on the fog of war...
    float4 fogColor = tex2D(FOGLIGHTING, in_texcoord4.xy);
    #ifndef DISABLE_FOW
        fogColor = lerp(fowFactors, fogColor, fowFactors.a);
    #endif
    float fogOpacity = envColor.a;
    #ifdef MOD2X_COLORMAP
        float colorMapOpacity = tex2D(COLORMAP, uv1.zw).a;
        fogOpacity = saturate( fogOpacity*colorMapOpacity*2.0f );
    #endif

    finalColor.rgb = lerp( finalColor, fogColor, fogOpacity );
#endif
    
    float3 delta = CAMERA_POSITION.xyz - Pos1.xyz;
    float dist = DEPTH_SCALE_OFFSET.x * (length(delta) + DEPTH_SCALE_OFFSET.y); 
    float4 out_color1 = float4(dist*OUTLINE_MOD.x, OUTLINE_MOD.x, 0.f, 1.f);
    
    //  This has the effect of thinning and lightening the outline as the fog gets more opaque.
    //However the outline never completely disappears, which is desirable in order to make 
    //characters easier to see even in foggy conditions.
    //  In this way the outline can be affected by the fog (it looks terrible otherwise) but 
    //without effecting the outline pass or drastically effecting performance.
#if defined(FOG_PIXELSHADER_BLEND) && !defined(FULLBRIGHT)
    out_color1.xy = lerp(out_color1.xy, 4.0f, fogOpacity);
#endif

    // Return fragment
    FRAGMENT fragment;
    fragment.m_Color0 = finalColor;
    #ifdef MRT_SUPPORTED
        fragment.m_Color1 = out_color1;
    #endif
    
    //Editor / Debugging features.
    #if defined(SHOW_LIGHTING)
        #if defined(USE_LIGHT_GRID)
            fragment.m_Color0.rgb = lighting;
        #else
            fragment.m_Color0.rgb = lighting*0.25f;
        #endif
    #elif defined(GRAYSCALE)
        float3 LUMINANCE_CONVERSION = float3(0.299f, 0.587f, 0.114f);
        fragment.m_Color0.rgb = dot( fragment.m_Color0.rgb, LUMINANCE_CONVERSION );
    #endif

    fragment.m_Color0.rgb = ApplyMipColorsVisualization(fragment.m_Color0.rgb, uv1.xy);
    return fragment;
}
