#include "Mesh.h"
#include <glm/gtc/type_ptr.hpp>

Mesh::Mesh(ShaderProgram* shader, std::size_t size) : GLObject(shader), _size(size) {

}

Mesh::~Mesh() {

}

VertexArray Mesh::generateVertices() const {
	std::size_t u = _size, v = _size;
	auto retVal = std::make_unique<Vertex[]>(u*v);
	const float step = (exp(4) - 1)/_size;

	for (std::size_t i = 0; i < u; i++)
		for (std::size_t j = 0; j < v; j++)
		{
//			Vertex vertex;
			float x = /*(float)i/(float)u*/ logf(i*step + 1)/4.0f - 0.5f;
			float y = (float)j/(float)v - 0.5f;
			retVal[j*u+i].coords[0] = x*3;
			retVal[j*u+i].coords[1] = y*3;
			retVal[j*u+i].coords[2] = heightMapFunc(j, i, x, y);
			retVal[j*u+i].normal[0] = 1.0f;
			retVal[j*u+i].normal[1] = 1.0f;
			retVal[j*u+i].normal[2] = 1.0f;
		}

	return std::make_tuple(std::move(retVal), u*v*sizeof(Vertex));
}

IndexArray Mesh::generateIndices() const {
	unsigned u = _size, v = _size;
	auto indices = std::make_unique<GLuint[]>((u-1)*(v-1)*6);
	for (unsigned i = 0; i < (u - 1); i++)
		for (unsigned j = 0; j < (v - 1); j++)
		{
			unsigned int indexa=j*(u-1)+i;
			unsigned int indexb=j*u+i;
			indices[indexa*6+0]=indexb;
			indices[indexa*6+1]=indexb+1+u;
			indices[indexa*6+2]=indexb+1;

			indices[indexa*6+3]=indexb;
			indices[indexa*6+4]=indexb+u;
			indices[indexa*6+5]=indexb+u+1;
		}

	return std::make_tuple(std::move(indices), (u-1)*(v-1)*6*sizeof(GLuint));
}
