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

typedef struct
{
    float frequency;
    float intensity;
} fxVars;


float hash(float2 p)
{
    p  = 50.0*fract( p*0.3183099 + float2(0.71,0.113));
    return -1.0+2.0*fract( p.x*p.y*(p.x+p.y) );
}

float noise(float2 p )
{
    float2 i = floor( p );
    float2 f = fract( p );

    float2 u = f*f*(3.0-2.0*f);

    return mix( mix( hash( i + float2(0.0,0.0) ),
                    hash( i + float2(1.0,0.0) ), u.x),
               mix( hash( i + float2(0.0,1.0) ),
                   hash( i + float2(1.0,1.0) ), u.x), u.y);
}

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());
    vec2 tmp = in[vertexID].tex1; //0,0 -> 1,1
    out.normPos=tmp;
    tmp-=.5;    //-.5,-.5 -> .5,.5
    tmp*=2.;    //-1,-1 -> 1,1
    tmp/=(vars.intensity+1.);
    float dx=u.globalTime*4.*(vars.frequency+.1);

    tmp.x+=noise(float2(dx,-dx))*(vars.intensity*.5);
    tmp.y-=noise(float2(-dx,dx))*(vars.intensity*.5);

    tmp*=.5;
    tmp+=.5;
    out.tex1=tmp;

    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)]])
{
    float4 outColor = getColor(inputTex, fsTexture);
    float4 texel = getColor(inputTex, input.normPos);

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

    return outColor;
}
