player.cpp 237 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include "platform/platform.h"
#include "T3D/player.h"

#include "platform/profiler.h"
#include "math/mMath.h"
#include "math/mathIO.h"
#include "core/resourceManager.h"
#include "core/stringTable.h"
#include "core/volume.h"
#include "core/stream/bitStream.h"
#include "console/consoleTypes.h"
#include "console/engineAPI.h"
#include "collision/extrudedPolyList.h"
#include "collision/clippedPolyList.h"
#include "collision/earlyOutPolyList.h"
#include "ts/tsShapeInstance.h"
#include "sfx/sfxSystem.h"
#include "sfx/sfxTrack.h"
#include "sfx/sfxSource.h"
#include "sfx/sfxTypes.h"
#include "scene/sceneManager.h"
#include "scene/sceneRenderState.h"
#include "T3D/gameBase/gameConnection.h"
#include "T3D/trigger.h"
#include "T3D/physicalZone.h"
#include "T3D/item.h"
#include "T3D/missionArea.h"
#include "T3D/fx/particleEmitter.h"
#include "T3D/fx/cameraFXMgr.h"
#include "T3D/fx/splash.h"
#include "T3D/tsStatic.h"
#include "T3D/physics/physicsPlugin.h"
#include "T3D/physics/physicsPlayer.h"
#include "T3D/decal/decalManager.h"
#include "T3D/decal/decalData.h"
#include "materials/baseMatInstance.h"

60 61 62 63
#ifdef TORQUE_EXTENDED_MOVE
   #include "T3D/gameBase/extended/extendedMove.h"
#endif

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
// Amount of time if takes to transition to a new action sequence.
static F32 sAnimationTransitionTime = 0.25f;
static bool sUseAnimationTransitions = true;
static F32 sLandReverseScale = 0.25f;
static F32 sSlowStandThreshSquared = 1.69f;
static S32 sRenderMyPlayer = true;
static S32 sRenderMyItems = true;
static bool sRenderPlayerCollision = false;

// Chooses new action animations every n ticks.
static const F32 sNewAnimationTickTime = 4.0f;
static const F32 sMountPendingTickWait = 13.0f * F32(TickMs);

// Number of ticks before we pick non-contact animations
static const S32 sContactTickTime = 10;

// Movement constants
static F32 sVerticalStepDot = 0.173f;   // 80
static F32 sMinFaceDistance = 0.01f;
static F32 sTractionDistance = 0.04f;
static F32 sNormalElasticity = 0.01f;
static U32 sMoveRetryCount = 5;
static F32 sMaxImpulseVelocity = 200.0f;

// Move triggers
static S32 sJumpTrigger = 2;
static S32 sCrouchTrigger = 3;
static S32 sProneTrigger = 4;
static S32 sSprintTrigger = 5;
static S32 sImageTrigger0 = 0;
static S32 sImageTrigger1 = 1;
static S32 sJumpJetTrigger = 1;
static S32 sVehicleDismountTrigger = 2;

// Client prediction
static F32 sMinWarpTicks = 0.5f;       // Fraction of tick at which instant warp occurs
static S32 sMaxWarpTicks = 3;          // Max warp duration in ticks
static S32 sMaxPredictionTicks = 30;   // Number of ticks to predict

103 104
S32 Player::smExtendedMoveHeadPosRotIndex = 0;  // The ExtendedMove position/rotation index used for head movements

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
// Anchor point compression
const F32 sAnchorMaxDistance = 32.0f;

//
static U32 sCollisionMoveMask =  TerrainObjectType       |
                                 WaterObjectType         | 
                                 PlayerObjectType        |
                                 StaticShapeObjectType   | 
                                 VehicleObjectType       |
                                 PhysicalZoneObjectType;

static U32 sServerCollisionContactMask = sCollisionMoveMask |
                                         ItemObjectType     |
                                         TriggerObjectType  |
                                         CorpseObjectType;

static U32 sClientCollisionContactMask = sCollisionMoveMask |
                                         TriggerObjectType;

enum PlayerConstants {
   JumpSkipContactsMax = 8
};

//----------------------------------------------------------------------------
// Player shape animation sequences:

// Action Animations:
PlayerData::ActionAnimationDef PlayerData::ActionAnimationList[NumTableActionAnims] =
{
   // *** WARNING ***
   // This array is indexed using the enum values defined in player.h

   // Root is the default animation
   { "root" },       // RootAnim,

   // These are selected in the move state based on velocity
   { "run",          { 0.0f, 1.0f, 0.0f } },       // RunForwardAnim,
   { "back",         { 0.0f,-1.0f, 0.0f } },       // BackBackwardAnim
   { "side",         {-1.0f, 0.0f, 0.0f } },       // SideLeftAnim,
   { "side_right",   { 1.0f, 0.0f, 0.0f } },       // SideRightAnim,

   { "sprint_root" },
   { "sprint_forward",  { 0.0f, 1.0f, 0.0f } },
   { "sprint_backward", { 0.0f,-1.0f, 0.0f } },
   { "sprint_side",     {-1.0f, 0.0f, 0.0f } },
   { "sprint_right",    { 1.0f, 0.0f, 0.0f } },

   { "crouch_root" },
   { "crouch_forward",  { 0.0f, 1.0f, 0.0f } },
   { "crouch_backward", { 0.0f,-1.0f, 0.0f } },
   { "crouch_side",     {-1.0f, 0.0f, 0.0f } },
   { "crouch_right",    { 1.0f, 0.0f, 0.0f } },

   { "prone_root" },
   { "prone_forward",   { 0.0f, 1.0f, 0.0f } },
   { "prone_backward",  { 0.0f,-1.0f, 0.0f } },

   { "swim_root" },
   { "swim_forward",    { 0.0f, 1.0f, 0.0f } },
   { "swim_backward",   { 0.0f,-1.0f, 0.0f }  },
   { "swim_left",       {-1.0f, 0.0f, 0.0f }  },
   { "swim_right",      { 1.0f, 0.0f, 0.0f }  },

   // These are set explicitly based on player actions
   { "fall" },       // FallAnim
   { "jump" },       // JumpAnim
   { "standjump" },  // StandJumpAnim
   { "land" },       // LandAnim
   { "jet" },        // JetAnim
};


//----------------------------------------------------------------------------
//----------------------------------------------------------------------------

//----------------------------------------------------------------------------

IMPLEMENT_CO_DATABLOCK_V1(PlayerData);

ConsoleDocClass( PlayerData,
   "@brief Defines properties for a Player object.\n\n"
   "@see Player\n"
   "@ingroup gameObjects\n"
);

IMPLEMENT_CALLBACK( PlayerData, onPoseChange, void, ( Player* obj, const char* oldPose, const char* newPose ), ( obj, oldPose, newPose ),
   "@brief Called when the player changes poses.\n\n"
   "@param obj The Player object\n"
   "@param oldPose The pose the player is switching from.\n"
   "@param newPose The pose the player is switching to.\n");

IMPLEMENT_CALLBACK( PlayerData, onStartSwim, void, ( Player* obj ), ( obj ),
   "@brief Called when the player starts swimming.\n\n"
   "@param obj The Player object\n" );

IMPLEMENT_CALLBACK( PlayerData, onStopSwim, void, ( Player* obj ), ( obj ),
   "@brief Called when the player stops swimming.\n\n"
   "@param obj The Player object\n" );

IMPLEMENT_CALLBACK( PlayerData, onStartSprintMotion, void, ( Player* obj ), ( obj ),
   "@brief Called when the player starts moving while in a Sprint pose.\n\n"
   "@param obj The Player object\n" );

IMPLEMENT_CALLBACK( PlayerData, onStopSprintMotion, void, ( Player* obj ), ( obj ),
   "@brief Called when the player stops moving while in a Sprint pose.\n\n"
   "@param obj The Player object\n" );

IMPLEMENT_CALLBACK( PlayerData, doDismount, void, ( Player* obj ), ( obj ),
   "@brief Called when attempting to dismount the player from a vehicle.\n\n"
   "It is up to the doDismount() method to actually perform the dismount.  Often "
   "there are some conditions that prevent this, such as the vehicle moving too fast.\n"
   "@param obj The Player object\n" );

IMPLEMENT_CALLBACK( PlayerData, onEnterLiquid, void, ( Player* obj, F32 coverage, const char* type ), ( obj, coverage, type ),
   "@brief Called when the player enters a liquid.\n\n"
   "@param obj The Player object\n"
   "@param coverage Percentage of the player's bounding box covered by the liquid\n"
   "@param type The type of liquid the player has entered\n" );

IMPLEMENT_CALLBACK( PlayerData, onLeaveLiquid, void, ( Player* obj, const char* type ), ( obj, type ),
   "@brief Called when the player leaves a liquid.\n\n"
   "@param obj The Player object\n"
   "@param type The type of liquid the player has left\n" );

IMPLEMENT_CALLBACK( PlayerData, animationDone, void, ( Player* obj ), ( obj ),
   "@brief Called on the server when a scripted animation completes.\n\n"
   "@param obj The Player object\n"
   "@see Player::setActionThread() for setting a scripted animation and its 'hold' parameter to "
   "determine if this callback is used.\n" );

IMPLEMENT_CALLBACK( PlayerData, onEnterMissionArea, void, ( Player* obj ), ( obj ),
   "@brief Called when the player enters the mission area.\n\n"
   "@param obj The Player object\n"
   "@see MissionArea\n" );

IMPLEMENT_CALLBACK( PlayerData, onLeaveMissionArea, void, ( Player* obj ), ( obj ),
   "@brief Called when the player leaves the mission area.\n"
   "@param obj The Player object\n"
   "@see MissionArea\n" );

PlayerData::PlayerData()
{
   shadowEnable = true;
   shadowSize = 256;
   shadowProjectionDistance = 14.0f;

   renderFirstPerson = true;
252
   firstPersonShadows = false;
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588

   // Used for third person image rendering
   imageAnimPrefix = StringTable->insert("");

   allowImageStateAnimation = false;

   // Used for first person image rendering
   imageAnimPrefixFP = StringTable->insert("");
   for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
   {
      shapeNameFP[i] = StringTable->insert("");
      mCRCFP[i] = 0;
      mValidShapeFP[i] = false;
   }

   pickupRadius = 0.0f;
   minLookAngle = -1.4f;
   maxLookAngle = 1.4f;
   maxFreelookAngle = 3.0f;
   maxTimeScale = 1.5f;

   mass = 9.0f;         // from ShapeBase
   maxEnergy = 60.0f;   // from ShapeBase
   drag = 0.3f;         // from ShapeBase
   density = 1.1f;      // from ShapeBase

   maxStepHeight = 1.0f;
   runSurfaceAngle = 80.0f;

   fallingSpeedThreshold = -10.0f;

   recoverDelay = 30;
   recoverRunForceScale = 1.0f;
   landSequenceTime = 0.0f;
   transitionToLand = false;

   // Running/Walking
   runForce = 40.0f * 9.0f;
   runEnergyDrain = 0.0f;
   minRunEnergy = 0.0f;
   maxForwardSpeed = 10.0f;
   maxBackwardSpeed = 10.0f;
   maxSideSpeed = 10.0f;

   // Jumping
   jumpForce = 75.0f;
   jumpEnergyDrain = 0.0f;
   minJumpEnergy = 0.0f;
   jumpSurfaceAngle = 78.0f;
   jumpDelay = 30;
   minJumpSpeed = 500.0f;
   maxJumpSpeed = 2.0f * minJumpSpeed;

   // Sprinting
   sprintForce = 50.0f * 9.0f;
   sprintEnergyDrain = 0.0f;
   minSprintEnergy = 0.0f;
   maxSprintForwardSpeed = 15.0f;
   maxSprintBackwardSpeed = 10.0f;
   maxSprintSideSpeed = 10.0f;
   sprintStrafeScale = 1.0f;
   sprintYawScale = 1.0f;
   sprintPitchScale = 1.0f;
   sprintCanJump = true;

   // Swimming
   swimForce = 55.0f * 9.0f;  
   maxUnderwaterForwardSpeed = 6.0f;
   maxUnderwaterBackwardSpeed = 6.0f;
   maxUnderwaterSideSpeed = 6.0f;

   // Crouching
   crouchForce = 45.0f * 9.0f;
   maxCrouchForwardSpeed = 4.0f;
   maxCrouchBackwardSpeed = 4.0f;
   maxCrouchSideSpeed = 4.0f;    

   // Prone
   proneForce = 45.0f * 9.0f;            
   maxProneForwardSpeed = 2.0f;  
   maxProneBackwardSpeed = 2.0f; 
   maxProneSideSpeed = 0.0f;     

   // Jetting
   jetJumpForce = 0;
   jetJumpEnergyDrain = 0;
   jetMinJumpEnergy = 0;
   jetJumpSurfaceAngle = 78;
   jetMinJumpSpeed = 20;
   jetMaxJumpSpeed = 100;

   horizMaxSpeed = 80.0f;
   horizResistSpeed = 38.0f;
   horizResistFactor = 1.0f;

   upMaxSpeed = 80.0f;
   upResistSpeed = 38.0f;
   upResistFactor = 1.0f;

   minImpactSpeed = 25.0f;
   minLateralImpactSpeed = 25.0f;

   decalData      = NULL;
   decalID        = 0;
   decalOffset      = 0.0f;

   lookAction = 0;

   // size of bounding box
   boxSize.set(1.0f, 1.0f, 2.3f);
   crouchBoxSize.set(1.0f, 1.0f, 2.0f);
   proneBoxSize.set(1.0f, 2.3f, 1.0f);
   swimBoxSize.set(1.0f, 2.3f, 1.0f);

   // location of head, torso, legs
   boxHeadPercentage = 0.85f;
   boxTorsoPercentage = 0.55f;

   // damage locations
   boxHeadLeftPercentage  = 0;
   boxHeadRightPercentage = 1;
   boxHeadBackPercentage  = 0;
   boxHeadFrontPercentage = 1;

   for (S32 i = 0; i < MaxSounds; i++)
      sound[i] = NULL;

   footPuffEmitter = NULL;
   footPuffID = 0;
   footPuffNumParts = 15;
   footPuffRadius = .25f;

   dustEmitter = NULL;
   dustID = 0;

   splash = NULL;
   splashId = 0;
   splashVelocity = 1.0f;
   splashAngle = 45.0f;
   splashFreqMod = 300.0f;
   splashVelEpsilon = 0.25f;
   bubbleEmitTime = 0.4f;

   medSplashSoundVel = 2.0f;
   hardSplashSoundVel = 3.0f;
   exitSplashSoundVel = 2.0f;
   footSplashHeight = 0.1f;

   dMemset( splashEmitterList, 0, sizeof( splashEmitterList ) );
   dMemset( splashEmitterIDList, 0, sizeof( splashEmitterIDList ) );

   groundImpactMinSpeed = 10.0f;
   groundImpactShakeFreq.set( 10.0f, 10.0f, 10.0f );
   groundImpactShakeAmp.set( 20.0f, 20.0f, 20.0f );
   groundImpactShakeDuration = 1.0f;
   groundImpactShakeFalloff = 10.0f;

   // Air control
   airControl = 0.0f;

   jumpTowardsNormal = true;

   physicsPlayerType = StringTable->insert("");

   dMemset( actionList, 0, sizeof(actionList) );
}

