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

typedef struct
{
    float scale;
} 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 vertexOut vertexFunc(uint vertexID [[ vertex_id ]],const device txShaderVers* in[[ buffer(0) ]],constant txShaderUniforms& uniforms[[ buffer(3) ]],constant fxVars& vars[[ buffer(2)]])
{
    vertexOut out;

    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& uniforms[[ buffer(2) ]]
                             ,constant fxVars& vars[[ buffer(1)]])
{
    float4 newColor = float4(inputTex0.sample(linearSampler,input.tex1));
    float4 oldColor = float4(inputTex1.sample(linearSampler,input.tex2));

    float2 p=input.tex2;
    float2 uv2 = p*float2(inputTex1.get_width()/inputTex1.get_height(),1.0);

    float f = 0.0;
    f = noise( vars.scale*uv2 );
    f = 0.5 + 0.5*f;

    f *= smoothstep( 0.0, 0.005, abs(p.x-0.0) );

    float2 uv0 = (input.tex1*2.0 - 1.0) * 0.5;
    float length0 = sqrt(dot(uv0, uv0));
    float time = uniforms.transitionProgress * 150.0;
    float mask = 1.0 - clamp(length0 * 100.0 - (time*(f*0.5+0.5)),0.0,1.0);

    float4 outColor=mix(oldColor,newColor,mask);

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

    return outColor;
}
