#include "Mix/Tool/Win32/Core/Graphics/VertexLayout.h"
#include "Mix/Tool/Win32/Core/Graphics/Manager.h"

namespace Mix{ namespace Tool{ namespace Win32{ namespace Graphics{

VertexLayout* VertexLayout::CreateInstance( const D3DVERTEXELEMENT9* pElements, unsigned int strid )
{
	return new VertexLayout( pElements, strid );
}

VertexLayout::VertexLayout( const D3DVERTEXELEMENT9* pElements, unsigned int stride ) :
m_pD3DVertexLayout( NULL ),
m_Stride( stride )
{
	const D3DVERTEXELEMENT9* pSrcElement = &( pElements[0] );

	for( ;; )
	{
		m_ElementList.push_back( *pSrcElement );

		if( ( pSrcElement->Stream != 0xFF ) ||
			( pSrcElement->Offset != 0 ) ||
			( pSrcElement->Type != D3DDECLTYPE_UNUSED ) ||
			( pSrcElement->Method != 0 ) ||
			( pSrcElement->Usage != 0 ) ||
			( pSrcElement->UsageIndex != 0 ) )
		{
			pSrcElement++;
		}
		else
		{
			break;
		}
	}
}

VertexLayout::~VertexLayout( void )
{
	MIX_RELEASE( m_pD3DVertexLayout );
}

unsigned int VertexLayout::GetStride( void ) const
{
	return m_Stride;
}

const std::vector<D3DVERTEXELEMENT9>& VertexLayout::GetElementList( void ) const
{
	return m_ElementList;
}

IDirect3DVertexDeclaration9* VertexLayout::GetInterfacePtr( void )
{
	return m_pD3DVertexLayout;
}

void VertexLayout::OnInvalidate( void )
{
	MIX_RELEASE( m_pD3DVertexLayout );
}

void VertexLayout::OnValidate( void )
{
	Mix::Tool::Win32::Graphics::Manager* pManager = Manager::GetInstance();
	if( pManager == NULL )
	{
		return;
	}

	m_pD3DVertexLayout = pManager->D3D_CreateVertexLayout( &( m_ElementList[0] ) );
}

Mix::Tool::Win32::Object::TYPE VertexLayout::GetType( void ) const
{
	return Mix::Tool::Win32::Object::GRAPHICS__VERTEX_LAYOUT;
}

}}}}
