// KNMagicMove.frag
#version 100

precision mediump float;

uniform float Opacity;
uniform sampler2D Texture;

varying vec2 v_TexCoord;

#if ENABLE_DEBUG_COLORS
uniform vec4 DebugColor;
uniform vec2 DebugTextureSize;
uniform float DebugBorderWidth;
uniform vec2 DebugAnchorPoint;
#endif

#if SHOULD_BLEND_INCOMING
uniform sampler2D TextureIncoming;
uniform float Percent;
varying vec2 v_TexCoordIncoming;
#endif

#ifdef MOTION_BLUR
varying vec2 v_Velocity;
#endif

void main()
{
    vec4 result = texture2D(Texture, v_TexCoord);
#if SHOULD_BLEND_INCOMING
    // Blend incoming texture as well
    vec4 incomingColor = texture2D(TextureIncoming, v_TexCoordIncoming);
    result = mix(result, incomingColor, Percent);
#endif
    
    vec4 texColor = result;
    result *= Opacity;
    
#if ENABLE_DEBUG_COLORS
    // Draw striped debug lines
    vec2 texel = v_TexCoord*DebugTextureSize;
    result = (   texel.x <= DebugBorderWidth
              || texel.y <= DebugBorderWidth
              || texel.x >= DebugTextureSize.x-DebugBorderWidth
              || texel.y >= DebugTextureSize.y-DebugBorderWidth)
            ? DebugColor : result;
    
    // Draw anchor point
    vec2 anchorPt = DebugAnchorPoint * DebugTextureSize;
    float dist = distance(anchorPt, texel);
    float maxDist = 10.0;
    if (dist < maxDist) {
        vec4 anchorColor = mix(vec4(1,0,1,1), vec4(1,1,0,1), dist/maxDist);
        float rad = 4.0;
        result = mix(result, anchorColor, (mod(dist, rad)/rad < 1.0/rad ? 1.0 : 0.0));
    }
#endif
    
#ifdef MOTION_BLUR
    gl_FragData[0] = result;
    gl_FragData[1] = (texColor.a > 0.1 ? 1.0 : 0.0) * vec4(v_Velocity,1,1);
#else
    gl_FragColor = result;
#endif
}
