layout(location = 0) out vec4 albedoData;
layout(location = 1) out vec4 colortex7Out;
layout(location = 2) out vec4 colortex3Out;

/* DRAWBUFFERS:673 */

#include "/lib/Head/Common.inc"

uniform sampler2D tex;
#ifdef MC_NORMAL_MAP
    uniform sampler2D normals;
#endif
#ifdef MC_SPECULAR_MAP
    uniform sampler2D specular;
#endif

in vec4 tint;
in vec2 texcoord;
in vec4 viewPos;

in vec2 lightmap;

flat in mat3 tbnMatrix;
flat in int itemId;

float bayer2 (vec2 a) { a = 0.5 * floor(a); return fract(1.5 * fract(a.y) + a.x); }
#define bayer4(a) (bayer2(0.5 * (a)) * 0.25 + bayer2(a))

void main() {	
	vec4 albedo = texture(tex, texcoord) * tint;

	#ifdef WHITE_WORLD
		albedo.rgb = vec3(1.0);
	#endif

	if (albedo.a < 0.1) { discard; return; }

	#ifdef MC_SPECULAR_MAP
		vec4 specularData = texture(specular, texcoord);
	#else
		vec4 specularData = vec4(0.0);
	#endif

    #ifdef MC_NORMAL_MAP
        vec3 normalData = texture(normals, texcoord).rgb;
        DecodeNormalTex(normalData);
    #else
        vec3 normalData = vec3(0.0, 0.0, 1.0);
    #endif

	bool isSword = (itemId == 15010);
	
	if (isSword) {
		specularData.r = 0.98;
		specularData.g = 0.95;
		specularData.b = 0.0;
		specularData.a = 0.0;
		
		albedo.rgb = mix(albedo.rgb, albedo.rgb * vec3(0.85, 0.9, 1.05), 0.45);
		albedo.rgb = pow(albedo.rgb, vec3(0.88));
		
		vec3 viewDir = normalize(viewPos.xyz);
		float fresnel = pow(1.0 - abs(dot(tbnMatrix[2], viewDir)), 2.5);
		albedo.rgb += fresnel * vec3(0.15, 0.18, 0.25);
	}

	normalData = normalize(tbnMatrix * normalData);

	albedoData = vec4(albedo.rgb, PackUnorm2x8(specularData.rg));

	colortex7Out.xy = lightmap + (bayer4(gl_FragCoord.xy) - 0.5) * rcp(255.0);
	colortex7Out.z = 17.1 / 255.0;
	colortex7Out.w = 1.0;

	colortex3Out.xy = EncodeNormal(normalData);
	colortex3Out.z = PackUnorm2x8(specularData.ba);
	colortex3Out.w = 1.0;
}