/** 
 * @file llcharacter.cpp
 * @brief Implementation of LLCharacter class.
 *
 * Copyright (c) 2001-$CurrentYear$, Linden Research, Inc.
 * $License$
 */

//-----------------------------------------------------------------------------
// Header Files
//-----------------------------------------------------------------------------

#include "linden_common.h"

#include "llcharacter.h"
#include "llstring.h"

#define SKEL_HEADER "Linden Skeleton 1.0"

LLStringTable LLCharacter::sVisualParamNames(1024);

// helper functions
BOOL larger_screen_area( LLCharacter* data_new, LLCharacter* data_tested )
{
	return data_new->getPixelArea() > data_tested->getPixelArea();
}

LLLinkedList< LLCharacter > LLCharacter::sInstances( larger_screen_area );


//-----------------------------------------------------------------------------
// LLCharacter()
// Class Constructor
//-----------------------------------------------------------------------------
LLCharacter::LLCharacter()
	: 
	mPreferredPelvisHeight( 0.f ),
	mSex( SEX_FEMALE ),
	mAppearanceSerialNum( 0 ),
	mSkeletonSerialNum( 0 )
{
	mMotionController.setCharacter( this );
	sInstances.addData(this);
	mPauseRequest = new LLPauseRequestHandle();
}


//-----------------------------------------------------------------------------
// ~LLCharacter()
// Class Destructor
//-----------------------------------------------------------------------------
LLCharacter::~LLCharacter()
{
	for (LLVisualParam *param = getFirstVisualParam(); 
		param;
		param = getNextVisualParam())
	{
		delete param;
	}
	sInstances.removeData(this);
}


//-----------------------------------------------------------------------------
// getJoint()
//-----------------------------------------------------------------------------
LLJoint *LLCharacter::getJoint( const std::string &name )
{
	LLJoint *joint = NULL;

	LLJoint *root = getRootJoint();
	if (root)
	{
		joint = root->findJoint(name);
	}

	if (!joint)
	{
		llwarns << "Failed to find joint." << llendl;
	}
	return joint;
}

//-----------------------------------------------------------------------------
// addMotion()
//-----------------------------------------------------------------------------
BOOL LLCharacter::addMotion( const LLUUID& id, LLMotionConstructor create )
{
	return mMotionController.addMotion(id, create);
}

//-----------------------------------------------------------------------------
// removeMotion()
//-----------------------------------------------------------------------------
void LLCharacter::removeMotion( const LLUUID& id )
{
	mMotionController.removeMotion(id);
}

//-----------------------------------------------------------------------------
// getMotion()
//-----------------------------------------------------------------------------
LLMotion* LLCharacter::createMotion( const LLUUID &id )
{
	return mMotionController.createMotion( id );
}

//-----------------------------------------------------------------------------
// startMotion()
//-----------------------------------------------------------------------------
BOOL LLCharacter::startMotion(const LLUUID &id, F32 start_offset)
{
	return mMotionController.startMotion(id, start_offset);
}


//-----------------------------------------------------------------------------
// stopMotion()
//-----------------------------------------------------------------------------
BOOL LLCharacter::stopMotion(const LLUUID& id, BOOL stop_immediate)
{
	return mMotionController.stopMotionLocally(id, stop_immediate);
}

//-----------------------------------------------------------------------------
// isMotionActive()
//-----------------------------------------------------------------------------
BOOL LLCharacter::isMotionActive(const LLUUID& id)
{
	LLMotion *motionp = mMotionController.findMotion(id);
	if (motionp)
	{
		return mMotionController.isMotionActive(motionp);
	}

	return FALSE;
}


//-----------------------------------------------------------------------------
// onDeactivateMotion()
//-----------------------------------------------------------------------------
void LLCharacter::requestStopMotion( LLMotion* motion)
{
//	llinfos << "DEBUG: Char::onDeactivateMotion( " << motionName << " )" << llendl;
}


//-----------------------------------------------------------------------------
// updateMotion()
//-----------------------------------------------------------------------------
void LLCharacter::updateMotion(BOOL force_update)
{
	// unpause if we're forcing an update or
	// number of outstanding pause requests has dropped
	// to the initial one
	if (mMotionController.isPaused() && 
		(force_update || mPauseRequest->getNumRefs() == 1))
	{
		mMotionController.unpause();
	}

	mMotionController.updateMotion();

	// pause once again, after forced update, if there are outstanding
	// pause requests
	if (force_update && mPauseRequest->getNumRefs() > 1)
	{
		mMotionController.pause();
	}
}


//-----------------------------------------------------------------------------
// flushAllMotions()
//-----------------------------------------------------------------------------
void LLCharacter::flushAllMotions()
{
	mMotionController.flushAllMotions();
}


