#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.0, 0.0, 0.0, 0.0 );

vec3 rayEntrancePosition;
vec3 rayExitPosition;
vec3 rayDirection;



layout(location = 0 ) out vec4 fragColor;


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



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

	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 ) );
}







const float aperture = 5; //=f/i
const float zf = 0.5; //distance which should be in focus
const float f = 50.0; //focal length will belater set through program


vec4 calcDoF( vec3 pos ){
	float A = f/aperture;
	float cimg = A * (zf - pos.z)/pos.z * f / (zf - f);
	return vec4(cimg, cimg, cimg, 1.0); 
}



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 = singleSliceY();
	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();
}

