Texture2D g_texDecal: register(t0);
SamplerState g_samLinear : register(s0);

cbuffer global
{
	matrix g_mWorld;
	matrix g_mWVP;
	matrix g_mMeshMatrix;
	matrix g_mBoneMatrixList[128];
	float4 g_vLightDir;
	float4 g_vViewDir;
	float4 g_vColor;
	float4 g_vAmbient;
	float4 g_vSpecular;
	float4 g_vDiffuse;
	float4 g_vEmissive;
	float4 g_vPower;
};

struct VS_OUTPUT
{
	float4 m_Pos    : SV_POSITION;
	float3 m_Normal : TEXCOORD0;
    float2 m_Tex    : TEXCOORD1;
};

VS_OUTPUT VS( float4 Pos : POSITION ,float3 Normal : NORMAL, float2 Tex : TEXCOORD, float4 vsBoneIndex : BONE, float4 vsBoneWeight : WEIGHT)
{
	VS_OUTPUT output = (VS_OUTPUT)0;

	matrix boneMatrix = g_mBoneMatrixList[vsBoneIndex.x] * vsBoneWeight.x;
	boneMatrix += g_mBoneMatrixList[vsBoneIndex.y] * vsBoneWeight.y;
	boneMatrix += g_mBoneMatrixList[vsBoneIndex.z] * vsBoneWeight.z;
	boneMatrix += g_mBoneMatrixList[vsBoneIndex.w] * vsBoneWeight.w;
	
	matrix mat = mul(g_mMeshMatrix,g_mWVP);
	matrix mat2 = mul(boneMatrix,mat);
	output.m_Pos = mul(Pos,mat2);
	output.m_Tex = Tex;
	matrix mat3 = mul(boneMatrix,g_mWorld);
	output.m_Normal = mul(Normal,(float3x3)mat3);

	return output;
}

float4 PS( VS_OUTPUT input ) : SV_Target
{
	float3 Normal = normalize(input.m_Normal);
	float dif_coef = dot(Normal, (float3)g_vLightDir);
	float3 Reflect = (float3)normalize(2 * dif_coef * Normal - (float3)g_vLightDir);
	float spc_coef = pow(saturate(dot(Reflect, (float3)g_vViewDir)), g_vPower.x);

	float4 col = g_vAmbient + g_vColor * (g_vEmissive.x + g_vDiffuse.x * saturate(dif_coef)) + g_vSpecular * spc_coef;
	col.a = g_vColor.a;

	return saturate(col);
}

float4 PS_TEX( VS_OUTPUT input ) : SV_Target
{
	float4 tex_col = g_texDecal.Sample( g_samLinear, input.m_Tex );
	float3 Normal = normalize(input.m_Normal);
	float dif_coef = dot(Normal, (float3)g_vLightDir);
	float3 Reflect = (float3)normalize(2 * dif_coef * Normal - (float3)g_vLightDir);
	float spc_coef = pow(saturate(dot(Reflect, (float3)g_vViewDir)), g_vPower.x);

	float4 col = g_vAmbient + tex_col * g_vColor * (g_vEmissive.x + g_vDiffuse.x * saturate(dif_coef)) + g_vSpecular * spc_coef;
	col.a = tex_col.a * g_vColor.a;

	return saturate(col);
}
