#version 460 compatibility

/*
====================================================================================================

    Copyright (C) 2025 Pyvtron VX Shaders - Pyvtron

    All Rights Reserved unless otherwise explicitly stated.

    Before You Do Something With Pyvtron VX Shaders, You MUST Read This:

    You Must Read The License: https://pyvtron.pages.dev/minecraft-shaders/pyvtron-shaders-license
    And Read The Agreement: https://pyvtron.pages.dev/minecraft-shaders/pyvtron-shaders-agreement

====================================================================================================
*/


#include "/Include/Settings.glsl"
#include "/Include/Core/Core.glsl"

uniform int renderStage;
uniform sampler2D texture;

in vec4 color;
in vec2 texcoord;
in vec3 normal;
in vec2 blockLight;

#ifdef DISTANT_HORIZONS
uniform bool dh_is_lod;
uniform int dhMaterialId;
#endif

uniform vec3 sunDirection;
uniform vec3 sunColor;

float CurveBlockLightTorch(float blockLight) {
    float falloff = 10.0;
    blockLight = exp(-(1.0 - blockLight) * falloff);
    blockLight = max(0.0, blockLight - exp(-falloff));
    return blockLight;
}

void main() {
    vec4 albedo = color;
    vec2 mcLightmap = blockLight;
    float materialIDs = 1.0;
    vec3 lighting = vec3(1.0);

    #ifdef DISTANT_HORIZONS
    if (dh_is_lod) {
        albedo = texture2D(texture, texcoord);
        if (albedo.a < 0.1) discard;

        vec3 safeNormal = length(normal) > 0.1 ? normalize(normal) : vec3(0.0, 1.0, 0.0);

        vec3 sunDir = normalize(sunDirection);
        float sunDot = max(dot(safeNormal, sunDir), 0.0);

        vec3 directLight = sunDot * sunColor * 2.0;

        vec3 ambientLight = vec3(0.45);
        ambientLight = mix(ambientLight, vec3(0.6, 0.65, 0.7), (safeNormal.y * 0.6 + 0.4));

        lighting = directLight + ambientLight * 0.7;
        lighting = max(lighting, vec3(0.3));

        mcLightmap = vec2(1.0);

        materialIDs = 254.0;
    }
    #endif

    if (renderStage == MC_RENDER_STAGE_OUTLINE || renderStage == MC_RENDER_STAGE_DEBUG) {
        if (renderStage == MC_RENDER_STAGE_OUTLINE) {
            albedo.rgb = vec3(SELECTION_BOX_COLOR);
        }
        materialIDs = 200.0;
        mcLightmap = vec2(0.0);
    }

    if (albedo.a < 0.1) discard;

    gl_FragData[0] = vec4(albedo.rgb * lighting, 1.0);
    gl_FragData[1] = vec4(EncodeNormal(normalize(normal)), mcLightmap);
    gl_FragData[2] = vec4(0.0, 0.0, (materialIDs + 0.1) / 255.0, 1.0);
}

/* DRAWBUFFERS:036 */