#include "StdAfx.h"
#include ".\aniplane.h"

#include "Application.h"

cAniPlane::cAniPlane()
{
	mFrames = 0;
	mCurFrame = 0;
	mLoop = false;

	mBeginAnim = false;

	mTimeOut = 0;
	mLastAccumTime = 0;

	mTexX = 0;
	mTexY = 0;
	mTexW = 0;
	mTexH = 0;
	mColumCount = 0;
}

cAniPlane::~cAniPlane()
{
}

bool cAniPlane::Create( NiTexture* pTexture, short screenX, short screenY, unsigned short screenW, unsigned short screenH,
					unsigned short texLeft, unsigned short texTop, unsigned short texRight, unsigned short texBottom )
{
	bool check = cPlaneObject::Create( pTexture, screenX, screenY, screenW, screenH, texLeft, texTop, texRight, texBottom );
	if( check == false )
		return false;

	mTexX = texLeft;
	mTexY = texTop;

	mTexW = texRight - texLeft;
	mTexH = texBottom - texTop;

	if( mTexW == 0 )
		return false;

	mColumCount = mTextureWidth / mTexW;
	if( mColumCount == 0 )
		return false;

	mpAlphaProp->SetDestBlendMode( NiAlphaProperty::ALPHA_ONE );
	mpAlphaProp->SetSrcBlendMode( NiAlphaProperty::ALPHA_ONE );

	return true;
}


void cAniPlane::Process( unsigned long accumTime )
{
	if( mBeginAnim == false )
		return;

	if( mLastAccumTime - accumTime >= mTimeOut )
	{
		/// frame change
		if( mCurFrame >= mFrames )
		{
			if( mLoop )
				mCurFrame = 0;
			else
				EndAnimation();
		}
		mLastAccumTime = accumTime;

		unsigned int row = mCurFrame % mColumCount;
		unsigned int col = mCurFrame / mColumCount;

		unsigned int tx = mTexX + ( row * mTexW );
		unsigned int ty = mTexY + ( col * mTexH );

		SetTextureRect( tx, ty, tx + mTexW, ty + mTexH );

		mCurFrame++;
	}
}

void cAniPlane::SetAnimationInfo( short totalFrame, unsigned long timeOut, bool loop )
{
	mFrames = totalFrame;
	mTimeOut = timeOut;
	mLoop = loop;

	mCurFrame = 0;
}

void cAniPlane::BeginAnimation()
{
	mBeginAnim = true;
	mCurFrame = 0;
	mLastAccumTime = THEAPP->GetWorldAccumTime();
}

void cAniPlane::EndAnimation()
{
	mBeginAnim = false;
}

void cAniPlane::Draw()
{
	if( mBeginAnim == false )
		return;

	cPlaneObject::Draw();
}
