#version 120

uniform sampler2D mVelocity;
uniform sampler2D mNoise;
uniform sampler2D mFilter;
uniform vec3 mExtends;

uniform float mAlpha;
uniform int mSteps;
uniform int mStepSize;
uniform float mTextureOffset;

void main()
{
	vec2 velcoord = gl_TexCoord[0].xy;
	vec2 velocity = texture2D(mVelocity, velcoord).xy;
	velocity.x *= -1.0f;
	velocity = normalize(velocity);
	velocity /= (mExtends.xy * mStepSize);
	


	vec2 lookup = vec2(0.5 + mTextureOffset, 0.5);
	float multi = texture2D(mFilter, lookup).x;
	vec4 color = texture2D(mNoise, velcoord) * multi;

	float sum = multi;
	
	float factor = lookup.x;

	float stepSize = 1.0 / ( 2.0 * mSteps);

	for (int i = 0; i < mSteps; i++)
	{
		velcoord -= velocity;
		velcoord = clamp(velcoord, 0.0, 1.0);
		lookup.x -= stepSize * i;
		multi = texture2D(mFilter, lookup).x;
		color += texture2D(mNoise, velcoord) * multi;
		sum += multi;
		velocity = texture2D(mVelocity, velcoord).xy;
		velocity.x *= -1.0f;
		velocity = normalize(velocity);
		velocity /= (mExtends.xy * mStepSize);
		
	}
	
	velcoord = gl_TexCoord[0].xy;
	velocity = texture2D(mVelocity, velcoord).xy;
	velocity.x *= -1.0f;
	velocity = normalize(velocity);
	velocity /= (mExtends.xy * mStepSize);
	lookup = vec2(0.5 + mTextureOffset, 0.5);
	

	for (int i = 0; i < mSteps; i++)
	{
		velcoord += velocity;
		velcoord = clamp(velcoord, 0.0, 1.0);
		lookup.x += stepSize * i;
		multi = texture2D(mFilter, lookup).x;
		color += texture2D(mNoise, velcoord) * multi;
		sum += multi;
		velocity = texture2D(mVelocity, velcoord).xy;
		velocity.x *= -1.0f;
		velocity = normalize(velocity);
		velocity /= (mExtends.xy * mStepSize);
		
	}
	
	color /= sum;
		
	gl_FragColor = vec4(color.rgb, mAlpha);
}