#extension GL_ARB_texture_rectangle : enable

uniform sampler2DRect backFaces;
uniform sampler2DRect frontFaces;

uniform sampler1D lookUp;
uniform sampler3D volumeData;

uniform float stepSize;
uniform float threshold;
uniform float lum;

void main(void)
{
   vec3 rayStart = vec3(texture2DRect(frontFaces, gl_TexCoord[0].st).rgb);
   vec3 rayEnd = vec3(texture2DRect(backFaces, gl_TexCoord[0].st).rgb);
   vec3 rayDirection = rayEnd - rayStart; 
   int iterations = int(length(rayDirection)/stepSize);
   vec3 stepVector = normalize(rayDirection) * stepSize;
   vec4 color = vec4(0.0,0.0,0.0,1.0);
   vec3 currentPos = rayStart;
   vec4 temp;
   vec3 backStepVector = stepVector * 0.1;
   bool hit = false;
   
   for(int i = 0; i < iterations; i++){
       temp = texture3D(volumeData, currentPos.xyz);
       color = texture1D(lookUp, temp.x);
        
       if(color.w > threshold){
       
		   for (int j = 0; j < 10; j++){
			   currentPos -= backStepVector;
			   temp = texture3D(volumeData, currentPos.xyz);
			   color = texture1D(lookUp, temp.x);
			   if (color.w < threshold){
			      break;
			   }			   
		   }
		   
		   currentPos += backStepVector;
		   temp = texture3D(volumeData, currentPos.xyz); 
		   color = texture1D(lookUp, temp.x);
		   color.w = 1.0;
		   hit = true;
		   break; 
       }
       
       currentPos += stepVector;
   }
   
   if (hit){
       gl_FragColor = color * lum;
   }else{
       gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
   }
}