
#include "/lib/config/master.glsl"

#ifdef FRAGMENT_SHADER

flat in int mat;

in vec2 texCoord;
in vec2 lmCoord;
in vec2 signMidCoordPos;
flat in vec2 absMidCoordPos;

flat in vec3 upVec, sunVec, northVec, eastVec;
in vec3 playerPos;
in vec3 normal;
in vec3 viewVector;

in vec4 glColor;

#if LU_WATER_STYLE >= 2 || LU_RAIN_PUDDLES >= 1 && LU_WATER_STYLE == 1 && LU_WATER_MAT_QUALITY >= 2 || defined LU_GENERATED_NORMALS || defined LU_CUSTOM_PBR
    flat in vec3 binormal, tangent;
#endif

#ifdef LU_POM
    in vec4 vTexCoordAM;
#endif

float NdotU = dot(normal, upVec);
float NdotUmax0 = max(NdotU, 0.0);
float SdotU = dot(sunVec, upVec);

float sunFactor = SdotU < 0.0 ? clamp(SdotU + 0.375, 0.0, 0.75) / 0.75 : clamp(SdotU + 0.03125, 0.0, 0.0625) / 0.0625;
float sunVisibility = clamp(SdotU + 0.0625, 0.0, 0.125) / 0.125;
float sunVisibility2 = sunVisibility * sunVisibility;
float shadowTimeVar1 = abs(sunVisibility - 0.5) * 2.0;
float shadowTimeVar2 = shadowTimeVar1 * shadowTimeVar1;
float shadowTime = shadowTimeVar2 * shadowTimeVar2;

#ifdef OVERWORLD
    vec3 lightVec = sunVec * ((timeAngle < 0.5325 || timeAngle > 0.9675) ? 1.0 : -1.0);
#else
    vec3 lightVec = sunVec;
#endif

#if LU_WATER_STYLE >= 2 || LU_RAIN_PUDDLES >= 1 && LU_WATER_STYLE == 1 && LU_WATER_MAT_QUALITY >= 2 || defined LU_GENERATED_NORMALS || defined LU_CUSTOM_PBR
    mat3 tbnMatrix = mat3(
        tangent.x, binormal.x, normal.x,
        tangent.y, binormal.y, normal.y,
        tangent.z, binormal.z, normal.z
    );
#endif

float lu_GetLinearDepth(float depth) {
    return (2.0 * near) / (far + near - depth * (far - near));
}

#include "/lib/sky/globals.glsl"
#include "/lib/light/core.glsl"
#include "/lib/sky/aero/main.glsl"

#ifdef OVERWORLD
    #include "/lib/sky/volumetric.glsl"
#endif

#if LU_WATER_REFLECT_QUALITY >= 0
    #if defined LU_SKY_EFFECT_REFLECTION && defined OVERWORLD
        #include "/lib/sky/volumetric.glsl"

        #ifdef LU_VL_CLOUDS_ACTIVE
            #include "/lib/sky/scatter/main.glsl"
        #endif
    #endif

    #include "/lib/mtl_method/reflect.glsl"
#endif

#ifdef LU_TAA
    #include "/lib/filter/offset.glsl"
#endif

#if defined LU_GENERATED_NORMALS || defined LU_COATED_TEXTURES || LU_WATER_STYLE >= 2

    vec2 dcdx = dFdx(texCoord.xy);
    vec2 dcdy = dFdy(texCoord.xy);
    vec2 midCoordPos = absMidCoordPos * signMidCoordPos;

    vec2 mipx = dcdx / absMidCoordPos * 8.0;
    vec2 mipy = dcdy / absMidCoordPos * 8.0;

    float mipDelta = max(dot(mipx, mipx), dot(mipy, mipy));
    float miplevel = max(0.5 * log2(mipDelta), 0.0);

    #if !defined LU_GBUFFERS_ENTITIES && !defined LU_GBUFFERS_HAND
        vec2 atlasSizeM = atlasSize;
    #else
        vec2 atlasSizeM = atlasSize.x + atlasSize.y > 0.5 ? atlasSize : textureSize(tex, 0);
    #endif
#endif

#ifdef LU_GENERATED_NORMALS
    #include "/lib/mtl_method/normals.glsl"
#endif

#if LU_IPBR_EMISSIVE_MODE != 1
    #include "/lib/mtl_method/emission.glsl"
#endif

#ifdef LU_CUSTOM_PBR
    #include "/lib/mtl_handle/custom.glsl"
#endif

#ifdef ATM_COLOR_MULTS
    #include "/lib/colors/effects.glsl"
#endif
#ifdef MOON_PHASE_INF_ATMOSPHERE
    #include "/lib/colors/effects.glsl"
#endif

#ifdef COLOR_CODED_PROGRAMS
    #include "/lib/fx/unified.glsl"
#endif

#ifdef LU_PORTAL_EDGE_EFFECT

    #include "/lib/fx/unified.glsl"
#endif

#ifdef LU_CONNECTED_GLASS_EFFECT
    #include "/lib/mtl_method/glass_connect.glsl"
