float4x4 mVP;	// View * Projection matrix

float4 vColor;
float4x4 mWorld;

float3 vLight = {0, -20, -30};
float3 vEyePos = {0, 0, 0};
float4 vBgCol;

texture tBase;
sampler smpBase = sampler_state {
    Texture = <tBase>;    
    MipFilter = None; MinFilter = Linear; MagFilter = Linear;
};


struct SInput {
	float4 pos : POSITION;
	float3 normal : NORMAL;
        float2 tex : TEXCOORD0;
};

struct SOutput {
	float4 pos : POSITION;
        float2 tex : TEXCOORD0;
	float3 normal : TEXCOORD1;
	float3 wPos : TEXCOORD2;
};


SOutput RenderSceneVS( SInput i )
{
	SOutput o;
	float4 pos = mul( i.pos, mWorld );
	o.pos = mul( pos, mVP );
	o.tex = i.tex;
	o.normal = normalize(mul( i.normal, (float3x3)mWorld ));
	//o.normal = i.normal;
	o.wPos = pos;

	return o; 
}

float4 RenderScenePS( SOutput i ) : COLOR
{ 
	float4 tcol = tex2D( smpBase, i.tex );

	float4 col;
	col.a = 1;

	float3 ld = -normalize(i.wPos - vLight);
	float3 normal = normalize(i.normal);
	
	float3 eye = normalize(vEyePos - i.wPos);
	float3 r = -normal + eye * 2 * dot(eye, normal);


	float diffuse = clamp(dot(normal, ld), 0, 1);
	float specular = pow(clamp(dot(r, ld), 0, 1), 15);

	//col.rgb = diffuse * 0.2 + specular * 0.9;
	col.rgb = diffuse * 1 + specular * 0.5;

	//col.rgb = eye * 0.5 + 0.5;
	//col.rgb = ld * 0.5 + 0.5;

	//col.rgb = normal * 0.5 + 0.5;	
	//col.rgb = i.normal * 0.5 + 0.5;	
	//col.rgb = i.wPos * 0.01 * 0.5 + 0.5;	
	
	//return col;
	//return tcol;
	col = col * tcol;

	float fl = length(i.wPos) - 100;
	//fl = clamp(fl / 200, 0, 1);
	//fl = pow(fl, 0.7);

	fl = 1 - 1 / (1 + max(0, fl / 100));
	
	fl = 0.5 - cos(fl * 3.14) * 0.5;

	col = col * (1 - fl) + vBgCol * fl;
	//col.rgb = fl;

	return col;
}


technique RenderScene {
	pass P0 {          
		VertexShader = compile vs_1_1 RenderSceneVS();
		PixelShader  = compile ps_2_0 RenderScenePS();
	
		ZEnable = True;
		ZWriteEnable = True;
		CullMode = None;

		AlphaBlendEnable = False;
	}
}

	