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

#include "GameFrameVertexLibrary.h"
#include "GameFrame.h"

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

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

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

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

		Library = new VBNODE[num_nodes];
		NumNodes = num_nodes;
		NumUsed = 0;
		
		for(int i=0; i<NumNodes; i++)
		{
			Library[i].FVF = 0;
			Library[i].NumVertices = 0;
			Library[i].VertexSize = 0;
			Library[i].Vertices = NULL;
		}

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

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

		delete[] Library;
		Library = NULL;
	}

	NumNodes = 0;
	NumUsed = 0;

	GFParent = NULL;
}

int CGFVertexLibrary::AddVertexBuffer(int num_vertices, DWORD vertex_size, DWORD fvf)
{
	int result = -1;
	if((NumNodes <= 0) || (Library == NULL) || (GFParent == NULL)) return -1;

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

		if(tmp == NULL) return -1;

		for(i=0; i<NumNodes; i++)
		{
			tmp[i].FVF = Library[i].FVF;
			tmp[i].NumVertices = Library[i].NumVertices;
			tmp[i].VertexSize = Library[i].VertexSize;
			tmp[i].Vertices = Library[i].Vertices;
		}

		for(i=NumNodes; i<(NumNodes * 2); i++)
		{
			tmp[i].FVF = 0;
			tmp[i].NumVertices = 0;
			tmp[i].VertexSize = 0;
			tmp[i].Vertices = NULL;
		}

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

	if(D3D_OK == GFParent->D3DDevice->CreateVertexBuffer(num_vertices * vertex_size, 
				 D3DUSAGE_WRITEONLY, fvf, D3DPOOL_MANAGED, &(Library[NumUsed].Vertices)))
	{
		Library[NumUsed].FVF = fvf;
		Library[NumUsed].NumVertices = num_vertices;
		Library[NumUsed].VertexSize = vertex_size;
		result = NumUsed;
		NumUsed++;
	}

	return result;
}