//-----------------------------------------------------------------------------
// dumpCharacter()
//-----------------------------------------------------------------------------
void LLCharacter::dumpCharacter( LLJoint *joint )
{
	// handle top level entry into recursion
	if (joint == NULL)
	{
		llinfos << "DEBUG: Dumping Character @" << this << llendl;
		dumpCharacter( getRootJoint() );
		llinfos << "DEBUG: Done." << llendl;
		return;
	}

	// print joint info
	llinfos << "DEBUG: " << joint->getName() << " (" << (joint->getParent()?joint->getParent()->getName():std::string("ROOT")) << ")" << llendl;

	// recurse
	for (	LLJoint *j = joint->mChildren.getFirstData();
			j != NULL;
			j = joint->mChildren.getNextData() )
	{
		dumpCharacter(j);
	}
}

//-----------------------------------------------------------------------------
// setAnimationData()
//-----------------------------------------------------------------------------
void LLCharacter::setAnimationData(std::string name, void *data)
{
	if(mAnimationData.getValue(name))
	{
		*mAnimationData[name] = data;
	}
	else
	{
		mAnimationData.addToHead(name, data);
	}
}

//-----------------------------------------------------------------------------
// getAnimationData()
//-----------------------------------------------------------------------------
void * LLCharacter::getAnimationData(std::string name)
{
	void **result = mAnimationData.getValue(name);
	void *return_value;		// Necessary to suppress VC6 warning. JC
	if (!result)
	{
		return_value = NULL;
	}
	else 
	{
		return_value = *result;
	}

	return return_value;
}

//-----------------------------------------------------------------------------
// removeAnimationData()
//-----------------------------------------------------------------------------
void LLCharacter::removeAnimationData(std::string name)
{
	mAnimationData.remove(name);
}

//-----------------------------------------------------------------------------
// setVisualParamWeight()
//-----------------------------------------------------------------------------
BOOL LLCharacter::setVisualParamWeight(LLVisualParam* which_param, F32 weight, BOOL set_by_user)
{
	S32 index = which_param->getID();
	VisualParamIndexMap_t::iterator index_iter = mVisualParamIndexMap.find(index);
	if (index_iter != mVisualParamIndexMap.end())
	{
		index_iter->second->setWeight(weight, set_by_user);
		return TRUE;
	}
	return FALSE;
}

//-----------------------------------------------------------------------------
// setVisualParamWeight()
//-----------------------------------------------------------------------------
BOOL LLCharacter::setVisualParamWeight(const char* param_name, F32 weight, BOOL set_by_user)
{
	LLString tname(param_name);
	LLString::toLower(tname);
	char *tableptr = sVisualParamNames.checkString(tname);
	VisualParamNameMap_t::iterator name_iter = mVisualParamNameMap.find(tableptr);
	if (name_iter != mVisualParamNameMap.end())
	{
		name_iter->second->setWeight(weight, set_by_user);
		return TRUE;
	}
	llwarns << "LLCharacter::setVisualParamWeight() Invalid visual parameter: " << param_name << llendl;
	return FALSE;
}

//-----------------------------------------------------------------------------
// setVisualParamWeight()
//-----------------------------------------------------------------------------
BOOL LLCharacter::setVisualParamWeight(S32 index, F32 weight, BOOL set_by_user)
{
	VisualParamIndexMap_t::iterator index_iter = mVisualParamIndexMap.find(index);
	if (index_iter != mVisualParamIndexMap.end())
	{
		index_iter->second->setWeight(weight, set_by_user);
		return TRUE;
	}
	llwarns << "LLCharacter::setVisualParamWeight() Invalid visual parameter index: " << index << llendl;
	return FALSE;
}

//-----------------------------------------------------------------------------
// getVisualParamWeight()
//-----------------------------------------------------------------------------
F32 LLCharacter::getVisualParamWeight(LLVisualParam *which_param)
{
	S32 index = which_param->getID();
	VisualParamIndexMap_t::iterator index_iter = mVisualParamIndexMap.find(index);
	if (index_iter != mVisualParamIndexMap.end())
	{
		return index_iter->second->getWeight();
	}
	else
	{
		llwarns << "LLCharacter::getVisualParamWeight() Invalid visual parameter*, index= " << index << llendl;
		return 0.f;
	}
}

//-----------------------------------------------------------------------------
// getVisualParamWeight()
//-----------------------------------------------------------------------------
F32 LLCharacter::getVisualParamWeight(const char* param_name)
{
	LLString tname(param_name);
	LLString::toLower(tname);
	char *tableptr = sVisualParamNames.checkString(tname);
	VisualParamNameMap_t::iterator name_iter = mVisualParamNameMap.find(tableptr);
	if (name_iter != mVisualParamNameMap.end())
	{
		return name_iter->second->getWeight();
	}
	llwarns << "LLCharacter::getVisualParamWeight() Invalid visual parameter: " << param_name << llendl;
	return 0.f;
}