#endif

void main() {

    vec4 colorP = texture2D(tex, texCoord);
    vec4 color = colorP * vec4(glColor.rgb, 1.0);

    vec3 screenPos = vec3(gl_FragCoord.xy / vec2(viewWidth, viewHeight), gl_FragCoord.z);
    #ifdef LU_TAA
        vec3 viewPos = lu_ScreenToView(vec3(lu_TAAJitter(screenPos.xy, -0.5), screenPos.z));
    #else
        vec3 viewPos = lu_ScreenToView(screenPos);
    #endif
    float lViewPos = length(viewPos);

    float dither = Bayer64(gl_FragCoord.xy);
    #ifdef LU_TAA
        dither = fract(dither + goldenRatio * mod(float(frameCounter), 3600.0));
    #endif

    #ifdef LIGHT_COLOR_MULTS
        lightColorMult = GetLightColorMult();
    #endif
    #ifdef ATM_COLOR_MULTS
        atmColorMult = GetAtmColorMult();
        sqrtAtmColorMult = sqrt(atmColorMult);
    #endif

    #ifdef LU_VL_CLOUDS_ACTIVE
        float cloudLinearDepth = texelFetch(gaux1, texelCoord, 0).r;

        if (lu_pow2(cloudLinearDepth + OSIEBCA * dither) * renderDistance < min(lViewPos, renderDistance)) discard;
    #endif

    #if LU_WATER_MAT_QUALITY >= 3
        float materialMask = 0.0;
    #endif

    vec3 nViewPos = normalize(viewPos);
    float VdotU = dot(nViewPos, upVec);
    float VdotS = dot(nViewPos, sunVec);
    float VdotN = dot(nViewPos, normal);

    vec4 translucentMult = vec4(1.0);
    bool noSmoothLighting = false;
    bool noDirectionalShading = false;
    bool translucentMultCalculated = false;
    bool noGeneratedNormals = false;

    int subsurfaceMode = 0;
    float smoothnessG = 0.0;
    float highlightMult = 1.0;
    float reflectMult = 0.0;
    float emission = 0.0;

    vec2 lmCoordM = lmCoord;
    vec3 normalM = VdotN > 0.0 ? -normal : normal;
    vec3 geoNormal = normalM;
    vec3 worldGeoNormal = normalize(lu_ViewToPlayer(geoNormal * 10000.0));
    vec3 shadowMult = vec3(1.0);
    float fresnel = clamp(1.0 + dot(normalM, nViewPos), 0.0, 1.0);

    #ifdef LU_IPBR
        #include "/lib/mtl_handle/translucent.glsl"

        #ifdef LU_GENERATED_NORMALS
            if (!noGeneratedNormals) lu_GenerateNormals(normalM, colorP.rgb * colorP.a * 1.5);
        #endif

        #if LU_IPBR_EMISSIVE_MODE != 1
            emission = GetCustomEmissionForIPBR(color, emission);
        #endif
    #else
        #ifdef LU_CUSTOM_PBR
            float smoothnessD, materialMaskPh;
            lu_GetCustomMaterials(color, normalM, lmCoordM, NdotU, shadowMult, smoothnessG, smoothnessD, highlightMult, emission, materialMaskPh, viewPos, lViewPos);
            reflectMult = smoothnessD;
        #endif

        if (mat == 32000) {
            #include "/lib/blocks/translucent/water.glsl"
        } else if (mat == 30020) {
            #ifdef LU_SPECIAL_PORTAL_EFFECTS
                #include "/lib/blocks/translucent/portal_nether.glsl"
            #endif
        }
    #endif

    #if LU_WATER_MAT_QUALITY >= 3 && LU_SELECT_OUTLINE == 4
        int materialMaskInt = int(texelFetch(colortex6, texelCoord, 0).g * 255.1);
        if (materialMaskInt == 252) {
            materialMask = OSIEBCA * 252.0;
        }
    #endif

    if (!translucentMultCalculated)
        translucentMult = vec4(mix(vec3(0.666), color.rgb * (1.0 - lu_pow2(lu_pow2(color.a))), color.a), 1.0);

    translucentMult.rgb = mix(translucentMult.rgb, vec3(1.0), lu_min1(lu_pow2(lu_pow2(lViewPos / far))));

    lu_DoLighting(color, shadowMult, playerPos, viewPos, lViewPos, geoNormal, normalM, dither,
               worldGeoNormal, lmCoordM, noSmoothLighting, noDirectionalShading, false,
               false, subsurfaceMode, smoothnessG, highlightMult, emission);

    #if LU_WATER_REFLECT_QUALITY >= 0
        #ifdef LIGHT_COLOR_MULTS
            highlightColor *= lightColorMult;
        #endif
        #ifdef LU_MOON_PHASE_INF_REFLECTION
            highlightColor *= lu_pow2(moonPhaseInfluence);
        #endif

        float fresnelM = (lu_pow3(fresnel) * 0.7 + 0.08) * reflectMult * 0.65;

        #ifdef OVERWORLD
            float lu_nightDim = mix(0.18, 1.0, sunFactor);
            fresnelM *= lu_nightDim;
        #endif

        float skyLightFactor = lu_pow2(max(lmCoordM.y - 0.7, 0.0) * 3.33333);
        #if LU_SHADOW_QUALITY > -1 && LU_WATER_REFLECT_QUALITY >= 2 && LU_WATER_MAT_QUALITY >= 2
            skyLightFactor = max(skyLightFactor, lu_min1(dot(shadowMult, shadowMult)));
        #endif

        vec4 reflection = lu_GetReflection(normalM, viewPos.xyz, nViewPos, playerPos, lViewPos, -1.0,
                                        depthtex1, dither, skyLightFactor, fresnel,
                                        smoothnessG, geoNormal, color.rgb, shadowMult, highlightMult);

        color.rgb = mix(color.rgb, reflection.rgb, fresnelM);
    #endif

    #ifdef COLOR_CODED_PROGRAMS
        lu_ColorCodeProgram(color, mat);
    #endif

    float sky = 0.0;
    lu_DoFog(color.rgb, sky, lViewPos, playerPos, VdotU, VdotS, dither);
    color.a *= 1.0 - sky;

    /* DRAWBUFFERS:03 */
    gl_FragData[0] = color;
    gl_FragData[1] = vec4(1.0 - translucentMult.rgb, translucentMult.a);

    #if LU_DETAIL_QUALITY >= 3

        /* DRAWBUFFERS:036 */
        gl_FragData[2] = vec4(0.0, materialMask, 0.0, 1.0);
    #endif
}

