#version 150

// This came from some tutorial, mentioning some drivers required this to function
//   properly but did not delve into why. 
precision highp float;

#include "ice_shader_api.frag"

in vec3 fsWorldPosition;
in vec3 fsNormal;
in vec4 fsColor;
in vec2 fsTextureUV;
in float fsDotLight;

in vec3 fsDirectionVS;

uniform mat4 uWorldToView;

in vec4 shadowCoordinates[4];

out vec4 finalFragColor;

void main(void)
{
	vec4 texturedfsColor = uMaterialColor; //fsColor * uMaterialColor * texture(sAlbedoTexture, fsTextureUV);

	vec3 x_deriv = dFdx(fsWorldPosition);
	vec3 y_deriv = dFdy(fsWorldPosition);
	vec3 flatNormal = normalize(cross(x_deriv, y_deriv));

	vec3 L = normalize(vec3(uSunLightDirection));
	float nDotL = max(0.0, dot(flatNormal, L));
	
	vec3 diffuseLighting = (nDotL * vec3(texturedfsColor) * vec3(uSunLightColor));

	vec3 view_nor = normalize(flatNormal * inverse(transpose(mat3(uWorldToView))));
	vec3 mirror_dir = reflect(-normalize(fsDirectionVS), view_nor);
	vec3 U = vec3(0.0, 1.0, 0.0);
	float mDotU = dot(flatNormal, U);
	vec3 low = vec3(10.0, 5.0, 0.0);
	vec3 high = vec3(0.0, 0.2, 3.0);
	diffuseLighting += mix(low, high, mDotU * 0.5 + 0.5) * pow(max(0.0, mDotU), 10.0);

	vec3 ambientLighting = vec3(uAmbientLightColor) * vec3(texturedfsColor);
	vec3 finalColor = ambientLighting + diffuseLighting;

	// vec3 white = tonemap_aces(vec3(1000.0));
	// vec3 white_point = vec3(3.75, 4.0, 4.5);
	// float exposure = 1.25;
	// finalColor *= exp2(exposure);
	// finalColor = tonemap_aces(finalColor / white_point) * white;
	// finalColor = sampleLUT(sColorTableTexture, finalColor).rgb;

	// float gamma = 2.2;
	// finalFragColor = vec4(pow(finalColor, vec3(1.0 / gamma, 1.0 / gamma, 1.0 / gamma)), texturedfsColor.a);


		// float exposure = 1.5;
		// finalColor *= exp2(exposure);
		// finalFragColor = vec4(finalColor, 1.0);
		// finalFragColor *= texturedfsColor.a;

	// float exposure = 1.5;
	// finalColor *= exp2(exposure);
	finalFragColor = MakeFinalOutputColor(finalColor, texturedfsColor.a);
}
