#version 120
uniform sampler2D iChannel0;

uniform sampler2D outlineColorLookup;

uniform sampler2D noiseTexture;
uniform vec2 noiseOffset;
uniform vec2 noiseScale;

uniform vec4 fillColor;

uniform vec2 bufferSize;

#include "shaders/logic.glsl"

const vec2 right = vec2(1.0,0.0);
const vec2 left = -right;
const vec2 down = vec2(0.0,1.0);
const vec2 up = -down;

vec4 checkOutline(vec2 direction)
{
    return texture2D(iChannel0, gl_TexCoord[0].xy + direction/bufferSize);
}

void main()
{
    vec4 c = texture2D(iChannel0, gl_TexCoord[0].xy);

    float noise = texture2D(noiseTexture, mod(floor((gl_FragCoord.xy + noiseOffset)*0.5)*2.0*noiseScale,1.0)).r;

    //float outline = max(checkOutline(up), max(checkOutline(down), max(checkOutline(left), checkOutline(right))));
    vec4 outline1 = checkOutline(up);
    vec4 outline2 = checkOutline(down);
    vec4 outline3 = checkOutline(left);
    vec4 outline4 = checkOutline(right);

    float outlineDisintegration = 1.0 - max(outline1.r, max(outline2.r, max(outline3.r, outline4.r)));
    //float outlineColorIndex = mix(outline1.g, mix(mix(outline2.g, mix(outline3.g, outline4.g, outline4.a), outline3.a), outline2.a));
    float outlineColorIndex = mix(mix(mix(outline1.g, outline2.g, outline2.a), outline3.g, outline3.a), outline4.g, outline4.a);
    float outlineAlpha = max(outline1.a, max(outline2.a, max(outline3.a, outline4.a)));

    vec4 outlineColor = texture2D(outlineColorLookup, vec2(outlineColorIndex, 0.5));

	gl_FragColor = mix(outlineColor*outlineAlpha*ge(noise,outlineDisintegration),fillColor*ge(noise,1.0 - c.r),c.a);
    //gl_FragColor = vec4(vec3(noise), 1.0);
}