#include "../DeathScreen.hls"
#include "../MipLevels.hls"
#include "../FogOfWar/FogOfWar_PS.hls"
#include "../Transition/Transition.hls"

// Diffuse map = Base color/texture for a model
sampler DIFFUSE_MAP :           register (s0);
//Material map  | Red = metalness  | Green = Roughness  |  Blue = Spec Intensity | alpha  = not currently used
sampler MATERIAL_MAP : register(s2);
//Specular Color Map  |  Called reflection map so that it's easy to understand when using legacy content
sampler REFLECTION_MAP : register (s4);

#if EMISSIVE
// Funky emissive map which contains diffuse/emissive slider and team color mask
sampler EMISSIVE_MAP :          register (s1);
#endif
sampler ENVIRONMENT_MAP : register (s3);

float4   vCamera;

float4 SpecInfo; // x= Min Spec Value | y= Max Spec Value | z = Environment intensity | w = Lambert Bias
float4 RimLightColor; // xyz = Rim Lighting Color | w = Influence Bias 
float4 SunLightColor;
float4 SpecularColor;// xyz = Specular Highlight Color | w = Influence Bias
float4 RimLightDir; // xyz = This is an additional offset for a "secondary light" to simulate rim lighting on the characters. | w = refelection map multiplier
float4 SunLightDir;

float TIME;
float4 DebugValues; // x = HALF_AND_HALF_MODE screen slider

// 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
#if HALF_AND_HALF_MODE
    float4        clipSpacePos : TEXCOORD6,
#endif
        float3 inWorldNormal : 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

#if EMISSIVE
    // Read emissive texture which contains emissive/diffuse factor
    float4 texelEmissive = tex2D(EMISSIVE_MAP, uv1.xy);
    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

#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

// no lighting

//===============================================================
//  BEGIN 
//      League Lighting Model
//===============================================================
//******************************************
//  Created by Cody Adams | 04/2017 |
//  League of Legends (Riot Games LAX) 
//******************************************

    // Sample DIFFUSE_MAP
    float4 texelDiffuse = tex2D( DIFFUSE_MAP, uv1.xy );

#if SEPARATE_ALPHA_UV
    texelDiffuse.a = tex2D( DIFFUSE_MAP, alphaUV ).a;
#endif
    
    // Compute albedo color using a combination of diffuse and emissive values
    float4 oldAlbedoColor = texelDiffuse * lighting;

    //Camera & "Lighting"
    float3 eyeRay = normalize( vCamera.xyz - Pos1 );
    float3 lightRay = normalize( vCamera.xyz - Pos1 );

    //Vertex Normals
    float3 worldNormal = inWorldNormal;
    worldNormal = normalize( worldNormal );

    //Rim Lighting
    float rim = -1.0f * max( dot( lightRay + RimLightDir, worldNormal ), -2.0f ) * RimLightColor.w;// inverted Lambertian + offset for lights
    float4 rimLighting = saturate( rim ) * RimLightColor;

#if SUN_LIGHTING
    //sun Lighting
    float sun = -1.0f * max( dot( lightRay + SunLightDir, worldNormal ), -2.0f ) * SunLightColor.w;// inverted Lambertian + offset for lights
    float4 sunLighting = saturate( sun ) * SunLightColor;
#endif

    //Lighting Model
    float lambertian = saturate( max( dot( lightRay, worldNormal ), 0.0f ) + SpecInfo.w );
    float3 halfDir = normalize( lightRay + eyeRay );
    float specAngle = max( dot( halfDir, worldNormal ), 0.0 );

    //Sample MATERIAL_MAP
    float3 Materials = tex2D( MATERIAL_MAP, uv1.xy );//Materials.x = metalness , .y = roughness , .z = mask

    //Remap Roughness map values to be used as the EnvMap MIP Bias.
    float roughness = lerp( 0, 8, Materials.y );//Materials.y = Roughness map

    //Use the original Roughness map to modulate between Min and Max Specualr values to determine Highlight sizes
    //white is loose spec (rough) black is tight spec (shiny)
    float specular = pow( specAngle, lerp( SpecInfo.y, SpecInfo.x, Materials.y ) );

#if USE_SPECULAR_MASK
    float specIntenstity = Materials.z;
#else
    float specIntenstity = SpecularColor.w;
#endif

    //sample ENVIRONMENT_MAP
    float3 r = 2.0f * dot( eyeRay, worldNormal ) * worldNormal - eyeRay;
    float m = 2.0f * sqrt( pow( r.x, 2.0f ) + pow( r.y, 2.0f ) + pow( r.z + 1.0f, 2.0f ) );
    float2 vN = r.xy / m + 0.5f;
    float4 EnvMap = tex2Dbias( ENVIRONMENT_MAP, float4( vN.x, vN.y, 0.0f, roughness ) );

    float3 refMap = tex2D(REFLECTION_MAP, uv1.xy);
#if USE_REFLECTION_MAP
    float3 metalness = refMap * RimLightDir.w;
#else
    //Metalness = modulating between SPecualr color and EnvMap to simulate light on metal and non metal surfaces.
    float3 metalness = lerp( SpecularColor * specIntenstity, ( EnvMap * SpecInfo.z) * texelDiffuse, Materials.x );//Materials.x = Metalness map | SpecInfo.z = ENVIRONMENT_MAP Intensity
#endif

#if USE_SPECULAR_MASK
    //mask the metalness to specular highlight areas.
    metalness *= specular * specIntenstity;
#else
    metalness *= specular;
#endif

//FRESNEL BUSH TEST
float fresnel = smoothstep( DebugValues.y, DebugValues.z, dot( eyeRay, worldNormal ) );
#if FRESNEL_OPACITY
    float fresnel2 = smoothstep( 0.42f, 0.84f, dot( eyeRay, worldNormal ) );
    fresnel2 = saturate( fresnel2 + 0.7f );
#endif

    //OUTPUT
#if DIFFUSE_ONLY
    float3 colorLinear = texelDiffuse;
#else
    #if SUN_LIGHTING
        float3 colorLinear = saturate( lambertian * texelDiffuse + metalness + rimLighting + sunLighting );
    #else
        float3 colorLinear = saturate( lambertian * texelDiffuse + metalness + rimLighting );
    #endif
#endif


    float4 finalColor = float4( colorLinear.xyz, 1 );// setting up final color to use the gloabal alpahas
    //float4 finalColor = float4( fresnel,fresnel,fresnel,1);
    //finalColor = lerp(finalColor, float4(colorLinear,1), fresnel);


#if HALF_AND_HALF_MODE
    float clipX = clipSpacePos.x / clipSpacePos.w;
    if (clipX < DebugValues.x)
    {
        finalColor = oldAlbedoColor;

    }
#endif
   
    fresnel = 1-fresnel;
    fresnel = saturate(fresnel + 0.1f);
    
    finalColor = ApplyTransition(finalColor, lighting.rgb, uv1.xy);
#if FRESNEL_OPACITY
    finalColor.a *= lerp( fresnel * DebugValues.w , fresnel2, step( 1, kGrassFade.a ) );
#else
    finalColor.a *= lerp( fresnel * DebugValues.w , 1.0f, step( 1, kGrassFade.a ) );
#endif

//===============================================================
//  END 
//      League Lighting Model
//===============================================================

#if 0//!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;
}
