#version 130

#define SHADOW_RANGE 12.

#ifdef GL_ES
precision mediump float;
#endif

in vec2 vTexCoord;
in float vNeighbors;

out vec4 fragColor;

uniform sampler2D uImage0;

float f(float a)
{
	return log(1. + a) / log(2.);
}

void main(void)
{
	vec4 color = texture2D(uImage0, vTexCoord);
	if (color.a == 0.0)
		color = vec4(0.0, 0.0, 0.0, 0.0);

	// the texture is cut into 32x32 blocks
	vec2 texDims = vec2(textureSize(uImage0, 0));
	vec2 texCoord = vTexCoord * texDims;
	vec2 texGrid = floor(texCoord / 32.) * 32.;
	vec2 texGridCorner = texGrid + vec2(32.);

	float shade = 1.;

	int neighbors = int(floor(vNeighbors));

	// From south to south-east clockwise
	bool fs = (neighbors & 1) == 0, fw = (neighbors & 4) == 0, fn = (neighbors & 16) == 0, fe = (neighbors & 64) == 0;
	if(fs)
		shade *= f(min(abs(texCoord.y - texGridCorner.y) / SHADOW_RANGE, 1.));
	if((neighbors & 2) == 0 && !fs && !fw)
		shade *= f(min(distance(texCoord, vec2(texGrid.x, texGridCorner.y)) / SHADOW_RANGE, 1.));
	if(fw)
		shade *= f(min(abs(texCoord.x - texGrid.x) / SHADOW_RANGE, 1.));
	if((neighbors & 8) == 0 && !fw && !fn)
		shade *= f(min(distance(texCoord, texGrid) / SHADOW_RANGE, 1.));
	if(fn)
		shade *= f(min(abs(texCoord.y - texGrid.y) / SHADOW_RANGE, 1.));
	if((neighbors & 32) == 0 && !fn && !fe)
		shade *= f(min(distance(texCoord, vec2(texGridCorner.x, texGrid.y)) / SHADOW_RANGE, 1.));
	if(fe)
		shade *= f(min(abs(texCoord.x - texGridCorner.x) / SHADOW_RANGE, 1.));
	if((neighbors & 128) == 0 && !fe && !fs)
		shade *= f(min(distance(texCoord, texGridCorner) / SHADOW_RANGE, 1.));

	fragColor = vec4(color.xyz * shade, color.a);
}