#include "Gos.pch"
#include "Graphics.h"

GosVertexBuffer*	(*GosVertexBuffer::CreateEmpty)(UINT, DWORD, DWORD ) = VertexBuffer::CreateEmpty;
GosVertexBuffer*	(*GosVertexBuffer::CreateFromMemory)(void *,UINT, DWORD, DWORD ) = VertexBuffer::CreateFromMemory;
	
GosVertexBuffer* VertexBuffer::CreateEmpty(UINT Length, DWORD FVF, DWORD Usage)
{
	LOG_API("VertexBuffer::CreateEmpty");
	HRESULT rc;
	IDirect3DVertexBuffer8 *pD3DVertexBuffer;
	rc = Graphics::D3DDevice()->CreateVertexBuffer( Length, Usage, FVF, D3DPOOL_DEFAULT, &pD3DVertexBuffer );
	if( FAILED(rc) )
		STOP(("Failed to create IDirect3DVertexBuffer8"));

	VertexBuffer *pVertexBuffer = new VertexBuffer( pD3DVertexBuffer, Length );
	if( !pVertexBuffer )
			STOP(("Error creating an Vertex buffer object"));

	return (GosVertexBuffer *)pVertexBuffer;	
}

GosVertexBuffer* VertexBuffer::CreateFromMemory(void *pData,UINT Length, DWORD FVF, DWORD Usage)
{
	LOG_API("VertexBuffer::CreateFromMemory");
	GosVertexBuffer *pBuffer = GosVertexBuffer::CreateEmpty( Length, FVF, Usage );
	void *pDst = pBuffer->Lock();
	memcpy( pDst, pData, Length );
	pBuffer->Unlock();
	return pBuffer;
}

void *VertexBuffer::Lock( DWORD Usage )
{
	LOG_API("VertexBuffer::Lock");
	BYTE *pData;
	HRESULT rc;
	rc = m_pD3DVertexBuffer->Lock( 0, m_SizeBytes, &pData, Usage );
	if( FAILED(rc) )
		STOP(("Failed to lock Vertex Buffer"));
	return (void *)pData;
}

void VertexBuffer::Unlock()
{
	LOG_API("VertexBuffer::Unlock");
	HRESULT rc = m_pD3DVertexBuffer->Unlock();
	if( FAILED(rc) )
		STOP(("Failed to unlock Vertex Buffer"));
}

VertexBuffer::VertexBuffer( IDirect3DVertexBuffer8 *pD3DVertexBuffer, UINT SizeBytes )
{
	m_pD3DVertexBuffer = pD3DVertexBuffer;
	m_SizeBytes = SizeBytes;
}

VertexBuffer::~VertexBuffer()
{
	if(m_pD3DVertexBuffer)
		m_pD3DVertexBuffer->Release();
}

GosVertexBuffer::~GosVertexBuffer()
{
	;
}
