#include"CVertexMemory.h"
#include"../Auxiliary/Debug/CAssert.h"
#include"../Auxiliary/CString.h"
#include"CRenderMessageImpl3.h"

#include"CGraphic.h"

#include<string.h>

namespace Maid
{

ReferenceCount<mstring>	CVertexMemory::s_Cache;
unt CVertexMemory::s_AutoCount;

CVertexMemory::CVertexMemory()
{
}

CVertexMemory::CVertexMemory( const CVertexMemory& rha )
{
	const mstring id = rha.m_VertexName;

	if( !id.empty() )
	{
		m_VertexName = id;
		s_Cache.Add(id);
	}
}

CVertexMemory::~CVertexMemory()
{
	Delete();
}


void CVertexMemory::Create( VERTEXFORMAT fmt, void* pVertex, int Count )
{
	Delete();

	mstring name = VERTEXNAME::GeneratMemory( s_AutoCount );

	if( s_Cache.Add(name) )
	{
		const unt size = GetFVFSize(fmt) * Count;
		SPBINARY p( new MySTL::vector<unt08> );
		p->resize( size );

		MySTL::vector<unt08>& dst = *(p);
		::memcpy( &(dst[0]), pVertex, size );

		GlobalPointer<CGraphic>::Get()->RegistVertex( name, p, fmt );

		++s_AutoCount;
	}

	m_VertexName = name;

}

void CVertexMemory::Delete()
{
	if( m_VertexName.empty() ) { return ; }

	if( s_Cache.Del(m_VertexName) )
	{
		GlobalPointer<CGraphic>::Get()->DeleteVertex( m_VertexName );
	}

	m_VertexName.clear();
}

mstring CVertexMemory::GetID() const
{
	return m_VertexName;
}

CVertexMemory& CVertexMemory::operator = ( const CVertexMemory& rha )
{
	Delete();

	const mstring id = rha.m_VertexName;

	if( !id.empty() )
	{
		m_VertexName = id;
		s_Cache.Add(id);
	}

	return *this;
}
}

