#include "world.inc"
#include "material.inc"
#include "texture.inc."
#include "light.inc"
#if OIT
#include "oit.inc"
#endif

Texture2D EnvMap : register( t4 );
SamplerState EnvMapSampler : register( s4 );

struct VS_INPUT
{
	float4 Pos : POSITION;
	float3 Normal : NORMAL;
	float2 TexCoord : TEXCOORD0;
};

struct VS_OUTPUT
{
	float4 Pos : SV_POSITION;
	float4 WorldPos : TEXCOORD3;
};

struct PS_INPUT
{
	float4 Pos : SV_POSITION;
	float4 WorldPos : TEXCOORD3;
#if MSAA
    uint Coverage : SV_COVERAGE;
#endif
};

struct PS_OUTPUT
{
	float4 Color    : SV_Target0;
#if RENDER_NORMAL
	float4 Normal   : SV_Target1;
#endif
};

#include "oit_store.inc"


static const float PI = 3.141592653589793;

float2 dirToUV(float3 dir)
{
	return float2(
		atan2(dir.z, dir.x) / (PI*2),
		acos(dir.y) / PI);
}

float2 envmapUV(float3 dir)
{
	return dirToUV(dir) + float2(EnvMapRotate, 0.0);
}

// Vertex shader
VS_OUTPUT VS(const VS_INPUT In)
{
	VS_OUTPUT Out;
	Out.Pos = mul(In.Pos, WorldViewProj);
	Out.Pos.z = 1.0;
	Out.WorldPos = In.Pos;
	return Out;
}

// Pixel shader
#if OIT
[earlydepthstencil]
#endif
PS_OUTPUT PS(PS_INPUT In)
{
	PS_OUTPUT output;

	float3 V = normalize(CameraPos - In.WorldPos.xyz);
	float3 col = LINEARtoSRGB(EnvMap.Sample(EnvMapSampler, envmapUV(-V)) * BaseColor, HasEnvMap == 2).xyz;
	output.Color = float4(saturate(col), 1);

#if OIT
    StoreOIT(In, output.Color);
    output.Color = float4(0,0,0,0);	// This does not affect anything because RenderTargetWriteMask is 0.
#endif

#if RENDER_NORMAL
	output.Normal = float4(0,0,1,1);
#endif

	return output;
}