bool PlayerData::preload(bool server, String &errorStr)
{
   if(!Parent::preload(server, errorStr))
      return false;

   // Resolve objects transmitted from server
   if( !server )
   {
      for( U32 i = 0; i < MaxSounds; ++ i )
      {
         String errorStr;
         if( !sfxResolve( &sound[ i ], errorStr ) )
            Con::errorf( "PlayerData::preload: %s", errorStr.c_str() );
      }
   }

   //
   runSurfaceCos = mCos(mDegToRad(runSurfaceAngle));
   jumpSurfaceCos = mCos(mDegToRad(jumpSurfaceAngle));
   if (minJumpEnergy < jumpEnergyDrain)
      minJumpEnergy = jumpEnergyDrain;   

   // Jetting
   if (jetMinJumpEnergy < jetJumpEnergyDrain)
      jetMinJumpEnergy = jetJumpEnergyDrain;

   // Validate some of the data
   if (fallingSpeedThreshold > 0.0f)
      Con::printf("PlayerData:: Falling speed threshold should be downwards (negative)");

   if (recoverDelay > (1 << RecoverDelayBits) - 1) {
      recoverDelay = (1 << RecoverDelayBits) - 1;
      Con::printf("PlayerData:: Recover delay exceeds range (0-%d)",recoverDelay);
   }
   if (jumpDelay > (1 << JumpDelayBits) - 1) {
      jumpDelay = (1 << JumpDelayBits) - 1;
      Con::printf("PlayerData:: Jump delay exceeds range (0-%d)",jumpDelay);
   }

   // If we don't have a shape don't crash out trying to
   // setup animations and sequences.
   if ( mShape )
   {
      // Go ahead a pre-load the player shape
      TSShapeInstance* si = new TSShapeInstance(mShape, false);
      TSThread* thread = si->addThread();

      // Extract ground transform velocity from animations
      // Get the named ones first so they can be indexed directly.
      ActionAnimation *dp = &actionList[0];
      for (int i = 0; i < NumTableActionAnims; i++,dp++)
      {
         ActionAnimationDef *sp = &ActionAnimationList[i];
         dp->name          = sp->name;
         dp->dir.set(sp->dir.x,sp->dir.y,sp->dir.z);
         dp->sequence      = mShape->findSequence(sp->name);

         // If this is a sprint action and is missing a sequence, attempt to use
         // the standard run ones.
         if(dp->sequence == -1 && i >= SprintRootAnim && i <= SprintRightAnim)
         {
            S32 offset = i-SprintRootAnim;
            ActionAnimationDef *standDef = &ActionAnimationList[RootAnim+offset];
            dp->sequence = mShape->findSequence(standDef->name);
         }

         dp->velocityScale = true;
         dp->death         = false;
         if (dp->sequence != -1)
            getGroundInfo(si,thread,dp);

         // No real reason to spam the console about a missing jet animation
         if (dStricmp(sp->name, "jet") != 0)
            AssertWarn(dp->sequence != -1, avar("PlayerData::preload - Unable to find named animation sequence '%s'!", sp->name));
      }
      for (int b = 0; b < mShape->sequences.size(); b++)
      {
         if (!isTableSequence(b))
         {
            dp->sequence      = b;
            dp->name          = mShape->getName(mShape->sequences[b].nameIndex);
            dp->velocityScale = false;
            getGroundInfo(si,thread,dp++);
         }
      }
      actionCount = dp - actionList;
      AssertFatal(actionCount <= NumActionAnims, "Too many action animations!");
      delete si;

      // Resolve lookAction index
      dp = &actionList[0];
      String lookName("look");
      for (int c = 0; c < actionCount; c++,dp++)
         if( dStricmp( dp->name, lookName ) == 0 )
            lookAction = c;

      // Resolve spine
      spineNode[0] = mShape->findNode("Bip01 Pelvis");
      spineNode[1] = mShape->findNode("Bip01 Spine");
      spineNode[2] = mShape->findNode("Bip01 Spine1");
      spineNode[3] = mShape->findNode("Bip01 Spine2");
      spineNode[4] = mShape->findNode("Bip01 Neck");
      spineNode[5] = mShape->findNode("Bip01 Head");

      // Recoil animations
      recoilSequence[0] = mShape->findSequence("light_recoil");
      recoilSequence[1] = mShape->findSequence("medium_recoil");
      recoilSequence[2] = mShape->findSequence("heavy_recoil");
   }

   // Convert pickupRadius to a delta of boundingBox
   //
   // NOTE: it is not really correct to precalculate a pickupRadius based 
   // on boxSize since the actual player's bounds can vary by "pose".
   //
   F32 dr = (boxSize.x > boxSize.y)? boxSize.x: boxSize.y;
   if (pickupRadius < dr)
      pickupRadius = dr;
   else
      if (pickupRadius > 2.0f * dr)
         pickupRadius = 2.0f * dr;
   pickupDelta = (S32)(pickupRadius - dr);

   // Validate jump speed
   if (maxJumpSpeed <= minJumpSpeed)
      maxJumpSpeed = minJumpSpeed + 0.1f;

   // Load up all the emitters
   if (!footPuffEmitter && footPuffID != 0)
      if (!Sim::findObject(footPuffID, footPuffEmitter))
         Con::errorf(ConsoleLogEntry::General, "PlayerData::preload - Invalid packet, bad datablockId(footPuffEmitter): 0x%x", footPuffID);

   if (!decalData && decalID != 0 )
      if (!Sim::findObject(decalID, decalData))
         Con::errorf(ConsoleLogEntry::General, "PlayerData::preload Invalid packet, bad datablockId(decalData): 0x%x", decalID);

   if (!dustEmitter && dustID != 0 )
      if (!Sim::findObject(dustID, dustEmitter))
         Con::errorf(ConsoleLogEntry::General, "PlayerData::preload - Invalid packet, bad datablockId(dustEmitter): 0x%x", dustID);

   for (int i=0; i<NUM_SPLASH_EMITTERS; i++)
      if( !splashEmitterList[i] && splashEmitterIDList[i] != 0 )
         if( Sim::findObject( splashEmitterIDList[i], splashEmitterList[i] ) == false)
            Con::errorf(ConsoleLogEntry::General, "PlayerData::onAdd - Invalid packet, bad datablockId(particle emitter): 0x%x", splashEmitterIDList[i]);

   // First person mounted image shapes.
   for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
   {
      bool shapeError = false;

      if (shapeNameFP[i] && shapeNameFP[i][0])
      {
         mShapeFP[i] = ResourceManager::get().load(shapeNameFP[i]);
         if (bool(mShapeFP[i]) == false)
         {
            errorStr = String::ToString("PlayerData: Couldn't load mounted image %d shape \"%s\"",i,shapeNameFP[i]);
            return false;
         }

         if(!server && !mShapeFP[i]->preloadMaterialList(mShapeFP[i].getPath()) && NetConnection::filesWereDownloaded())
            shapeError = true;

         if(computeCRC)
         {
            Con::printf("Validation required for mounted image %d shape: %s", i, shapeNameFP[i]);

            Torque::FS::FileNodeRef    fileRef = Torque::FS::GetFileNode(mShapeFP[i].getPath());

            if (!fileRef)
589 590
            {
               errorStr = String::ToString("PlayerData: Mounted image %d loading failed, shape \"%s\" is not found.",i,mShapeFP[i].getPath());
591
               return false;
592
            }
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682

            if(server)
               mCRCFP[i] = fileRef->getChecksum();
            else if(mCRCFP[i] != fileRef->getChecksum())
            {
               errorStr = String::ToString("PlayerData: Mounted image %d shape \"%s\" does not match version on server.",i,shapeNameFP[i]);
               return false;
            }
         }

         mValidShapeFP[i] = true;
      }
   }

   return true;
}

void PlayerData::getGroundInfo(TSShapeInstance* si, TSThread* thread,ActionAnimation *dp)
{
   dp->death = !dStrnicmp(dp->name, "death", 5);
   if (dp->death)
   {
      // Death animations use roll frame-to-frame changes in ground transform into position
      dp->speed = 0.0f;
      dp->dir.set(0.0f, 0.0f, 0.0f);

      // Death animations MUST define ground transforms, so add dummy ones if required
      if (si->getShape()->sequences[dp->sequence].numGroundFrames == 0)
         si->getShape()->setSequenceGroundSpeed(dp->name, Point3F(0, 0, 0), Point3F(0, 0, 0));
   }
   else
   {
      VectorF save = dp->dir;
      si->setSequence(thread,dp->sequence,0);
      si->animate();
      si->advanceTime(1);
      si->animateGround();
      si->getGroundTransform().getColumn(3,&dp->dir);
      if ((dp->speed = dp->dir.len()) < 0.01f)
      {
         // No ground displacement... In this case we'll use the
         // default table entry, if there is one.
         if (save.len() > 0.01f)
         {
            dp->dir = save;
            dp->speed = 1.0f;
            dp->velocityScale = false;
         }
         else
            dp->speed = 0.0f;
      }
      else
         dp->dir *= 1.0f / dp->speed;
   }
}

bool PlayerData::isTableSequence(S32 seq)
{
   // The sequences from the table must already have
   // been loaded for this to work.
   for (int i = 0; i < NumTableActionAnims; i++)
      if (actionList[i].sequence == seq)
         return true;
   return false;
}

bool PlayerData::isJumpAction(U32 action)
{
   return (action == JumpAnim || action == StandJumpAnim);
}