#endif

#ifdef VERTEX_SHADER

flat out int mat;

out vec2 texCoord;
out vec2 lmCoord;
out vec2 signMidCoordPos;
flat out vec2 absMidCoordPos;

flat out vec3 upVec, sunVec, northVec, eastVec;
out vec3 playerPos;
out vec3 normal;
out vec3 viewVector;

out vec4 glColor;

#if LU_WATER_STYLE >= 2 || LU_RAIN_PUDDLES >= 1 && LU_WATER_STYLE == 1 && LU_WATER_MAT_QUALITY >= 2 || defined LU_GENERATED_NORMALS || defined LU_CUSTOM_PBR
    flat out vec3 binormal, tangent;
#endif

#ifdef LU_POM
    out vec4 vTexCoordAM;
#endif

attribute vec4 mc_Entity;
attribute vec4 mc_midTexCoord;
attribute vec4 at_tangent;

#if LU_WATER_STYLE >= 2 || LU_RAIN_PUDDLES >= 1 && LU_WATER_STYLE == 1 && LU_WATER_MAT_QUALITY >= 2 || defined LU_GENERATED_NORMALS || defined LU_CUSTOM_PBR
#else
    vec3 binormal;
    vec3 tangent;
#endif

#ifdef LU_TAA
    #include "/lib/filter/offset.glsl"
#endif

#ifdef LU_WAVING_WATER_VERTEX
    #include "/lib/mtl_method/wave.glsl"
#endif

void main() {

    texCoord = (gl_TextureMatrix[0] * gl_MultiTexCoord0).xy;
    lmCoord  = GetLightMapCoordinates();

    glColor = gl_Color;
    mat = int(mc_Entity.x + 0.5);

    normal = normalize(gl_NormalMatrix * gl_Normal);
    upVec = normalize(gbufferModelView[1].xyz);
    eastVec = normalize(gbufferModelView[0].xyz);
    northVec = normalize(gbufferModelView[2].xyz);
    sunVec = GetSunVector();

    binormal = normalize(gl_NormalMatrix * cross(at_tangent.xyz, gl_Normal.xyz) * at_tangent.w);
    tangent  = normalize(gl_NormalMatrix * at_tangent.xyz);

    mat3 tbnMatrix = mat3(
        tangent.x, binormal.x, normal.x,
        tangent.y, binormal.y, normal.y,
        tangent.z, binormal.z, normal.z
    );

    viewVector = tbnMatrix * (gl_ModelViewMatrix * gl_Vertex).xyz;

    vec2 midCoord = (gl_TextureMatrix[0] * mc_midTexCoord).st;
    vec2 texMinMidCoord = texCoord - midCoord;
    signMidCoordPos = sign(texMinMidCoord);
    absMidCoordPos  = abs(texMinMidCoord);

    #ifdef LU_POM
        vTexCoordAM.zw  = abs(texMinMidCoord) * 2;
        vTexCoordAM.xy  = min(texCoord, midCoord - texMinMidCoord);
    #endif

    vec4 position = gbufferModelViewInverse * gl_ModelViewMatrix * gl_Vertex;
    playerPos = position.xyz;

    #ifdef LU_WAVING_WATER_VERTEX
        lu_DoWave(position.xyz, mat);
    #endif

    gl_Position = gl_ProjectionMatrix * gbufferModelView * position;

    #ifdef LU_TAA
        gl_Position.xy = lu_TAAJitter(gl_Position.xy, gl_Position.w);
    #endif
}

#endif
