#include "metalShaderTypes.h"
#include "alpha.h"

typedef struct
{
    float pixelSize;
} fxVars;


vertex fxVertexOut vertexFunc(uint vertexID [[ vertex_id ]]
                              ,const device fxShaderVerts* in[[ buffer(0) ]]
                              ,texture2d<half> inputTex0 [[ texture(0) ]]
                              ,texture2d<half> inputTexMask [[ texture(1) ]]
                              ,constant fxGeneralUniforms& u[[ buffer(1) ]]
                              ,constant fxVars& vars[[ buffer(2)]])
{
    fxVertexOut out;

    out.normPos=in[vertexID].pos.xy*vec2(.5,-.5f)+vec2(.5,.5);
    out.position=in[vertexID].pos;
    out.texSize=float2(inputTex0.get_width(),inputTex0.get_height());
    out.tex1=in[vertexID].tex1*out.texSize;
    out.texMask=in[vertexID].texMask;
    return out;
}

fragment float4 fragmentFunc(fxVertexOut input [[stage_in]]
                             ,texture2d<half> inputTex [[ texture(0) ]]
                             ,texture2d<half> inputTexMask [[ texture(1) ]]
                             ,constant fxGeneralUniforms& u[[ buffer(0) ]]
                             ,constant fxVars& vars[[ buffer(1)]])
{
    vec2 fsTextureStep=input.texSize*.05;
    fsTextureStep*=vars.pixelSize*max(0.01,u.blendValue);
    fsTextureStep.y=fsTextureStep.x;

    vec4 texel = getColor(inputTex, fsTexture/input.texSize);
    vec2 tmp=(fsTexture+fsTextureStep*.5)/fsTextureStep;
    int2 grad=int2(tmp);
    vec2 pixTexture=vec2(grad);
    pixTexture*=fsTextureStep;

    float4 outColor = getColor(inputTex, pixTexture/input.texSize);

    float blendValue=u.blendValue;
#ifdef USE_MASK
    blendValue*=getColor(inputTexMask,input.texMask).a;
#endif
    mixColor(outColor, texel, outColor, blendValue);

    return outColor;
}
