//============================================================
// Program:		CGFMaterialLibrary
// Description:	Material storage class
// Author:		Benjamin Gottemoller
// Website:		http://www.particlefield.com
// Date:		who knows
// Legal:		Licensed under the gnu GPL (see gpl.txt for details)
//============================================================

#include "GameFrameMaterialLibrary.h"
#include "GameFrame.h"

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

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

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

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

		Library = new MTNODE[num_nodes];
		NumNodes = num_nodes;
		NumUsed = 0;
		
		for(int i=0; i<NumNodes; i++)
		{
			ZeroMemory(&Library[i].Material, sizeof(D3DMATERIAL8));
		}

		if(Library != NULL) return 1;
	}
	
	return 0;
}

void CGFMaterialLibrary::Destroy(void)
{
	if(Library != NULL)
	{
		delete[] Library;
		Library = NULL;
	}

	NumNodes = 0;
	NumUsed = 0;

	GFParent = NULL;
}

int CGFMaterialLibrary::AddMaterial(D3DMATERIAL8 *material)
{
	int result = -1;
	if((NumNodes <= 0) || (Library == NULL) || (GFParent == NULL) || (material == NULL)) return -1;

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

		if(tmp == NULL) return -1;

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

		for(i=NumNodes; i<(NumNodes * 2); i++)
		{
			ZeroMemory(&tmp[i].Material, sizeof(D3DMATERIAL8));
		}

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

	Library[NumUsed].Material = (*material);
	result = NumUsed;
	NumUsed++;

	return result;
}