//-----------------------------------------------------------------------------
// getVisualParamWeight()
//-----------------------------------------------------------------------------
F32 LLCharacter::getVisualParamWeight(S32 index)
{
	VisualParamIndexMap_t::iterator index_iter = mVisualParamIndexMap.find(index);
	if (index_iter != mVisualParamIndexMap.end())
	{
		return index_iter->second->getWeight();
	}
	else
	{
		llwarns << "LLCharacter::getVisualParamWeight() Invalid visual parameter index: " << index << llendl;
		return 0.f;
	}
}

//-----------------------------------------------------------------------------
// clearVisualParamWeights()
//-----------------------------------------------------------------------------
void LLCharacter::clearVisualParamWeights()
{
	for (LLVisualParam *param = getFirstVisualParam(); 
		param;
		param = getNextVisualParam())
	{
		if (param->getGroup() == VISUAL_PARAM_GROUP_TWEAKABLE)
		{
			param->setWeight( param->getDefaultWeight(), FALSE );
		}
	}
}

//-----------------------------------------------------------------------------
// getVisualParam()
//-----------------------------------------------------------------------------
LLVisualParam*	LLCharacter::getVisualParam(const char *param_name)
{
	LLString tname(param_name);
	LLString::toLower(tname);
	char *tableptr = sVisualParamNames.checkString(tname);
	VisualParamNameMap_t::iterator name_iter = mVisualParamNameMap.find(tableptr);
	if (name_iter != mVisualParamNameMap.end())
	{
		return name_iter->second;
	}
	llwarns << "LLCharacter::getVisualParam() Invalid visual parameter: " << param_name << llendl;
	return NULL;
}

//-----------------------------------------------------------------------------
// addSharedVisualParam()
//-----------------------------------------------------------------------------
void LLCharacter::addSharedVisualParam(LLVisualParam *param)
{
	S32 index = param->getID();
	VisualParamIndexMap_t::iterator index_iter = mVisualParamIndexMap.find(index);
	LLVisualParam* current_param = 0;
	if (index_iter != mVisualParamIndexMap.end())
		current_param = index_iter->second;
	if( current_param )
	{
		LLVisualParam* next_param = current_param;
		while(next_param->getNextParam())
		{
			next_param = next_param->getNextParam();
		}
		next_param->setNextParam(param);
	}
	else
	{
		llwarns << "Shared visual parameter " << param->getName() << " does not already exist with ID " << 
			param->getID() << llendl;
	}
}

//-----------------------------------------------------------------------------
// addVisualParam()
//-----------------------------------------------------------------------------
void LLCharacter::addVisualParam(LLVisualParam *param)
{
	S32 index = param->getID();
	// Add Index map
	std::pair<VisualParamIndexMap_t::iterator, bool> idxres;
	idxres = mVisualParamIndexMap.insert(VisualParamIndexMap_t::value_type(index, param));
	if (!idxres.second)
	{
		llwarns << "Visual parameter " << param->getName() << " already exists with same ID as " << 
			param->getName() << llendl;
		VisualParamIndexMap_t::iterator index_iter = idxres.first;
		index_iter->second = param;
	}

	if (param->getInfo())
	{
		// Add name map
		LLString tname(param->getName());
		LLString::toLower(tname);
		char *tableptr = sVisualParamNames.addString(tname);
		std::pair<VisualParamNameMap_t::iterator, bool> nameres;
		nameres = mVisualParamNameMap.insert(VisualParamNameMap_t::value_type(tableptr, param));
		if (!nameres.second)
		{
			// Already exists, copy param
			VisualParamNameMap_t::iterator name_iter = nameres.first;
			name_iter->second = param;
		}
	}
	//llinfos << "Adding Visual Param '" << param->getName() << "' ( " << index << " )" << llendl;
}

//-----------------------------------------------------------------------------
// updateVisualParams()
//-----------------------------------------------------------------------------
void LLCharacter::updateVisualParams()
{
	for (LLVisualParam *param = getFirstVisualParam(); 
		param;
		param = getNextVisualParam())
	{
		if (param->isAnimating())
		{
			continue;
		}
		// only apply parameters whose effective weight has changed
		F32 effective_weight = ( param->getSex() & mSex ) ? param->getWeight() : param->getDefaultWeight();
		if (effective_weight != param->getLastWeight())
		{
			param->apply( mSex );
		}
	}
}
 
LLAnimPauseRequest LLCharacter::requestPause()
{
	mMotionController.pause();
	return mPauseRequest;
}

