precision mediump float;

uniform sampler2D texture;
uniform float gridColumnCount;
uniform float isEndlessTileList;

varying vec2 pass_TexCoords;

const float texAtlasWidth = 3.0;

float getAtlasIndex();
vec2 getTexCoordsInAtlas(in vec2 texCoordsInGrid, in float atlasIndex);

void main() {

    float atlasIndex = getAtlasIndex();
    vec2 texCoordsInGrid = pass_TexCoords;
    texCoordsInGrid.x *= gridColumnCount;
    texCoordsInGrid.x = mod(texCoordsInGrid.x, 1.0);
    vec2 texCoordsInAtlas = getTexCoordsInAtlas(texCoordsInGrid, atlasIndex);

    gl_FragColor = texture2D(texture, texCoordsInAtlas);
    gl_FragColor.rgb = gl_FragColor.rgb / gl_FragColor.a;
}

float getAtlasIndex(){

    if(isEndlessTileList == 1.0)
        return 1.0;

    if(pass_TexCoords.x < 1.0 / gridColumnCount)
        return 0.0;
    if(pass_TexCoords.x > 1.0 - 1.0 / gridColumnCount)
        return 2.0;
    return 1.0;

}

vec2 getTexCoordsInAtlas(in vec2 texCoordsInGrid, in float atlasIndex){

    vec2 texAtlasCoords = vec2(0.0, texCoordsInGrid.y);
    texAtlasCoords.x = texCoordsInGrid.x / texAtlasWidth;
    texAtlasCoords.x += mod(atlasIndex, texAtlasWidth) / texAtlasWidth;
    return texAtlasCoords;

}