/***************************************************************************
 *            textures.cpp
 *
 *  Thu Dec  1 17:46:50 2005
 *  Copyright  2005  Joe Venzon
 *  joe@venzon.net
 ****************************************************************************/

/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
 
#include "textures.h"

TEXTURENODE::TEXTURENODE()
{
	texfile = "";
	texid = 0;
	next = NULL;
	loaded = false;
}

TEXTURENODE::~TEXTURENODE()
{
	if (loaded)
	{
		//delete the texture
		glDeleteTextures(1, &texid);
	}
}

// --- TEXTURES class ---

TEXTURES::TEXTURES()
{
	texnodes = NULL;
}

TEXTURES::~TEXTURES()
{
	DeleteAll();
}

void TEXTURES::DeleteAll()
{
	TEXTURENODE * curnode;
	
	while (texnodes != NULL)
	{
		curnode = texnodes;
		texnodes = texnodes->next;
		
		delete curnode;
	}
}

GLuint TEXTURES::Load(string newtexfile, bool mipmap, int &w, int &h)
{
	TEXTURENODE * curnode = texnodes;
	GLuint newtexid;
	
	while (curnode != NULL)
	{
		if (curnode->texfile == newtexfile)
		{
			return curnode->texid;
		}
		
		curnode = curnode->next;
	}
	
	bool error = false;
	newtexid = utility.TexLoad(newtexfile, GL_RGBA, mipmap, w, h, false, error);
	if (error)
	{
		return 0;
	}
	else
	{
		curnode = new TEXTURENODE;
		curnode->texid = newtexid;
		curnode->texfile = newtexfile;
		curnode->mipmap = mipmap;
		curnode->loaded = true;
		curnode->next = texnodes;
		texnodes = curnode;
		
		return newtexid;
	}
}

void TEXTURES::ReloadAll()
{
	TEXTURENODE * tempnodes = texnodes;
	
	texnodes = NULL;
	
	TEXTURENODE * curnode;
	string tfile;
	bool mmap;
	
	while (tempnodes != NULL)
	{
		curnode = tempnodes;
		tempnodes = tempnodes->next;
		mmap = curnode->mipmap;
		tfile = curnode->texfile;
		delete curnode;
		Load(tfile, mmap);
	}
}
