//============================================================
// Program:		CGFTextureLibrary
// Description:	Class for storing textures
// Author:		Benjamin Gottemoller
// Website:		http://www.particlefield.com
// Date:		who knows
// Legal:		Licensed under the gnu GPL (see gpl.txt for details)
//============================================================

#include "GameFrameTextureLibrary.h"
#include "GameFrame.h"

CGFTextureLibrary::CGFTextureLibrary() 
{ 
	GFParent = NULL; 
	Library = NULL;
	NumNodes = 0;
	NumUsed = 0;
	UseCompressedTextures = 0;
};

CGFTextureLibrary::~CGFTextureLibrary() 
{ 
	Destroy(); 
}

int CGFTextureLibrary::Initialize(GameFrame *gfparent, int num_nodes)
{
	GFParent = gfparent; 

	if(num_nodes > 0)
	{
		if(Library != NULL) Destroy();

		Library = new TXNODE[num_nodes];
		NumNodes = num_nodes;
		NumUsed = 0;
		
		for(int i=0; i<NumNodes; i++)
		{
			Library[i].Texture = NULL;
		}

		if(Library != NULL) return 1;
	}

	UseCompressedTextures = 0;
	
	return 0;
}

void CGFTextureLibrary::Destroy(void)
{
	if(Library != NULL)
	{
		for(int i=0; i<NumNodes; i++)
		{
			if(Library[i].Texture != NULL)
			{
				Library[i].Texture->Release();
				Library[i].Texture = NULL;
			}
		}

		delete[] Library;
		Library = NULL;
	}

	NumNodes = 0;
	NumUsed = 0;
	UseCompressedTextures = 0;

	GFParent = NULL;
}

int CGFTextureLibrary::AddTexture(char *file)
{
	int result = -1;
	if((NumNodes <= 0) || (Library == NULL) || (GFParent == NULL)) return -1;

	if(NumUsed >= NumNodes)
	{
		int i = 0;
		TXNODE *tmp = NULL;
		tmp = new TXNODE[NumNodes * 2];

		if(tmp == NULL) return -1;

		for(i=0; i<NumNodes; i++)
		{
			tmp[i].Texture = Library[i].Texture;
		}

		for(i=NumNodes; i<(NumNodes * 2); i++)
		{
			tmp[i].Texture = NULL;
		}

		delete[] Library;
		Library = tmp;
		tmp = NULL;
		NumNodes *= 2;
	}

	if(UseCompressedTextures)
	{
		D3DFORMAT compression_type = D3DFMT_DXT4;
		D3DCOLOR transparency_color = 0xFF000000;

		if(D3D_OK == D3DXCreateTextureFromFileEx(GFParent->D3DDevice, file, D3DX_DEFAULT, D3DX_DEFAULT, 
													D3DX_DEFAULT, 0, compression_type, D3DPOOL_MANAGED,
													D3DX_DEFAULT, D3DX_DEFAULT, transparency_color,
													NULL, NULL, &(Library[NumUsed].Texture)))
		{
			char msg[300];
			sprintf(msg, "COMPRESSED TEXTURE: %s loaded successfully. WOOHOO!!!", file);
			Message(msg);

			result = NumUsed;
			strcpy((Library[NumUsed].TextureName), file);
			NumUsed++;
		}
	}
	else
	{
		if(D3D_OK == D3DXCreateTextureFromFile(GFParent->D3DDevice, file, &(Library[NumUsed].Texture)))
		{
			result = NumUsed;
			strcpy((Library[NumUsed].TextureName), file);
			NumUsed++;
		}
	}

	return result;
}

int CGFTextureLibrary::FindTexture(char *name)
{
	for(int i=0; i<NumUsed; i++)
	{
		if(strcmp(name, Library[i].TextureName) == 0)
		{
			return i;
		}
	}
	return -1;
}

