/// Inlcudes
#include "VectorUtils4.h"
#include "LittleOBJLoader.h"
#include "LoadTGA.h"


/// Generate terrain
Model * GenerateTerrain(const char * filename)
{
	TextureData textureData;
	if (!LoadTGATextureData(filename, &textureData))
		return nullptr;

	int vertexCount   =  textureData.width    *  textureData.height;
	int triangleCount = (textureData.width-1) * (textureData.height-1) * 2;

	vec3   * position = (vec3 *)  malloc(sizeof(GLfloat) * 3 * vertexCount);
	vec3   * normal   = (vec3 *)  malloc(sizeof(GLfloat) * 3 * vertexCount);
	vec2   * texCoord = (vec2 *)  malloc(sizeof(GLfloat) * 2 * vertexCount);
	GLuint * indices  = (GLuint *)malloc(sizeof(GLuint)  * 3 * triangleCount);

	int bytesPerPixel = textureData.bpp / 8;
	for (unsigned int x = 0; x < textureData.width;  ++x)
	for (unsigned int z = 0; z < textureData.height; ++z)
	{
		int indexBase = (x + z * textureData.width);
		// Vertex array. You need to scale this properly.
		GLubyte data = textureData.imageData[indexBase * bytesPerPixel];
		position[indexBase].x = x    / 1.0;
		position[indexBase].y = data / 100.0;
		position[indexBase].z = z    / 1.0;
		// Normal vectors. You need to calculate these.
		normal[indexBase].x = 0.0;
		normal[indexBase].y = 1.0;
		normal[indexBase].z = 0.0;
		// Texture coordinates. You may want to scale them.
		texCoord[indexBase].x = x; // (float)x / textureData.width;
		texCoord[indexBase].y = z; // (float)z / textureData.height;
	}
	for (unsigned int x = 0; x < textureData.width-1;  ++x)
	for (unsigned int z = 0; z < textureData.height-1; ++z)
	{
		int indexBase = (x + z * (textureData.width-1))*6;
		// Triangle 1
		indices[indexBase + 0] = (x+0) + (z+0) * textureData.width;
		indices[indexBase + 1] = (x+0) + (z+1) * textureData.width;
		indices[indexBase + 2] = (x+1) + (z+0) * textureData.width;
		// Triangle 2
		indices[indexBase + 3] = (x+1) + (z+0) * textureData.width;
		indices[indexBase + 4] = (x+0) + (z+1) * textureData.width;
		indices[indexBase + 5] = (x+1) + (z+1) * textureData.width;
	}

	// Create Model and upload to GPU:
	Model * model = LoadDataToModel(
		position,
		normal,
		texCoord,
		nullptr,
		indices,
		vertexCount,
		triangleCount * 3
	);

	free(textureData.imageData);
	return model;
}