#version 330

// Include lights
#include light.ss;

// Textures
uniform sampler2D uDiffuseMap;
uniform sampler2D uRoughnessMap;
uniform sampler2D uMetallicMap;

uniform sampler2D uNormalMap;
uniform mat4 ucNormalRotationMatrix;


in vec3 wPosition;
//in vec3 wNormal;

in vec3 fPosition;
//in vec3 fNormal;

in vec2 fTexCoord;

out vec4 fragColor;

void main()
{
	vec4 textureColor = texture(uDiffuseMap, fTexCoord);
	vec4 roughnessSample = texture(uRoughnessMap, fTexCoord);
	vec4 metallicSample = texture(uMetallicMap, fTexCoord);
	
	float roughness = roughnessSample.x;
	float metallic = metallicSample.x;
	
	Material mat = getMaterial(metallic, roughness);
	
	// Hack. We know that terrain is flat
	vec3 mapNormal = texture(uNormalMap, fTexCoord).rgb * 2.0f - 1.0f;
	mapNormal = mat3(ucNormalRotationMatrix) * mapNormal;
	
	vec3 wNormal = mapNormal;
	vec3 fNormal = mat3(transpose(inverse(uViewMatrix))) * mapNormal;
	
	
	vec4 finalColor = calculateAllLighting(wPosition
	, fPosition
	, wNormal
	, fNormal
	, textureColor
	, mat);
	
	//  Normal debug 
	float dotNormal = dot(normalize(-fPosition), fNormal);
	fragColor = vec4(wNormal, 1) * dotNormal + vec4(finalColor.xyz, 1.0f);
	
	/*
	fragColor = vec4(finalColor.xyz, 1.0f);
	*/
}