#include "stdafx.h"
#include "VBOHelper.h"



GeometryVBOElementBase::GeometryVBOElementBase(void)
{
	m_BufID = 0;
}

GeometryVBOElementBase::~GeometryVBOElementBase(void)
{
	ReleaseBufferElement();
}

void GeometryVBOElementBase::GenerateBuffer(void)
{
	glGenBuffers(1, &m_BufID);
}

GLuint GeometryVBOElementBase::GetID(void)
{
	return m_BufID;
}

void GeometryVBOElementBase::ReleaseBufferElement(void)
{
	if(m_BufID == 0)
		return;

	glDeleteBuffers(1, &m_BufID);
	m_BufID = 0;
}

bool GeometryVBOElementBase::HasBuffer(void) const
{
	return m_BufID != 0;
}


void GeometryVBOElement::BindArray(void)
{
	glBindBuffer(GL_ARRAY_BUFFER, m_BufID);
}


void GeometryVBOIndex::BindElementArray(void)
{
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_BufID);
}




void GeometryVBO::Release(void)
{
	m_Vertex.ReleaseBufferElement();
	m_Normal.ReleaseBufferElement();
	m_Texture.ReleaseBufferElement();
	m_Index.ReleaseBufferElement();

	NumTriangles = 0;
}

void GeometryVBO::BindBuffer(void)
{
	glEnableClientState(GL_VERTEX_ARRAY);
	m_Vertex.BindArray();
	glVertexPointer(3, GL_FLOAT, 0, VBO_BUFFER_OFFSET(0));

	if(m_Normal.HasBuffer())
	{
		glEnableClientState(GL_NORMAL_ARRAY);
		m_Normal.BindArray();
		glNormalPointer(GL_FLOAT, 0, VBO_BUFFER_OFFSET(0));
	}

	if(m_Texture.HasBuffer())
	{
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);
		m_Texture.BindArray();
		glTexCoordPointer(2, GL_FLOAT, 0, VBO_BUFFER_OFFSET(0));
	}

	m_Index.BindElementArray();
}

void GeometryVBO::DrawVBOAll(GLenum primitive_type, bool AutoClose)
{
	BindBuffer();
	glDrawElements(primitive_type, NumTriangles * 3 *4 , GL_UNSIGNED_INT, VBO_BUFFER_OFFSET(0));
	if(AutoClose)
		DisableStates();
}

void GeometryVBO::DisableStates(void)
{
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_NORMAL_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
