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

typedef struct
{
    int direction;
    float easeInOut;
    float motionRamp;
    float motionSpeed;
} fxVars;

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

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

    if(uniforms.transitionState==0)
    {
        float scale = mix(.16, 1.0, uniforms.segmentStart[vars.direction]);

        tmpPos.xy *= scale;
    }
    else if(uniforms.transitionState==2)
    {
        tmpPos.xy *= (smoothstep(0.0, 1.0, 1.0 - uniforms.segmentStart[vars.direction]) * 4.0 + 1.0);
    }

    tmpPos = handleContinuedMotion(tmpPos, uniforms.localTime, vars.motionRamp, vars.motionSpeed);

    out.position = tmpPos;

    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 fxVars& vars[[ buffer(1)]]
                             ,constant subFXVars& subVars[[buffer(3)]])
{
    float4 outColor = getColor(inputTex0, input.tex1);
    float distance = u.segmentEnd[vars.direction] - u.segmentStart[vars.direction];
    float progress = u.segmentStart[vars.direction] + distance * input.normPos.x;
    float alpha = u.baseAlpha * progress;

#ifdef IS_MEDIA_FILL
    alpha *= outColor.a;
    outColor = float4(inputTex1.sample(linearSampler, input.tex2));
#endif

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

    multiplyOpacity(outColor, alpha);

#ifdef SHOW_SEGMENT_OUTLINE
    showSegmentOutline(outColor);
#endif

    return outColor;
}
