attribute vec3 position;
attribute vec2 texCoord;
attribute vec3 normal;
attribute vec4 boneInds;
attribute vec4 boneWeights;

varying vec2 v_texCoord;
varying vec2 v_texCoord_SSR;
varying vec2 v_texCoord_sphereMap;
varying vec3 v_normal;
varying vec3 v_color;

vec3 eyeDir = normalize(vec3( 0, -0.7, -1));
vec3 lightDir = normalize(vec3( 0.3, -0.9, 0.15));

//uniform mat4 mvp;

uniform mat4 projMat;
uniform mat4 modelViewMat;

uniform mat4 boneMats[32];

vec2 getSphereMapCoords(vec3 eye, vec3 normal) 
{
	vec3 reflected = reflect(eye, normal);
	float m = 2.8284271247461903 * sqrt( reflected.z+1.0 );
	return reflected.xy / m + 0.5;
}

vec2 getSSRCoords(vec3 eye, vec3 normal, vec2 scrPos) 
{
	vec3 reflected = (reflect(eye, normal)*0.5);
	float m = 2.8284271247461903 * sqrt( reflected.z+1.0 );
	return normal.xy / (4.0 + dot(eye,normal)) + ((scrPos+1.0)/2.0);
}
	
void main()
{

	vec4 pos = vec4(position, 1.0);
	
	int boneIndex = int(boneInds.x);
	vec4 newPos = (boneMats[boneIndex] * pos) * boneWeights.x;
	vec3 newNormal = (mat3(boneMats[boneIndex]) * normal) * boneWeights.x;
	
	boneIndex = int(boneInds.y);
	newPos = (boneMats[boneIndex] * pos) * boneWeights.y + newPos;
	newNormal += (mat3(boneMats[boneIndex]) * normal) * boneWeights.y;
	
	boneIndex = int(boneInds.z);
	newPos = (boneMats[boneIndex] * pos) * boneWeights.z + newPos;
	newNormal += (mat3(boneMats[boneIndex]) * normal) * boneWeights.z;
	
	boneIndex = int(boneInds.w);
	newPos = (boneMats[boneIndex] * pos) * boneWeights.w + newPos;
	newNormal += (mat3(boneMats[boneIndex]) * normal) * boneWeights.w;
	
	newNormal = normalize( mat3(modelViewMat) * newNormal);
	
	gl_Position = projMat * modelViewMat * newPos;
	v_normal = newNormal;
	v_texCoord = texCoord;
	v_texCoord_SSR = getSSRCoords( eyeDir, newNormal, gl_Position.xy);
	v_texCoord_sphereMap = getSphereMapCoords( eyeDir, newNormal);
	
	v_color = 1.0 - clamp(dot(lightDir,newNormal),0.3, 1);
	v_color = 1.0 - v_color*v_color;
}