/**
 *
 * \file	terrain.cc
 *
 * \brief Code for the Terrain class.
 *
 * \author	MAxx Headroom
 * \version	0.0
 * \date	25.01.2004 22:50:19
 *
 **/

#include "stdafx.h"
#include "terrain.h"


//{{{ Terrain::Terrain()
Terrain::Terrain()
:
	points(0),
	height(1.0),
	pos(0.0, 0.0, 0.0),
	sizeX(0),
	sizeY(0),
	tex(0)
{
} /* Terrain::Terrain() */
//}}}


//{{{ Terrain::Terrain(std::string hf)
Terrain::Terrain(std::string hf, float h, Texture *t)
:
	height(h),
	pos(0.0, 0.0, 0.0),
	tex(t)
{
	FILE* f = fopen(hf.c_str(), "r");
	//if (!f) throw EFileNotFound(hf);
	AUX_RGBImageRec* img;
	img=auxDIBImageLoad(hf.c_str());
	sizeX = img->sizeX;
	sizeY = img->sizeY;
	points = new GLfloat[sizeX*sizeY];
	float max = 0;
	for(int i=0; i<sizeX*sizeY; ++i) {
		points[i] = img->data[i*3];
		max = (float)((img->data[i*3]>max) ? img->data[i*3] : max);
	}
	for(int i=0; i<sizeX*sizeY; ++i)
		points[i] = (points[i] / max) * h;

	if (img) {
		if (img->data) delete [] img->data;
		delete img;
	}
} /* Terrain::Terrain(std::string hf) */
//}}}


//{{{ Terrain::~Terrain()
Terrain::~Terrain()
{
	if (points) delete [] points;
} /* Terrain::~Terrain() */
//}}}


//{{{ void Terrain::setPosition(float x, float y, float z)
void Terrain::setPosition(float x, float y, float z)
{
	pos.X = x; pos.Y = y; pos.Z = z;
} /* void Terrain::setPosition(float x, float y, float z) */
//}}}


//{{{ void Terrain::draw()
void Terrain::draw()
{
	glPushMatrix();
	glTranslatef(pos.X, pos.Y, pos.Z);
	//glPolygonMode(GL_FRONT, GL_LINE);
	//glPolygonMode(GL_BACK, GL_LINE);
	glPolygonMode(GL_FRONT, GL_FILL);
	glPolygonMode(GL_BACK, GL_FILL);

	//glColor4f(1.0, 1.0, 1.0, 1.0);
	glBindTexture(GL_TEXTURE_2D, tex->getTexture());
	tex->setupTex();
	glEnable(GL_FOG);
	//glFogf(GL_FOG_END, 100.0);
	glFogf(GL_FOG_DENSITY, 0.05);
	for(int y=0; y<sizeY-1; ++y) {
		glBegin(GL_TRIANGLE_STRIP);
		for(int x=0; x<sizeX; ++x) {
			glTexCoord2f((float)x/(float)sizeX*20, (float)(y+1.0f)/(float)sizeY*20);
			glVertex3f((float)x, points[x+sizeX*(y+1)], (float)y+1.0f);
			glTexCoord2f((float)x/(float)sizeX*20, (float)y/(float)sizeY*20);
			glVertex3f((float)x, points[x+sizeX*y], (float)y);
		}
		glEnd();
	}
	glDisable(GL_FOG);

	glPolygonMode(GL_FRONT, GL_FILL);
	glPopMatrix();
} /* void Terrain::draw() */
//}}}