void PlayerData::initPersistFields()
{
   addField( "pickupRadius", TypeF32, Offset(pickupRadius, PlayerData),
      "@brief Radius around the player to collide with Items in the scene (on server).\n\n"
      "Internally the pickupRadius is added to the larger side of the initial bounding box "
      "to determine the actual distance, to a maximum of 2 times the bounding box size.  The "
      "initial bounding box is that used for the root pose, and therefore doesn't take into "
      "account the change in pose.\n");
   addField( "maxTimeScale", TypeF32, Offset(maxTimeScale, PlayerData),
      "@brief Maximum time scale for action animations.\n\n"
      "If an action animation has a defined ground frame, it is automatically scaled to match the "
      "player's ground velocity.  This field limits the maximum time scale used even if "
      "the player's velocity exceeds it." );

   addGroup( "Camera" );

      addField( "renderFirstPerson", TypeBool, Offset(renderFirstPerson, PlayerData),
         "@brief Flag controlling whether to render the player shape in first person view.\n\n" );

683 684 685
      addField( "firstPersonShadows", TypeBool, Offset(firstPersonShadows, PlayerData),
         "@brief Forces shadows to be rendered in first person when renderFirstPerson is disabled.  Defaults to false.\n\n" );

686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
      addField( "minLookAngle", TypeF32, Offset(minLookAngle, PlayerData),
         "@brief Lowest angle (in radians) the player can look.\n\n"
         "@note An angle of zero is straight ahead, with positive up and negative down." );
      addField( "maxLookAngle", TypeF32, Offset(maxLookAngle, PlayerData),
         "@brief Highest angle (in radians) the player can look.\n\n"
         "@note An angle of zero is straight ahead, with positive up and negative down." );
      addField( "maxFreelookAngle", TypeF32, Offset(maxFreelookAngle, PlayerData),
         "@brief Defines the maximum left and right angles (in radians) the player can "
         "look in freelook mode.\n\n" );

   endGroup( "Camera" );

   addGroup( "Movement" );

      addField( "maxStepHeight", TypeF32, Offset(maxStepHeight, PlayerData),
         "@brief Maximum height the player can step up.\n\n"
         "The player will automatically step onto changes in ground height less "
         "than maxStepHeight.  The player will collide with ground height changes "
         "greater than this." );

      addField( "runForce", TypeF32, Offset(runForce, PlayerData),
         "@brief Force used to accelerate the player when running.\n\n" );

      addField( "runEnergyDrain", TypeF32, Offset(runEnergyDrain, PlayerData),
         "@brief Energy value drained each tick that the player is moving.\n\n"
         "The player will not be able to move when his energy falls below "
         "minRunEnergy.\n"
         "@note Setting this to zero will disable any energy drain.\n"
         "@see minRunEnergy\n");
      addField( "minRunEnergy", TypeF32, Offset(minRunEnergy, PlayerData),
         "@brief Minimum energy level required to run or swim.\n\n"
         "@see runEnergyDrain\n");

      addField( "maxForwardSpeed", TypeF32, Offset(maxForwardSpeed, PlayerData),
         "@brief Maximum forward speed when running." );
      addField( "maxBackwardSpeed", TypeF32, Offset(maxBackwardSpeed, PlayerData),
         "@brief Maximum backward speed when running." );
      addField( "maxSideSpeed", TypeF32, Offset(maxSideSpeed, PlayerData),
         "@brief Maximum sideways speed when running." );

      addField( "runSurfaceAngle", TypeF32, Offset(runSurfaceAngle, PlayerData),
         "@brief Maximum angle from vertical (in degrees) the player can run up.\n\n" );

      addField( "minImpactSpeed", TypeF32, Offset(minImpactSpeed, PlayerData),
         "@brief Minimum impact speed to apply falling damage.\n\n"
         "This field also sets the minimum speed for the onImpact callback "
         "to be invoked.\n"
         "@see ShapeBaseData::onImpact()\n");
      addField( "minLateralImpactSpeed", TypeF32, Offset(minLateralImpactSpeed, PlayerData),
         "@brief Minimum impact speed to apply non-falling damage.\n\n"
         "This field also sets the minimum speed for the onLateralImpact callback "
         "to be invoked.\n"
         "@see ShapeBaseData::onLateralImpact()\n");

      addField( "horizMaxSpeed", TypeF32, Offset(horizMaxSpeed, PlayerData),
         "@brief Maximum horizontal speed.\n\n"
         "@note This limit is only enforced if the player's horizontal speed "
         "exceeds horizResistSpeed.\n"
         "@see horizResistSpeed\n"
         "@see horizResistFactor\n" );
      addField( "horizResistSpeed", TypeF32, Offset(horizResistSpeed, PlayerData),
         "@brief Horizontal speed at which resistence will take place.\n\n"
         "@see horizMaxSpeed\n"
         "@see horizResistFactor\n" );
      addField( "horizResistFactor", TypeF32, Offset(horizResistFactor, PlayerData),
         "@brief Factor of resistence once horizResistSpeed has been reached.\n\n"
         "@see horizMaxSpeed\n"
         "@see horizResistSpeed\n" );

      addField( "upMaxSpeed", TypeF32, Offset(upMaxSpeed, PlayerData),
         "@brief Maximum upwards speed.\n\n"
         "@note This limit is only enforced if the player's upward speed exceeds "
         "upResistSpeed.\n"
         "@see upResistSpeed\n"
         "@see upResistFactor\n" );
      addField( "upResistSpeed", TypeF32, Offset(upResistSpeed, PlayerData),
         "@brief Upwards speed at which resistence will take place.\n\n"
         "@see upMaxSpeed\n"
         "@see upResistFactor\n" );
      addField( "upResistFactor", TypeF32, Offset(upResistFactor, PlayerData),
         "@brief Factor of resistence once upResistSpeed has been reached.\n\n"
         "@see upMaxSpeed\n"
         "@see upResistSpeed\n" );

   endGroup( "Movement" );
   
   addGroup( "Movement: Jumping" );

      addField( "jumpForce", TypeF32, Offset(jumpForce, PlayerData),
         "@brief Force used to accelerate the player when a jump is initiated.\n\n" );

      addField( "jumpEnergyDrain", TypeF32, Offset(jumpEnergyDrain, PlayerData),
         "@brief Energy level drained each time the player jumps.\n\n"
         "@note Setting this to zero will disable any energy drain\n"
         "@see minJumpEnergy\n");
      addField( "minJumpEnergy", TypeF32, Offset(minJumpEnergy, PlayerData),
         "@brief Minimum energy level required to jump.\n\n"
         "@see jumpEnergyDrain\n");

      addField( "minJumpSpeed", TypeF32, Offset(minJumpSpeed, PlayerData),
         "@brief Minimum speed needed to jump.\n\n"
         "If the player's own z velocity is greater than this, then it is used to scale "
         "the jump speed, up to maxJumpSpeed.\n"
         "@see maxJumpSpeed\n");
      addField( "maxJumpSpeed", TypeF32, Offset(maxJumpSpeed, PlayerData),
         "@brief Maximum vertical speed before the player can no longer jump.\n\n" );
      addField( "jumpSurfaceAngle", TypeF32, Offset(jumpSurfaceAngle, PlayerData),
         "@brief Angle from vertical (in degrees) where the player can jump.\n\n" );
      addField( "jumpDelay", TypeS32, Offset(jumpDelay, PlayerData),
         "@brief Delay time in number of ticks ticks between jumps.\n\n" );
      addField( "airControl", TypeF32, Offset(airControl, PlayerData),
         "@brief Amount of movement control the player has when in the air.\n\n"
         "This is applied as a multiplier to the player's x and y motion.\n");
      addField( "jumpTowardsNormal", TypeBool, Offset(jumpTowardsNormal, PlayerData),
         "@brief Controls the direction of the jump impulse.\n"
         "When false, jumps are always in the vertical (+Z) direction. When true "
         "jumps are in the direction of the ground normal so long as the player is not "
         "directly facing the surface.  If the player is directly facing the surface, then "
         "they will jump straight up.\n" );
   
   endGroup( "Movement: Jumping" );
   
   addGroup( "Movement: Sprinting" );

      addField( "sprintForce", TypeF32, Offset(sprintForce, PlayerData),
         "@brief Force used to accelerate the player when sprinting.\n\n" );

      addField( "sprintEnergyDrain", TypeF32, Offset(sprintEnergyDrain, PlayerData),
         "@brief Energy value drained each tick that the player is sprinting.\n\n"
         "The player will not be able to move when his energy falls below "
         "sprintEnergyDrain.\n"
         "@note Setting this to zero will disable any energy drain.\n"
         "@see minSprintEnergy\n");
      addField( "minSprintEnergy", TypeF32, Offset(minSprintEnergy, PlayerData),
         "@brief Minimum energy level required to sprint.\n\n"
         "@see sprintEnergyDrain\n");

      addField( "maxSprintForwardSpeed", TypeF32, Offset(maxSprintForwardSpeed, PlayerData),
         "@brief Maximum forward speed when sprinting." );
      addField( "maxSprintBackwardSpeed", TypeF32, Offset(maxSprintBackwardSpeed, PlayerData),
         "@brief Maximum backward speed when sprinting." );
      addField( "maxSprintSideSpeed", TypeF32, Offset(maxSprintSideSpeed, PlayerData),
         "@brief Maximum sideways speed when sprinting." );

      addField( "sprintStrafeScale", TypeF32, Offset(sprintStrafeScale, PlayerData),
         "@brief Amount to scale strafing motion vector while sprinting." );
      addField( "sprintYawScale", TypeF32, Offset(sprintYawScale, PlayerData),
         "@brief Amount to scale yaw motion while sprinting." );
      addField( "sprintPitchScale", TypeF32, Offset(sprintPitchScale, PlayerData),
         "@brief Amount to scale pitch motion while sprinting." );

      addField( "sprintCanJump", TypeBool, Offset(sprintCanJump, PlayerData),
         "@brief Can the player jump while sprinting." );

   endGroup( "Movement: Sprinting" );

   addGroup( "Movement: Swimming" );

      addField( "swimForce", TypeF32, Offset(swimForce, PlayerData),
         "@brief Force used to accelerate the player when swimming.\n\n" );
      addField( "maxUnderwaterForwardSpeed", TypeF32, Offset(maxUnderwaterForwardSpeed, PlayerData),
         "@brief Maximum forward speed when underwater.\n\n" );
      addField( "maxUnderwaterBackwardSpeed", TypeF32, Offset(maxUnderwaterBackwardSpeed, PlayerData),
         "@brief Maximum backward speed when underwater.\n\n" );
      addField( "maxUnderwaterSideSpeed", TypeF32, Offset(maxUnderwaterSideSpeed, PlayerData),
         "@brief Maximum sideways speed when underwater.\n\n" );

   endGroup( "Movement: Swimming" );

   addGroup( "Movement: Crouching" );

      addField( "crouchForce", TypeF32, Offset(crouchForce, PlayerData),
         "@brief Force used to accelerate the player when crouching.\n\n" );
      addField( "maxCrouchForwardSpeed", TypeF32, Offset(maxCrouchForwardSpeed, PlayerData),
         "@brief Maximum forward speed when crouching.\n\n" );
      addField( "maxCrouchBackwardSpeed", TypeF32, Offset(maxCrouchBackwardSpeed, PlayerData),
         "@brief Maximum backward speed when crouching.\n\n" );
      addField( "maxCrouchSideSpeed", TypeF32, Offset(maxCrouchSideSpeed, PlayerData),
         "@brief Maximum sideways speed when crouching.\n\n" );

   endGroup( "Movement: Crouching" );

   addGroup( "Movement: Prone" );

      addField( "proneForce", TypeF32, Offset(proneForce, PlayerData),
         "@brief Force used to accelerate the player when prone (laying down).\n\n" );
      addField( "maxProneForwardSpeed", TypeF32, Offset(maxProneForwardSpeed, PlayerData),
         "@brief Maximum forward speed when prone (laying down).\n\n" );
      addField( "maxProneBackwardSpeed", TypeF32, Offset(maxProneBackwardSpeed, PlayerData),
         "@brief Maximum backward speed when prone (laying down).\n\n" );
      addField( "maxProneSideSpeed", TypeF32, Offset(maxProneSideSpeed, PlayerData),
         "@brief Maximum sideways speed when prone (laying down).\n\n" );

   endGroup( "Movement: Prone" );

   addGroup( "Movement: Jetting" );

      addField( "jetJumpForce", TypeF32, Offset(jetJumpForce, PlayerData),
         "@brief Force used to accelerate the player when a jet jump is initiated.\n\n" );

      addField( "jetJumpEnergyDrain", TypeF32, Offset(jetJumpEnergyDrain, PlayerData),
         "@brief Energy level drained each time the player jet jumps.\n\n"
         "@note Setting this to zero will disable any energy drain\n"
         "@see jetMinJumpEnergy\n");
      addField( "jetMinJumpEnergy", TypeF32, Offset(jetMinJumpEnergy, PlayerData),
         "@brief Minimum energy level required to jet jump.\n\n"
         "@see jetJumpEnergyDrain\n");

      addField( "jetMinJumpSpeed", TypeF32, Offset(jetMinJumpSpeed, PlayerData),
         "@brief Minimum speed needed to jet jump.\n\n"
         "If the player's own z velocity is greater than this, then it is used to scale "
         "the jet jump speed, up to jetMaxJumpSpeed.\n"
         "@see jetMaxJumpSpeed\n");
      addField( "jetMaxJumpSpeed", TypeF32, Offset(jetMaxJumpSpeed, PlayerData),
         "@brief Maximum vertical speed before the player can no longer jet jump.\n\n" );
      addField( "jetJumpSurfaceAngle", TypeF32, Offset(jetJumpSurfaceAngle, PlayerData),
         "@brief Angle from vertical (in degrees) where the player can jet jump.\n\n" );

   endGroup( "Movement: Jetting" );

   addGroup( "Falling" );

      addField( "fallingSpeedThreshold", TypeF32, Offset(fallingSpeedThreshold, PlayerData),
         "@brief Downward speed at which we consider the player falling.\n\n" );

      addField( "recoverDelay", TypeS32, Offset(recoverDelay, PlayerData),
         "@brief Number of ticks for the player to recover from falling.\n\n" );

      addField( "recoverRunForceScale", TypeF32, Offset(recoverRunForceScale, PlayerData),
         "@brief Scale factor applied to runForce while in the recover state.\n\n"
         "This can be used to temporarily slow the player's movement after a fall, or "
         "prevent the player from moving at all if set to zero.\n" );

      addField( "landSequenceTime", TypeF32, Offset(landSequenceTime, PlayerData),
         "@brief Time of land sequence play back when using new recover system.\n\n"
         "If greater than 0 then the legacy fall recovery system will be bypassed "
         "in favour of just playing the player's land sequence.  The time to "
         "recover from a fall then becomes this parameter's time and the land "
         "sequence's playback will be scaled to match.\n"
         "@see transitionToLand\n" );

      addField( "transitionToLand", TypeBool, Offset(transitionToLand, PlayerData),
         "@brief When going from a fall to a land, should we transition between the two.\n\n"
         "@note Only takes affect when landSequenceTime is greater than 0.\n"
         "@see landSequenceTime\n" );

   endGroup( "Falling" );

   addGroup( "Collision" );

      addField( "boundingBox", TypePoint3F, Offset(boxSize, PlayerData),
         "@brief Size of the bounding box used by the player for collision.\n\n"
         "Dimensions are given as \"width depth height\"." );
      addField( "crouchBoundingBox", TypePoint3F, Offset(crouchBoxSize, PlayerData),
         "@brief Collision bounding box used when the player is crouching.\n\n"
         "@see boundingBox" );
      addField( "proneBoundingBox", TypePoint3F, Offset(proneBoxSize, PlayerData),
         "@brief Collision bounding box used when the player is prone (laying down).\n\n"
         "@see boundingBox" );
      addField( "swimBoundingBox", TypePoint3F, Offset(swimBoxSize, PlayerData),
         "@brief Collision bounding box used when the player is swimming.\n\n"
         "@see boundingBox" );

      addField( "boxHeadPercentage", TypeF32, Offset(boxHeadPercentage, PlayerData),
         "@brief Percentage of the player's bounding box height that represents the head.\n\n"
         "Used when computing the damage location.\n"
         "@see Player::getDamageLocation" );
      addField( "boxTorsoPercentage", TypeF32, Offset(boxTorsoPercentage, PlayerData),
         "@brief Percentage of the player's bounding box height that represents the torso.\n\n"
         "Used when computing the damage location.\n"
         "@see Player::getDamageLocation" );
      addField( "boxHeadLeftPercentage", TypeF32, Offset(boxHeadLeftPercentage, PlayerData),
         "@brief Percentage of the player's bounding box width that represents the left side of the head.\n\n"
         "Used when computing the damage location.\n"
         "@see Player::getDamageLocation" );
      addField( "boxHeadRightPercentage", TypeF32, Offset(boxHeadRightPercentage, PlayerData),
         "@brief Percentage of the player's bounding box width that represents the right side of the head.\n\n"
         "Used when computing the damage location.\n"
         "@see Player::getDamageLocation" );
      addField( "boxHeadBackPercentage", TypeF32, Offset(boxHeadBackPercentage, PlayerData),
         "@brief Percentage of the player's bounding box depth that represents the back side of the head.\n\n"
         "Used when computing the damage location.\n"
         "@see Player::getDamageLocation" );
      addField( "boxHeadFrontPercentage", TypeF32, Offset(boxHeadFrontPercentage, PlayerData),
         "@brief Percentage of the player's bounding box depth that represents the front side of the head.\n\n"
         "Used when computing the damage location.\n"
         "@see Player::getDamageLocation" );

   endGroup( "Collision" );
   
   addGroup( "Interaction: Footsteps" );

      addField( "footPuffEmitter", TYPEID< ParticleEmitterData >(), Offset(footPuffEmitter, PlayerData),
         "@brief Particle emitter used to generate footpuffs (particles created as the player "
         "walks along the ground).\n\n"
         "@note The generation of foot puffs requires the appropriate triggeres to be defined in the "
         "player's animation sequences.  Without these, no foot puffs will be generated.\n");
      addField( "footPuffNumParts", TypeS32, Offset(footPuffNumParts, PlayerData),
         "@brief Number of footpuff particles to generate each step.\n\n"
         "Each foot puff is randomly placed within the defined foot puff radius.  This "
         "includes having footPuffNumParts set to one.\n"
         "@see footPuffRadius\n");
      addField( "footPuffRadius", TypeF32, Offset(footPuffRadius, PlayerData),
         "@brief Particle creation radius for footpuff particles.\n\n"
         "This is applied to each foot puff particle, even if footPuffNumParts is set to one.  So "
         "set this value to zero if you want a single foot puff placed at exactly the same location "
         "under the player each time.\n");
      addField( "dustEmitter", TYPEID< ParticleEmitterData >(), Offset(dustEmitter, PlayerData),
         "@brief Emitter used to generate dust particles.\n\n"
         "@note Currently unused." );

      addField( "decalData", TYPEID< DecalData >(), Offset(decalData, PlayerData),
         "@brief Decal to place on the ground for player footsteps.\n\n" );
      addField( "decalOffset",TypeF32, Offset(decalOffset, PlayerData),
         "@brief Distance from the center of the model to the right foot.\n\n"
         "While this defines the distance to the right foot, it is also used to place "
         "the left foot decal as well.  Just on the opposite side of the player." );

   endGroup( "Interaction: Footsteps" );

   addGroup( "Interaction: Sounds" );

      addField( "FootSoftSound", TypeSFXTrackName, Offset(sound[FootSoft], PlayerData),
         "@brief Sound to play when walking on a surface with Material footstepSoundId 0.\n\n" );
      addField( "FootHardSound", TypeSFXTrackName, Offset(sound[FootHard], PlayerData),
         "@brief Sound to play when walking on a surface with Material footstepSoundId 1.\n\n" );
      addField( "FootMetalSound", TypeSFXTrackName, Offset(sound[FootMetal], PlayerData),
         "@brief Sound to play when walking on a surface with Material footstepSoundId 2.\n\n" );
      addField( "FootSnowSound", TypeSFXTrackName, Offset(sound[FootSnow], PlayerData),
         "@brief Sound to play when walking on a surface with Material footstepSoundId 3.\n\n" );

      addField( "FootShallowSound", TypeSFXTrackName, Offset(sound[FootShallowSplash], PlayerData),
         "@brief Sound to play when walking in water and coverage is less than "
         "footSplashHeight.\n\n"
         "@see footSplashHeight\n" );
      addField( "FootWadingSound", TypeSFXTrackName, Offset(sound[FootWading], PlayerData),
         "@brief Sound to play when walking in water and coverage is less than 1, "
         "but > footSplashHeight.\n\n"
         "@see footSplashHeight\n" );
      addField( "FootUnderwaterSound", TypeSFXTrackName, Offset(sound[FootUnderWater], PlayerData),
         "@brief Sound to play when walking in water and coverage equals 1.0 "
         "(fully underwater).\n\n" );
      addField( "FootBubblesSound", TypeSFXTrackName, Offset(sound[FootBubbles], PlayerData),
         "@brief Sound to play when walking in water and coverage equals 1.0 "
         "(fully underwater).\n\n" );
      addField( "movingBubblesSound", TypeSFXTrackName, Offset(sound[MoveBubbles], PlayerData),
         "@brief Sound to play when in water and coverage equals 1.0 (fully underwater).\n\n"
         "Note that unlike FootUnderwaterSound, this sound plays even if the "
         "player is not moving around in the water.\n" );
      addField( "waterBreathSound", TypeSFXTrackName, Offset(sound[WaterBreath], PlayerData),
         "@brief Sound to play when in water and coverage equals 1.0 (fully underwater).\n\n"
         "Note that unlike FootUnderwaterSound, this sound plays even if the "
         "player is not moving around in the water.\n" );

      addField( "impactSoftSound", TypeSFXTrackName, Offset(sound[ImpactSoft], PlayerData),
         "@brief Sound to play after falling on a surface with Material footstepSoundId 0.\n\n" );
      addField( "impactHardSound", TypeSFXTrackName, Offset(sound[ImpactHard], PlayerData),
         "@brief Sound to play after falling on a surface with Material footstepSoundId 1.\n\n" );
      addField( "impactMetalSound", TypeSFXTrackName, Offset(sound[ImpactMetal], PlayerData),
         "@brief Sound to play after falling on a surface with Material footstepSoundId 2.\n\n" );
      addField( "impactSnowSound", TypeSFXTrackName, Offset(sound[ImpactSnow], PlayerData),
         "@brief Sound to play after falling on a surface with Material footstepSoundId 3.\n\n" );

      addField( "impactWaterEasy", TypeSFXTrackName, Offset(sound[ImpactWaterEasy], PlayerData),
         "@brief Sound to play when entering the water with velocity < "
         "mediumSplashSoundVelocity.\n\n"
         "@see mediumSplashSoundVelocity\n");
      addField( "impactWaterMedium", TypeSFXTrackName, Offset(sound[ImpactWaterMedium], PlayerData),
         "@brief Sound to play when entering the water with velocity >= "
         "mediumSplashSoundVelocity and < hardSplashSoundVelocity.\n\n"
         "@see mediumSplashSoundVelocity\n"
         "@see hardSplashSoundVelocity\n");
      addField( "impactWaterHard", TypeSFXTrackName, Offset(sound[ImpactWaterHard], PlayerData),
         "@brief Sound to play when entering the water with velocity >= "
         "hardSplashSoundVelocity.\n\n"
         "@see hardSplashSoundVelocity\n");
      addField( "exitingWater", TypeSFXTrackName, Offset(sound[ExitWater], PlayerData),
         "@brief Sound to play when exiting the water with velocity >= exitSplashSoundVelocity.\n\n"
         "@see exitSplashSoundVelocity\n");

   endGroup( "Interaction: Sounds" );

   addGroup( "Interaction: Splashes" );

      addField( "splash", TYPEID< SplashData >(), Offset(splash, PlayerData),
         "@brief SplashData datablock used to create splashes when the player moves "
         "through water.\n\n" );
      addField( "splashVelocity", TypeF32, Offset(splashVelocity, PlayerData),
         "@brief Minimum velocity when moving through water to generate splashes.\n\n" );
      addField( "splashAngle", TypeF32, Offset(splashAngle, PlayerData),
         "@brief Maximum angle (in degrees) from pure vertical movement in water to "
         "generate splashes.\n\n" );

      addField( "splashFreqMod", TypeF32, Offset(splashFreqMod, PlayerData),
         "@brief Multipled by speed to determine the number of splash particles to generate.\n\n" );
      addField( "splashVelEpsilon", TypeF32, Offset(splashVelEpsilon, PlayerData),
         "@brief Minimum speed to generate splash particles.\n\n" );
      addField( "bubbleEmitTime", TypeF32, Offset(bubbleEmitTime, PlayerData),
         "@brief Time in seconds to generate bubble particles after entering the water.\n\n" );
      addField( "splashEmitter", TYPEID< ParticleEmitterData >(), Offset(splashEmitterList, PlayerData), NUM_SPLASH_EMITTERS,
         "@brief Particle emitters used to generate splash particles.\n\n" );

      addField( "footstepSplashHeight", TypeF32, Offset(footSplashHeight, PlayerData),
         "@brief Water coverage level to choose between FootShallowSound and FootWadingSound.\n\n"
         "@see FootShallowSound\n"
         "@see FootWadingSound\n");

      addField( "mediumSplashSoundVelocity", TypeF32, Offset(medSplashSoundVel, PlayerData),
         "@brief Minimum velocity when entering the water for choosing between the impactWaterEasy and "
         "impactWaterMedium sounds to play.\n\n"
         "@see impactWaterEasy\n"
         "@see impactWaterMedium\n" );
      addField( "hardSplashSoundVelocity", TypeF32, Offset(hardSplashSoundVel, PlayerData),
         "@brief Minimum velocity when entering the water for choosing between the impactWaterMedium and "
         "impactWaterHard sound to play.\n\n"
         "@see impactWaterMedium\n"
         "@see impactWaterHard\n" );
      addField( "exitSplashSoundVelocity", TypeF32, Offset(exitSplashSoundVel, PlayerData),
         "@brief Minimum velocity when leaving the water for the exitingWater sound to "
         "play.\n\n"
         "@see exitingWater");

   endGroup( "Interaction: Splashes" );

   addGroup( "Interaction: Ground Impact" );

      addField( "groundImpactMinSpeed", TypeF32, Offset(groundImpactMinSpeed, PlayerData),
         "@brief Minimum falling impact speed to apply damage and initiate the camera "
         "shaking effect.\n\n" );
      addField( "groundImpactShakeFreq", TypePoint3F, Offset(groundImpactShakeFreq, PlayerData),
         "@brief Frequency of the camera shake effect after falling.\n\n"
         "This is how fast to shake the camera.\n");
      addField( "groundImpactShakeAmp", TypePoint3F, Offset(groundImpactShakeAmp, PlayerData),
         "@brief Amplitude of the camera shake effect after falling.\n\n"
         "This is how much to shake the camera.\n");
      addField( "groundImpactShakeDuration", TypeF32, Offset(groundImpactShakeDuration, PlayerData),
         "@brief Duration (in seconds) of the camera shake effect after falling.\n\n"
         "This is how long to shake the camera.\n");
      addField( "groundImpactShakeFalloff", TypeF32, Offset(groundImpactShakeFalloff, PlayerData),
         "@brief Falloff factor of the camera shake effect after falling.\n\n"
         "This is how to fade the camera shake over the duration.\n");

   endGroup( "Interaction: Ground Impact" );

   addGroup( "Physics" );

      // PhysicsPlayer
      addField( "physicsPlayerType", TypeString, Offset(physicsPlayerType, PlayerData),
         "@brief Specifies the type of physics used by the player.\n\n"
         "This depends on the physics module used.  An example is 'Capsule'.\n"
         "@note Not current used.\n");

   endGroup( "Physics" );

   addGroup( "First Person Arms" );

      addField( "imageAnimPrefixFP", TypeCaseString, Offset(imageAnimPrefixFP, PlayerData),
         "@brief Optional prefix to all mounted image animation sequences in first person.\n\n"
         "This defines a prefix that will be added when looking up mounted image "
         "animation sequences while in first person.  It allows for the customization "
         "of a first person image based on the type of player.\n");

      // Mounted images arrays
      addArray( "Mounted Images", ShapeBase::MaxMountedImages );

         addField( "shapeNameFP", TypeShapeFilename, Offset(shapeNameFP, PlayerData), ShapeBase::MaxMountedImages,
            "@brief File name of this player's shape that will be used in conjunction with the corresponding mounted image.\n\n"
            "These optional parameters correspond to each mounted image slot to indicate a shape that is rendered "
            "in addition to the mounted image shape.  Typically these are a player's arms (or arm) that is "
            "animated along with the mounted image's state animation sequences.\n");

      endArray( "Mounted Images" );

   endGroup( "First Person Arms" );

   addGroup( "Third Person" );

      addField( "imageAnimPrefix", TypeCaseString, Offset(imageAnimPrefix, PlayerData),
         "@brief Optional prefix to all mounted image animation sequences in third person.\n\n"
         "This defines a prefix that will be added when looking up mounted image "
         "animation sequences while in third person.  It allows for the customization "
         "of a third person image based on the type of player.\n");

      addField( "allowImageStateAnimation", TypeBool, Offset(allowImageStateAnimation, PlayerData),
         "@brief Allow mounted images to request a sequence be played on the Player.\n\n"
         "When true a new thread is added to the player to allow for "
         "mounted images to request a sequence be played on the player "
         "through the image's state machine.  It is only optional so "
         "that we don't create a TSThread on the player if we don't "
         "need to.\n");

   endGroup( "Third Person" );

   Parent::initPersistFields();
}

