#version 330

#moj_import <minecraft:fog.glsl>
#moj_import <minecraft:dynamictransforms.glsl>

uniform sampler2D Sampler0;

in float sphericalVertexDistance;
in float cylindricalVertexDistance;
in vec4 vertexColor;
in vec4 lightColor; // From VSH
in vec4 baseColor;  // From VSH
in vec2 texCoord0;
out vec4 fragColor;

void main() {
    vec4 color = texture(Sampler0, texCoord0) * ColorModulator;
    
    // Extract the alpha channel as an integer
    ivec4 ich = ivec4(round(texelFetch(Sampler0, ivec2(texCoord0 * textureSize(Sampler0, 0)), 0) * 255));
    
    switch (ich.a) {
        // Emissive / Full-bright state
        case 254: 
            color *= baseColor; 
            break;
            
        // Unshaded / Flat-lit state
        case 200: 
        case 250:
        case 252: 
        case 253: 
        case 100: 
        case 50: 
            color *= lightColor; 
            color.rgb *= 0.9; // Slight dimming effect
            break;
            
        // Default Shaded state
        default: 
            color *= vertexColor; 
            break;
    }

    // Alpha cutout to prevent invisible pixels from rendering incorrectly
    if (color.a < 0.1) discard;

    fragColor = apply_fog(color, sphericalVertexDistance, cylindricalVertexDistance, FogEnvironmentalStart, FogEnvironmentalEnd, FogRenderDistanceStart, FogRenderDistanceEnd, FogColor);
}