#include "client/render/shader/EntityShader.h"

namespace blitz {
namespace shader {

#ifdef __ANDROID__
static const char vertexSource[] =
	R"(#version 300 es

precision mediump float;

layout(location = 0) in vec3 position;
layout(location = 1) in int color;

uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform vec3 modelPosition;

flat out int pass_color;

void main(void){
	pass_color = color;
	gl_Position = projectionMatrix * viewMatrix * vec4(position + modelPosition, 1.0);
}
)";

static const char fragmentSource[] =
	R"(#version 300 es

precision mediump float;

flat in int pass_color;

out vec4 out_color;

uniform vec3 ColorEffect;

void main(void){

    float r = float(pass_color >> 24 & 0xFF) / 255.0;
    float g = float(pass_color >> 16 & 0xFF) / 255.0;
    float b = float(pass_color >> 8 & 0xFF) / 255.0;
    float a = float(pass_color & 0xFF) / 255.0; 
	vec3 intermediate_color = vec3(r, g, b) * ColorEffect;
	out_color = vec4(intermediate_color, a);

}
)";
#else
static const char vertexSource[] = R"(
#version 330

layout(location = 0) in vec3 position;

uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform vec3 modelPosition;

//flat out int pass_color;

void main(void){
	//pass_color = color;
	gl_Position = vec4(position, 1.0);
	//gl_Position = projectionMatrix * viewMatrix * vec4(position + modelPosition, 1.0);
}
)";

static const char fragmentSource[] = R"(
#version 330

flat in int pass_color;

out vec4 out_color;

uniform vec3 ColorEffect;

void main(void){

	out_color = vec4(1, 1, 1, 1);

}
)";
#endif

EntityShader::EntityShader() : ShaderProgram() {}

void EntityShader::LoadShader() {
	ShaderProgram::LoadProgram(vertexSource, fragmentSource);
}

void EntityShader::GetAllUniformLocation() {
	m_LocationColorEffect = static_cast<unsigned int>(GetUniformLocation("ColorEffect"));
	m_LocationViewMatrix = static_cast<unsigned int>(GetUniformLocation("viewMatrix"));
	m_LocationPosition = static_cast<unsigned int>(GetUniformLocation("modelPosition"));
	m_LocationProjectionMatrix = static_cast<unsigned int>(GetUniformLocation("projectionMatrix"));
}

void EntityShader::SetColorEffect(const Vec3f& color) {
	LoadVector(m_LocationColorEffect, color);
}

void EntityShader::SetProjectionMatrix(const Mat4f& proj) const {
	LoadMat4(m_LocationProjectionMatrix, proj);
}

void EntityShader::SetViewMatrix(const Mat4f& view) const {
	LoadMat4(m_LocationViewMatrix, view);
}

void EntityShader::SetModelPos(const Vec3f& pos) const {
	LoadVector(m_LocationPosition, pos);
}

}  // namespace shader
}  // namespace blitz