void PlayerData::packData(BitStream* stream)
{
   Parent::packData(stream);

   stream->writeFlag(renderFirstPerson);
1187 1188
   stream->writeFlag(firstPersonShadows);
   
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
   stream->write(minLookAngle);
   stream->write(maxLookAngle);
   stream->write(maxFreelookAngle);
   stream->write(maxTimeScale);

   stream->write(mass);
   stream->write(maxEnergy);
   stream->write(drag);
   stream->write(density);

   stream->write(maxStepHeight);

   stream->write(runForce);
   stream->write(runEnergyDrain);
   stream->write(minRunEnergy);
   stream->write(maxForwardSpeed);
   stream->write(maxBackwardSpeed);
   stream->write(maxSideSpeed);
   stream->write(runSurfaceAngle);

   stream->write(fallingSpeedThreshold);

   stream->write(recoverDelay);
   stream->write(recoverRunForceScale);
   stream->write(landSequenceTime);
   stream->write(transitionToLand);

   // Jumping
   stream->write(jumpForce);
   stream->write(jumpEnergyDrain);
   stream->write(minJumpEnergy);
   stream->write(minJumpSpeed);
   stream->write(maxJumpSpeed);
   stream->write(jumpSurfaceAngle);
   stream->writeInt(jumpDelay,JumpDelayBits);

   // Sprinting
   stream->write(sprintForce);
   stream->write(sprintEnergyDrain);
   stream->write(minSprintEnergy);
   stream->write(maxSprintForwardSpeed);
   stream->write(maxSprintBackwardSpeed);
   stream->write(maxSprintSideSpeed);
   stream->write(sprintStrafeScale);
   stream->write(sprintYawScale);
   stream->write(sprintPitchScale);
   stream->writeFlag(sprintCanJump);

   // Swimming
   stream->write(swimForce);   
   stream->write(maxUnderwaterForwardSpeed);
   stream->write(maxUnderwaterBackwardSpeed);
   stream->write(maxUnderwaterSideSpeed);

   // Crouching
   stream->write(crouchForce);   
   stream->write(maxCrouchForwardSpeed);
   stream->write(maxCrouchBackwardSpeed);
   stream->write(maxCrouchSideSpeed);

   // Prone
   stream->write(proneForce);   
   stream->write(maxProneForwardSpeed);
   stream->write(maxProneBackwardSpeed);
   stream->write(maxProneSideSpeed);

   // Jetting
   stream->write(jetJumpForce);
   stream->write(jetJumpEnergyDrain);
   stream->write(jetMinJumpEnergy);
   stream->write(jetMinJumpSpeed);
   stream->write(jetMaxJumpSpeed);
   stream->write(jetJumpSurfaceAngle);

   stream->write(horizMaxSpeed);
   stream->write(horizResistSpeed);
   stream->write(horizResistFactor);

   stream->write(upMaxSpeed);
   stream->write(upResistSpeed);
   stream->write(upResistFactor);

   stream->write(splashVelocity);
   stream->write(splashAngle);
   stream->write(splashFreqMod);
   stream->write(splashVelEpsilon);
   stream->write(bubbleEmitTime);

   stream->write(medSplashSoundVel);
   stream->write(hardSplashSoundVel);
   stream->write(exitSplashSoundVel);
   stream->write(footSplashHeight);
   // Don't need damage scale on the client
   stream->write(minImpactSpeed);
   stream->write(minLateralImpactSpeed);

   for( U32 i = 0; i < MaxSounds; i++)
      sfxWrite( stream, sound[ i ] );

   mathWrite(*stream, boxSize);
   mathWrite(*stream, crouchBoxSize);
   mathWrite(*stream, proneBoxSize);
   mathWrite(*stream, swimBoxSize);

   if( stream->writeFlag( footPuffEmitter ) )
   {
      stream->writeRangedU32( footPuffEmitter->getId(), DataBlockObjectIdFirst,  DataBlockObjectIdLast );
   }

   stream->write( footPuffNumParts );
   stream->write( footPuffRadius );

   if( stream->writeFlag( decalData ) )
   {
      stream->writeRangedU32( decalData->getId(), DataBlockObjectIdFirst,  DataBlockObjectIdLast );
   }
   stream->write(decalOffset);

   if( stream->writeFlag( dustEmitter ) )
   {
      stream->writeRangedU32( dustEmitter->getId(), DataBlockObjectIdFirst,  DataBlockObjectIdLast );
   }


   if (stream->writeFlag( splash ))
   {
      stream->writeRangedU32(splash->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast);
   }

   for( U32 i=0; i<NUM_SPLASH_EMITTERS; i++ )
   {
      if( stream->writeFlag( splashEmitterList[i] != NULL ) )
      {
         stream->writeRangedU32( splashEmitterList[i]->getId(), DataBlockObjectIdFirst,  DataBlockObjectIdLast );
      }
   }


   stream->write(groundImpactMinSpeed);
   stream->write(groundImpactShakeFreq.x);
   stream->write(groundImpactShakeFreq.y);
   stream->write(groundImpactShakeFreq.z);
   stream->write(groundImpactShakeAmp.x);
   stream->write(groundImpactShakeAmp.y);
   stream->write(groundImpactShakeAmp.z);
   stream->write(groundImpactShakeDuration);
   stream->write(groundImpactShakeFalloff);

   // Air control
   stream->write(airControl);

   // Jump off at normal
   stream->writeFlag(jumpTowardsNormal);

   stream->writeString(physicsPlayerType);

   // Third person mounted image shapes
   stream->writeString(imageAnimPrefix);

   stream->writeFlag(allowImageStateAnimation);

   // First person mounted image shapes
   stream->writeString(imageAnimPrefixFP);
   for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
   {
      stream->writeString(shapeNameFP[i]);

      // computeCRC is handled in ShapeBaseData
      if (computeCRC)
      {
         stream->write(mCRCFP[i]);
      }
   }
}

