#version 330

layout(std140) uniform vsConstants
{
    mat4 projection;
} _173;

uniform samplerBuffer maskTexCoordTable;

flat out uint vFlags;
layout(location = 3) in uint flags;
out vec2 mask1UV;
out vec2 mask2UV;
layout(location = 2) in uvec2 masks;
flat out vec3 vTint;
out vec2 vUV;
layout(location = 1) in vec2 uv;
layout(location = 0) in vec2 position;

vec2 getMaskUV(vec2 corner, uint maskIndex)
{
    int offset = int(maskIndex) * 4;
    float u = texelFetch(maskTexCoordTable, offset + 0).x;
    float v = texelFetch(maskTexCoordTable, offset + 1).x;
    float w = texelFetch(maskTexCoordTable, offset + 2).x;
    float h = texelFetch(maskTexCoordTable, offset + 3).x;
    return vec2(u, v) + (corner * vec2(w, h));
}

vec3 decodeRGB565(int rgb5)
{
    ivec3 colorUnpacked = (ivec3(rgb5) >> ivec3(11, 5, 0)) & ivec3(31, 63, 31);
    return vec3(vec3(colorUnpacked) / vec3(31.0, 63.0, 31.0));
}

void main()
{
    vFlags = flags;
    mask1UV = vec2(-1.0);
    mask2UV = vec2(-1.0);
    int vertexID = int(flags >> uint(2)) & 3;
    vec2 corner = vec2(float(vertexID >> 1), float(vertexID & 1));
    if (masks.x != 65535u)
    {
        vec2 param = corner;
        uint param_1 = masks.x;
        mask1UV = getMaskUV(param, param_1);
    }
    if (masks.y != 65535u)
    {
        vec2 param_2 = corner;
        uint param_3 = masks.y;
        mask2UV = getMaskUV(param_2, param_3);
    }
    int param_4 = int(flags >> uint(16));
    vTint = decodeRGB565(param_4);
    vUV = uv;
    gl_Position = _173.projection * vec4(position, 0.0, 1.0);
}

