//

// Fragment shader for blend generated plasma with image
//
// Author: Blah, i can neither confirm nor deny i wrote this
//
//

#version 330

uniform sampler2DRect inputTex;
uniform sampler2DRect maskTex;
uniform float hexSize=40.0;
uniform float uBlendValue=1.0;

in vec2 fsTexture;
in vec2 fsNormalizedUV;
in vec2 fsMaskTexture;
in vec2 fsTextureSize;
in float fsTime;
out vec4 outColor;

float PI = 3.14159265359;
float TAU = 2.0*PI;
float deg30 = TAU/12.0;

// http://www.gamedev.net/page/resources/_/technical/game-programming/coordinates-in-hexagon-based-tile-maps-r1800
// nearest hexagon sampling, not quite sure if it's correct

float hexDist(vec2 a, vec2 b)
{
    vec2 p = abs(b-a);
    float s = sin(deg30);
    float c = cos(deg30);
    
    float diagDist = s*p.x + c*p.y;
    return max(diagDist, p.x)/c;
}

vec2 nearestHex(float s, vec2 st)
{
    float h = sin(deg30)*s;
    float r = cos(deg30)*s;
    float b = s + 2.0*h;
    float a = 2.0*r;
    float m = h/r;
    
    vec2 sect = st/vec2(2.0*r, h+s);
    vec2 sectPxl = mod(st, vec2(2.0*r, h+s));
    
    float aSection = mod(floor(sect.y), 2.0);
    
    vec2 coord = floor(sect);
    if(aSection > 0.0)
    {
        if(sectPxl.y < (h-sectPxl.x*m))
        {
            coord -= 1.0;
        }
        else if(sectPxl.y < (-h + sectPxl.x*m))
        {
            coord.y -= 1.0;
        }
        
    }
    else
    {
        if(sectPxl.x > r)
        {
            if(sectPxl.y < (2.0*h - sectPxl.x * m))
            {
                coord.y -= 1.0;
            }
        }
        else
        {
            if(sectPxl.y < (sectPxl.x*m))
            {
                coord.y -= 1.0;
            }
            else
            {
                coord.x -= 1.0;
            }
        }
    }
    
    float xoff = mod(coord.y, 2.0)*r;
    return vec2(coord.x*2.0*r-xoff, coord.y*(h+s))+vec2(r*2.0, s);
}

void main()
{
//    vec2 uv = fragCoord.xy/iResolution.xy;
    float s = fsTextureSize.x/((110-hexSize)*4.0);
    vec2 nearest = nearestHex(s, fsTexture);
    vec4 texel = texture(inputTex, nearest);
    vec4 texColor=texture(inputTex,fsTexture);
    float dist = hexDist(fsTexture, nearest);
    
    float luminance = (texel.r + texel.g + texel.b)/3.0;
    //float interiorSize = luminance*s;
    float interiorSize = s;
    float interior = 1.0 - smoothstep(interiorSize-1.0, interiorSize, dist);
    //fragColor = vec4(dist);
    outColor = vec4(texel.rgb*interior, texColor.a);

    float blendValue=uBlendValue;
#ifdef USE_MASK
    blendValue*=texture(maskTex,fsMaskTexture).a;
#endif
    outColor.rgb=mix(texColor.rgb,outColor.rgb,blendValue);
}