void PlayerData::unpackData(BitStream* stream)
{
   Parent::unpackData(stream);

   renderFirstPerson = stream->readFlag();
1369
   firstPersonShadows = stream->readFlag();
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652

   stream->read(&minLookAngle);
   stream->read(&maxLookAngle);
   stream->read(&maxFreelookAngle);
   stream->read(&maxTimeScale);

   stream->read(&mass);
   stream->read(&maxEnergy);
   stream->read(&drag);
   stream->read(&density);

   stream->read(&maxStepHeight);

   stream->read(&runForce);
   stream->read(&runEnergyDrain);
   stream->read(&minRunEnergy);
   stream->read(&maxForwardSpeed);
   stream->read(&maxBackwardSpeed);
   stream->read(&maxSideSpeed);
   stream->read(&runSurfaceAngle);

   stream->read(&fallingSpeedThreshold);
   stream->read(&recoverDelay);
   stream->read(&recoverRunForceScale);
   stream->read(&landSequenceTime);
   stream->read(&transitionToLand);

   // Jumping
   stream->read(&jumpForce);
   stream->read(&jumpEnergyDrain);
   stream->read(&minJumpEnergy);
   stream->read(&minJumpSpeed);
   stream->read(&maxJumpSpeed);
   stream->read(&jumpSurfaceAngle);
   jumpDelay = stream->readInt(JumpDelayBits);

   // Sprinting
   stream->read(&sprintForce);
   stream->read(&sprintEnergyDrain);
   stream->read(&minSprintEnergy);
   stream->read(&maxSprintForwardSpeed);
   stream->read(&maxSprintBackwardSpeed);
   stream->read(&maxSprintSideSpeed);
   stream->read(&sprintStrafeScale);
   stream->read(&sprintYawScale);
   stream->read(&sprintPitchScale);
   sprintCanJump = stream->readFlag();

   // Swimming
   stream->read(&swimForce);
   stream->read(&maxUnderwaterForwardSpeed);
   stream->read(&maxUnderwaterBackwardSpeed);
   stream->read(&maxUnderwaterSideSpeed);   

   // Crouching
   stream->read(&crouchForce);
   stream->read(&maxCrouchForwardSpeed);
   stream->read(&maxCrouchBackwardSpeed);
   stream->read(&maxCrouchSideSpeed);

   // Prone
   stream->read(&proneForce);
   stream->read(&maxProneForwardSpeed);
   stream->read(&maxProneBackwardSpeed);
   stream->read(&maxProneSideSpeed);

   // Jetting
   stream->read(&jetJumpForce);
   stream->read(&jetJumpEnergyDrain);
   stream->read(&jetMinJumpEnergy);
   stream->read(&jetMinJumpSpeed);
   stream->read(&jetMaxJumpSpeed);
   stream->read(&jetJumpSurfaceAngle);

   stream->read(&horizMaxSpeed);
   stream->read(&horizResistSpeed);
   stream->read(&horizResistFactor);

   stream->read(&upMaxSpeed);
   stream->read(&upResistSpeed);
   stream->read(&upResistFactor);

   stream->read(&splashVelocity);
   stream->read(&splashAngle);
   stream->read(&splashFreqMod);
   stream->read(&splashVelEpsilon);
   stream->read(&bubbleEmitTime);

   stream->read(&medSplashSoundVel);
   stream->read(&hardSplashSoundVel);
   stream->read(&exitSplashSoundVel);
   stream->read(&footSplashHeight);

   stream->read(&minImpactSpeed);
   stream->read(&minLateralImpactSpeed);

   for( U32 i = 0; i < MaxSounds; i++)
      sfxRead( stream, &sound[ i ] );

   mathRead(*stream, &boxSize);
   mathRead(*stream, &crouchBoxSize);
   mathRead(*stream, &proneBoxSize);
   mathRead(*stream, &swimBoxSize);

   if( stream->readFlag() )
   {
      footPuffID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
   }

   stream->read(&footPuffNumParts);
   stream->read(&footPuffRadius);

   if( stream->readFlag() )
   {
      decalID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
   }
   stream->read(&decalOffset);

   if( stream->readFlag() )
   {
      dustID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
   }


   if (stream->readFlag())
   {
      splashId = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
   }

   for( U32 i=0; i<NUM_SPLASH_EMITTERS; i++ )
   {
      if( stream->readFlag() )
      {
         splashEmitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
      }
   }

   stream->read(&groundImpactMinSpeed);
   stream->read(&groundImpactShakeFreq.x);
   stream->read(&groundImpactShakeFreq.y);
   stream->read(&groundImpactShakeFreq.z);
   stream->read(&groundImpactShakeAmp.x);
   stream->read(&groundImpactShakeAmp.y);
   stream->read(&groundImpactShakeAmp.z);
   stream->read(&groundImpactShakeDuration);
   stream->read(&groundImpactShakeFalloff);

   // Air control
   stream->read(&airControl);

   // Jump off at normal
   jumpTowardsNormal = stream->readFlag();

   physicsPlayerType = stream->readSTString();

   // Third person mounted image shapes
   imageAnimPrefix = stream->readSTString();

   allowImageStateAnimation = stream->readFlag();

   // First person mounted image shapes
   imageAnimPrefixFP = stream->readSTString();
   for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
   {
      shapeNameFP[i] = stream->readSTString();

      // computeCRC is handled in ShapeBaseData
      if (computeCRC)
      {
         stream->read(&(mCRCFP[i]));
      }
   }
}


//----------------------------------------------------------------------------
//----------------------------------------------------------------------------

