#include "metalShaderTypes.h"
#include "alpha.h"
#include "commonMLDX.h"
#include "outputColorHelper.h"

constant float4 std709X = float4(  0.183,   0.614,  0.062, 0.0  );
constant float4 std709Y = float4( -0.101,  -0.338,  0.439, 0.0  );
constant float4 std709Z = float4(  0.439,  -0.399, -0.040, 0.0  );

typedef struct
{
    float4 position [[position]];
    float2 texCoord1;
    float2 texCoord2;
    float2 texCoord3;
    float2 texCoord4;
} vertexOut4;


constexpr sampler nearestSampler(
    mip_filter::nearest,
    mag_filter::nearest,
    min_filter::nearest,
    address::clamp_to_border,
    border_color::transparent_black);


vertex vertexOut4 vertexFunc(uint vertexID [[ vertex_id ]],
                                   const device pixCopyVertexFormat* in [[ buffer(0) ]])
{
    vertexOut4 out;

    out.position = in[vertexID].pos;

    out.texCoord1 = in[vertexID].tc;

    out.texCoord2 = in[vertexID].tc;
    out.texCoord2.x+=1.0;

    out.texCoord3 = in[vertexID].tc;
    out.texCoord3.x+=2.0;

    out.texCoord4 = in[vertexID].tc;
    out.texCoord4.x+=3.0;

    return out;
}

fragment float4 fragmentFunc(vertexOut4 input [[stage_in]],
                             texture2d<half> inputTex0 [[ texture(0) ]])
{
    float2 texSize=float2(inputTex0.get_width(),inputTex0.get_height());

    float4 texColor0 = toOutput(float4(inputTex0.sample(nearestSampler,input.texCoord1/texSize)));
    float4 texColor1 = toOutput(float4(inputTex0.sample(nearestSampler,input.texCoord2/texSize)));
    float4 texColor2 = toOutput(float4(inputTex0.sample(nearestSampler,input.texCoord3/texSize)));
    float4 texColor3 = toOutput(float4(inputTex0.sample(nearestSampler,input.texCoord4/texSize)));

    float4 yuv0 = float4(dot(std709X, texColor0)+0.0625,
                         dot(std709Y, texColor0)+0.5,
                         dot(std709Z, texColor0)+0.5,
                         1.0 );

    float4 yuv1 = float4(dot(std709X, texColor1)+0.0625,
                         dot(std709Y, texColor1)+0.5,
                         dot(std709Z, texColor1)+0.5,
                         1.0 );

    float4 yuv2 = float4(dot(std709X, texColor2)+0.0625,
                         dot(std709Y, texColor2)+0.5,
                         dot(std709Z, texColor2)+0.5,
                         1.0 );

    float4 yuv3 = float4(dot(std709X, texColor3)+0.0625,
                         dot(std709Y, texColor3)+0.5,
                         dot(std709Z, texColor3)+0.5,
                         1.0 );

    float4 outColor;

    outColor=float4(yuv2.r,yuv1.r,yuv0.r,yuv3.r);

    return outColor;
}
