#version 330

in vec4 vertex;
in vec3 normal;
in vec4 tangent;
in vec2 texCoord;
in vec4 loc;
in vec4 rot;

uniform mat4 transform;
uniform mat4 modelMatrix;

out vec2 texcoord;
out vec3 worldNormal;
out vec3 worldPos;
out vec3 worldTangent;
out vec3 worldBinormal;

mat3 quatToMat(vec4 q) {
	vec3 x = vec3( 1.0-2.0*(q.y*q.y + q.z*q.z), 2.0*(q.x*q.y + q.w*q.z), 2.0*(q.x*q.z - q.w*q.y) );
	vec3 y = vec3( 2.0*(q.x*q.y - q.w*q.z), 1.0-2.0*(q.x*q.x + q.z*q.z), 2.0*(q.y*q.z + q.w*q.x) );
	vec3 z = cross(x, y);
	return mat3(x, y, z);
}

void main() {
	mat3 m = quatToMat(rot);
	vec3 pos = m * vertex.xyz * loc.w + loc.xyz;
	gl_Position = transform * vec4(pos, 1.0);
	texcoord = texCoord;
	worldNormal = mat3(modelMatrix) * m * normal;
	worldPos = (modelMatrix * vec4(pos, 1.0)).xyz;

	worldTangent = mat3(modelMatrix) * m * tangent.xyz;
	worldBinormal = cross(worldNormal, worldTangent) * tangent.w;
}

