// Genetic object shader

#version 130

#pragma vertex_shader

in vec4 vertex;
in vec3 normal;
in vec2 texCoord;


#ifdef SKINNED
in vec4  weights;
in ivec4 indices;
uniform mat4 boneMatrices[70];
#endif

uniform mat4  transform;
uniform mat4  modelMatrix;

out vec2 texcoord;
out vec3 worldNormal;
out vec3 worldPos;

void main() {
	vec4 pos = vertex;
	vec3 norm = normal;
	
	#ifdef SKINNED
	vec4 weight = weights;
	ivec4 index = indices;
	vec3 blendPos = vec3(0);
	vec3 blendNorm = vec3(0);
	for(int i=0; i<SKINNED; ++i) {
		blendPos  += (boneMatrices[index.x] * vertex).xyz * weight.x;
		blendNorm += mat3(boneMatrices[index.x]) * normal * weight.x;
		weight = weight.yzwx;
		index = index.yzwx;
	}
	pos.xyz = blendPos;
	norm = blendNorm;
	#endif

	gl_Position = transform * pos;
	texcoord = texCoord;
	worldNormal = mat3(modelMatrix) * norm;
	worldPos = (modelMatrix * pos).xyz;
}


#pragma fragment_shader

in vec2 texcoord;
in vec3 worldNormal;
in vec3 worldPos;
out vec4 fragment;

uniform sampler2D diffuse;
uniform vec3 lightDirection;

#ifdef GLOW
uniform sampler2D glowmap;
uniform vec2 glow; // mult, progress {0-1}
#endif

void main() {
	vec4 diff = texture2D(diffuse, texcoord.st);
	fragment = diff;

	float l = dot( normalize(worldNormal), normalize(lightDirection));
	float s = (l+1)/1.3*0.2+0.1; // dark side lighting

	fragment.rgb *= max(s, l);

	#ifdef GLOW
	vec4 glowvalue = texture2D(glowmap, texcoord.st);
	float amount = clamp((glowvalue.r - 1.0 + glow.y) * 100.0, 0.0, 1.0) * glowvalue.a;
	fragment.rgb += amount * glow.x;
	#endif


}

