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

vertex vertexOut vertexFunc(uint vertexID [[ vertex_id ]],const device txShaderVers* in[[ buffer(0) ]],constant txShaderUniforms& uniforms[[ buffer(3) ]])
{
    vertexOut out;

    out.position=in[vertexID].pos*uniforms.worldViewProj;

    if(uniforms.transitionState==0)
    {
        out.position.z=.10;
    }

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

constant float softEdgeMaxWidth = .09;
constant float edgeRamp = .3;


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)]])
{

    float4 outColor=vec4(0,0,0,0);
    float4 colorB=getColor(inputTex1,input.tex2);
    float4 colorA=getColor(inputTex0,input.tex1);

    float alpha = u.baseAlpha;
    //expanding old texture and splitting in middle
    vec2 tadj=input.tex1;
    float open=u.transitionProgressLinear*.5;
    float middle=.5;
    if(input.tex2.x<middle)
    {
        tadj.x+=open;
        if(tadj.x>middle)
        {
            outColor=colorA;
        }
        else
        {
            outColor=colorB;
            float distanceFromMiddle=fabs(.5-tadj.x);
            float softEdgeWidth=min(softEdgeMaxWidth,u.transitionProgressLinear*edgeRamp);
            if(distanceFromMiddle<softEdgeWidth)
            {
                float blend=smoothstep(0.0,.7,distanceFromMiddle/softEdgeWidth);
                mixColor(outColor, colorA, colorB, blend);
            }
        }
    }
    else
    {
        tadj.x-=open;
        if(tadj.x<middle)
        {
            outColor=colorA;
        }
        else
        {
            outColor=colorB;
            float distanceFromMiddle=fabs(.5-tadj.x);
            float softEdgeWidth=min(softEdgeMaxWidth,u.transitionProgressLinear*edgeRamp);
            if(distanceFromMiddle<softEdgeWidth)
            {
                float blend=smoothstep(0.0,.7,distanceFromMiddle/softEdgeWidth);
                mixColor(outColor, colorA, colorB, blend);
            }
        }
    }

#ifdef USE_MASK
    alpha *= float(inputTexMask.sample(linearSampler, input.texMask).a);
#endif
    multiplyOpacity(outColor, alpha);
    return outColor;
}
