#version 400

uniform sampler2D rayEntranceTexture; 
uniform sampler2D rayExitTexture;

uniform sampler3D volumeTex3D;
uniform sampler2D lastSlice;
uniform sampler1D transferFunctionTex;

uniform float	  volMinVal;
uniform float     volMaxVal;

in vec2 		  fragmentTexCoords;
in vec2			  texCoordsLastSlice[20];

vec4 backgroundColor = vec4( 0.15, 0.1, 0.15, 0.0 );

vec3 rayEntrancePosition;
vec3 rayExitPosition;
vec3 rayDirection;



layout(location = 0 ) out vec4 fragColor;


//volume:
uniform float 	stepDistance; 
uniform int 	sliceNumber;



//DVR things:
//r == x;
vec4 singleSliceX(){
	float pos = float(sliceNumber) * stepDistance;
	clamp( pos, 0.0, 1.0 );
	if( rayExitPosition.r < pos && rayEntrancePosition.r < pos ) return backgroundColor;
	else if( rayExitPosition.r > pos && rayEntrancePosition.r > pos ) return backgroundColor;
	
	float percent = ( pos - rayEntrancePosition.x)/(rayExitPosition.r - rayEntrancePosition.r);

	vec3 position = rayDirection * percent + rayEntrancePosition; //position of the cut through the slice plane
	float val = texture( volumeTex3D,  position ).r; //get volume value
	val /= (volMaxVal - volMinVal); //normaliziation
	return vec4( texture( transferFunctionTex, val ) );

	//for DoF set fragment depth:
	//gl_FragDepth = percent;
}




vec4 shading()
{
	rayEntrancePosition = texture( rayEntranceTexture, fragmentTexCoords).rgb;
	rayExitPosition = texture( rayExitTexture, fragmentTexCoords).rgb;
	rayDirection =  rayExitPosition - rayEntrancePosition;

	vec4 colLastSlice = texture(lastSlice, fragmentTexCoords);
	//if( colLastSlice.a >= 1.0 ) return colLastSlice;

	vec4 color = singleSliceX();
	if( color.a >= 1.0 ) return color;

	//blurring
	
	for( int i = 0; i < 20; ++i ){
		colLastSlice += texture( lastSlice, texCoordsLastSlice[i] );
	}
	colLastSlice /= 21.0;


	//compositing:
	color = ( color * color.a ) + (colLastSlice * (1.0 - color.a ) );
	//color = ( color * color.a ) + (colLastSlice);
	return color;
}



void main(void)
{	
	fragColor = shading();
}

