PageRenderTime 185ms CodeModel.GetById 11ms app.highlight 154ms RepoModel.GetById 1ms app.codeStats 1ms

/indra/newview/llvoavatar.cpp

https://bitbucket.org/lindenlab/viewer-beta/
C++ | 2117 lines | 1501 code | 311 blank | 305 comment | 187 complexity | b8371880310954f4104c8e87c8f309e3 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/** 
   2 * @File llvoavatar.cpp
   3 * @brief Implementation of LLVOAvatar class which is a derivation of LLViewerObject
   4 *
   5 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
   6 * Second Life Viewer Source Code
   7 * Copyright (C) 2010, Linden Research, Inc.
   8 * 
   9 * This library is free software; you can redistribute it and/or
  10 * modify it under the terms of the GNU Lesser General Public
  11 * License as published by the Free Software Foundation;
  12 * version 2.1 of the License only.
  13 * 
  14 * This library is distributed in the hope that it will be useful,
  15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  17 * Lesser General Public License for more details.
  18 * 
  19 * You should have received a copy of the GNU Lesser General Public
  20 * License along with this library; if not, write to the Free Software
  21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
  22 * 
  23 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
  24 * $/LicenseInfo$
  25 */
  26
  27#if LL_MSVC
  28// disable warning about boost::lexical_cast returning uninitialized data
  29// when it fails to parse the string
  30#pragma warning (disable:4701)
  31#endif
  32
  33#include "llviewerprecompiledheaders.h"
  34
  35#include "llvoavatar.h"
  36
  37#include <stdio.h>
  38#include <ctype.h>
  39
  40#include "llaudioengine.h"
  41#include "noise.h"
  42#include "sound_ids.h"
  43#include "raytrace.h"
  44
  45#include "llagent.h" //  Get state values from here
  46#include "llagentcamera.h"
  47#include "llagentwearables.h"
  48#include "llanimationstates.h"
  49#include "llavatarnamecache.h"
  50#include "llavatarpropertiesprocessor.h"
  51#include "llphysicsmotion.h"
  52#include "llviewercontrol.h"
  53#include "llcallingcard.h"		// IDEVO for LLAvatarTracker
  54#include "lldrawpoolavatar.h"
  55#include "lldriverparam.h"
  56#include "lleditingmotion.h"
  57#include "llemote.h"
  58//#include "llfirstuse.h"
  59#include "llfloatertools.h"
  60#include "llheadrotmotion.h"
  61#include "llhudeffecttrail.h"
  62#include "llhudmanager.h"
  63#include "llhudnametag.h"
  64#include "llhudtext.h"				// for mText/mDebugText
  65#include "llkeyframefallmotion.h"
  66#include "llkeyframestandmotion.h"
  67#include "llkeyframewalkmotion.h"
  68#include "llmanipscale.h"  // for get_default_max_prim_scale()
  69#include "llmeshrepository.h"
  70#include "llmutelist.h"
  71#include "llmoveview.h"
  72#include "llnotificationsutil.h"
  73#include "llquantize.h"
  74#include "llrand.h"
  75#include "llregionhandle.h"
  76#include "llresmgr.h"
  77#include "llselectmgr.h"
  78#include "llsprite.h"
  79#include "lltargetingmotion.h"
  80#include "lltexlayer.h"
  81#include "lltoolmorph.h"
  82#include "llviewercamera.h"
  83#include "llviewertexturelist.h"
  84#include "llviewermenu.h"
  85#include "llviewerobjectlist.h"
  86#include "llviewerparcelmgr.h"
  87#include "llviewershadermgr.h"
  88#include "llviewerstats.h"
  89#include "llvoavatarself.h"
  90#include "llvovolume.h"
  91#include "llworld.h"
  92#include "pipeline.h"
  93#include "llviewershadermgr.h"
  94#include "llsky.h"
  95#include "llanimstatelabels.h"
  96#include "lltrans.h"
  97#include "llappearancemgr.h"
  98
  99#include "llgesturemgr.h" //needed to trigger the voice gesticulations
 100#include "llvoiceclient.h"
 101#include "llvoicevisualizer.h" // Ventrella
 102
 103#include "lldebugmessagebox.h"
 104extern F32 SPEED_ADJUST_MAX;
 105extern F32 SPEED_ADJUST_MAX_SEC;
 106extern F32 ANIM_SPEED_MAX;
 107extern F32 ANIM_SPEED_MIN;
 108
 109#if LL_MSVC
 110// disable boost::lexical_cast warning
 111#pragma warning (disable:4702)
 112#endif
 113
 114#include <boost/lexical_cast.hpp>
 115
 116// #define OUTPUT_BREAST_DATA
 117
 118using namespace LLVOAvatarDefines;
 119
 120//-----------------------------------------------------------------------------
 121// Global constants
 122//-----------------------------------------------------------------------------
 123const LLUUID ANIM_AGENT_BODY_NOISE = LLUUID("9aa8b0a6-0c6f-9518-c7c3-4f41f2c001ad"); //"body_noise"
 124const LLUUID ANIM_AGENT_BREATHE_ROT	= LLUUID("4c5a103e-b830-2f1c-16bc-224aa0ad5bc8");  //"breathe_rot"
 125const LLUUID ANIM_AGENT_EDITING	= LLUUID("2a8eba1d-a7f8-5596-d44a-b4977bf8c8bb");  //"editing"
 126const LLUUID ANIM_AGENT_EYE	= LLUUID("5c780ea8-1cd1-c463-a128-48c023f6fbea");  //"eye"
 127const LLUUID ANIM_AGENT_FLY_ADJUST = LLUUID("db95561f-f1b0-9f9a-7224-b12f71af126e");  //"fly_adjust"
 128const LLUUID ANIM_AGENT_HAND_MOTION	= LLUUID("ce986325-0ba7-6e6e-cc24-b17c4b795578");  //"hand_motion"
 129const LLUUID ANIM_AGENT_HEAD_ROT = LLUUID("e6e8d1dd-e643-fff7-b238-c6b4b056a68d");  //"head_rot"
 130const LLUUID ANIM_AGENT_PELVIS_FIX = LLUUID("0c5dd2a2-514d-8893-d44d-05beffad208b");  //"pelvis_fix"
 131const LLUUID ANIM_AGENT_TARGET = LLUUID("0e4896cb-fba4-926c-f355-8720189d5b55");  //"target"
 132const LLUUID ANIM_AGENT_WALK_ADJUST	= LLUUID("829bc85b-02fc-ec41-be2e-74cc6dd7215d");  //"walk_adjust"
 133const LLUUID ANIM_AGENT_PHYSICS_MOTION = LLUUID("7360e029-3cb8-ebc4-863e-212df440d987");  //"physics_motion"
 134
 135
 136//-----------------------------------------------------------------------------
 137// Constants
 138//-----------------------------------------------------------------------------
 139const std::string AVATAR_DEFAULT_CHAR = "avatar";
 140
 141const S32 MIN_PIXEL_AREA_FOR_COMPOSITE = 1024;
 142const F32 SHADOW_OFFSET_AMT = 0.03f;
 143
 144const F32 DELTA_TIME_MIN = 0.01f;	// we clamp measured deltaTime to this
 145const F32 DELTA_TIME_MAX = 0.2f;	// range to insure stability of computations.
 146
 147const F32 PELVIS_LAG_FLYING		= 0.22f;// pelvis follow half life while flying
 148const F32 PELVIS_LAG_WALKING	= 0.4f;	// ...while walking
 149const F32 PELVIS_LAG_MOUSELOOK = 0.15f;
 150const F32 MOUSELOOK_PELVIS_FOLLOW_FACTOR = 0.5f;
 151const F32 PELVIS_LAG_WHEN_FOLLOW_CAM_IS_ON = 0.0001f; // not zero! - something gets divided by this!
 152
 153const F32 PELVIS_ROT_THRESHOLD_SLOW = 60.0f;	// amount of deviation allowed between
 154const F32 PELVIS_ROT_THRESHOLD_FAST = 2.0f;	// the pelvis and the view direction
 155											// when moving fast & slow
 156const F32 TORSO_NOISE_AMOUNT = 1.0f;	// Amount of deviation from up-axis, in degrees
 157const F32 TORSO_NOISE_SPEED = 0.2f;	// Time scale factor on torso noise.
 158
 159const F32 BREATHE_ROT_MOTION_STRENGTH = 0.05f;
 160const F32 BREATHE_SCALE_MOTION_STRENGTH = 0.005f;
 161
 162const F32 MIN_SHADOW_HEIGHT = 0.f;
 163const F32 MAX_SHADOW_HEIGHT = 0.3f;
 164
 165const S32 MIN_REQUIRED_PIXEL_AREA_BODY_NOISE = 10000;
 166const S32 MIN_REQUIRED_PIXEL_AREA_BREATHE = 10000;
 167const S32 MIN_REQUIRED_PIXEL_AREA_PELVIS_FIX = 40;
 168
 169const S32 TEX_IMAGE_SIZE_SELF = 512;
 170const S32 TEX_IMAGE_AREA_SELF = TEX_IMAGE_SIZE_SELF * TEX_IMAGE_SIZE_SELF;
 171const S32 TEX_IMAGE_SIZE_OTHER = 512 / 4;  // The size of local textures for other (!isSelf()) avatars
 172
 173const F32 HEAD_MOVEMENT_AVG_TIME = 0.9f;
 174
 175const S32 MORPH_MASK_REQUESTED_DISCARD = 0;
 176
 177// Discard level at which to switch to baked textures
 178// Should probably be 4 or 3, but didn't want to change it while change other logic - SJB
 179const S32 SWITCH_TO_BAKED_DISCARD = 5;
 180
 181const F32 FOOT_COLLIDE_FUDGE = 0.04f;
 182
 183const F32 HOVER_EFFECT_MAX_SPEED = 3.f;
 184const F32 HOVER_EFFECT_STRENGTH = 0.f;
 185const F32 UNDERWATER_EFFECT_STRENGTH = 0.1f;
 186const F32 UNDERWATER_FREQUENCY_DAMP = 0.33f;
 187const F32 APPEARANCE_MORPH_TIME = 0.65f;
 188const F32 TIME_BEFORE_MESH_CLEANUP = 5.f; // seconds
 189const S32 AVATAR_RELEASE_THRESHOLD = 10; // number of avatar instances before releasing memory
 190const F32 FOOT_GROUND_COLLISION_TOLERANCE = 0.25f;
 191const F32 AVATAR_LOD_TWEAK_RANGE = 0.7f;
 192const S32 MAX_BUBBLE_CHAT_LENGTH = DB_CHAT_MSG_STR_LEN;
 193const S32 MAX_BUBBLE_CHAT_UTTERANCES = 12;
 194const F32 CHAT_FADE_TIME = 8.0;
 195const F32 BUBBLE_CHAT_TIME = CHAT_FADE_TIME * 3.f;
 196
 197const LLColor4 DUMMY_COLOR = LLColor4(0.5,0.5,0.5,1.0);
 198
 199enum ERenderName
 200{
 201	RENDER_NAME_NEVER,
 202	RENDER_NAME_ALWAYS,	
 203	RENDER_NAME_FADE
 204};
 205
 206//-----------------------------------------------------------------------------
 207// Callback data
 208//-----------------------------------------------------------------------------
 209
 210struct LLTextureMaskData
 211{
 212	LLTextureMaskData( const LLUUID& id ) :
 213		mAvatarID(id), 
 214		mLastDiscardLevel(S32_MAX) 
 215	{}
 216	LLUUID				mAvatarID;
 217	S32					mLastDiscardLevel;
 218};
 219
 220/*********************************************************************************
 221 **                                                                             **
 222 ** Begin private LLVOAvatar Support classes
 223 **
 224 **/
 225
 226//------------------------------------------------------------------------
 227// LLVOBoneInfo
 228// Trans/Scale/Rot etc. info about each avatar bone.  Used by LLVOAvatarSkeleton.
 229//------------------------------------------------------------------------
 230class LLVOAvatarBoneInfo
 231{
 232	friend class LLVOAvatar;
 233	friend class LLVOAvatarSkeletonInfo;
 234public:
 235	LLVOAvatarBoneInfo() : mIsJoint(FALSE) {}
 236	~LLVOAvatarBoneInfo()
 237	{
 238		std::for_each(mChildList.begin(), mChildList.end(), DeletePointer());
 239	}
 240	BOOL parseXml(LLXmlTreeNode* node);
 241	
 242private:
 243	std::string mName;
 244	BOOL mIsJoint;
 245	LLVector3 mPos;
 246	LLVector3 mRot;
 247	LLVector3 mScale;
 248	LLVector3 mPivot;
 249	typedef std::vector<LLVOAvatarBoneInfo*> child_list_t;
 250	child_list_t mChildList;
 251};
 252
 253//------------------------------------------------------------------------
 254// LLVOAvatarSkeletonInfo
 255// Overall avatar skeleton
 256//------------------------------------------------------------------------
 257class LLVOAvatarSkeletonInfo
 258{
 259	friend class LLVOAvatar;
 260public:
 261	LLVOAvatarSkeletonInfo() :
 262		mNumBones(0), mNumCollisionVolumes(0) {}
 263	~LLVOAvatarSkeletonInfo()
 264	{
 265		std::for_each(mBoneInfoList.begin(), mBoneInfoList.end(), DeletePointer());
 266	}
 267	BOOL parseXml(LLXmlTreeNode* node);
 268	S32 getNumBones() const { return mNumBones; }
 269	S32 getNumCollisionVolumes() const { return mNumCollisionVolumes; }
 270	
 271private:
 272	S32 mNumBones;
 273	S32 mNumCollisionVolumes;
 274	typedef std::vector<LLVOAvatarBoneInfo*> bone_info_list_t;
 275	bone_info_list_t mBoneInfoList;
 276};
 277
 278//-----------------------------------------------------------------------------
 279// class LLBodyNoiseMotion
 280//-----------------------------------------------------------------------------
 281class LLBodyNoiseMotion :
 282	public LLMotion
 283{
 284public:
 285	// Constructor
 286	LLBodyNoiseMotion(const LLUUID &id)
 287		: LLMotion(id)
 288	{
 289		mName = "body_noise";
 290		mTorsoState = new LLJointState;
 291	}
 292
 293	// Destructor
 294	virtual ~LLBodyNoiseMotion() { }
 295
 296public:
 297	//-------------------------------------------------------------------------
 298	// functions to support MotionController and MotionRegistry
 299	//-------------------------------------------------------------------------
 300	// static constructor
 301	// all subclasses must implement such a function and register it
 302	static LLMotion *create(const LLUUID &id) { return new LLBodyNoiseMotion(id); }
 303
 304public:
 305	//-------------------------------------------------------------------------
 306	// animation callbacks to be implemented by subclasses
 307	//-------------------------------------------------------------------------
 308
 309	// motions must specify whether or not they loop
 310	virtual BOOL getLoop() { return TRUE; }
 311
 312	// motions must report their total duration
 313	virtual F32 getDuration() { return 0.0; }
 314
 315	// motions must report their "ease in" duration
 316	virtual F32 getEaseInDuration() { return 0.0; }
 317
 318	// motions must report their "ease out" duration.
 319	virtual F32 getEaseOutDuration() { return 0.0; }
 320
 321	// motions must report their priority
 322	virtual LLJoint::JointPriority getPriority() { return LLJoint::HIGH_PRIORITY; }
 323
 324	virtual LLMotionBlendType getBlendType() { return ADDITIVE_BLEND; }
 325
 326	// called to determine when a motion should be activated/deactivated based on avatar pixel coverage
 327	virtual F32 getMinPixelArea() { return MIN_REQUIRED_PIXEL_AREA_BODY_NOISE; }
 328
 329	// run-time (post constructor) initialization,
 330	// called after parameters have been set
 331	// must return true to indicate success and be available for activation
 332	virtual LLMotionInitStatus onInitialize(LLCharacter *character)
 333	{
 334		if( !mTorsoState->setJoint( character->getJoint("mTorso") ))
 335		{
 336			return STATUS_FAILURE;
 337		}
 338
 339		mTorsoState->setUsage(LLJointState::ROT);
 340
 341		addJointState( mTorsoState );
 342		return STATUS_SUCCESS;
 343	}
 344
 345	// called when a motion is activated
 346	// must return TRUE to indicate success, or else
 347	// it will be deactivated
 348	virtual BOOL onActivate() { return TRUE; }
 349
 350	// called per time step
 351	// must return TRUE while it is active, and
 352	// must return FALSE when the motion is completed.
 353	virtual BOOL onUpdate(F32 time, U8* joint_mask)
 354	{
 355		F32 nx[2];
 356		nx[0]=time*TORSO_NOISE_SPEED;
 357		nx[1]=0.0f;
 358		F32 ny[2];
 359		ny[0]=0.0f;
 360		ny[1]=time*TORSO_NOISE_SPEED;
 361		F32 noiseX = noise2(nx);
 362		F32 noiseY = noise2(ny);
 363
 364		F32 rx = TORSO_NOISE_AMOUNT * DEG_TO_RAD * noiseX / 0.42f;
 365		F32 ry = TORSO_NOISE_AMOUNT * DEG_TO_RAD * noiseY / 0.42f;
 366		LLQuaternion tQn;
 367		tQn.setQuat( rx, ry, 0.0f );
 368		mTorsoState->setRotation( tQn );
 369
 370		return TRUE;
 371	}
 372
 373	// called when a motion is deactivated
 374	virtual void onDeactivate() {}
 375
 376private:
 377	//-------------------------------------------------------------------------
 378	// joint states to be animated
 379	//-------------------------------------------------------------------------
 380	LLPointer<LLJointState> mTorsoState;
 381};
 382
 383//-----------------------------------------------------------------------------
 384// class LLBreatheMotionRot
 385//-----------------------------------------------------------------------------
 386class LLBreatheMotionRot :
 387	public LLMotion
 388{
 389public:
 390	// Constructor
 391	LLBreatheMotionRot(const LLUUID &id) :
 392		LLMotion(id),
 393		mBreatheRate(1.f),
 394		mCharacter(NULL)
 395	{
 396		mName = "breathe_rot";
 397		mChestState = new LLJointState;
 398	}
 399
 400	// Destructor
 401	virtual ~LLBreatheMotionRot() {}
 402
 403public:
 404	//-------------------------------------------------------------------------
 405	// functions to support MotionController and MotionRegistry
 406	//-------------------------------------------------------------------------
 407	// static constructor
 408	// all subclasses must implement such a function and register it
 409	static LLMotion *create(const LLUUID &id) { return new LLBreatheMotionRot(id); }
 410
 411public:
 412	//-------------------------------------------------------------------------
 413	// animation callbacks to be implemented by subclasses
 414	//-------------------------------------------------------------------------
 415
 416	// motions must specify whether or not they loop
 417	virtual BOOL getLoop() { return TRUE; }
 418
 419	// motions must report their total duration
 420	virtual F32 getDuration() { return 0.0; }
 421
 422	// motions must report their "ease in" duration
 423	virtual F32 getEaseInDuration() { return 0.0; }
 424
 425	// motions must report their "ease out" duration.
 426	virtual F32 getEaseOutDuration() { return 0.0; }
 427
 428	// motions must report their priority
 429	virtual LLJoint::JointPriority getPriority() { return LLJoint::MEDIUM_PRIORITY; }
 430
 431	virtual LLMotionBlendType getBlendType() { return NORMAL_BLEND; }
 432
 433	// called to determine when a motion should be activated/deactivated based on avatar pixel coverage
 434	virtual F32 getMinPixelArea() { return MIN_REQUIRED_PIXEL_AREA_BREATHE; }
 435
 436	// run-time (post constructor) initialization,
 437	// called after parameters have been set
 438	// must return true to indicate success and be available for activation
 439	virtual LLMotionInitStatus onInitialize(LLCharacter *character)
 440	{		
 441		mCharacter = character;
 442		BOOL success = true;
 443
 444		if ( !mChestState->setJoint( character->getJoint( "mChest" ) ) ) { success = false; }
 445
 446		if ( success )
 447		{
 448			mChestState->setUsage(LLJointState::ROT);
 449			addJointState( mChestState );
 450		}
 451
 452		if ( success )
 453		{
 454			return STATUS_SUCCESS;
 455		}
 456		else
 457		{
 458			return STATUS_FAILURE;
 459		}
 460	}
 461
 462	// called when a motion is activated
 463	// must return TRUE to indicate success, or else
 464	// it will be deactivated
 465	virtual BOOL onActivate() { return TRUE; }
 466
 467	// called per time step
 468	// must return TRUE while it is active, and
 469	// must return FALSE when the motion is completed.
 470	virtual BOOL onUpdate(F32 time, U8* joint_mask)
 471	{
 472		mBreatheRate = 1.f;
 473
 474		F32 breathe_amt = (sinf(mBreatheRate * time) * BREATHE_ROT_MOTION_STRENGTH);
 475
 476		mChestState->setRotation(LLQuaternion(breathe_amt, LLVector3(0.f, 1.f, 0.f)));
 477
 478		return TRUE;
 479	}
 480
 481	// called when a motion is deactivated
 482	virtual void onDeactivate() {}
 483
 484private:
 485	//-------------------------------------------------------------------------
 486	// joint states to be animated
 487	//-------------------------------------------------------------------------
 488	LLPointer<LLJointState> mChestState;
 489	F32					mBreatheRate;
 490	LLCharacter*		mCharacter;
 491};
 492
 493//-----------------------------------------------------------------------------
 494// class LLPelvisFixMotion
 495//-----------------------------------------------------------------------------
 496class LLPelvisFixMotion :
 497	public LLMotion
 498{
 499public:
 500	// Constructor
 501	LLPelvisFixMotion(const LLUUID &id)
 502		: LLMotion(id), mCharacter(NULL)
 503	{
 504		mName = "pelvis_fix";
 505
 506		mPelvisState = new LLJointState;
 507	}
 508
 509	// Destructor
 510	virtual ~LLPelvisFixMotion() { }
 511
 512public:
 513	//-------------------------------------------------------------------------
 514	// functions to support MotionController and MotionRegistry
 515	//-------------------------------------------------------------------------
 516	// static constructor
 517	// all subclasses must implement such a function and register it
 518	static LLMotion *create(const LLUUID& id) { return new LLPelvisFixMotion(id); }
 519
 520public:
 521	//-------------------------------------------------------------------------
 522	// animation callbacks to be implemented by subclasses
 523	//-------------------------------------------------------------------------
 524
 525	// motions must specify whether or not they loop
 526	virtual BOOL getLoop() { return TRUE; }
 527
 528	// motions must report their total duration
 529	virtual F32 getDuration() { return 0.0; }
 530
 531	// motions must report their "ease in" duration
 532	virtual F32 getEaseInDuration() { return 0.5f; }
 533
 534	// motions must report their "ease out" duration.
 535	virtual F32 getEaseOutDuration() { return 0.5f; }
 536
 537	// motions must report their priority
 538	virtual LLJoint::JointPriority getPriority() { return LLJoint::LOW_PRIORITY; }
 539
 540	virtual LLMotionBlendType getBlendType() { return NORMAL_BLEND; }
 541
 542	// called to determine when a motion should be activated/deactivated based on avatar pixel coverage
 543	virtual F32 getMinPixelArea() { return MIN_REQUIRED_PIXEL_AREA_PELVIS_FIX; }
 544
 545	// run-time (post constructor) initialization,
 546	// called after parameters have been set
 547	// must return true to indicate success and be available for activation
 548	virtual LLMotionInitStatus onInitialize(LLCharacter *character)
 549	{
 550		mCharacter = character;
 551
 552		if (!mPelvisState->setJoint( character->getJoint("mPelvis")))
 553		{
 554			return STATUS_FAILURE;
 555		}
 556
 557		mPelvisState->setUsage(LLJointState::POS);
 558
 559		addJointState( mPelvisState );
 560		return STATUS_SUCCESS;
 561	}
 562
 563	// called when a motion is activated
 564	// must return TRUE to indicate success, or else
 565	// it will be deactivated
 566	virtual BOOL onActivate() { return TRUE; }
 567
 568	// called per time step
 569	// must return TRUE while it is active, and
 570	// must return FALSE when the motion is completed.
 571	virtual BOOL onUpdate(F32 time, U8* joint_mask)
 572	{
 573		mPelvisState->setPosition(LLVector3::zero);
 574
 575		return TRUE;
 576	}
 577
 578	// called when a motion is deactivated
 579	virtual void onDeactivate() {}
 580
 581private:
 582	//-------------------------------------------------------------------------
 583	// joint states to be animated
 584	//-------------------------------------------------------------------------
 585	LLPointer<LLJointState> mPelvisState;
 586	LLCharacter*		mCharacter;
 587};
 588
 589/**
 590 **
 591 ** End LLVOAvatar Support classes
 592 **                                                                             **
 593 *********************************************************************************/
 594
 595
 596//-----------------------------------------------------------------------------
 597// Static Data
 598//-----------------------------------------------------------------------------
 599LLXmlTree LLVOAvatar::sXMLTree;
 600LLXmlTree LLVOAvatar::sSkeletonXMLTree;
 601LLVOAvatarSkeletonInfo* LLVOAvatar::sAvatarSkeletonInfo = NULL;
 602LLVOAvatar::LLVOAvatarXmlInfo* LLVOAvatar::sAvatarXmlInfo = NULL;
 603LLVOAvatarDictionary *LLVOAvatar::sAvatarDictionary = NULL;
 604S32 LLVOAvatar::sFreezeCounter = 0;
 605U32 LLVOAvatar::sMaxVisible = 12;
 606F32 LLVOAvatar::sRenderDistance = 256.f;
 607S32	LLVOAvatar::sNumVisibleAvatars = 0;
 608S32	LLVOAvatar::sNumLODChangesThisFrame = 0;
 609
 610const LLUUID LLVOAvatar::sStepSoundOnLand("e8af4a28-aa83-4310-a7c4-c047e15ea0df");
 611const LLUUID LLVOAvatar::sStepSounds[LL_MCODE_END] =
 612{
 613	SND_STONE_RUBBER,
 614	SND_METAL_RUBBER,
 615	SND_GLASS_RUBBER,
 616	SND_WOOD_RUBBER,
 617	SND_FLESH_RUBBER,
 618	SND_RUBBER_PLASTIC,
 619	SND_RUBBER_RUBBER
 620};
 621
 622S32 LLVOAvatar::sRenderName = RENDER_NAME_ALWAYS;
 623BOOL LLVOAvatar::sRenderGroupTitles = TRUE;
 624S32 LLVOAvatar::sNumVisibleChatBubbles = 0;
 625BOOL LLVOAvatar::sDebugInvisible = FALSE;
 626BOOL LLVOAvatar::sShowAttachmentPoints = FALSE;
 627BOOL LLVOAvatar::sShowAnimationDebug = FALSE;
 628BOOL LLVOAvatar::sShowFootPlane = FALSE;
 629BOOL LLVOAvatar::sVisibleInFirstPerson = FALSE;
 630F32 LLVOAvatar::sLODFactor = 1.f;
 631F32 LLVOAvatar::sPhysicsLODFactor = 1.f;
 632BOOL LLVOAvatar::sUseImpostors = FALSE;
 633BOOL LLVOAvatar::sJointDebug = FALSE;
 634
 635F32 LLVOAvatar::sUnbakedTime = 0.f;
 636F32 LLVOAvatar::sUnbakedUpdateTime = 0.f;
 637F32 LLVOAvatar::sGreyTime = 0.f;
 638F32 LLVOAvatar::sGreyUpdateTime = 0.f;
 639
 640//-----------------------------------------------------------------------------
 641// Helper functions
 642//-----------------------------------------------------------------------------
 643static F32 calc_bouncy_animation(F32 x);
 644
 645//-----------------------------------------------------------------------------
 646// LLVOAvatar()
 647//-----------------------------------------------------------------------------
 648LLVOAvatar::LLVOAvatar(const LLUUID& id,
 649					   const LLPCode pcode,
 650					   LLViewerRegion* regionp) :
 651	LLViewerObject(id, pcode, regionp),
 652	mIsDummy(FALSE),
 653	mSpecialRenderMode(0),
 654	mTurning(FALSE),
 655	mPelvisToFoot(0.f),
 656	mLastSkeletonSerialNum( 0 ),
 657	mHeadOffset(),
 658	mIsSitting(FALSE),
 659	mTimeVisible(),
 660	mTyping(FALSE),
 661	mMeshValid(FALSE),
 662	mVisible(FALSE),
 663	mWindFreq(0.f),
 664	mRipplePhase( 0.f ),
 665	mBelowWater(FALSE),
 666	mLastAppearanceBlendTime(0.f),
 667	mAppearanceAnimating(FALSE),
 668	mNameString(),
 669	mTitle(),
 670	mNameAway(false),
 671	mNameBusy(false),
 672	mNameMute(false),
 673	mNameAppearance(false),
 674	mNameFriend(false),
 675	mNameAlpha(0.f),
 676	mRenderGroupTitles(sRenderGroupTitles),
 677	mNameCloud(false),
 678	mFirstTEMessageReceived( FALSE ),
 679	mFirstAppearanceMessageReceived( FALSE ),
 680	mCulled( FALSE ),
 681	mVisibilityRank(0),
 682	mTexSkinColor( NULL ),
 683	mTexHairColor( NULL ),
 684	mTexEyeColor( NULL ),
 685	mNeedsSkin(FALSE),
 686	mLastSkinTime(0.f),
 687	mUpdatePeriod(1),
 688	mFullyLoaded(FALSE),
 689	mPreviousFullyLoaded(FALSE),
 690	mFullyLoadedInitialized(FALSE),
 691	mSupportsAlphaLayers(FALSE),
 692	mLoadedCallbacksPaused(FALSE),
 693	mHasPelvisOffset( FALSE ),
 694	mRenderUnloadedAvatar(LLCachedControl<bool>(gSavedSettings, "RenderUnloadedAvatar"))
 695{
 696	LLMemType mt(LLMemType::MTYPE_AVATAR);
 697	//VTResume();  // VTune
 698	
 699	// mVoiceVisualizer is created by the hud effects manager and uses the HUD Effects pipeline
 700	const BOOL needsSendToSim = false; // currently, this HUD effect doesn't need to pack and unpack data to do its job
 701	mVoiceVisualizer = ( LLVoiceVisualizer *)LLHUDManager::getInstance()->createViewerEffect( LLHUDObject::LL_HUD_EFFECT_VOICE_VISUALIZER, needsSendToSim );
 702
 703	lldebugs << "LLVOAvatar Constructor (0x" << this << ") id:" << mID << llendl;
 704
 705	mPelvisp = NULL;
 706
 707	mBakedTextureDatas.resize(BAKED_NUM_INDICES);
 708	for (U32 i = 0; i < mBakedTextureDatas.size(); i++ )
 709	{
 710		mBakedTextureDatas[i].mLastTextureIndex = IMG_DEFAULT_AVATAR;
 711		mBakedTextureDatas[i].mTexLayerSet = NULL;
 712		mBakedTextureDatas[i].mIsLoaded = false;
 713		mBakedTextureDatas[i].mIsUsed = false;
 714		mBakedTextureDatas[i].mMaskTexName = 0;
 715		mBakedTextureDatas[i].mTextureIndex = LLVOAvatarDictionary::bakedToLocalTextureIndex((EBakedTextureIndex)i);
 716	}
 717
 718	mDirtyMesh = 2;	// Dirty geometry, need to regenerate.
 719	mMeshTexturesDirty = FALSE;
 720	mHeadp = NULL;
 721
 722	mIsBuilt = FALSE;
 723
 724	mNumJoints = 0;
 725	mSkeleton = NULL;
 726
 727	mNumCollisionVolumes = 0;
 728	mCollisionVolumes = NULL;
 729
 730	// set up animation variables
 731	mSpeed = 0.f;
 732	setAnimationData("Speed", &mSpeed);
 733
 734	mNeedsImpostorUpdate = TRUE;
 735	mNeedsAnimUpdate = TRUE;
 736
 737	mImpostorDistance = 0;
 738	mImpostorPixelArea = 0;
 739
 740	setNumTEs(TEX_NUM_INDICES);
 741
 742	mbCanSelect = TRUE;
 743
 744	mSignaledAnimations.clear();
 745	mPlayingAnimations.clear();
 746
 747	mWasOnGroundLeft = FALSE;
 748	mWasOnGroundRight = FALSE;
 749
 750	mTimeLast = 0.0f;
 751	mSpeedAccum = 0.0f;
 752
 753	mRippleTimeLast = 0.f;
 754
 755	mInAir = FALSE;
 756
 757	mStepOnLand = TRUE;
 758	mStepMaterial = 0;
 759
 760	mLipSyncActive = false;
 761	mOohMorph      = NULL;
 762	mAahMorph      = NULL;
 763
 764	mCurrentGesticulationLevel = 0;
 765
 766	mRuthTimer.reset();
 767	mRuthDebugTimer.reset();
 768	mDebugExistenceTimer.reset();
 769	mPelvisOffset = LLVector3(0.0f,0.0f,0.0f);
 770	mLastPelvisToFoot = 0.0f;
 771	mPelvisFixup = 0.0f;
 772	mLastPelvisFixup = 0.0f;
 773}
 774
 775//------------------------------------------------------------------------
 776// LLVOAvatar::~LLVOAvatar()
 777//------------------------------------------------------------------------
 778LLVOAvatar::~LLVOAvatar()
 779{
 780	if (gSavedSettings.getBOOL("DebugAvatarRezTime"))
 781	{
 782		if (!mFullyLoaded)
 783		{
 784			llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' left after " << (U32)mRuthDebugTimer.getElapsedTimeF32() << " seconds as cloud." << llendl;
 785			LLSD args;
 786			args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
 787			args["TIME"] = llformat("%d",(U32)mRuthDebugTimer.getElapsedTimeF32());
 788			args["NAME"] = getFullname();
 789			LLNotificationsUtil::add("AvatarRezLeftCloudNotification",args);
 790		}
 791		else
 792		{
 793			llinfos << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() << "sec ] Avatar '" << getFullname() << "' left." << llendl;
 794			LLSD args;
 795			args["EXISTENCE"] = llformat("%d",(U32)mDebugExistenceTimer.getElapsedTimeF32());
 796			args["NAME"] = getFullname();
 797			LLNotificationsUtil::add("AvatarRezLeftNotification",args);
 798		}
 799
 800	}
 801	lldebugs << "LLVOAvatar Destructor (0x" << this << ") id:" << mID << llendl;
 802
 803	mRoot.removeAllChildren();
 804
 805	deleteAndClearArray(mSkeleton);
 806	deleteAndClearArray(mCollisionVolumes);
 807
 808	mNumJoints = 0;
 809
 810	for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
 811	{
 812		deleteAndClear(mBakedTextureDatas[i].mTexLayerSet);
 813		mBakedTextureDatas[i].mMeshes.clear();
 814
 815		for (morph_list_t::iterator iter2 = mBakedTextureDatas[i].mMaskedMorphs.begin();
 816			 iter2 != mBakedTextureDatas[i].mMaskedMorphs.end(); iter2++)
 817		{
 818			LLMaskedMorph* masked_morph = (*iter2);
 819			delete masked_morph;
 820		}
 821	}
 822
 823	std::for_each(mAttachmentPoints.begin(), mAttachmentPoints.end(), DeletePairedPointer());
 824	mAttachmentPoints.clear();
 825
 826	deleteAndClear(mTexSkinColor);
 827	deleteAndClear(mTexHairColor);
 828	deleteAndClear(mTexEyeColor);
 829
 830	std::for_each(mMeshes.begin(), mMeshes.end(), DeletePairedPointer());
 831	mMeshes.clear();
 832
 833	for (std::vector<LLViewerJoint*>::iterator jointIter = mMeshLOD.begin();
 834		 jointIter != mMeshLOD.end(); 
 835		 ++jointIter)
 836	{
 837		LLViewerJoint* joint = (LLViewerJoint *) *jointIter;
 838		std::for_each(joint->mMeshParts.begin(), joint->mMeshParts.end(), DeletePointer());
 839		joint->mMeshParts.clear();
 840	}
 841	std::for_each(mMeshLOD.begin(), mMeshLOD.end(), DeletePointer());
 842	mMeshLOD.clear();
 843	
 844	mDead = TRUE;
 845	
 846	mAnimationSources.clear();
 847	LLLoadedCallbackEntry::cleanUpCallbackList(&mCallbackTextureList) ;
 848
 849	lldebugs << "LLVOAvatar Destructor end" << llendl;
 850}
 851
 852void LLVOAvatar::markDead()
 853{
 854	if (mNameText)
 855	{
 856		mNameText->markDead();
 857		mNameText = NULL;
 858		sNumVisibleChatBubbles--;
 859	}
 860	mVoiceVisualizer->markDead();
 861	LLLoadedCallbackEntry::cleanUpCallbackList(&mCallbackTextureList) ;
 862	LLViewerObject::markDead();
 863}
 864
 865
 866BOOL LLVOAvatar::isFullyBaked()
 867{
 868	if (mIsDummy) return TRUE;
 869	if (getNumTEs() == 0) return FALSE;
 870
 871	for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
 872	{
 873		if (!isTextureDefined(mBakedTextureDatas[i].mTextureIndex)
 874			&& ( (i != BAKED_SKIRT) || isWearingWearableType(LLWearableType::WT_SKIRT) ) )
 875		{
 876			return FALSE;
 877		}
 878	}
 879	return TRUE;
 880}
 881
 882void LLVOAvatar::deleteLayerSetCaches(bool clearAll)
 883{
 884	for (U32 i = 0; i < mBakedTextureDatas.size(); i++)
 885	{
 886		if (mBakedTextureDatas[i].mTexLayerSet)
 887		{
 888			// ! BACKWARDS COMPATIBILITY !
 889			// Can be removed after hair baking is mandatory on the grid
 890			if ((i != BAKED_HAIR || isSelf()) && !clearAll)
 891			{
 892				mBakedTextureDatas[i].mTexLayerSet->deleteCaches();
 893			}
 894		}
 895		if (mBakedTextureDatas[i].mMaskTexName)
 896		{
 897			glDeleteTextures(1, (GLuint*)&(mBakedTextureDatas[i].mMaskTexName));
 898			mBakedTextureDatas[i].mMaskTexName = 0 ;
 899		}
 900	}
 901}
 902
 903// static 
 904BOOL LLVOAvatar::areAllNearbyInstancesBaked(S32& grey_avatars)
 905{
 906	BOOL res = TRUE;
 907	grey_avatars = 0;
 908	for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
 909		 iter != LLCharacter::sInstances.end(); ++iter)
 910	{
 911		LLVOAvatar* inst = (LLVOAvatar*) *iter;
 912		if( inst->isDead() )
 913		{
 914			continue;
 915		}
 916		else if( !inst->isFullyBaked() )
 917		{
 918			res = FALSE;
 919			if (inst->mHasGrey)
 920			{
 921				++grey_avatars;
 922			}
 923		}
 924	}
 925	return res;
 926}
 927
 928// static
 929void LLVOAvatar::dumpBakedStatus()
 930{
 931	LLVector3d camera_pos_global = gAgentCamera.getCameraPositionGlobal();
 932
 933	for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
 934		 iter != LLCharacter::sInstances.end(); ++iter)
 935	{
 936		LLVOAvatar* inst = (LLVOAvatar*) *iter;
 937		llinfos << "Avatar ";
 938
 939		LLNameValue* firstname = inst->getNVPair("FirstName");
 940		LLNameValue* lastname = inst->getNVPair("LastName");
 941
 942		if( firstname )
 943		{
 944			llcont << firstname->getString();
 945		}
 946		if( lastname )
 947		{
 948			llcont << " " << lastname->getString();
 949		}
 950
 951		llcont << " " << inst->mID;
 952
 953		if( inst->isDead() )
 954		{
 955			llcont << " DEAD ("<< inst->getNumRefs() << " refs)";
 956		}
 957
 958		if( inst->isSelf() )
 959		{
 960			llcont << " (self)";
 961		}
 962
 963
 964		F64 dist_to_camera = (inst->getPositionGlobal() - camera_pos_global).length();
 965		llcont << " " << dist_to_camera << "m ";
 966
 967		llcont << " " << inst->mPixelArea << " pixels";
 968
 969		if( inst->isVisible() )
 970		{
 971			llcont << " (visible)";
 972		}
 973		else
 974		{
 975			llcont << " (not visible)";
 976		}
 977
 978		if( inst->isFullyBaked() )
 979		{
 980			llcont << " Baked";
 981		}
 982		else
 983		{
 984			llcont << " Unbaked (";
 985			
 986			for (LLVOAvatarDictionary::BakedTextures::const_iterator iter = LLVOAvatarDictionary::getInstance()->getBakedTextures().begin();
 987				 iter != LLVOAvatarDictionary::getInstance()->getBakedTextures().end();
 988				 ++iter)
 989			{
 990				const LLVOAvatarDictionary::BakedEntry *baked_dict = iter->second;
 991				const ETextureIndex index = baked_dict->mTextureIndex;
 992				if (!inst->isTextureDefined(index))
 993				{
 994					llcont << " " << LLVOAvatarDictionary::getInstance()->getTexture(index)->mName;
 995				}
 996			}
 997			llcont << " ) " << inst->getUnbakedPixelAreaRank();
 998			if( inst->isCulled() )
 999			{
1000				llcont << " culled";
1001			}
1002		}
1003		llcont << llendl;
1004	}
1005}
1006
1007//static
1008void LLVOAvatar::restoreGL()
1009{
1010	if (!isAgentAvatarValid()) return;
1011
1012	gAgentAvatarp->setCompositeUpdatesEnabled(TRUE);
1013	for (U32 i = 0; i < gAgentAvatarp->mBakedTextureDatas.size(); i++)
1014	{
1015		gAgentAvatarp->invalidateComposite(gAgentAvatarp->mBakedTextureDatas[i].mTexLayerSet, FALSE);
1016	}
1017	gAgentAvatarp->updateMeshTextures();
1018}
1019
1020//static
1021void LLVOAvatar::destroyGL()
1022{
1023	deleteCachedImages();
1024
1025	resetImpostors();
1026}
1027
1028//static
1029void LLVOAvatar::resetImpostors()
1030{
1031	for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
1032		 iter != LLCharacter::sInstances.end(); ++iter)
1033	{
1034		LLVOAvatar* avatar = (LLVOAvatar*) *iter;
1035		avatar->mImpostor.release();
1036	}
1037}
1038
1039// static
1040void LLVOAvatar::deleteCachedImages(bool clearAll)
1041{	
1042	if (LLTexLayerSet::sHasCaches)
1043	{
1044		lldebugs << "Deleting layer set caches" << llendl;
1045		for (std::vector<LLCharacter*>::iterator iter = LLCharacter::sInstances.begin();
1046			 iter != LLCharacter::sInstances.end(); ++iter)
1047		{
1048			LLVOAvatar* inst = (LLVOAvatar*) *iter;
1049			inst->deleteLayerSetCaches(clearAll);
1050		}
1051		LLTexLayerSet::sHasCaches = FALSE;
1052	}
1053	LLVOAvatarSelf::deleteScratchTextures();
1054	LLTexLayerStaticImageList::getInstance()->deleteCachedImages();
1055}
1056
1057
1058//------------------------------------------------------------------------
1059// static
1060// LLVOAvatar::initClass()
1061//------------------------------------------------------------------------
1062void LLVOAvatar::initClass()
1063{ 
1064	std::string xmlFile;
1065
1066	xmlFile = gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,AVATAR_DEFAULT_CHAR) + "_lad.xml";
1067	BOOL success = sXMLTree.parseFile( xmlFile, FALSE );
1068	if (!success)
1069	{
1070		llerrs << "Problem reading avatar configuration file:" << xmlFile << llendl;
1071	}
1072
1073	// now sanity check xml file
1074	LLXmlTreeNode* root = sXMLTree.getRoot();
1075	if (!root) 
1076	{
1077		llerrs << "No root node found in avatar configuration file: " << xmlFile << llendl;
1078		return;
1079	}
1080
1081	//-------------------------------------------------------------------------
1082	// <linden_avatar version="1.0"> (root)
1083	//-------------------------------------------------------------------------
1084	if( !root->hasName( "linden_avatar" ) )
1085	{
1086		llerrs << "Invalid avatar file header: " << xmlFile << llendl;
1087	}
1088	
1089	std::string version;
1090	static LLStdStringHandle version_string = LLXmlTree::addAttributeString("version");
1091	if( !root->getFastAttributeString( version_string, version ) || (version != "1.0") )
1092	{
1093		llerrs << "Invalid avatar file version: " << version << " in file: " << xmlFile << llendl;
1094	}
1095
1096	S32 wearable_def_version = 1;
1097	static LLStdStringHandle wearable_definition_version_string = LLXmlTree::addAttributeString("wearable_definition_version");
1098	root->getFastAttributeS32( wearable_definition_version_string, wearable_def_version );
1099	LLWearable::setCurrentDefinitionVersion( wearable_def_version );
1100
1101	std::string mesh_file_name;
1102
1103	LLXmlTreeNode* skeleton_node = root->getChildByName( "skeleton" );
1104	if (!skeleton_node)
1105	{
1106		llerrs << "No skeleton in avatar configuration file: " << xmlFile << llendl;
1107		return;
1108	}
1109	
1110	std::string skeleton_file_name;
1111	static LLStdStringHandle file_name_string = LLXmlTree::addAttributeString("file_name");
1112	if (!skeleton_node->getFastAttributeString(file_name_string, skeleton_file_name))
1113	{
1114		llerrs << "No file name in skeleton node in avatar config file: " << xmlFile << llendl;
1115	}
1116	
1117	std::string skeleton_path;
1118	skeleton_path = gDirUtilp->getExpandedFilename(LL_PATH_CHARACTER,skeleton_file_name);
1119	if (!parseSkeletonFile(skeleton_path))
1120	{
1121		llerrs << "Error parsing skeleton file: " << skeleton_path << llendl;
1122	}
1123
1124	// Process XML data
1125
1126	// avatar_skeleton.xml
1127	if (sAvatarSkeletonInfo)
1128	{ //this can happen if a login attempt failed
1129		delete sAvatarSkeletonInfo;
1130	}
1131	sAvatarSkeletonInfo = new LLVOAvatarSkeletonInfo;
1132	if (!sAvatarSkeletonInfo->parseXml(sSkeletonXMLTree.getRoot()))
1133	{
1134		llerrs << "Error parsing skeleton XML file: " << skeleton_path << llendl;
1135	}
1136	// parse avatar_lad.xml
1137	if (sAvatarXmlInfo)
1138	{ //this can happen if a login attempt failed
1139		deleteAndClear(sAvatarXmlInfo);
1140	}
1141	sAvatarXmlInfo = new LLVOAvatarXmlInfo;
1142	if (!sAvatarXmlInfo->parseXmlSkeletonNode(root))
1143	{
1144		llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
1145	}
1146	if (!sAvatarXmlInfo->parseXmlMeshNodes(root))
1147	{
1148		llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
1149	}
1150	if (!sAvatarXmlInfo->parseXmlColorNodes(root))
1151	{
1152		llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
1153	}
1154	if (!sAvatarXmlInfo->parseXmlLayerNodes(root))
1155	{
1156		llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
1157	}
1158	if (!sAvatarXmlInfo->parseXmlDriverNodes(root))
1159	{
1160		llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
1161	}
1162	if (!sAvatarXmlInfo->parseXmlMorphNodes(root))
1163	{
1164		llerrs << "Error parsing skeleton node in avatar XML file: " << skeleton_path << llendl;
1165	}
1166
1167	gAnimLibrary.animStateSetString(ANIM_AGENT_BODY_NOISE,"body_noise");
1168	gAnimLibrary.animStateSetString(ANIM_AGENT_BREATHE_ROT,"breathe_rot");
1169	gAnimLibrary.animStateSetString(ANIM_AGENT_PHYSICS_MOTION,"physics_motion");
1170	gAnimLibrary.animStateSetString(ANIM_AGENT_EDITING,"editing");
1171	gAnimLibrary.animStateSetString(ANIM_AGENT_EYE,"eye");
1172	gAnimLibrary.animStateSetString(ANIM_AGENT_FLY_ADJUST,"fly_adjust");
1173	gAnimLibrary.animStateSetString(ANIM_AGENT_HAND_MOTION,"hand_motion");
1174	gAnimLibrary.animStateSetString(ANIM_AGENT_HEAD_ROT,"head_rot");
1175	gAnimLibrary.animStateSetString(ANIM_AGENT_PELVIS_FIX,"pelvis_fix");
1176	gAnimLibrary.animStateSetString(ANIM_AGENT_TARGET,"target");
1177	gAnimLibrary.animStateSetString(ANIM_AGENT_WALK_ADJUST,"walk_adjust");
1178}
1179
1180
1181void LLVOAvatar::cleanupClass()
1182{
1183	deleteAndClear(sAvatarXmlInfo);
1184	sSkeletonXMLTree.cleanup();
1185	sXMLTree.cleanup();
1186}
1187
1188void LLVOAvatar::initInstance(void)
1189{
1190	//-------------------------------------------------------------------------
1191	// initialize joint, mesh and shape members
1192	//-------------------------------------------------------------------------
1193	mRoot.setName( "mRoot" );
1194	
1195	for (LLVOAvatarDictionary::Meshes::const_iterator iter = LLVOAvatarDictionary::getInstance()->getMeshes().begin();
1196		 iter != LLVOAvatarDictionary::getInstance()->getMeshes().end();
1197		 ++iter)
1198	{
1199		const EMeshIndex mesh_index = iter->first;
1200		const LLVOAvatarDictionary::MeshEntry *mesh_dict = iter->second;
1201		LLViewerJoint* joint = new LLViewerJoint();
1202		joint->setName(mesh_dict->mName);
1203		joint->setMeshID(mesh_index);
1204		mMeshLOD.push_back(joint);
1205		
1206		/* mHairLOD.setName("mHairLOD");
1207		   mHairMesh0.setName("mHairMesh0");
1208		   mHairMesh0.setMeshID(MESH_ID_HAIR);
1209		   mHairMesh1.setName("mHairMesh1"); */
1210		for (U32 lod = 0; lod < mesh_dict->mLOD; lod++)
1211		{
1212			LLViewerJointMesh* mesh = new LLViewerJointMesh();
1213			std::string mesh_name = "m" + mesh_dict->mName + boost::lexical_cast<std::string>(lod);
1214			// We pre-pended an m - need to capitalize first character for camelCase
1215			mesh_name[1] = toupper(mesh_name[1]);
1216			mesh->setName(mesh_name);
1217			mesh->setMeshID(mesh_index);
1218			mesh->setPickName(mesh_dict->mPickName);
1219			mesh->setIsTransparent(FALSE);
1220			switch((int)mesh_index)
1221			{
1222				case MESH_ID_HAIR:
1223					mesh->setIsTransparent(TRUE);
1224					break;
1225				case MESH_ID_SKIRT:
1226					mesh->setIsTransparent(TRUE);
1227					break;
1228				case MESH_ID_EYEBALL_LEFT:
1229				case MESH_ID_EYEBALL_RIGHT:
1230					mesh->setSpecular( LLColor4( 1.0f, 1.0f, 1.0f, 1.0f ), 1.f );
1231					break;
1232			}
1233			
1234			joint->mMeshParts.push_back(mesh);
1235		}
1236	}
1237	
1238	//-------------------------------------------------------------------------
1239	// associate baked textures with meshes
1240	//-------------------------------------------------------------------------
1241	for (LLVOAvatarDictionary::Meshes::const_iterator iter = LLVOAvatarDictionary::getInstance()->getMeshes().begin();
1242		 iter != LLVOAvatarDictionary::getInstance()->getMeshes().end();
1243		 ++iter)
1244	{
1245		const EMeshIndex mesh_index = iter->first;
1246		const LLVOAvatarDictionary::MeshEntry *mesh_dict = iter->second;
1247		const EBakedTextureIndex baked_texture_index = mesh_dict->mBakedID;
1248		// Skip it if there's no associated baked texture.
1249		if (baked_texture_index == BAKED_NUM_INDICES) continue;
1250		
1251		for (std::vector<LLViewerJointMesh* >::iterator iter = mMeshLOD[mesh_index]->mMeshParts.begin();
1252			 iter != mMeshLOD[mesh_index]->mMeshParts.end(); 
1253			 ++iter)
1254		{
1255			LLViewerJointMesh* mesh = (LLViewerJointMesh*) *iter;
1256			mBakedTextureDatas[(int)baked_texture_index].mMeshes.push_back(mesh);
1257		}
1258	}
1259	
1260	
1261	//-------------------------------------------------------------------------
1262	// register motions
1263	//-------------------------------------------------------------------------
1264	if (LLCharacter::sInstances.size() == 1)
1265	{
1266		LLKeyframeMotion::setVFS(gStaticVFS);
1267		registerMotion( ANIM_AGENT_BUSY,					LLNullMotion::create );
1268		registerMotion( ANIM_AGENT_CROUCH,					LLKeyframeStandMotion::create );
1269		registerMotion( ANIM_AGENT_CROUCHWALK,				LLKeyframeWalkMotion::create );
1270		registerMotion( ANIM_AGENT_EXPRESS_AFRAID,			LLEmote::create );
1271		registerMotion( ANIM_AGENT_EXPRESS_ANGER,			LLEmote::create );
1272		registerMotion( ANIM_AGENT_EXPRESS_BORED,			LLEmote::create );
1273		registerMotion( ANIM_AGENT_EXPRESS_CRY,				LLEmote::create );
1274		registerMotion( ANIM_AGENT_EXPRESS_DISDAIN,			LLEmote::create );
1275		registerMotion( ANIM_AGENT_EXPRESS_EMBARRASSED,		LLEmote::create );
1276		registerMotion( ANIM_AGENT_EXPRESS_FROWN,			LLEmote::create );
1277		registerMotion( ANIM_AGENT_EXPRESS_KISS,			LLEmote::create );
1278		registerMotion( ANIM_AGENT_EXPRESS_LAUGH,			LLEmote::create );
1279		registerMotion( ANIM_AGENT_EXPRESS_OPEN_MOUTH,		LLEmote::create );
1280		registerMotion( ANIM_AGENT_EXPRESS_REPULSED,		LLEmote::create );
1281		registerMotion( ANIM_AGENT_EXPRESS_SAD,				LLEmote::create );
1282		registerMotion( ANIM_AGENT_EXPRESS_SHRUG,			LLEmote::create );
1283		registerMotion( ANIM_AGENT_EXPRESS_SMILE,			LLEmote::create );
1284		registerMotion( ANIM_AGENT_EXPRESS_SURPRISE,		LLEmote::create );
1285		registerMotion( ANIM_AGENT_EXPRESS_TONGUE_OUT,		LLEmote::create );
1286		registerMotion( ANIM_AGENT_EXPRESS_TOOTHSMILE,		LLEmote::create );
1287		registerMotion( ANIM_AGENT_EXPRESS_WINK,			LLEmote::create );
1288		registerMotion( ANIM_AGENT_EXPRESS_WORRY,			LLEmote::create );
1289		registerMotion( ANIM_AGENT_FEMALE_RUN_NEW,			LLKeyframeWalkMotion::create );
1290		registerMotion( ANIM_AGENT_FEMALE_WALK,				LLKeyframeWalkMotion::create );
1291		registerMotion( ANIM_AGENT_FEMALE_WALK_NEW,			LLKeyframeWalkMotion::create );
1292		registerMotion( ANIM_AGENT_RUN,						LLKeyframeWalkMotion::create );
1293		registerMotion( ANIM_AGENT_RUN_NEW,					LLKeyframeWalkMotion::create );
1294		registerMotion( ANIM_AGENT_STAND,					LLKeyframeStandMotion::create );
1295		registerMotion( ANIM_AGENT_STAND_1,					LLKeyframeStandMotion::create );
1296		registerMotion( ANIM_AGENT_STAND_2,					LLKeyframeStandMotion::create );
1297		registerMotion( ANIM_AGENT_STAND_3,					LLKeyframeStandMotion::create );
1298		registerMotion( ANIM_AGENT_STAND_4,					LLKeyframeStandMotion::create );
1299		registerMotion( ANIM_AGENT_STANDUP,					LLKeyframeFallMotion::create );
1300		registerMotion( ANIM_AGENT_TURNLEFT,				LLKeyframeWalkMotion::create );
1301		registerMotion( ANIM_AGENT_TURNRIGHT,				LLKeyframeWalkMotion::create );
1302		registerMotion( ANIM_AGENT_WALK,					LLKeyframeWalkMotion::create );
1303		registerMotion( ANIM_AGENT_WALK_NEW,				LLKeyframeWalkMotion::create );
1304		
1305		// motions without a start/stop bit
1306		registerMotion( ANIM_AGENT_BODY_NOISE,				LLBodyNoiseMotion::create );
1307		registerMotion( ANIM_AGENT_BREATHE_ROT,				LLBreatheMotionRot::create );
1308		registerMotion( ANIM_AGENT_PHYSICS_MOTION,			LLPhysicsMotionController::create );
1309		registerMotion( ANIM_AGENT_EDITING,					LLEditingMotion::create	);
1310		registerMotion( ANIM_AGENT_EYE,						LLEyeMotion::create	);
1311		registerMotion( ANIM_AGENT_FEMALE_WALK,				LLKeyframeWalkMotion::create );
1312		registerMotion( ANIM_AGENT_FLY_ADJUST,				LLFlyAdjustMotion::create );
1313		registerMotion( ANIM_AGENT_HAND_MOTION,				LLHandMotion::create );
1314		registerMotion( ANIM_AGENT_HEAD_ROT,				LLHeadRotMotion::create );
1315		registerMotion( ANIM_AGENT_PELVIS_FIX,				LLPelvisFixMotion::create );
1316		registerMotion( ANIM_AGENT_SIT_FEMALE,				LLKeyframeMotion::create );
1317		registerMotion( ANIM_AGENT_TARGET,					LLTargetingMotion::create );
1318		registerMotion( ANIM_AGENT_WALK_ADJUST,				LLWalkAdjustMotion::create );
1319		
1320	}
1321	
1322	buildCharacter();
1323	
1324	// preload specific motions here
1325	createMotion( ANIM_AGENT_CUSTOMIZE);
1326	createMotion( ANIM_AGENT_CUSTOMIZE_DONE);
1327	
1328	//VTPause();  // VTune
1329	
1330	mVoiceVisualizer->setVoiceEnabled( LLVoiceClient::getInstance()->getVoiceEnabled( mID ) );
1331
1332}
1333
1334const LLVector3 LLVOAvatar::getRenderPosition() const
1335{
1336	if (mDrawable.isNull() || mDrawable->getGeneration() < 0)
1337	{
1338		return getPositionAgent();
1339	}
1340	else if (isRoot())
1341	{
1342		if ( !mHasPelvisOffset )
1343		{
1344			return mDrawable->getPositionAgent();
1345		}
1346		else
1347		{
1348			//Apply a pelvis fixup (as defined by the avs skin)
1349			LLVector3 pos = mDrawable->getPositionAgent();
1350			pos[VZ] += mPelvisFixup;
1351			return pos;
1352		}
1353	}
1354	else
1355	{
1356		return getPosition() * mDrawable->getParent()->getRenderMatrix();
1357	}
1358}
1359
1360void LLVOAvatar::updateDrawable(BOOL force_damped)
1361{
1362	clearChanged(SHIFTED);
1363}
1364
1365void LLVOAvatar::onShift(const LLVector4a& shift_vector)
1366{
1367	const LLVector3& shift = reinterpret_cast<const LLVector3&>(shift_vector);
1368	mLastAnimExtents[0] += shift;
1369	mLastAnimExtents[1] += shift;
1370	mNeedsImpostorUpdate = TRUE;
1371	mNeedsAnimUpdate = TRUE;
1372}
1373
1374void LLVOAvatar::updateSpatialExtents(LLVector4a& newMin, LLVector4a &newMax)
1375{
1376	if (isImpostor() && !needsImpostorUpdate())
1377	{
1378		LLVector3 delta = getRenderPosition() -
1379			((LLVector3(mDrawable->getPositionGroup().getF32ptr())-mImpostorOffset));
1380		
1381		newMin.load3( (mLastAnimExtents[0] + delta).mV);
1382		newMax.load3( (mLastAnimExtents[1] + delta).mV);
1383	}
1384	else
1385	{
1386		getSpatialExtents(newMin,newMax);
1387		mLastAnimExtents[0].set(newMin.getF32ptr());
1388		mLastAnimExtents[1].set(newMax.getF32ptr());
1389		LLVector4a pos_group;
1390		pos_group.setAdd(newMin,newMax);
1391		pos_group.mul(0.5f);
1392		mImpostorOffset = LLVector3(pos_group.getF32ptr())-getRenderPosition();
1393		mDrawable->setPositionGroup(pos_group);
1394	}
1395}
1396
1397void LLVOAvatar::getSpatialExtents(LLVector4a& newMin, LLVector4a& newMax)
1398{
1399	LLVector4a buffer(0.25f);
1400	LLVector4a pos;
1401	pos.load3(getRenderPosition().mV);
1402	newMin.setSub(pos, buffer);
1403	newMax.setAdd(pos, buffer);
1404
1405	float max_attachment_span = get_default_max_prim_scale() * 5.0f;
1406	
1407	//stretch bounding box by joint positions
1408	for (polymesh_map_t::iterator i = mMeshes.begin(); i != mMeshes.end(); ++i)
1409	{
1410		LLPolyMesh* mesh = i->second;
1411		for (S32 joint_num = 0; joint_num < mesh->mJointRenderData.count(); joint_num++)
1412		{
1413			LLVector4a trans;
1414			trans.load3( mesh->mJointRenderData[joint_num]->mWorldMatrix->getTranslation().mV);
1415			update_min_max(newMin, newMax, trans);
1416		}
1417	}
1418
1419	LLVector4a center, size;
1420	center.setAdd(newMin, newMax);
1421	center.mul(0.5f);
1422
1423	size.setSub(newMax,newMin);
1424	size.mul(0.5f);
1425
1426	mPixelArea = LLPipeline::calcPixelArea(center, size, *LLViewerCamera::getInstance());
1427
1428	//stretch bounding box by attachments
1429	for (attachment_map_t::iterator iter = mAttachmentPoints.begin(); 
1430		 iter != mAttachmentPoints.end();
1431		 ++iter)
1432	{
1433		LLViewerJointAttachment* attachment = iter->second;
1434
1435		if (!attachment->getValid())
1436		{
1437			continue ;
1438		}
1439
1440		for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
1441			 attachment_iter != attachment->mAttachedObjects.end();
1442			 ++attachment_iter)
1443		{
1444			const LLViewerObject* attached_object = (*attachment_iter);
1445			if (attached_object && !attached_object->isHUDAttachment())
1446			{
1447				LLDrawable* drawable = attached_object->mDrawable;
1448				if (drawable && !drawable->isState(LLDrawable::RIGGED))
1449				{
1450					LLSpatialBridge* bridge = drawable->getSpatialBridge();
1451					if (bridge)
1452					{
1453						const LLVector4a* ext = bridge->getSpatialExtents();
1454						LLVector4a distance;
1455						distance.setSub(ext[1], ext[0]);
1456						LLVector4a max_span(max_attachment_span);
1457
1458						S32 lt = distance.lessThan(max_span).getGatheredBits() & 0x7;
1459						
1460						// Only add the prim to spatial extents calculations if it isn't a megaprim.
1461						// max_attachment_span calculated at the start of the function 
1462						// (currently 5 times our max prim size) 
1463						if (lt == 0x7)
1464						{
1465							update_min_max(newMin,newMax,ext[0]);
1466							update_min_max(newMin,newMax,ext[1]);
1467						}
1468					}
1469				}
1470			}
1471		}
1472	}
1473
1474	//pad bounding box	
1475
1476	newMin.sub(buffer);
1477	newMax.add(buffer);
1478}
1479
1480//-----------------------------------------------------------------------------
1481// renderCollisionVolumes()
1482//-----------------------------------------------------------------------------
1483void LLVOAvatar::renderCollisionVolumes()
1484{
1485	for (S32 i = 0; i < mNumCollisionVolumes; i++)
1486	{
1487		mCollisionVolumes[i].renderCollision();
1488	}
1489
1490	if (mNameText.notNull())
1491	{
1492		LLVector3 unused;
1493		mNameText->lineSegmentIntersect(LLVector3(0,0,0), LLVector3(0,0,1), unused, TRUE);
1494	}
1495}
1496
1497BOOL LLVOAvatar::lineSegmentIntersect(const LLVector3& start, const LLVector3& end,
1498									  S32 face,
1499									  BOOL pick_transparent,
1500									  S32* face_hit,
1501									  LLVector3* intersection,
1502									  LLVector2* tex_coord,
1503									  LLVector3* normal,
1504									  LLVector3* bi_normal)
1505{
1506	if ((isSelf() && !gAgent.needsRenderAvatar()) || !LLPipeline::sPickAvatar)
1507	{
1508		return FALSE;
1509	}
1510
1511	if (lineSegmentBoundingBox(start, end))
1512	{
1513		for (S32 i = 0; i < mNumCollisionVolumes; ++i)
1514		{
1515			mCollisionVolumes[i].updateWorldMatrix();
1516
1517			glh::matrix4f mat((F32*) mCollisionVolumes[i].getXform()->getWorldMatrix().mMatrix);
1518			glh::matrix4f inverse = mat.inverse();
1519			glh::matrix4f norm_mat = inverse.transpose();
1520
1521			glh::vec3f p1(start.mV);
1522			glh::vec3f p2(end.mV);
1523
1524			inverse.mult_matrix_vec(p1);
1525			inverse.mult_matrix_vec(p2);
1526
1527			LLVector3 position;
1528			LLVector3 norm;
1529
1530			if (linesegment_sphere(LLVector3(p1.v), LLVector3(p2.v), LLVector3(0,0,0), 1.f, position, norm))
1531			{
1532				glh::vec3f res_pos(position.mV);
1533				mat.mult_matrix_vec(res_pos);
1534				
1535				norm.normalize();
1536				glh::vec3f res_norm(norm.mV);
1537				norm_mat.mult_matrix_dir(res_norm);
1538
1539				if (intersection)
1540				{
1541					*intersection = LLVector3(res_pos.v);
1542				}
1543
1544				if (normal)
1545				{
1546					*normal = LLVector3(res_norm.v);
1547				}
1548
1549				return TRUE;
1550			}
1551		}
1552
1553		if (isSelf())
1554		{
1555			for (attachment_map_t::iterator iter = mAttachmentPoints.begin(); 
1556			 iter != mAttachmentPoints.end();
1557			 ++iter)
1558			{
1559				LLViewerJointAttachment* attachment = iter->second;
1560
1561				for (LLViewerJointAttachment::attachedobjs_vec_t::iterator attachment_iter = attachment->mAttachedObjects.begin();
1562					 attachment_iter != attachment->mAttachedObjects.end();
1563					 ++attachment_iter)
1564				{
1565					LLViewerObject* attached_object = (*attachment_iter);
1566					
1567					if (attached_object && !attached_object->isDead() && attachment->getValid())
1568					{
1569						LLDrawable* drawable = attached_object->mDrawable;
1570						if (drawable->isState(LLDrawable::RIGGED))
1571						{ //regenerate octree for rigged attachment
1572							gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_RIGGED, TRUE);
1573						}
1574					}
1575				}
1576			}
1577		}
1578	}
1579
1580	
1581	
1582	LLVector3 position;
1583	if (mNameText.notNull() && mNameText->lineSegmentIntersect(start, end, position))
1584	{
1585		if (intersection)
1586		{
1587			*intersection = position;
1588		}
1589
1590		return TRUE;
1591	}
1592
1593	return FALSE;
1594}
1595
1596LLViewerObject* LLVOAvatar::lineSegmentIntersectRiggedAttachments(const LLVector3& start, const LLVec

Large files files are truncated, but you can click here to view the full file