
#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.normPos=in[vertexID].pos.xy;



    vec4 deltaTransIn=vec4(0.,0.,-3.0,.0);
    vec4 transOffsetIn=vec4(0.0,0.0,-3.0,.0);

    mat4 projection = mat4(
                           2.4140,0.0000,0.0000,0.0000,
                           0.0000,2.4140,0.0000,0.0000,
                           0.0000,0.0000,-1.020,-.4870,
                           0.0000,0.0000,-1.000,0.0000);
    mat4 translation=mat4(
                          1.0, 0.0, 0.0, 0.00,
                          0.0, 1.0, 0.0, 0.00,
                          0.0, 0.0, 1.0,-2.414,
                          0.0, 0.0, 0.0, 1.00);

    vec4 worldPos=vec4(in[vertexID].pos.xyz,1.0)*uniforms.worldViewProj;

    if(uniforms.transitionState==0)
    {
        float progress=uniforms.transitionProgress*1.;
        transOffsetIn-=deltaTransIn*progress;

        translation[0][3]+=transOffsetIn.x;
        translation[1][3]+=transOffsetIn.y;
        translation[2][3]+=transOffsetIn.z;
    }

    worldPos*=translation;
    out.position=worldPos*projection;

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

    float4 outColor=vec4(0,0,0,0);
    float alpha = u.baseAlpha;
    if(u.transitionState==0)
    {
        outColor=getColor(inputTex0,input.tex1);
        alpha *= u.transitionProgress;
    }
    else
    {
        //expanding old texture and splitting in middle
        vec2 tadj=input.tex1;
        float open=u.transitionProgress*.5;
        float middle=.5;
        if(input.tex1.x<middle)
        {
            tadj.x+=open;
            if(tadj.x>middle)
                discard_fragment();
        }
        else
        {
            tadj.x-=open;
            if(tadj.x<middle)
                discard_fragment();
        }
        outColor=getColor(inputTex0,tadj);
    }
#ifdef USE_MASK
    alpha *= float(inputTexMask.sample(linearSampler, input.texMask).a);
#endif
    multiplyOpacity(outColor, alpha);
    return outColor;
}
