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

GosIndexBuffer*	(*GosIndexBuffer::CreateEmpty)(UINT, DWORD, D3DFORMAT ) = IndexBuffer::CreateEmpty;
GosIndexBuffer*	(*GosIndexBuffer::CreateFromMemory)(void *,UINT, DWORD, D3DFORMAT ) = IndexBuffer::CreateFromMemory;
	
GosIndexBuffer*	IndexBuffer::CreateEmpty(UINT Length, DWORD Usage, D3DFORMAT Format)
{
	LOG_API("IndexBuffer::CreateEmpty");
	HRESULT rc;
	IDirect3DIndexBuffer8 *pD3DIndexBuffer;
	rc = Graphics::D3DDevice()->CreateIndexBuffer( Length, Usage, Format, D3DPOOL_DEFAULT, &pD3DIndexBuffer );
	if( FAILED(rc) )
		STOP(("Failed to create IDirect3DIndexBuffer8"));

	IndexBuffer *pIndexBuffer = new IndexBuffer( pD3DIndexBuffer, Length );
	if( !pIndexBuffer )
			STOP(("Error creating an index buffer object"));

	return (GosIndexBuffer *)pIndexBuffer;	
}

GosIndexBuffer*	IndexBuffer::CreateFromMemory(void *pData,UINT Length, DWORD Usage, D3DFORMAT Format)
{
	LOG_API("IndexBuffer::CreateFromMemory");
	GosIndexBuffer *pBuffer = GosIndexBuffer::CreateEmpty( Length, Usage, Format );
	void *pDst = pBuffer->Lock();
	memcpy( pDst, pData, Length );
	pBuffer->Unlock();
	return pBuffer;
}

void *IndexBuffer::Lock()
{
	LOG_API("IndexBuffer::Lock");
	BYTE *pData;
	HRESULT rc;
	rc = m_pD3DIndexBuffer->Lock( 0, m_SizeBytes, &pData, 0 );
	if( FAILED(rc) )
		STOP(("Failed to lock Index Buffer"));
	return (void *)pData;
}

void IndexBuffer::Unlock()
{
	LOG_API("IndexBuffer::Unlock");
	HRESULT rc = m_pD3DIndexBuffer->Unlock();
	if( FAILED(rc) )
		STOP(("Failed to unlock Index Buffer"));
}

IndexBuffer::IndexBuffer( IDirect3DIndexBuffer8 *pD3DIndexBuffer, UINT SizeBytes )
{
	LOG_API("IndexBuffer::IndexBuffer");
	m_pD3DIndexBuffer = pD3DIndexBuffer;
	m_SizeBytes = SizeBytes;
}

IndexBuffer::~IndexBuffer()
{
	LOG_API("IndexBuffer::~IndexBuffer");
	if(m_pD3DIndexBuffer)
		m_pD3DIndexBuffer->Release();
}

GosIndexBuffer::~GosIndexBuffer()
{
	LOG_API("GosIndexBuffer::~GosIndexBuffer");
	;
}