ImplementEnumType( PlayerPose,
   "@brief The pose of the Player.\n\n"
   "@ingroup gameObjects\n\n")
   { Player::StandPose,    "Stand",    "Standard movement pose.\n" },
   { Player::SprintPose,   "Sprint",   "Sprinting pose.\n" },
   { Player::CrouchPose,   "Crouch",   "Crouch pose.\n" },
   { Player::PronePose,    "Prone",    "Prone pose.\n" },
   { Player::SwimPose,     "Swim",     "Swimming pose.\n" },
EndImplementEnumType;

//----------------------------------------------------------------------------

IMPLEMENT_CO_NETOBJECT_V1(Player);

ConsoleDocClass( Player,
   "@ingroup gameObjects\n"
);

F32 Player::mGravity = -20;

//----------------------------------------------------------------------------

Player::Player()
{
   mTypeMask |= PlayerObjectType | DynamicShapeObjectType;

   delta.pos = mAnchorPoint = Point3F(0,0,100);
   delta.rot = delta.head = Point3F(0,0,0);
   delta.rotOffset.set(0.0f,0.0f,0.0f);
   delta.warpOffset.set(0.0f,0.0f,0.0f);
   delta.posVec.set(0.0f,0.0f,0.0f);
   delta.rotVec.set(0.0f,0.0f,0.0f);
   delta.headVec.set(0.0f,0.0f,0.0f);
   delta.warpTicks = 0;
   delta.dt = 1.0f;
   delta.move = NullMove;
   mPredictionCount = sMaxPredictionTicks;
   mObjToWorld.setColumn(3,delta.pos);
   mRot = delta.rot;
   mHead = delta.head;
   mVelocity.set(0.0f, 0.0f, 0.0f);
   mDataBlock = 0;
   mHeadHThread = mHeadVThread = mRecoilThread = mImageStateThread = 0;
   mArmAnimation.action = PlayerData::NullAnimation;
   mArmAnimation.thread = 0;
   mActionAnimation.action = PlayerData::NullAnimation;
   mActionAnimation.thread = 0;
   mActionAnimation.delayTicks = 0;
   mActionAnimation.forward = true;
   mActionAnimation.firstPerson = false;
   //mActionAnimation.time = 1.0f; //ActionAnimation::Scale;
   mActionAnimation.waitForEnd = false;
   mActionAnimation.holdAtEnd = false;
   mActionAnimation.animateOnServer = false;
   mActionAnimation.atEnd = false;
   mState = MoveState;
   mJetting = false;
   mFalling = false;
   mSwimming = false;
   mInWater = false;
   mPose = StandPose;
   mContactTimer = 0;
   mJumpDelay = 0;
   mJumpSurfaceLastContact = 0;
   mJumpSurfaceNormal.set(0.0f, 0.0f, 1.0f);
   mControlObject = 0;
   dMemset( mSplashEmitter, 0, sizeof( mSplashEmitter ) );

   mUseHeadZCalc = true;

   allowAllPoses();

   mImpactSound = 0;
   mRecoverTicks = 0;
   mReversePending = 0;

   mLastPos.set( 0.0f, 0.0f, 0.0f );

   mMoveBubbleSound = 0;
   mWaterBreathSound = 0;   

   mConvex.init(this);
   mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
   mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);

   mWeaponBackFraction = 0.0f;

   mInMissionArea = true;

   mBubbleEmitterTime = 10.0;
   mLastWaterPos.set( 0.0, 0.0, 0.0 );

   mMountPending = 0;

   mPhysicsRep = NULL;

   for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
   {
      mShapeFPInstance[i] = 0;
      mShapeFPAmbientThread[i] = 0;
      mShapeFPVisThread[i] = 0;
      mShapeFPAnimThread[i] = 0;
      mShapeFPFlashThread[i] = 0;
      mShapeFPSpinThread[i] = 0;
   }
1653 1654 1655

   mLastAbsoluteYaw = 0.0f;
   mLastAbsolutePitch = 0.0f;
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
}

Player::~Player()
{
   for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
   {
      delete mShapeFPInstance[i];
      mShapeFPInstance[i] = 0;
   }
}


//----------------------------------------------------------------------------

bool Player::onAdd()
{
   ActionAnimation serverAnim = mActionAnimation;
   if(!Parent::onAdd() || !mDataBlock)
      return false;

   mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
   mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);

   addToScene();

   // Make sure any state and animation passed from the server
   // in the initial update is set correctly.
   ActionState state = mState;
   mState = NullState;
   setState(state);
   setPose(StandPose);

   if (serverAnim.action != PlayerData::NullAnimation)
   {
      setActionThread(serverAnim.action, true, serverAnim.holdAtEnd, true, false, true);
      if (serverAnim.atEnd)
      {
         mShapeInstance->clearTransition(mActionAnimation.thread);
         mShapeInstance->setPos(mActionAnimation.thread,
                                mActionAnimation.forward ? 1.0f : 0.0f);
         if (inDeathAnim())
            mDeath.lastPos = 1.0f;
      }

      // We have to leave them sitting for a while since mounts don't come through right
      // away (and sometimes not for a while).  Still going to let this time out because
      // I'm not sure if we're guaranteed another anim will come through and cancel.
      if (!isServerObject() && inSittingAnim())
         mMountPending = (S32) sMountPendingTickWait;
      else
         mMountPending = 0;
   }
   if (mArmAnimation.action != PlayerData::NullAnimation)
      setArmThread(mArmAnimation.action);

   //
   if (isServerObject())
   {
      scriptOnAdd();
   }
   else
   {
      U32 i;
      for( i=0; i<PlayerData::NUM_SPLASH_EMITTERS; i++ )
      {
         if ( mDataBlock->splashEmitterList[i] ) 
         {
            mSplashEmitter[i] = new ParticleEmitter;
            mSplashEmitter[i]->onNewDataBlock( mDataBlock->splashEmitterList[i], false );
            if( !mSplashEmitter[i]->registerObject() )
            {
               Con::warnf( ConsoleLogEntry::General, "Could not register splash emitter for class: %s", mDataBlock->getName() );
               mSplashEmitter[i].getPointer()->destroySelf();
               mSplashEmitter[i] = NULL;
            }
         }
      }
      mLastWaterPos = getPosition();

      // clear out all camera effects
      gCamFXMgr.clear();
   }

   if ( PHYSICSMGR )
   {
      PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );

      mPhysicsRep = PHYSICSMGR->createPlayer();
      mPhysicsRep->init(   mDataBlock->physicsPlayerType,
                           mDataBlock->boxSize,
                           mDataBlock->runSurfaceCos,
                           mDataBlock->maxStepHeight,
                           this, 
                           world );
      mPhysicsRep->setTransform( getTransform() );
   }

   return true;
}

void Player::onRemove()
{
   setControlObject(0);
   scriptOnRemove();
   removeFromScene();
1761 1762 1763 1764 1765 1766
   
   if ( isGhost() )
   {
      SFX_DELETE( mMoveBubbleSound );
      SFX_DELETE( mWaterBreathSound );
   }
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534

   U32 i;
   for( i=0; i<PlayerData::NUM_SPLASH_EMITTERS; i++ )
   {
      if( mSplashEmitter[i] )
      {
         mSplashEmitter[i]->deleteWhenEmpty();
         mSplashEmitter[i] = NULL;
      }
   }

   mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
   mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);

   SAFE_DELETE( mPhysicsRep );		

   Parent::onRemove();
}

void Player::onScaleChanged()
{
   const Point3F& scale = getScale();
   mScaledBox = mObjBox;
   mScaledBox.minExtents.convolve( scale );
   mScaledBox.maxExtents.convolve( scale );
}


//----------------------------------------------------------------------------

bool Player::onNewDataBlock( GameBaseData *dptr, bool reload )
{
   PlayerData* prevData = mDataBlock;
   mDataBlock = dynamic_cast<PlayerData*>(dptr);
   if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
      return false;

   // Player requires a shape instance.
   if ( mShapeInstance == NULL )
      return false;

   // Initialize arm thread, preserve arm sequence from last datablock.
   // Arm animation can be from last datablock, or sent from the server.
   U32 prevAction = mArmAnimation.action;
   mArmAnimation.action = PlayerData::NullAnimation;
   if (mDataBlock->lookAction) {
      mArmAnimation.thread = mShapeInstance->addThread();
      mShapeInstance->setTimeScale(mArmAnimation.thread,0);
      if (prevData) {
         if (prevAction != prevData->lookAction && prevAction != PlayerData::NullAnimation)
            setArmThread(prevData->actionList[prevAction].name);
         prevAction = PlayerData::NullAnimation;
      }
      if (mArmAnimation.action == PlayerData::NullAnimation) {
         mArmAnimation.action = (prevAction != PlayerData::NullAnimation)?
            prevAction: mDataBlock->lookAction;
         mShapeInstance->setSequence(mArmAnimation.thread,
           mDataBlock->actionList[mArmAnimation.action].sequence,0);
      }
   }
   else
      mArmAnimation.thread = 0;

   // Initialize head look thread
   TSShape const* shape = mShapeInstance->getShape();
   S32 headSeq = shape->findSequence("head");
   if (headSeq != -1) {
      mHeadVThread = mShapeInstance->addThread();
      mShapeInstance->setSequence(mHeadVThread,headSeq,0);
      mShapeInstance->setTimeScale(mHeadVThread,0);
   }
   else
      mHeadVThread = 0;

   headSeq = shape->findSequence("headside");
   if (headSeq != -1) {
      mHeadHThread = mShapeInstance->addThread();
      mShapeInstance->setSequence(mHeadHThread,headSeq,0);
      mShapeInstance->setTimeScale(mHeadHThread,0);
   }
   else
      mHeadHThread = 0;

   // Create Recoil thread if any recoil sequences are specified.
   // Note that the server player does not play this animation.
   mRecoilThread = 0;
   if (isGhost())
      for (U32 s = 0; s < PlayerData::NumRecoilSequences; s++)
         if (mDataBlock->recoilSequence[s] != -1) {
            mRecoilThread = mShapeInstance->addThread();
            mShapeInstance->setSequence(mRecoilThread, mDataBlock->recoilSequence[s], 0);
            mShapeInstance->setTimeScale(mRecoilThread, 0);
            break;
         }

   // Reset the image state driven animation thread.  This will be properly built
   // in onImageStateAnimation() when needed.
   mImageStateThread = 0;

   // Initialize the primary thread, the actual sequence is
   // set later depending on player actions.
   mActionAnimation.action = PlayerData::NullAnimation;
   mActionAnimation.thread = mShapeInstance->addThread();
   updateAnimationTree(!isGhost());

   // First person mounted image shapes.  Only on client.
   if ( isGhost() )
   {
      for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
      {
         if (bool(mDataBlock->mShapeFP[i]))
         {
            mShapeFPInstance[i] = new TSShapeInstance(mDataBlock->mShapeFP[i], isClientObject());

            mShapeFPInstance[i]->cloneMaterialList();

            // Ambient animation
            if (mShapeFPAmbientThread[i])
            {
               S32 seq = mShapeFPInstance[i]->getShape()->findSequence("ambient");
               if (seq != -1)
               {
                  mShapeFPAmbientThread[i] = mShapeFPInstance[i]->addThread();
                  mShapeFPInstance[i]->setTimeScale(mShapeFPAmbientThread[i], 1);
                  mShapeFPInstance[i]->setSequence(mShapeFPAmbientThread[i], seq, 0);
               }
            }

            // Standard state animation
            mShapeFPAnimThread[i] = mShapeFPInstance[i]->addThread();
            if (mShapeFPAnimThread[i])
            {
               mShapeFPInstance[i]->setTimeScale(mShapeFPAnimThread[i],0);
            }
         }
      }
   }

   if ( isGhost() )
   {
      // Create the sounds ahead of time.  This reduces runtime
      // costs and makes the system easier to understand.

      SFX_DELETE( mMoveBubbleSound );
      SFX_DELETE( mWaterBreathSound );

      if ( mDataBlock->sound[PlayerData::MoveBubbles] )
         mMoveBubbleSound = SFX->createSource( mDataBlock->sound[PlayerData::MoveBubbles] );

      if ( mDataBlock->sound[PlayerData::WaterBreath] )
         mWaterBreathSound = SFX->createSource( mDataBlock->sound[PlayerData::WaterBreath] );
   }

   mObjBox.maxExtents.x = mDataBlock->boxSize.x * 0.5f;
   mObjBox.maxExtents.y = mDataBlock->boxSize.y * 0.5f;
   mObjBox.maxExtents.z = mDataBlock->boxSize.z;
   mObjBox.minExtents.x = -mObjBox.maxExtents.x;
   mObjBox.minExtents.y = -mObjBox.maxExtents.y;
   mObjBox.minExtents.z = 0.0f;

   // Setup the box for our convex object...
   mObjBox.getCenter(&mConvex.mCenter);
   mConvex.mSize.x = mObjBox.len_x() / 2.0f;
   mConvex.mSize.y = mObjBox.len_y() / 2.0f;
   mConvex.mSize.z = mObjBox.len_z() / 2.0f;

   // Initialize our scaled attributes as well
   onScaleChanged();
   resetWorldBox();

   scriptOnNewDataBlock();
   return true;
}

//----------------------------------------------------------------------------

