//
// Asura_Chunk_ResourceFile_PS3_StaticDecals.h
//
// Created by DMR - 15 Aug 2007
//
// Copyright (C) 2007 Rebellion, All Rights Reserved.
//

/******************************************************************************/
/* Included Files                                                             */
/******************************************************************************/

#include "Core/Asura.h"

#include "ChunkSystem/Asura_Chunk_ResourceFile_PS3_StaticDecals.h"

// Asura Platform-independent
#include "ChunkSystem/Asura_Chunk_Stream.h"
#include "Core/Asura_Material_System.h"
#include "SpecialFX/Asura_PS3_DecalSystem.h"
#include "ChunkSystem/Asura_Chunk_ResourceFile_PS3.h"

/******************************************************************************/
/* Asura_Chunk_ResourceFile_PS3_StaticDecals Class Functions              */
/******************************************************************************/

void Asura_Chunk_ResourceFile_PS3_StaticDecals::Process( const char* szFilename, Asura_Chunk_Stream& xStream )
{
	if( Version != ASURA_PS3_STATICDECALS_CHUNK_VERSION )
	{
		Asura_Assertf( false, ("Invalid static decals chunk version (%d) encountered. Should be %d. You may need new code, or to re-export the level.", Version, ASURA_PS3_STATICDECALS_CHUNK_VERSION) );
		return;
	}
	int iNumDecalBuffers;	

	// Read the data...
	xStream >> iNumDecalBuffers;

	Asura_PS3_DecalSystem::AllocateStaticDecalBuffers( iNumDecalBuffers );

	for(int i=0; i<iNumDecalBuffers; i++)
	{
		Asura_PS3_StaticDecalBuffer *pxBuffer = Asura_PS3_DecalSystem::GetStaticDecalBuffer( i );

		xStream >> pxBuffer->m_iModuleIndex;
		xStream >> pxBuffer->m_uDecalMaterialHash;
		xStream >> pxBuffer->m_iNumVertices;
		xStream >> pxBuffer->m_iNumIndices; 
		xStream >> pxBuffer->m_xAABB;

		pxBuffer->m_iDecalMaterialIndex = -1;
			
		if (pxBuffer->m_iNumVertices>0)
		{		
			// Read the vertices
			int iVertSize = 0;

			// Normal vertices - With tangent/normal/binormal
			iVertSize = sizeof(Asura_PS3_Decal_Vertex);
			pxBuffer->m_xVertexBuffer.Initialise( iVertSize, pxBuffer->m_iNumVertices, CELL_GCM_LOCATION_MAIN );
			Asura_PS3_Decal_Vertex *pxVerts = (Asura_PS3_Decal_Vertex *)pxBuffer->m_xVertexBuffer.LockForWriting();

			xStream.Read( iVertSize * pxBuffer->m_iNumVertices, pxVerts);

			pxBuffer->m_xVertexBuffer.Unlock();

			// Read the indices
			pxBuffer->m_xIndexBuffer.Initialise( pxBuffer->m_iNumIndices );	// argh... size is in bytes, not num indices
			uint16 *pxIndices = (uint16 *)pxBuffer->m_xIndexBuffer.LockForWriting();

			xStream.Read( 2 * pxBuffer->m_iNumIndices, pxIndices);
		}
		
	}
}
