#include "common_header.h"
#include "skybox.h"

void CSkybox::loadSkybox(char *Front, char *Back, char *Left, char *Right, char *Top, char *Bottom)
{
	Textures[0].loadTexture2D(Front);
	Textures[1].loadTexture2D(Back);
	Textures[2].loadTexture2D(Left);
	Textures[3].loadTexture2D(Right);
	Textures[4].loadTexture2D(Top);
	Textures[5].loadTexture2D(Bottom);

	FOR(i, 6)
	{
		glBindTexture(GL_TEXTURE_2D, Textures[i]);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glBindTexture(GL_TEXTURE_2D, 0);
	}

	glGenVertexArrays(1, &VAO);
	glBindVertexArray(VAO);

	vboRenderData.createVBO();
	vboRenderData.bindVBO();

	vec3 vSkyBoxVertices[24] = 
	{
		vec3(50.0f, 50.0f, 50.0f), vec3(50.0f, -50.0f, 50.0f), vec3(-50.0f, 50.0f, 50.0f), vec3(-50.0f, -50.0f, 50.0f),
		vec3(-50.0f, 50.0f, -50.0f), vec3(-50.0f, -50.0f, -50.0f), vec3(50.0f, 50.0f, -50.0f), vec3(50.0f, -50.0f, -50.0f),
		vec3(-50.0f, 50.0f, 50.0f), vec3(-50.0f, -50.0f, 50.0f), vec3(-50.0f, 50.0f, -50.0f), vec3(-50.0f, -50.0f, -50.0f),
		vec3(50.0f, 50.0f, -50.0f), vec3(50.0f, -50.0f, -50.0f), vec3(50.0f, 50.0f, 50.0f), vec3(50.0f, -50.0f, 50.0f),
		vec3(-50.0f, 50.0f, -50.0f), vec3(50.0f, 50.0f, -50.0f), vec3(-50.0f, 50.0f, 50.0f), vec3(50.0f, 50.0f, 50.0f),
		vec3(50.0f, -50.0f, -50.0f), vec3(-50.0f, -50.0f, -50.0f), vec3(50.0f, -50.0f, 50.0f), vec3(-50.0f, -50.0f, 50.0f),
	};

	vec2 vSkyBoxTexCoords[4] =
	{
		vec2(0.0f, 1.0f), vec2(0.0f, 0.0f), vec2(1.0f, 1.0f), vec2(1.0f, 0.0f)
	};

	vec3 vSkyBoxNormals[6] = 
	{
		vec3(0.0f, 0.0f, -1.0f),
		vec3(0.0f, 0.0f, 1.0f),
		vec3(1.0f, 0.0f, 0.0f),
		vec3(-1.0f, 0.0f, 0.0f),
		vec3(0.0f, -1.0f, 0.0f),
		vec3(0.0f, 1.0f, 0.0f)
	};

	FOR(i, 24)
	{
		vboRenderData.addData(&vSkyBoxVertices[i], sizeof(vec3));
		vboRenderData.addData(&vSkyBoxTexCoords[i%4], sizeof(vec2));
		vboRenderData.addData(&vSkyBoxNormals[i/4], sizeof(vec3));
	}

	vboRenderData.uploadDataToGPU(GL_STATIC_DRAW);

	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 2*sizeof(vec3)+sizeof(vec2), 0);
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2*sizeof(vec3)+sizeof(vec2), (void*)sizeof(vec3));
	glEnableVertexAttribArray(2);
	glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 2*sizeof(vec3)+sizeof(vec2), (void*)(sizeof(vec3)+sizeof(vec2)));
}

void CSkybox::renderSkybox()
{
	glDepthMask(0);
	glBindVertexArray(VAO);
	FOR(i, 6)
	{
		glBindTexture(GL_TEXTURE_2D, Textures[i]);
		glDrawArrays(GL_TRIANGLE_STRIP, i*4, 4);
	}
	glDepthMask(1);
}

void CSkybox::releaseSkybox()
{
	FOR(i, 6)Textures[i].releaseTexture();
	glDeleteVertexArrays(1, &VAO);
	vboRenderData.releaseVBO();
}