void Player::reSkin()
{
   if ( isGhost() && mShapeInstance && mSkinNameHandle.isValidString() )
   {
      Vector<String> skins;
      String(mSkinNameHandle.getString()).split( ";", skins );

      for ( int i = 0; i < skins.size(); i++ )
      {
         String oldSkin( mAppliedSkinName.c_str() );
         String newSkin( skins[i] );

         // Check if the skin handle contains an explicit "old" base string. This
         // allows all models to support skinning, even if they don't follow the 
         // "base_xxx" material naming convention.
         S32 split = newSkin.find( '=' );    // "old=new" format skin?
         if ( split != String::NPos )
         {
            oldSkin = newSkin.substr( 0, split );
            newSkin = newSkin.erase( 0, split+1 );
         }

         // Apply skin to both 3rd person and 1st person shape instances
         mShapeInstance->reSkin( newSkin, oldSkin );
         for ( int j = 0; j < ShapeBase::MaxMountedImages; j++ )
         {
            if (mShapeFPInstance[j])
               mShapeFPInstance[j]->reSkin( newSkin, oldSkin );
         }

         mAppliedSkinName = newSkin;
      }
   }
}

//----------------------------------------------------------------------------

void Player::setControllingClient(GameConnection* client)
{
   Parent::setControllingClient(client);
   if (mControlObject)
      mControlObject->setControllingClient(client);
}

void Player::setControlObject(ShapeBase* obj)
{
   if (mControlObject == obj)
      return;

   if (mControlObject) {
      mControlObject->setControllingObject(0);
      mControlObject->setControllingClient(0);
   }
   if (obj == this || obj == 0)
      mControlObject = 0;
   else {
      if (ShapeBase* coo = obj->getControllingObject())
         coo->setControlObject(0);
      if (GameConnection* con = obj->getControllingClient())
         con->setControlObject(0);

      mControlObject = obj;
      mControlObject->setControllingObject(this);
      mControlObject->setControllingClient(getControllingClient());
   }
}

void Player::onCameraScopeQuery(NetConnection *connection, CameraScopeQuery *query)
{
   // First, we are certainly in scope, and whatever we're riding is too...
   if(mControlObject.isNull() || mControlObject == mMount.object)
      Parent::onCameraScopeQuery(connection, query);
   else
   {
      connection->objectInScope(this);
      if (isMounted())
         connection->objectInScope(mMount.object);
      mControlObject->onCameraScopeQuery(connection, query);
   }
}

ShapeBase* Player::getControlObject()
{
   return mControlObject;
}

void Player::processTick(const Move* move)
{
   PROFILE_SCOPE(Player_ProcessTick);

   bool prevMoveMotion = mMoveMotion;
   Pose prevPose = getPose();

   // If we're not being controlled by a client, let the
   // AI sub-module get a chance at producing a move.
   Move aiMove;
   if (!move && isServerObject() && getAIMove(&aiMove))
      move = &aiMove;

   // Manage the control object and filter moves for the player
   Move pMove,cMove;
   if (mControlObject) {
      if (!move)
         mControlObject->processTick(0);
      else {
         pMove = NullMove;
         cMove = *move;
         //if (isMounted()) {
            // Filter Jump trigger if mounted
            //pMove.trigger[2] = move->trigger[2];
            //cMove.trigger[2] = false;
         //}
         if (move->freeLook) {
            // Filter yaw/picth/roll when freelooking.
            pMove.yaw = move->yaw;
            pMove.pitch = move->pitch;
            pMove.roll = move->roll;
            pMove.freeLook = true;
            cMove.freeLook = false;
            cMove.yaw = cMove.pitch = cMove.roll = 0.0f;
         }
         mControlObject->processTick((mDamageState == Enabled)? &cMove: &NullMove);
         move = &pMove;
      }
   }

   Parent::processTick(move);
   // Warp to catch up to server
   if (delta.warpTicks > 0) {
      delta.warpTicks--;

      // Set new pos
      getTransform().getColumn(3, &delta.pos);
      delta.pos += delta.warpOffset;
      delta.rot += delta.rotOffset;

      // Wrap yaw to +/-PI
      if (delta.rot.z < - M_PI_F)
         delta.rot.z += M_2PI_F;
      else if (delta.rot.z > M_PI_F)
         delta.rot.z -= M_2PI_F;

      setPosition(delta.pos,delta.rot);
      updateDeathOffsets();
      updateLookAnimation();

      // Backstepping
      delta.posVec = -delta.warpOffset;
      delta.rotVec = -delta.rotOffset;
   }
   else {
      // If there is no move, the player is either an
      // unattached player on the server, or a player's
      // client ghost.
      if (!move) {
         if (isGhost()) {
            // If we haven't run out of prediction time,
            // predict using the last known move.
            if (mPredictionCount-- <= 0)
               return;

            move = &delta.move;
         }
         else
            move = &NullMove;
      }
      if (!isGhost())
         updateAnimation(TickSec);

      PROFILE_START(Player_PhysicsSection);
      if ( isServerObject() || didRenderLastRender() || getControllingClient() )
      {
         if ( !mPhysicsRep )
         {
            if ( isMounted() )
            {
               // If we're mounted then do not perform any collision checks
               // and clear our previous working list.
               mConvex.clearWorkingList();
            }
            else
            {
               updateWorkingCollisionSet();
            }
         }

         updateState();
         updateMove(move);
         updateLookAnimation();
         updateDeathOffsets();
         updatePos();
      }
      PROFILE_END();

      if (!isGhost())
      {
         // Animations are advanced based on frame rate on the
         // client and must be ticked on the server.
         updateActionThread();
         updateAnimationTree(true);

         // Check for sprinting motion changes
         Pose currentPose = getPose();
         // Player has just switched into Sprint pose and is moving
         if (currentPose == SprintPose && prevPose != SprintPose && mMoveMotion)
         {
            mDataBlock->onStartSprintMotion_callback( this );
         }
         // Player has just switched out of Sprint pose and is moving, or was just moving
         else if (currentPose != SprintPose && prevPose == SprintPose && (mMoveMotion || prevMoveMotion))
         {
            mDataBlock->onStopSprintMotion_callback( this );
         }
         // Player is in Sprint pose and has modified their motion
         else if (currentPose == SprintPose && prevMoveMotion != mMoveMotion)
         {
            if (mMoveMotion)
            {
               mDataBlock->onStartSprintMotion_callback( this );
            }
            else
            {
               mDataBlock->onStopSprintMotion_callback( this );
            }
         }
      }
   }
}

void Player::interpolateTick(F32 dt)
{
   if (mControlObject)
      mControlObject->interpolateTick(dt);

   // Client side interpolation
   Parent::interpolateTick(dt);

   Point3F pos = delta.pos + delta.posVec * dt;
   Point3F rot = delta.rot + delta.rotVec * dt;

   setRenderPosition(pos,rot,dt);

/*
   // apply camera effects - is this the best place? - bramage
   GameConnection* connection = GameConnection::getConnectionToServer();
   if( connection->isFirstPerson() )
   {
      ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject());
      if( obj == this )
      {
         MatrixF curTrans = getRenderTransform();
         curTrans.mul( gCamFXMgr.getTrans() );
         Parent::setRenderTransform( curTrans );
      }
   }
*/

   updateLookAnimation(dt);
   delta.dt = dt;
}

void Player::advanceTime(F32 dt)
{
   // Client side animations
   Parent::advanceTime(dt);
   updateActionThread();
   updateAnimation(dt);
   updateSplash();
   updateFroth(dt);
   updateWaterSounds(dt);

   mLastPos = getPosition();

   if (mImpactSound)
      playImpactSound();

   // update camera effects.  Definitely need to find better place for this - bramage
   if( isControlObject() )
   {
      if( mDamageState == Disabled || mDamageState == Destroyed )
      {
         // clear out all camera effects being applied to player if dead
         gCamFXMgr.clear();
      }
   }
}

bool Player::getAIMove(Move* move)
{
   return false;
}

void Player::setState(ActionState state, U32 recoverTicks)
{
   if (state != mState) {
      // Skip initialization if there is no manager, the state
      // will get reset when the object is added to a manager.
      if (isProperlyAdded()) {
         switch (state) {
            case RecoverState: {
               if (mDataBlock->landSequenceTime > 0.0f)
               {
                  // Use the land sequence as the basis for the recovery
                  setActionThread(PlayerData::LandAnim, true, false, true, true);
                  F32 timeScale = mShapeInstance->getDuration(mActionAnimation.thread) / mDataBlock->landSequenceTime;
                  mShapeInstance->setTimeScale(mActionAnimation.thread,timeScale);
                  mRecoverDelay =  mDataBlock->landSequenceTime;
               }
               else
               {
                  // Legacy recover system
                  mRecoverTicks = recoverTicks;
                  mReversePending = U32(F32(mRecoverTicks) / sLandReverseScale);
                  setActionThread(PlayerData::LandAnim, true, false, true, true);
               }
               break;
            }
            
            default:
               break;
         }
      }

      mState = state;
   }
}

void Player::updateState()
{
   switch (mState)
   {
      case RecoverState:
         if (mDataBlock->landSequenceTime > 0.0f)
         {
            // Count down the land time
            mRecoverDelay -= TickSec;
            if (mRecoverDelay <= 0.0f)
            {
               setState(MoveState);
            }
         }
         else
         {
            // Legacy recover system
            if (mRecoverTicks-- <= 0)
            {
               if (mReversePending && mActionAnimation.action != PlayerData::NullAnimation)
               {
                  // this serves and counter, and direction state
                  mRecoverTicks = mReversePending;
                  mActionAnimation.forward = false;

                  S32 seq = mDataBlock->actionList[mActionAnimation.action].sequence;
                  S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action);
                  if (imageBasedSeq != -1)
                     seq = imageBasedSeq;

                  F32 pos = mShapeInstance->getPos(mActionAnimation.thread);

                  mShapeInstance->setTimeScale(mActionAnimation.thread, -sLandReverseScale);
                  mShapeInstance->transitionToSequence(mActionAnimation.thread,
                                                       seq, pos, sAnimationTransitionTime, true);
                  mReversePending = 0;
               }
               else
               {
                  setState(MoveState);
               }
            }        // Stand back up slowly only if not moving much-
            else if (!mReversePending && mVelocity.lenSquared() > sSlowStandThreshSquared)
            {
               mActionAnimation.waitForEnd = false;
               setState(MoveState);
            }
         }
         break;
      
      default:
         break;
   }
}

const char* Player::getStateName()
{
   if (mDamageState != Enabled)
      return "Dead";
   if (isMounted())
      return "Mounted";
   if (mState == RecoverState)
      return "Recover";
   return "Move";
}

void Player::getDamageLocation(const Point3F& in_rPos, const char *&out_rpVert, const char *&out_rpQuad)
{
   // TODO: This will be WRONG when player is prone or swimming!

   Point3F newPoint;
   mWorldToObj.mulP(in_rPos, &newPoint);

   Point3F boxSize = mObjBox.getExtents();
   F32 zHeight = boxSize.z;
   F32 zTorso  = mDataBlock->boxTorsoPercentage;
   F32 zHead   = mDataBlock->boxHeadPercentage;

   zTorso *= zHeight;
   zHead  *= zHeight;

   if (newPoint.z <= zTorso)
      out_rpVert = "legs";
   else if (newPoint.z <= zHead)
      out_rpVert = "torso";
   else
      out_rpVert = "head";

   if(dStrcmp(out_rpVert, "head") != 0)
   {
      if (newPoint.y >= 0.0f)
      {
         if (newPoint.x <= 0.0f)
            out_rpQuad = "front_left";
         else
            out_rpQuad = "front_right";
      }
      else
      {
         if (newPoint.x <= 0.0f)
            out_rpQuad = "back_left";
         else
            out_rpQuad = "back_right";
      }
   }
   else
   {
      F32 backToFront = boxSize.x;
      F32 leftToRight = boxSize.y;

      F32 backPoint  = backToFront * mDataBlock->boxHeadBackPercentage;
      F32 frontPoint = backToFront * mDataBlock->boxHeadFrontPercentage;
      F32 leftPoint  = leftToRight * mDataBlock->boxHeadLeftPercentage;
      F32 rightPoint = leftToRight * mDataBlock->boxHeadRightPercentage;

      S32 index = 0;
      if (newPoint.y < backPoint)
         index += 0;
      else if (newPoint.y >= frontPoint)
         index += 3;
      else
         index += 6;

      if (newPoint.x < leftPoint)
         index += 0;
      else if (newPoint.x >= rightPoint)
         index += 1;
      else
         index += 2;

      switch (index)
      {
         case 0: out_rpQuad = "left_back";      break;
         case 1: out_rpQuad = "middle_back";    break;
         case 2: out_rpQuad = "right_back";     break;
         case 3: out_rpQuad = "left_middle";    break;
         case 4: out_rpQuad = "middle_middle";  break;
         case 5: out_rpQuad = "right_middle";   break;
         case 6: out_rpQuad = "left_front";     break;
         case 7: out_rpQuad = "middle_front";   break;
         case 8: out_rpQuad = "right_front";    break;

         default:
            AssertFatal(0, "Bad non-tant index");
      };
   }
}

const char* Player::getPoseName() const
{
   return EngineMarshallData< PlayerPose >(getPose());
}

