#version 120
#extension GL_EXT_gpu_shader4 : enable

uniform mat4 localMatrix;
uniform mat4 viewMatrix; 
uniform mat4 projectionMatrix; 
uniform sampler2D flockData;
uniform float dataWidth;
uniform float boidsCount;

varying vec4 normal;
varying vec4 instanceDiffuseColour;

void main() 
{ 	
	float texelSize = 1.0 / dataWidth;
	float texelHalfSize = texelSize / 2.0;
	float id = gl_InstanceID * 2.0 * texelSize;
	vec2 positionCoord = vec2(fract(id), floor(id) * texelSize);
	
	vec4 position = vec4(texture2D(flockData, positionCoord).xyz, 1.0);
	
	vec3 up = vec3(0.0, 0.1, 0.0);
	
	vec2 dirCoord = positionCoord + vec2(texelSize, 0.0);
	vec4 z = normalize(vec4(texture2D(flockData, dirCoord).xyz, 0.0));
	vec4 x = vec4(normalize(cross(up, z.xyz)), 0.0);
	vec4 y = vec4(normalize(cross(z.xyz, x.xyz)), 0.0);
											  
	mat4 modelMatrix =  mat4(vec4(1.0, 0.0, 0.0, 0.0), 
							vec4(0.0, 1.0, 0.0, 0.0), 
							vec4(0.0, 0.0, 1.0, 0.0), 
							position) * 
						mat4(x, y, z, vec4(0.0, 0.0, 0.0, 1.0)) *
						localMatrix;
							
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * gl_Vertex; 
    
    normal = modelMatrix * vec4(gl_Normal, 0.0);
    
    float idNorm = gl_InstanceID / boidsCount;
    instanceDiffuseColour = vec4(0.0, 0.0, 0.0, 1.0);
    
    if (idNorm < 0.5)
    {
		instanceDiffuseColour.r = -2.0 * idNorm + 1.0;
		instanceDiffuseColour.g = 2.0 * idNorm;
    }
    else
    {
		instanceDiffuseColour.g = -2.0 * idNorm + 1.5;
		instanceDiffuseColour.b = 2.0 * idNorm - 1.0;
    }
}
