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

typedef struct
{
    float size;
    float angle;
} fxVars;


#define QUALITY 8


constant float GOLDEN_ANGLE = 2.399963229728653; // PI * (3.0 - sqrt(5.0))

vec4 blur(texture2d<half> tpipe,vec2 c,float radius)
{
    vec4 sum = vec4(0.0);
    float q = float(QUALITY);
    // Using a "spiral" to propagate points.
    for (int i=0; i<QUALITY; ++i)
    {
        float fi = float(i);
        float a = fi * GOLDEN_ANGLE;
        float r = sqrt(fi / q) * radius;
        vec2 p = c + r * vec2(cos(a), sin(a));
        sum += getColor(tpipe, p);
    }
    return sum / q;
}


vertex vertexOut vertexFunc(uint vertexID [[ vertex_id ]],const device txShaderVers* in[[ buffer(0) ]],constant txShaderUniforms& uniforms[[ buffer(3) ]])
{
    vertexOut out;
    
    out.normPos=in[vertexID].pos.xy;
    out.position=in[vertexID].pos*uniforms.worldViewProj;

    out.tex1=in[vertexID].tex1;
    out.tex2=in[vertexID].tex2;
    out.texMask=in[vertexID].texMask;
    return out;
}

fragment float4 fragmentFunc(vertexOut input [[stage_in]]
                             ,texture2d<half> inputTex0 [[ texture(0) ]]
                             ,texture2d<half> inputTex1 [[ texture(1) ]]
                             ,texture2d<half> inputTexMask [[ texture(2) ]]
                             ,constant txShaderUniforms& u[[ buffer(2) ]]
                             ,constant subFXVars& subVars[[buffer(3)]]
                             ,constant fxVars& vars[[ buffer(1)]])

{

    float fsMix=1.0;
    if(u.transitionProgress<=.5)
        fsMix=u.transitionProgress*2.;
    else
        fsMix=(1.-u.transitionProgress)*2.;
    vec4 color1=blur(inputTex0,input.tex1,fsMix*vars.size);
    vec4 color2=blur(inputTex1,input.tex2,fsMix*vars.size);
    float4 outColor;
    mixColor(outColor, color2, color1, u.transitionProgressLinear);

#ifdef USE_MASK
    multiplyOpacity(outColor, float(inputTexMask.sample(linearSampler, input.texMask).a));
#endif

    return outColor;
}
