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

typedef struct
{
    float cells;
    int gridSize;
} 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.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 xy;
    float4 outColor;
    vec4 texel=getColor(inputTex,fsTexture);
    float rows=vars.cells;
    float columns=vars.cells;
    if(vars.gridSize!=0)
    {
        xy=input.tex1*vec2(float(columns),float(rows));
        xy=fract(xy);
        vec2 pos=vec2(3.1415926535,3.1415926535)*xy;
        vec2 dim=sqrt(min(vec2(1.0),sin(pos)*vec2(22.0-float(vars.gridSize))));
        outColor = getColor(inputTex, xy);
        multiplyOpacity(outColor, dim.x * dim.y);
    }
    else
    {
        xy=input.tex1*vec2(columns,rows);
        xy=fract(xy);
        outColor = getColor(inputTex,xy);
    }

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

    return outColor;
}