void Player::setPose( Pose pose )
{
   // Already the set pose, return.
   if ( pose == mPose ) 
      return;

   Pose oldPose = mPose;

   mPose = pose;

   // Not added yet, just assign the pose and return.
   if ( !isProperlyAdded() )   
      return;
        
   Point3F boxSize(1,1,1);

   // Resize the player boxes
   switch (pose) 
   {
      case StandPose:
      case SprintPose:
         boxSize = mDataBlock->boxSize;
         break;
      case CrouchPose:
         boxSize = mDataBlock->crouchBoxSize;         
         break;
      case PronePose:
         boxSize = mDataBlock->proneBoxSize;         
         break;
      case SwimPose:
         boxSize = mDataBlock->swimBoxSize;
         break;
   }

   // Object and World Boxes...
   mObjBox.maxExtents.x = boxSize.x * 0.5f;
   mObjBox.maxExtents.y = boxSize.y * 0.5f;
   mObjBox.maxExtents.z = boxSize.z;
   mObjBox.minExtents.x = -mObjBox.maxExtents.x;
   mObjBox.minExtents.y = -mObjBox.maxExtents.y;
   mObjBox.minExtents.z = 0.0f;

   resetWorldBox();

   // Setup the box for our convex object...
   mObjBox.getCenter(&mConvex.mCenter);
   mConvex.mSize.x = mObjBox.len_x() / 2.0f;
   mConvex.mSize.y = mObjBox.len_y() / 2.0f;
   mConvex.mSize.z = mObjBox.len_z() / 2.0f;

   // Initialize our scaled attributes as well...
   onScaleChanged();

   // Resize the PhysicsPlayer rep. should we have one
   if ( mPhysicsRep )
      mPhysicsRep->setSpacials( getPosition(), boxSize );

   if ( isServerObject() )
      mDataBlock->onPoseChange_callback( this, EngineMarshallData< PlayerPose >(oldPose), EngineMarshallData< PlayerPose >(mPose));
}

void Player::allowAllPoses()
{
   mAllowJumping = true;
   mAllowJetJumping = true;
   mAllowSprinting = true;
   mAllowCrouching = true;
   mAllowProne = true;
   mAllowSwimming = true;
}

void Player::updateMove(const Move* move)
{
   delta.move = *move;

   // Is waterCoverage high enough to be 'swimming'?
   {
      bool swimming = mWaterCoverage > 0.65f && canSwim();      

      if ( swimming != mSwimming )
      {
         if ( !isGhost() )
         {
            if ( swimming )
               mDataBlock->onStartSwim_callback( this );
            else
               mDataBlock->onStopSwim_callback( this );
         }

         mSwimming = swimming;
      }
   }

   // Trigger images
   if (mDamageState == Enabled) 
   {
      setImageTriggerState( 0, move->trigger[sImageTrigger0] );

      // If you have a secondary mounted image then
      // send the second trigger to it.  Else give it
      // to the first image as an alt fire.
      if ( getMountedImage( 1 ) )
         setImageTriggerState( 1, move->trigger[sImageTrigger1] );
      else
         setImageAltTriggerState( 0, move->trigger[sImageTrigger1] );
   }

   // Update current orientation
   if (mDamageState == Enabled) {
      F32 prevZRot = mRot.z;
      delta.headVec = mHead;

2535
      bool doStandardMove = true;
2536
      GameConnection* con = getControllingClient();
2537 2538 2539 2540

#ifdef TORQUE_EXTENDED_MOVE
      // Work with an absolute rotation from the ExtendedMove class?
      if(con && con->getControlSchemeAbsoluteRotation())
2541
      {
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
         doStandardMove = false;
         const ExtendedMove* emove = dynamic_cast<const ExtendedMove*>(move);
         U32 emoveIndex = smExtendedMoveHeadPosRotIndex;
         if(emoveIndex >= ExtendedMove::MaxPositionsRotations)
            emoveIndex = 0;

         if(emove->EulerBasedRotation[emoveIndex])
         {
            // Head pitch
            mHead.x += (emove->rotX[emoveIndex] - mLastAbsolutePitch);

            // Do we also include the relative yaw value?
            if(con->getControlSchemeAddPitchToAbsRot())
            {
               F32 x = move->pitch;
               if (x > M_PI_F)
                  x -= M_2PI_F;

               mHead.x += x;
            }

            // Constrain the range of mHead.x
            while (mHead.x < -M_PI_F) 
               mHead.x += M_2PI_F;
            while (mHead.x > M_PI_F) 
               mHead.x -= M_2PI_F;

            // Rotate (heading) head or body?
            if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson())))
            {
               // Rotate head
               mHead.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw);

               // Do we also include the relative yaw value?
               if(con->getControlSchemeAddYawToAbsRot())
               {
                  F32 z = move->yaw;
                  if (z > M_PI_F)
                     z -= M_2PI_F;

                  mHead.z += z;
               }

               // Constrain the range of mHead.z
               while (mHead.z < 0.0f)
                  mHead.z += M_2PI_F;
               while (mHead.z > M_2PI_F)
                  mHead.z -= M_2PI_F;
            }
            else
            {
               // Rotate body
               mRot.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw);

               // Do we also include the relative yaw value?
               if(con->getControlSchemeAddYawToAbsRot())
               {
                  F32 z = move->yaw;
                  if (z > M_PI_F)
                     z -= M_2PI_F;

                  mRot.z += z;
               }

               // Constrain the range of mRot.z
               while (mRot.z < 0.0f)
                  mRot.z += M_2PI_F;
               while (mRot.z > M_2PI_F)
                  mRot.z -= M_2PI_F;
            }
            mLastAbsoluteYaw = emove->rotZ[emoveIndex];
            mLastAbsolutePitch = emove->rotX[emoveIndex];

            // Head bank
            mHead.y = emove->rotY[emoveIndex];

            // Constrain the range of mHead.y
            while (mHead.y > M_PI_F) 
               mHead.y -= M_2PI_F;
         }
2622
      }
2623 2624 2625
#endif

      if(doStandardMove)
2626
      {
2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
         F32 p = move->pitch * (mPose == SprintPose ? mDataBlock->sprintPitchScale : 1.0f);
         if (p > M_PI_F) 
            p -= M_2PI_F;
         mHead.x = mClampF(mHead.x + p,mDataBlock->minLookAngle,
                           mDataBlock->maxLookAngle);

         F32 y = move->yaw * (mPose == SprintPose ? mDataBlock->sprintYawScale : 1.0f);
         if (y > M_PI_F)
            y -= M_2PI_F;

         if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson())))
         {
            mHead.z = mClampF(mHead.z + y,
                              -mDataBlock->maxFreelookAngle,
                              mDataBlock->maxFreelookAngle);
         }
         else
         {
            mRot.z += y;
            // Rotate the head back to the front, center horizontal
            // as well if we're controlling another object.
            mHead.z *= 0.5f;
            if (mControlObject)
               mHead.x *= 0.5f;
         }
2652

2653 2654 2655 2656 2657 2658
         // constrain the range of mRot.z
         while (mRot.z < 0.0f)
            mRot.z += M_2PI_F;
         while (mRot.z > M_2PI_F)
            mRot.z -= M_2PI_F;
      }
2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669

      delta.rot = mRot;
      delta.rotVec.x = delta.rotVec.y = 0.0f;
      delta.rotVec.z = prevZRot - mRot.z;
      if (delta.rotVec.z > M_PI_F)
         delta.rotVec.z -= M_2PI_F;
      else if (delta.rotVec.z < -M_PI_F)
         delta.rotVec.z += M_2PI_F;

      delta.head = mHead;
      delta.headVec -= mHead;
2670 2671 2672 2673 2674 2675 2676
      for(U32 i=0; i<3; ++i)
      {
         if (delta.headVec[i] > M_PI_F)
            delta.headVec[i] -= M_2PI_F;
         else if (delta.headVec[i] < -M_PI_F)
            delta.headVec[i] += M_2PI_F;
      }
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867
   }
   MatrixF zRot;
   zRot.set(EulerF(0.0f, 0.0f, mRot.z));

   // Desired move direction & speed
   VectorF moveVec;
   F32 moveSpeed;
   if ((mState == MoveState || (mState == RecoverState && mDataBlock->recoverRunForceScale > 0.0f)) && mDamageState == Enabled)
   {
      zRot.getColumn(0,&moveVec);
      moveVec *= (move->x * (mPose == SprintPose ? mDataBlock->sprintStrafeScale : 1.0f));
      VectorF tv;
      zRot.getColumn(1,&tv);
      moveVec += tv * move->y;

      // Clamp water movement
      if (move->y > 0.0f)
      {
         if ( mSwimming )
            moveSpeed = getMax(mDataBlock->maxUnderwaterForwardSpeed * move->y,
                               mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x));
         else if ( mPose == PronePose )
            moveSpeed = getMax(mDataBlock->maxProneForwardSpeed * move->y,
                               mDataBlock->maxProneSideSpeed * mFabs(move->x));
         else if ( mPose == CrouchPose )
            moveSpeed = getMax(mDataBlock->maxCrouchForwardSpeed * move->y,
                               mDataBlock->maxCrouchSideSpeed * mFabs(move->x));
         else if ( mPose == SprintPose )
            moveSpeed = getMax(mDataBlock->maxSprintForwardSpeed * move->y,
                               mDataBlock->maxSprintSideSpeed * mFabs(move->x));

         else // StandPose
            moveSpeed = getMax(mDataBlock->maxForwardSpeed * move->y,
                               mDataBlock->maxSideSpeed * mFabs(move->x));
      }
      else
      {
         if ( mSwimming )
            moveSpeed = getMax(mDataBlock->maxUnderwaterBackwardSpeed * mFabs(move->y),
                               mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x));
         else if ( mPose == PronePose )
            moveSpeed = getMax(mDataBlock->maxProneBackwardSpeed * mFabs(move->y),
                               mDataBlock->maxProneSideSpeed * mFabs(move->x));
         else if ( mPose == CrouchPose )
            moveSpeed = getMax(mDataBlock->maxCrouchBackwardSpeed * mFabs(move->y),
                               mDataBlock->maxCrouchSideSpeed * mFabs(move->x));         
         else if ( mPose == SprintPose )
            moveSpeed = getMax(mDataBlock->maxSprintBackwardSpeed * mFabs(move->y),
                               mDataBlock->maxSprintSideSpeed * mFabs(move->x));         
         else // StandPose
            moveSpeed = getMax(mDataBlock->maxBackwardSpeed * mFabs(move->y),
                               mDataBlock->maxSideSpeed * mFabs(move->x));
      }

      // Cancel any script driven animations if we are going to move.
      if (moveVec.x + moveVec.y + moveVec.z != 0.0f &&
          (mActionAnimation.action >= PlayerData::NumTableActionAnims
               || mActionAnimation.action == PlayerData::LandAnim))
         mActionAnimation.action = PlayerData::NullAnimation;
   }
   else
   {
      moveVec.set(0.0f, 0.0f, 0.0f);
      moveSpeed = 0.0f;
   }

   // Acceleration due to gravity
   VectorF acc(0.0f, 0.0f, mGravity * mGravityMod * TickSec);

   // Determine ground contact normal. Only look for contacts if
   // we can move and aren't mounted.
   VectorF contactNormal(0,0,0);
   bool jumpSurface = false, runSurface = false;
   if ( !isMounted() )
      findContact( &runSurface, &jumpSurface, &contactNormal );
   if ( jumpSurface )
      mJumpSurfaceNormal = contactNormal;
   
   // If we don't have a runSurface but we do have a contactNormal,
   // then we are standing on something that is too steep.
   // Deflect the force of gravity by the normal so we slide.
   // We could also try aligning it to the runSurface instead,
   // but this seems to work well.
   if ( !runSurface && !contactNormal.isZero() )  
      acc = ( acc - 2 * contactNormal * mDot( acc, contactNormal ) );   

   // Acceleration on run surface
   if (runSurface && !mSwimming) {
      mContactTimer = 0;

      // Remove acc into contact surface (should only be gravity)
      // Clear out floating point acc errors, this will allow
      // the player to "rest" on the ground.
      // However, no need to do that if we're using a physics library.
      // It will take care of itself.
      if (!mPhysicsRep)
      {
         F32 vd = -mDot(acc,contactNormal);
         if (vd > 0.0f) {
            VectorF dv = contactNormal * (vd + 0.002f);
            acc += dv;
            if (acc.len() < 0.0001f)
               acc.set(0.0f, 0.0f, 0.0f);
         }
      }

      // Force a 0 move if there is no energy, and only drain
      // move energy if we're moving.
      VectorF pv;
      if (mPose == SprintPose && mEnergy >= mDataBlock->minSprintEnergy) {
         if (moveSpeed)
            mEnergy -= mDataBlock->sprintEnergyDrain;
         pv = moveVec;
      }
      else if (mEnergy >= mDataBlock->minRunEnergy) {
         if (moveSpeed)
            mEnergy -= mDataBlock->runEnergyDrain;
         pv = moveVec;
      }
      else
         pv.set(0.0f, 0.0f, 0.0f);

      // Adjust the player's requested dir. to be parallel
      // to the contact surface.
      F32 pvl = pv.len();
      if(mJetting)
      {
         pvl = moveVec.len();
         if (pvl)
         {
            VectorF nn;
            mCross(pv,VectorF(0.0f, 0.0f, 0.0f),&nn);
            nn *= 1 / pvl;
            VectorF cv(0.0f, 0.0f, 0.0f);
            cv -= nn * mDot(