
uniform sampler2DArray u_textures;
uniform samplerBuffer u_tints;
uniform ivec4 u_texture_info;
uniform int u_atlas;
uniform sampler2D u_tint_info;

#if !defined shadow_pass
    in vec3 v_normal;
#endif

in vec2 v_uv;
in vec4 v_tint;
in vec4 v_highlight;
flat in int v_tint_offset;
in vec3 v_fragpos;

layout (location = 0) out vec3 frag_color;

#if !defined shadow_pass && !defined highlight
    layout (location = 1) out vec3 g_normal;
    layout (location = 2) out vec3 g_position;
#endif


void main() {
    ivec3 texture_size = textureSize(u_textures, 0);
    vec4 col = texture(u_textures, vec3(
        (vec2(u_texture_info.xy) + vec2(u_texture_info.zw) * v_uv) / vec2(texture_size.xy),
        float(u_atlas))
    ) * v_tint;

    float tint_o = texture(u_tint_info, v_uv).r;

    vec4 tint = texelFetch(u_tints, v_tint_offset + int(tint_o * 255.0 + 0.5));
    col *= tint;
    if (col.a < 0.3) discard;

    #if defined highlight
        if (all(lessThan(v_highlight.rgb, vec3(0.1)))) discard;
        frag_color = v_highlight.rgb;
    #else
        frag_color = col.rgb;
    #endif
    #if !defined shadow_pass && !defined highlight
        vec3 normal = normalize(v_normal);
        g_normal = normal * 0.5 + 0.5;
        g_position = v_fragpos;
    #endif
}
