// KeyFrame.cpp: implementation of the CKeyFrame class.
//
//////////////////////////////////////////////////////////////////////

#include "KeyFrame.h"

#include "NodeKey.h"

#include "..\Common\FileStream.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CKeyFrame::CKeyFrame()
{
	m_pszClassName = "CKeyFrame";

	///////////////////////////////////////////////////////////////////////////
	m_pNodeKeys = NULL;

	m_fCurrentFrame = 0;
	m_fFramePerSecond = 30.0f;
}

CKeyFrame::~CKeyFrame()
{
	Destroy();
}

void CKeyFrame::Destroy()
{
	if (m_pNodeKeys)
	{
		delete [] m_pNodeKeys;
		m_pNodeKeys = NULL;
	}

	CUnknown::Destroy();
}

bool CKeyFrame::Load(LPSTR lpszFileName)
{
	if (!CUnknown::Create(lpszFileName))
		return false;

	///////////////////////////////////////////////////////////////////////////
	CFileStream stream;
	if (!stream.Open(lpszFileName, CFileStream::READONLY))
		return false;

	if (!ReadHeader(&stream))
		return false;

	// Read Node
	///////////////////////////////////////////////////////////////////////////////////////////////
	stream.Read(&m_dwNumNodeKeys, sizeof(DWORD), 1);

	m_pNodeKeys = new CNodeKey [m_dwNumNodeKeys];
	if (!m_pNodeKeys)
		return false;

	stream.Read(&m_dwTicksPerFrame, sizeof(DWORD), 1);
	stream.Read(&m_dwNumFrames, sizeof(DWORD), 1);

	CNodeKey* pNodeKey = m_pNodeKeys;
	for (int i = 0; i < (int) m_dwNumNodeKeys; i ++)
	{
		if (!pNodeKey->Read(&stream, m_dwNumFrames))
			return false;

		pNodeKey ++;
	}

	//m_fFramePerSecond = m_dwTicksPerFrame / 30.0f;

	return true;
}

bool CKeyFrame::ReadHeader(CFileStream *lpStream)
{
	// Read file header
	char szHeader[255];
	
	int nLength = lpStream->ReadString(szHeader);
	if (strncmp(szHeader, "RIFF", 4))
		return false;

	DWORD dwVersion;
	lpStream->Read(&dwVersion, sizeof(DWORD), 1);
	if (dwVersion != 100)
		return false;

	return true;
}

void CKeyFrame::AdvanceFrame(float dt)
{
	if (dt > 0.1f)
		dt = 0.1f;

	m_fCurrentFrame += dt * m_fFramePerSecond;

	if (m_dwNumFrames <= 1)
		m_fCurrentFrame = 0;
	else
	{
		// wrap
		m_fCurrentFrame -= (int)( m_fCurrentFrame / (m_dwNumFrames - 1) ) * (m_dwNumFrames - 1);
	}
}


