#ifdef GL_ES
precision mediump float;
#endif
// this is a modified spritebatch shader

uniform sampler2D texSampler;
uniform float testAlpha;

varying lowp vec4 vColor;
varying vec2 vTexCoords;

// vignette radius from center
uniform float vignetteOuterRadius;// = 0.71;
uniform float vignetteInnerRadius;// = 0.30;
uniform float vignetteIntensity;
uniform vec3 vignetteColor;

float rand(const in vec2 uv) {
    vec2 noise = (fract(sin(dot(uv, vec2(12.9898, 78.233) * vec2(2.0))) * vec2(43758.5453)));
    return abs(noise.x + noise.y) * 0.5;
}

vec2 rand2(const in vec2 uv) {
    float noiseX = (fract(sin(dot(uv, vec2(12.9898, 78.233) * vec2(2.0))) * vec2(43758.5453))).x;
    float noiseY = sqrt(1.0 - noiseX * noiseX);
    return vec2(noiseX, noiseY);
}

vec3 Vignette(const in vec3 color) {
    // determine center position
    vec2 position = vTexCoords - vec2(0.5);

    // determine the vector length of the center position
    float len = length(position);

    // use smoothstep to create a smooth vignette
    float vignette = pow(smoothstep(vignetteOuterRadius, vignetteInnerRadius, len), vignetteIntensity);
#ifdef CHEAP_VIGNETTE
	vec3 vign3 = vec3(clamp(vignette, 0.0, 1.0));
#else
	// create some random noise to avoid color banding
	vec3 rnd = (vec3(rand2(vTexCoords), rand(vTexCoords)) * 2 - 1.0) * 0.020;
	// multiply random noise by smoothstep to make sure no noise is added where the vignette isn't applied
	vec3 vign3 = clamp(smoothstep(1.0, 0.997, vignette) * rnd + vignette, 0.0, 1.0);
#endif

    // apply the vignette
    return mix(vignetteColor, color.rgb, vign3);
}

void main() {
	vec4 frag = texture2D(texSampler, vTexCoords);
	vec3 color = Vignette(frag.rgb);
    gl_FragColor = vec4(color.rgb, frag.a);
}
