struct vertex {
	float4 position  : POSITION;
	float4 color0    : COLOR0;
	float2 texcoord0 : TEXCOORD0;
	float4 normal    : NORMAL;
};

struct fragment {
	float4 position  : POSITION;
	float4 color0    : COLOR0;	// r,g,b=lightdir a=nikovalue
	float2 texcoord0 : TEXCOORD0;
	float4 envcoord  : TEXCOORD1;
	float4 normal    : COLOR1;
	float3 view      : TEXCOORD2;
	float4 refraction: TEXCOORD3;
	float3 realPos   : TEXCOORD4;
	float4 realNormal: TEXCOORD5;
};


fragment main(vertex IN,
			  uniform float4x4 modelViewProj,
			  uniform float2x2 textureMatrix,
			  uniform float4x4 modelViewIT,
			  uniform float4x4 modelView,
			  uniform float3 camera)
{
	fragment OUT;

	OUT.realPos = IN.position.xyz;
	OUT.realNormal = IN.normal;

	OUT.position = mul(modelViewProj, IN.position);
	OUT.color0 = IN.color0;
	OUT.texcoord0 = mul(textureMatrix, IN.texcoord0);

	OUT.color0.a = OUT.position.z;
	if (OUT.color0.a < 0) OUT.color0.a = -OUT.color0.a;

	float4 worldpos = mul(modelViewIT, IN.normal);
	OUT.normal.xyz = normalize(worldpos.xyz);

	float3 eyeToVert = normalize(mul(modelView, IN.position).xyz);
	OUT.envcoord = float4(reflect(eyeToVert, OUT.normal.xyz), 1.0);	// not real envcoords

	OUT.refraction = float4(refract(eyeToVert, OUT.normal.xyz, 1.666), 1.0);

//	float diffuse = 1-dot(OUT.normal.xyz, float3(0.0, -0.1, 0.7));
	float diffuse = 1-dot(OUT.normal.xyz, float3(0.0, 0, 0));
	OUT.color0.a = 1-(1-diffuse*diffuse*diffuse*diffuse);
	OUT.color0.a = OUT.color0.a + (1-diffuse)*(1-diffuse)*(1-diffuse);
	OUT.color0.a = (OUT.color0.a * OUT.color0.a)*2;

	// paska shit
	float3 lightDir = IN.color0.rgb-IN.position.rgb;
	float3 bi = cross(IN.color0.rgb, IN.normal.xyz);
	float3x3 lightMatrix = {IN.color0.rgb, bi, IN.normal.rgb};
	lightDir = mul(lightMatrix, lightDir);
	OUT.view = camera-IN.position.xyz;
	OUT.view = mul(lightMatrix, OUT.view);

	return OUT;
}
