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

typedef struct
{
    float blendValue;
    float speed;
} fxVars;

constant float PI = 3.14159265;


vertex fxVertexOut vertexFunc(uint vertexID [[ vertex_id ]]
                              ,const device fxShaderVerts* in[[ buffer(0) ]]
                              ,texture2d<half> inputTex0 [[ texture(0) ]]
                              ,texture2d<half> inputTexMask [[ texture(1) ]]
                              ,constant fxGeneralUniforms& u[[ buffer(1) ]]
                              ,constant fxVars& vars[[ buffer(2)]])
{
    fxVertexOut out;

    out.normPos=in[vertexID].pos.xy*vec2(.5,-.5f)+vec2(.5,.5);
    out.position=in[vertexID].pos;
    out.texSize=float2(inputTex0.get_width(),inputTex0.get_height());
    out.tex1=in[vertexID].tex1;
    out.texMask=in[vertexID].texMask;
    return out;
}

fragment float4 fragmentFunc(fxVertexOut input [[stage_in]]
                             ,texture2d<half> inputTex [[ texture(0) ]]
                             ,texture2d<half> inputTexMask [[ texture(1) ]]
                             ,constant fxGeneralUniforms& u[[ buffer(0) ]]
                             ,constant fxVars& vars[[ buffer(1)]])
{
    float color1, color2, color;
    float fsTime=u.globalTime*vars.speed;
    float2 tmpTex=input.tex1*input.texSize;
    color1 = (sin(dot(tmpTex.xy,vec2(sin(fsTime*3.0),cos(fsTime*3.0)))*0.02+fsTime*3.0)+1.0)/2.0;

    vec2 center = vec2(input.texSize.x/2.0,input.texSize.y/2.0) + vec2(sin(-fsTime*3.0),cos(-fsTime*3.0));

    color2 = (cos(length(tmpTex.xy - center)*0.03)+1.0)/2.0;

    color = (color1+ color2)/2.0;

    float red = (cos(PI*color/0.5+fsTime*3.0)+1.0)/2.0;
    float green = (sin(PI*color/0.5+fsTime*3.0)+1.0)/2.0;
    float blue = (sin(+fsTime*3.0)+1.0)/2.0;

    vec4 plasma = vec4(red, green, blue, 1.0);
    float4 outColor=getColor(inputTex,input.tex1);
#ifdef PRE_MULT
    divideAlpha(outColor);
#endif
    float blendValue2=u.blendValue*vars.blendValue;

#ifdef USE_MASK
    blendValue2*=getColor(inputTexMask,input.texMask).a;
#endif
    outColor.rgb=mix(outColor.rgb,plasma.rgb * u.nitsScale,blendValue2);
#ifdef PRE_MULT
    multiplyAlpha(outColor);
#endif
    return outColor;
}
