#include "Environement.h"

Environement::Environement()
{
	skyid = 0;
	skyobj = NULL;
	r=0;
	stacks=0;
	slices=0;
}

Environement::~Environement()
{
}

void Environement::Load(char *skyname, float r, int slices, int stacks)
{
	this->r = r;
	this->slices = slices;
	this->stacks = stacks;
	LoadTexture(skyname, &skyid);
	skyobj = gluNewQuadric();
	gluQuadricTexture(skyobj,GL_TRUE);
}

void Environement::Render()
{
	glDisable(GL_LIGHTING);
	//glColor3f(1,1,1);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, skyid);
	glPushMatrix();
	glTranslatef(.5f*r,0,.5f*r);
	gluSphere(skyobj,r,slices,stacks);
	glPopMatrix();
	glDisable(GL_TEXTURE_2D);
	glEnable(GL_LIGHTING);
}

void Environement::LoadTexture(char *name, unsigned int* texid)
{
	AUX_RGBImageRec *TextureImage=NULL;					// Create Storage Space For The Texture

	if (TextureImage = LoadBMP(name))
	{
		glGenTextures(1, texid);									// Create The Texture

		// Typical Texture Generation Using Data From The Bitmap
		glBindTexture(GL_TEXTURE_2D, *texid);
		glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage->sizeX, TextureImage->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage->data);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	}
	if (TextureImage)														// If Texture Exists
	{
		if (TextureImage->data)										// If Texture Image Exists
		{
			free(TextureImage->data);								// Free The Texture Image Memory
		}

		free(TextureImage);												// Free The Image Structure
	}
}

AUX_RGBImageRec* Environement::LoadBMP(char *Filename)				// Loads A Bitmap Image
{
	FILE *File=NULL;														// File Handle

	if (!Filename)															// Make Sure A Filename Was Given
	{
		return NULL;															// If Not Return NULL
	}

	File=fopen(Filename,"r");										// Check To See If The File Exists

	if (File)																		// Does The File Exist?
	{
		fclose(File);															// Close The Handle
		return auxDIBImageLoad(Filename);					// Load The Bitmap And Return A Pointer
	}

	return NULL;																// If Load Failed Return NULL
}


