SHARE
TWEET

projectile.cpp

a guest Jul 27th, 2016 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22.  
  23. #include "platform/platform.h"
  24. #include "T3D/projectile.h"
  25.  
  26. #include "scene/sceneRenderState.h"
  27. #include "scene/sceneManager.h"
  28. #include "lighting/lightInfo.h"
  29. #include "lighting/lightManager.h"
  30. #include "console/consoleTypes.h"
  31. #include "console/typeValidators.h"
  32. #include "core/resourceManager.h"
  33. #include "core/stream/bitStream.h"
  34. #include "T3D/fx/explosion.h"
  35. #include "T3D/shapeBase.h"
  36. #include "ts/tsShapeInstance.h"
  37. #include "sfx/sfxTrack.h"
  38. #include "sfx/sfxSource.h"
  39. #include "sfx/sfxSystem.h"
  40. #include "sfx/sfxTypes.h"
  41. #include "math/mathUtils.h"
  42. #include "math/mathIO.h"
  43. #include "sim/netConnection.h"
  44. #include "T3D/fx/particleEmitter.h"
  45. #include "T3D/fx/splash.h"
  46. #include "T3D/physics/physicsPlugin.h"
  47. #include "T3D/physics/physicsWorld.h"
  48. #include "gfx/gfxTransformSaver.h"
  49. #include "T3D/containerQuery.h"
  50. #include "T3D/decal/decalManager.h"
  51. #include "T3D/decal/decalData.h"
  52. #include "T3D/lightDescription.h"
  53. #include "console/engineAPI.h"
  54.  
  55.  
  56. IMPLEMENT_CO_DATABLOCK_V1(ProjectileData);
  57.  
  58. ConsoleDocClass( ProjectileData,
  59.    "@brief Stores properties for an individual projectile type.\n"
  60.  
  61.    "@tsexample\n"
  62.         "datablock ProjectileData(GrenadeLauncherProjectile)\n"
  63.         "{\n"
  64.           " projectileShapeName = \"art/shapes/weapons/SwarmGun/rocket.dts\";\n"
  65.            "directDamage = 30;\n"
  66.            "radiusDamage = 30;\n"
  67.            "damageRadius = 5;\n"
  68.            "areaImpulse = 2000;\n"
  69.  
  70.            "explosion = GrenadeLauncherExplosion;\n"
  71.            "waterExplosion = GrenadeLauncherWaterExplosion;\n"
  72.  
  73.            "decal = ScorchRXDecal;\n"
  74.            "splash = GrenadeSplash;\n"
  75.  
  76.            "particleEmitter = GrenadeProjSmokeTrailEmitter;\n"
  77.            "particleWaterEmitter = GrenadeTrailWaterEmitter;\n"
  78.  
  79.            "muzzleVelocity = 30;\n"
  80.            "velInheritFactor = 0.3;\n"
  81.  
  82.            "armingDelay = 2000;\n"
  83.            "lifetime = 10000;\n"
  84.            "fadeDelay = 4500;\n"
  85.  
  86.            "bounceElasticity = 0.4;\n"
  87.            "bounceFriction = 0.3;\n"
  88.            "isBallistic = true;\n"
  89.            "gravityMod = 0.9;\n"
  90.  
  91.            "lightDesc = GrenadeLauncherLightDesc;\n"
  92.  
  93.            "damageType = \"GrenadeDamage\";\n"
  94.         "};\n"
  95.    "@endtsexample\n"
  96.  
  97.    "@ingroup gameObjects\n"
  98. );
  99.  
  100. IMPLEMENT_CO_NETOBJECT_V1(Projectile);
  101.  
  102. ConsoleDocClass( Projectile,
  103.    "@brief Base projectile class. Uses the ProjectileData class for properties of individual projectiles.\n"
  104.    "@ingroup gameObjects\n"
  105. );
  106.  
  107. IMPLEMENT_CALLBACK( ProjectileData, onExplode, void, ( Projectile* proj, Point3F pos, F32 fade ),
  108.                    ( proj, pos, fade ),
  109.                    "@brief Called when a projectile explodes.\n\n"
  110.                    "This function is only called on server objects.\n"
  111.                    "@param proj The exploding projectile.\n"
  112.                    "@param pos The position of the explosion.\n"
  113.                    "@param fade The current fadeValue of the projectile, affects its visibility.\n\n"
  114.                    "@see Projectile\n"
  115.                   );
  116.  
  117. IMPLEMENT_CALLBACK( ProjectileData, onCollision, void, ( Projectile* proj, SceneObject* col, F32 fade, Point3F pos, Point3F normal ),
  118.                    ( proj, col, fade, pos, normal ),
  119.                    "@brief Called when a projectile collides with another object.\n\n"
  120.                    "This function is only called on server objects."
  121.                    "@param proj The projectile colliding with SceneObject col.\n"
  122.                    "@param col The SceneObject hit by the projectile.\n"
  123.                    "@param fade The current fadeValue of the projectile, affects its visibility.\n"
  124.                    "@param pos The position of the collision.\n"
  125.                    "@param normal The normal of the collision.\n"
  126.                    "@see Projectile\n"
  127.                   );
  128.  
  129. const U32 Projectile::csmStaticCollisionMask =  TerrainObjectType | StaticShapeObjectType;
  130.  
  131. const U32 Projectile::csmDynamicCollisionMask = PlayerObjectType | VehicleObjectType;
  132.  
  133. const U32 Projectile::csmDamageableMask = Projectile::csmDynamicCollisionMask;
  134.  
  135. U32 Projectile::smProjectileWarpTicks = 5;
  136.  
  137.  
  138. //--------------------------------------------------------------------------
  139. //
  140. ProjectileData::ProjectileData()
  141. {
  142.    projectileShapeName = NULL;
  143.  
  144.    sound = NULL;
  145.  
  146.    explosion = NULL;
  147.    explosionId = 0;
  148.  
  149.    waterExplosion = NULL;
  150.    waterExplosionId = 0;
  151.  
  152.    //hasLight = false;
  153.    //lightRadius = 1;
  154.    //lightColor.set(1, 1, 1);
  155.    lightDesc = NULL;
  156.  
  157.    faceViewer = false;
  158.    scale.set( 1.0f, 1.0f, 1.0f );
  159.  
  160.    isBallistic = false;
  161.  
  162.     velInheritFactor = 1.0f;
  163.     muzzleVelocity = 50;
  164.    impactForce = 0.0f;
  165.  
  166.     armingDelay = 0;
  167.    fadeDelay = 20000 / 32;
  168.    lifetime = 20000 / 32;
  169.  
  170.    activateSeq = -1;
  171.    maintainSeq = -1;
  172.  
  173.    gravityMod = 1.0;
  174.    bounceElasticity = 0.999f;
  175.    bounceFriction = 0.3f;
  176.  
  177.    particleEmitter = NULL;
  178.    particleEmitterId = 0;
  179.  
  180.    particleWaterEmitter = NULL;
  181.    particleWaterEmitterId = 0;
  182.  
  183.    splash = NULL;
  184.    splashId = 0;
  185.  
  186.    decal = NULL;
  187.    decalId = 0;
  188.  
  189.    lightDesc = NULL;
  190.    lightDescId = 0;
  191. }
  192.  
  193. //--------------------------------------------------------------------------
  194.  
  195. void ProjectileData::initPersistFields()
  196. {
  197.    addField("particleEmitter", TYPEID< ParticleEmitterData >(), Offset(particleEmitter, ProjectileData),
  198.       "@brief Particle emitter datablock used to generate particles while the projectile is outside of water.\n\n"
  199.       "@note If datablocks are defined for both particleEmitter and particleWaterEmitter, both effects will play "
  200.       "as the projectile enters or leaves water.\n\n"
  201.       "@see particleWaterEmitter\n");
  202.    addField("particleWaterEmitter", TYPEID< ParticleEmitterData >(), Offset(particleWaterEmitter, ProjectileData),
  203.       "@brief Particle emitter datablock used to generate particles while the projectile is submerged in water.\n\n"
  204.       "@note If datablocks are defined for both particleWaterEmitter and particleEmitter , both effects will play "
  205.       "as the projectile enters or leaves water.\n\n"
  206.       "@see particleEmitter\n");
  207.  
  208.    addField("projectileShapeName", TypeShapeFilename, Offset(projectileShapeName, ProjectileData),
  209.       "@brief File path to the model of the projectile.\n\n");
  210.    addField("scale", TypePoint3F, Offset(scale, ProjectileData),
  211.       "@brief Scale to apply to the projectile's size.\n\n"
  212.       "@note This is applied after SceneObject::scale\n");
  213.  
  214.    addField("sound", TypeSFXTrackName, Offset(sound, ProjectileData),
  215.       "@brief SFXTrack datablock used to play sounds while in flight.\n\n");
  216.  
  217.    addField("explosion", TYPEID< ExplosionData >(), Offset(explosion, ProjectileData),
  218.       "@brief Explosion datablock used when the projectile explodes outside of water.\n\n");
  219.    addField("waterExplosion", TYPEID< ExplosionData >(), Offset(waterExplosion, ProjectileData),
  220.       "@brief Explosion datablock used when the projectile explodes underwater.\n\n");
  221.  
  222.    addField("splash", TYPEID< SplashData >(), Offset(splash, ProjectileData),
  223.       "@brief Splash datablock used to create splash effects as the projectile enters or leaves water\n\n");
  224.  
  225.    addField("decal", TYPEID< DecalData >(), Offset(decal, ProjectileData),
  226.       "@brief Decal datablock used for decals placed at projectile explosion points.\n\n");
  227.  
  228.    addField("lightDesc", TYPEID< LightDescription >(), Offset(lightDesc, ProjectileData),
  229.       "@brief LightDescription datablock used for lights attached to the projectile.\n\n");
  230.  
  231.    addField("isBallistic", TypeBool, Offset(isBallistic, ProjectileData),
  232.       "@brief Detetmines if the projectile should be affected by gravity and whether or not "
  233.       "it bounces before exploding.\n\n");
  234.  
  235.    addField("velInheritFactor", TypeF32, Offset(velInheritFactor, ProjectileData),
  236.       "@brief Amount of velocity the projectile recieves from the source that created it.\n\n"
  237.       "Use an amount between 0 and 1 for the best effect. "
  238.       "This value is never modified by the engine.\n"
  239.       "@note This value by default is not transmitted between the server and the client.");
  240.    addField("muzzleVelocity", TypeF32, Offset(muzzleVelocity, ProjectileData),
  241.       "@brief Amount of velocity the projectile recieves from the \"muzzle\" of the gun.\n\n"
  242.       "Used with velInheritFactor to determine the initial velocity of the projectile. "
  243.       "This value is never modified by the engine.\n\n"
  244.       "@note This value by default is not transmitted between the server and the client.\n\n"
  245.       "@see velInheritFactor");
  246.    
  247.    addField("impactForce", TypeF32, Offset(impactForce, ProjectileData));
  248.  
  249.    addProtectedField("lifetime", TypeS32, Offset(lifetime, ProjectileData), &setLifetime, &getScaledValue,
  250.       "@brief Amount of time, in milliseconds, before the projectile is removed from the simulation.\n\n"
  251.       "Used with fadeDelay to determine the transparency of the projectile at a given time. "
  252.       "A projectile may exist up to a maximum of 131040ms (or 4095 ticks) as defined by Projectile::MaxLivingTicks in the source code."
  253.       "@see fadeDelay");
  254.  
  255.    addProtectedField("armingDelay", TypeS32, Offset(armingDelay, ProjectileData), &setArmingDelay, &getScaledValue,
  256.       "@brief Amount of time, in milliseconds, before the projectile will cause damage or explode on impact.\n\n"
  257.       "This value must be equal to or less than the projectile's lifetime.\n\n"
  258.       "@see lifetime");
  259.    addProtectedField("fadeDelay", TypeS32, Offset(fadeDelay, ProjectileData), &setFadeDelay, &getScaledValue,
  260.       "@brief Amount of time, in milliseconds, before the projectile begins to fade out.\n\n"
  261.       "This value must be smaller than the projectile's lifetime to have an affect.");
  262.  
  263.    addField("bounceElasticity", TypeF32, Offset(bounceElasticity, ProjectileData),
  264.       "@brief Influences post-bounce velocity of a projectile that does not explode on contact.\n\n"
  265.       "Scales the velocity from a bounce after friction is taken into account. "
  266.       "A value of 1.0 will leave it's velocity unchanged while values greater than 1.0 will increase it.\n");
  267.    addField("bounceFriction", TypeF32, Offset(bounceFriction, ProjectileData),
  268.       "@brief Factor to reduce post-bounce velocity of a projectile that does not explode on contact.\n\n"
  269.       "Reduces bounce velocity by this factor and a multiple of the tangent to impact. "
  270.       "Used to simulate surface friction.\n");
  271.    addField("gravityMod", TypeF32, Offset(gravityMod, ProjectileData ),
  272.       "@brief Scales the influence of gravity on the projectile.\n\n"
  273.       "The larger this value is, the more that gravity will affect the projectile. "
  274.       "A value of 1.0 will assume \"normal\" influence upon it.\n"
  275.       "The magnitude of gravity is assumed to be 9.81 m/s/s\n\n"
  276.       "@note ProjectileData::isBallistic must be true for this to have any affect.");
  277.  
  278.    Parent::initPersistFields();
  279. }
  280.  
  281.  
  282. //--------------------------------------------------------------------------
  283. bool ProjectileData::onAdd()
  284. {
  285.    if(!Parent::onAdd())
  286.       return false;
  287.  
  288.    return true;
  289. }
  290.  
  291.  
  292. bool ProjectileData::preload(bool server, String &errorStr)
  293. {
  294.    if (Parent::preload(server, errorStr) == false)
  295.       return false;
  296.      
  297.    if( !server )
  298.    {
  299.       if (!particleEmitter && particleEmitterId != 0)
  300.          if (Sim::findObject(particleEmitterId, particleEmitter) == false)
  301.             Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(particleEmitter): %d", particleEmitterId);
  302.  
  303.       if (!particleWaterEmitter && particleWaterEmitterId != 0)
  304.          if (Sim::findObject(particleWaterEmitterId, particleWaterEmitter) == false)
  305.             Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(particleWaterEmitter): %d", particleWaterEmitterId);
  306.  
  307.       if (!explosion && explosionId != 0)
  308.          if (Sim::findObject(explosionId, explosion) == false)
  309.             Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(explosion): %d", explosionId);
  310.  
  311.       if (!waterExplosion && waterExplosionId != 0)
  312.          if (Sim::findObject(waterExplosionId, waterExplosion) == false)
  313.             Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(waterExplosion): %d", waterExplosionId);
  314.  
  315.       if (!splash && splashId != 0)
  316.          if (Sim::findObject(splashId, splash) == false)
  317.             Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(splash): %d", splashId);
  318.  
  319.       if (!decal && decalId != 0)
  320.          if (Sim::findObject(decalId, decal) == false)
  321.             Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(decal): %d", decalId);
  322.  
  323.       String sfxErrorStr;
  324.       if( !sfxResolve( &sound, sfxErrorStr ) )
  325.          Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet: %s", sfxErrorStr.c_str());
  326.  
  327.       if (!lightDesc && lightDescId != 0)
  328.          if (Sim::findObject(lightDescId, lightDesc) == false)
  329.             Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockid(lightDesc): %d", lightDescId);  
  330.    }
  331.  
  332.    if (projectileShapeName && projectileShapeName[0] != '\0')
  333.    {
  334.       projectileShape = ResourceManager::get().load(projectileShapeName);
  335.       if (bool(projectileShape) == false)
  336.       {
  337.          errorStr = String::ToString("ProjectileData::load: Couldn't load shape \"%s\"", projectileShapeName);
  338.          return false;
  339.       }
  340.       activateSeq = projectileShape->findSequence("activate");
  341.       maintainSeq = projectileShape->findSequence("maintain");
  342.    }
  343.  
  344.    if (bool(projectileShape)) // create an instance to preload shape data
  345.    {
  346.       TSShapeInstance* pDummy = new TSShapeInstance(projectileShape, !server);
  347.       delete pDummy;
  348.    }
  349.  
  350.    return true;
  351. }
  352.  
  353. //--------------------------------------------------------------------------
  354. void ProjectileData::packData(BitStream* stream)
  355. {
  356.    Parent::packData(stream);
  357.  
  358.    stream->writeString(projectileShapeName);
  359.    stream->writeFlag(faceViewer);
  360.    if(stream->writeFlag(scale.x != 1 || scale.y != 1 || scale.z != 1))
  361.    {
  362.       stream->write(scale.x);
  363.       stream->write(scale.y);
  364.       stream->write(scale.z);
  365.    }
  366.  
  367.    if (stream->writeFlag(particleEmitter != NULL))
  368.       stream->writeRangedU32(particleEmitter->getId(), DataBlockObjectIdFirst,
  369.                                                    DataBlockObjectIdLast);
  370.  
  371.    if (stream->writeFlag(particleWaterEmitter != NULL))
  372.       stream->writeRangedU32(particleWaterEmitter->getId(), DataBlockObjectIdFirst,
  373.                                                    DataBlockObjectIdLast);
  374.  
  375.    if (stream->writeFlag(explosion != NULL))
  376.       stream->writeRangedU32(explosion->getId(), DataBlockObjectIdFirst,
  377.                                                  DataBlockObjectIdLast);
  378.  
  379.    if (stream->writeFlag(waterExplosion != NULL))
  380.       stream->writeRangedU32(waterExplosion->getId(), DataBlockObjectIdFirst,
  381.                                                       DataBlockObjectIdLast);
  382.  
  383.    if (stream->writeFlag(splash != NULL))
  384.       stream->writeRangedU32(splash->getId(), DataBlockObjectIdFirst,
  385.                                               DataBlockObjectIdLast);
  386.  
  387.    if (stream->writeFlag(decal != NULL))
  388.       stream->writeRangedU32(decal->getId(), DataBlockObjectIdFirst,
  389.                                               DataBlockObjectIdLast);
  390.  
  391.    sfxWrite( stream, sound );
  392.  
  393.    if ( stream->writeFlag(lightDesc != NULL))
  394.       stream->writeRangedU32(lightDesc->getId(), DataBlockObjectIdFirst,
  395.                                                  DataBlockObjectIdLast);
  396.  
  397.    stream->write(impactForce);
  398.    
  399. //    stream->writeRangedU32(lifetime, 0, Projectile::MaxLivingTicks);
  400. //    stream->writeRangedU32(armingDelay, 0, Projectile::MaxLivingTicks);
  401. //    stream->writeRangedU32(fadeDelay, 0, Projectile::MaxLivingTicks);
  402.  
  403.    // [tom, 3/21/2007] Changing these to write all 32 bits as the previous
  404.    // code limited these to a max value of 4095.
  405.    stream->write(lifetime);
  406.    stream->write(armingDelay);
  407.    stream->write(fadeDelay);
  408.  
  409.    if(stream->writeFlag(isBallistic))
  410.    {
  411.       stream->write(gravityMod);
  412.       stream->write(bounceElasticity);
  413.       stream->write(bounceFriction);
  414.    }
  415.  
  416. }
  417.  
  418. void ProjectileData::unpackData(BitStream* stream)
  419. {
  420.    Parent::unpackData(stream);
  421.  
  422.    projectileShapeName = stream->readSTString();
  423.  
  424.    faceViewer = stream->readFlag();
  425.    if(stream->readFlag())
  426.    {
  427.       stream->read(&scale.x);
  428.       stream->read(&scale.y);
  429.       stream->read(&scale.z);
  430.    }
  431.    else
  432.       scale.set(1,1,1);
  433.  
  434.    if (stream->readFlag())
  435.       particleEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  436.  
  437.    if (stream->readFlag())
  438.       particleWaterEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  439.  
  440.    if (stream->readFlag())
  441.       explosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  442.  
  443.    if (stream->readFlag())
  444.       waterExplosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  445.    
  446.    if (stream->readFlag())
  447.       splashId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  448.  
  449.    if (stream->readFlag())
  450.       decalId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  451.    
  452.    sfxRead( stream, &sound );
  453.  
  454.    if (stream->readFlag())
  455.       lightDescId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  456.    
  457.    // [tom, 3/21/2007] See comment in packData()
  458. //    lifetime = stream->readRangedU32(0, Projectile::MaxLivingTicks);
  459. //    armingDelay = stream->readRangedU32(0, Projectile::MaxLivingTicks);
  460. //    fadeDelay = stream->readRangedU32(0, Projectile::MaxLivingTicks);
  461.  
  462.    stream->read(&impactForce);
  463.  
  464.    stream->read(&lifetime);
  465.    stream->read(&armingDelay);
  466.    stream->read(&fadeDelay);
  467.  
  468.    isBallistic = stream->readFlag();
  469.    if(isBallistic)
  470.    {
  471.       stream->read(&gravityMod);
  472.       stream->read(&bounceElasticity);
  473.       stream->read(&bounceFriction);
  474.    }
  475. }
  476.  
  477. bool ProjectileData::setLifetime( void *obj, const char *index, const char *data )
  478. {
  479.     S32 value = dAtoi(data);
  480.    value = scaleValue(value);
  481.    
  482.    ProjectileData *object = static_cast<ProjectileData*>(obj);
  483.    object->lifetime = value;
  484.  
  485.    return false;
  486. }
  487.  
  488. bool ProjectileData::setArmingDelay( void *obj, const char *index, const char *data )
  489. {
  490.     S32 value = dAtoi(data);
  491.    value = scaleValue(value);
  492.  
  493.    ProjectileData *object = static_cast<ProjectileData*>(obj);
  494.    object->armingDelay = value;
  495.  
  496.    return false;
  497. }
  498.  
  499. bool ProjectileData::setFadeDelay( void *obj, const char *index, const char *data )
  500. {
  501.     S32 value = dAtoi(data);
  502.    value = scaleValue(value);
  503.  
  504.    ProjectileData *object = static_cast<ProjectileData*>(obj);
  505.    object->fadeDelay = value;
  506.  
  507.    return false;
  508. }
  509.  
  510. const char *ProjectileData::getScaledValue( void *obj, const char *data)
  511. {
  512.  
  513.     S32 value = dAtoi(data);
  514.    value = scaleValue(value, false);
  515.  
  516.    String stringData = String::ToString(value);
  517.    char *strBuffer = Con::getReturnBuffer(stringData.size());
  518.    dMemcpy( strBuffer, stringData, stringData.size() );
  519.  
  520.    return strBuffer;
  521. }
  522.  
  523. S32 ProjectileData::scaleValue( S32 value, bool down )
  524. {
  525.    S32 minV = 0;
  526.    S32 maxV = Projectile::MaxLivingTicks;
  527.    
  528.    // scale down to ticks before we validate
  529.    if( down )
  530.       value /= TickMs;
  531.    
  532.    if(value < minV || value > maxV)
  533.     {
  534.       Con::errorf("ProjectileData::scaleValue(S32 value = %d, bool down = %b) - Scaled value must be between %d and %d", value, down, minV, maxV);
  535.         if(value < minV)
  536.             value = minV;
  537.         else if(value > maxV)
  538.             value = maxV;
  539.     }
  540.  
  541.    // scale up from ticks after we validate
  542.    if( !down )
  543.       value *= TickMs;
  544.  
  545.    return value;
  546. }
  547.  
  548. //--------------------------------------------------------------------------
  549. //--------------------------------------
  550. //
  551. Projectile::Projectile()
  552.  : mPhysicsWorld( NULL ),
  553.    mDataBlock( NULL ),
  554.    mCurrPosition( 0, 0, 0 ),
  555.    mCurrVelocity( 0, 0, 1 ),
  556.    mSourceObjectId( -1 ),
  557.    mSourceObjectSlot( -1 ),
  558.    mCurrTick( 0 ),
  559.    mParticleEmitter( NULL ),
  560.    mParticleWaterEmitter( NULL ),
  561.    mSound( NULL ),
  562.    mProjectileShape( NULL ),
  563.    mActivateThread( NULL ),
  564.    mMaintainThread( NULL ),
  565.    mHasExploded( false ),
  566.    mFadeValue( 1.0f )
  567. {
  568.    // Todo: ScopeAlways?
  569.    mNetFlags.set(Ghostable);
  570.    mTypeMask |= ProjectileObjectType | LightObjectType | DynamicShapeObjectType;
  571.  
  572.    mLight = LightManager::createLightInfo();
  573.    mLight->setType( LightInfo::Point );  
  574.  
  575.    mLightState.clear();
  576.    mLightState.setLightInfo( mLight );
  577. }
  578.  
  579. Projectile::~Projectile()
  580. {
  581.    SAFE_DELETE(mLight);
  582.  
  583.    delete mProjectileShape;
  584.    mProjectileShape = NULL;
  585. }
  586.  
  587. //--------------------------------------------------------------------------
  588. void Projectile::initPersistFields()
  589. {
  590.    addGroup("Physics");
  591.  
  592.    addProtectedField("initialPosition",  TypePoint3F, Offset(mInitialPosition, Projectile), &_setInitialPosition, &defaultProtectedGetFn,
  593.       "@brief Starting position for the projectile.\n\n");
  594.    //addField("initialPosition",  TypePoint3F, Offset(mCurrPosition, Projectile),
  595.    //   "@brief Starting position for the projectile.\n\n");
  596.    addProtectedField("initialVelocity", TypePoint3F, Offset(mInitialVelocity, Projectile), &_setInitialVelocity, &defaultProtectedGetFn,
  597.       "@brief Starting velocity for the projectile.\n\n");
  598.    //addField("initialVelocity", TypePoint3F, Offset(mCurrVelocity, Projectile),
  599.    //   "@brief Starting velocity for the projectile.\n\n");
  600.  
  601.    endGroup("Physics");
  602.  
  603.    addGroup("Source");
  604.  
  605.    addField("sourceObject",     TypeS32,     Offset(mSourceObjectId, Projectile),
  606.       "@brief ID number of the object that fired the projectile.\n\n"
  607.       "@note If the projectile was fired by a WeaponImage, sourceObject will be "
  608.       "the object that owns the WeaponImage. This is usually the player.");
  609.    addField("sourceSlot",       TypeS32,     Offset(mSourceObjectSlot, Projectile),
  610.       "@brief The sourceObject's weapon slot that the projectile originates from.\n\n");
  611.  
  612.    endGroup("Source");
  613.  
  614.  
  615.    Parent::initPersistFields();
  616. }
  617.  
  618. bool Projectile::_setInitialPosition( void *object, const char *index, const char *data )
  619. {
  620.    Projectile* p = static_cast<Projectile*>( object );
  621.    if ( p )
  622.    {
  623.        Point3F pos;
  624.  
  625.        S32 count = dSscanf( data, "%f %f %f",
  626.            &pos.x, &pos.y, &pos.z);
  627.    
  628.        if ( (count != 3) )
  629.       {
  630.          Con::printf("Projectile: Failed to parse initial position \"px py pz\" from '%s'", data);
  631.          return false;
  632.       }
  633.  
  634.       p->setInitialPosition( pos );
  635.    }
  636.    return false;
  637. }
  638.  
  639. void Projectile::setInitialPosition( const Point3F& pos )
  640. {
  641.    mInitialPosition = pos;
  642.    mCurrPosition = pos;
  643. }
  644.  
  645. bool Projectile::_setInitialVelocity( void *object, const char *index, const char *data )
  646. {
  647.    Projectile* p = static_cast<Projectile*>( object );
  648.    if ( p )
  649.    {
  650.        Point3F vel;
  651.  
  652.        S32 count = dSscanf( data, "%f %f %f",
  653.            &vel.x, &vel.y, &vel.z);
  654.    
  655.        if ( (count != 3) )
  656.       {
  657.          Con::printf("Projectile: Failed to parse initial velocity \"vx vy vz\" from '%s'", data);
  658.          return false;
  659.       }
  660.  
  661.       p->setInitialVelocity( vel );
  662.    }
  663.    return false;
  664. }
  665.  
  666. void Projectile::setInitialVelocity( const Point3F& vel )
  667. {
  668.    mInitialVelocity = vel;
  669.    mCurrVelocity = vel;
  670. }
  671.  
  672. //--------------------------------------------------------------------------
  673.  
  674. bool Projectile::calculateImpact(float,
  675.                                  Point3F& pointOfImpact,
  676.                                  float&   impactTime)
  677. {
  678.    Con::warnf(ConsoleLogEntry::General, "Projectile::calculateImpact: Should never be called");
  679.  
  680.    impactTime = 0;
  681.    pointOfImpact.set(0, 0, 0);
  682.    return false;
  683. }
  684.  
  685.  
  686. //--------------------------------------------------------------------------
  687. F32 Projectile::getUpdatePriority(CameraScopeQuery *camInfo, U32 updateMask, S32 updateSkips)
  688. {
  689.    F32 ret = Parent::getUpdatePriority(camInfo, updateMask, updateSkips);
  690.    // if the camera "owns" this object, it should have a slightly higher priority
  691.    if(mSourceObject == camInfo->camera)
  692.       return ret + 0.2;
  693.    return ret;
  694. }
  695.  
  696. bool Projectile::onAdd()
  697. {
  698.    if(!Parent::onAdd())
  699.       return false;
  700.  
  701.    if( !mDataBlock )
  702.    {
  703.       Con::errorf("Projectile::onAdd - Fail - Not datablock");
  704.       return false;
  705.    }
  706.  
  707.    if (isServerObject())
  708.    {
  709.       ShapeBase* ptr;
  710.       if (Sim::findObject(mSourceObjectId, ptr))
  711.       {
  712.          mSourceObject = ptr;
  713.  
  714.          // Since we later do processAfter( mSourceObject ) we must clearProcessAfter
  715.          // if it is deleted. SceneObject already handles this in onDeleteNotify so
  716.          // all we need to do is register for the notification.
  717.          deleteNotify( ptr );
  718.       }
  719.       else
  720.       {
  721.          if (mSourceObjectId != -1)
  722.             Con::errorf(ConsoleLogEntry::General, "Projectile::onAdd: mSourceObjectId is invalid");
  723.          mSourceObject = NULL;
  724.       }
  725.  
  726.       // If we're on the server, we need to inherit some of our parent's velocity
  727.       //
  728.       mCurrTick = 0;
  729.    }
  730.    else
  731.    {
  732.       if (bool(mDataBlock->projectileShape))
  733.       {
  734.          mProjectileShape = new TSShapeInstance(mDataBlock->projectileShape, isClientObject());
  735.  
  736.          if (mDataBlock->activateSeq != -1)
  737.          {
  738.             mActivateThread = mProjectileShape->addThread();
  739.             mProjectileShape->setTimeScale(mActivateThread, 1);
  740.             mProjectileShape->setSequence(mActivateThread, mDataBlock->activateSeq, 0);
  741.          }
  742.       }
  743.       if (mDataBlock->particleEmitter != NULL)
  744.       {
  745.          ParticleEmitter* pEmitter = new ParticleEmitter;
  746.          pEmitter->onNewDataBlock(mDataBlock->particleEmitter,false);
  747.          if (pEmitter->registerObject() == false)
  748.          {
  749.             Con::warnf(ConsoleLogEntry::General, "Could not register particle emitter for particle of class: %s", mDataBlock->getName());
  750.             delete pEmitter;
  751.             pEmitter = NULL;
  752.          }
  753.          mParticleEmitter = pEmitter;
  754.       }
  755.  
  756.       if (mDataBlock->particleWaterEmitter != NULL)
  757.       {
  758.          ParticleEmitter* pEmitter = new ParticleEmitter;
  759.          pEmitter->onNewDataBlock(mDataBlock->particleWaterEmitter,false);
  760.          if (pEmitter->registerObject() == false)
  761.          {
  762.             Con::warnf(ConsoleLogEntry::General, "Could not register particle emitter for particle of class: %s", mDataBlock->getName());
  763.             delete pEmitter;
  764.             pEmitter = NULL;
  765.          }
  766.          mParticleWaterEmitter = pEmitter;
  767.       }
  768.    }
  769.    if (mSourceObject.isValid())
  770.       processAfter(mSourceObject);
  771.  
  772.    // Setup our bounding box
  773.    if (bool(mDataBlock->projectileShape) == true)
  774.       mObjBox = mDataBlock->projectileShape->bounds;
  775.    else
  776.       mObjBox = Box3F(Point3F(0, 0, 0), Point3F(0, 0, 0));
  777.  
  778.    MatrixF initialTransform( true );
  779.    initialTransform.setPosition( mCurrPosition );
  780.    setTransform( initialTransform );   // calls resetWorldBox
  781.  
  782.    addToScene();
  783.  
  784.    if ( PHYSICSMGR )
  785.       mPhysicsWorld = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  786.  
  787.    return true;
  788. }
  789.  
  790.  
  791. void Projectile::onRemove()
  792. {
  793.    if( !mParticleEmitter.isNull() )
  794.    {
  795.       mParticleEmitter->deleteWhenEmpty();
  796.       mParticleEmitter = NULL;
  797.    }
  798.  
  799.    if( !mParticleWaterEmitter.isNull() )
  800.    {
  801.       mParticleWaterEmitter->deleteWhenEmpty();
  802.       mParticleWaterEmitter = NULL;
  803.    }
  804.  
  805.    SFX_DELETE( mSound );
  806.  
  807.    removeFromScene();
  808.    Parent::onRemove();
  809. }
  810.  
  811.  
  812. bool Projectile::onNewDataBlock( GameBaseData *dptr, bool reload )
  813. {
  814.    mDataBlock = dynamic_cast<ProjectileData*>( dptr );
  815.    if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  816.       return false;
  817.  
  818.    if ( isGhost() )
  819.    {
  820.       // Create the sound ahead of time.  This reduces runtime
  821.       // costs and makes the system easier to understand.
  822.  
  823.       SFX_DELETE( mSound );
  824.  
  825.       if ( mDataBlock->sound )
  826.          mSound = SFX->createSource( mDataBlock->sound );
  827.    }
  828.  
  829.    return true;
  830. }
  831.  
  832. void Projectile::submitLights( LightManager *lm, bool staticLighting )
  833. {
  834.    if ( staticLighting || mHasExploded || !mDataBlock->lightDesc )
  835.       return;
  836.    
  837.    mDataBlock->lightDesc->submitLight( &mLightState, getRenderTransform(), lm, this );  
  838. }
  839.  
  840. bool Projectile::pointInWater(const Point3F &point)
  841. {  
  842.    // This is pretty much a hack so we can use the existing ContainerQueryInfo
  843.    // and findObject router.
  844.    
  845.    // We only care if we intersect with water at all
  846.    // so build a box at the point that has only 1 z extent.
  847.    // And test if water coverage is anything other than zero.
  848.  
  849.    Box3F boundsBox( point, point );
  850.    boundsBox.maxExtents.z += 1.0f;
  851.  
  852.    ContainerQueryInfo info;
  853.    info.box = boundsBox;
  854.    info.mass = 0.0f;
  855.    
  856.    // Find and retreive physics info from intersecting WaterObject(s)
  857.    if(mContainer != NULL)
  858.    {
  859.       mContainer->findObjects( boundsBox, WaterObjectType, findRouter, &info );
  860.    }
  861.    else
  862.    {
  863.       // Handle special case where the projectile has exploded prior to having
  864.       // called onAdd() on the client.  This occurs when the projectile on the
  865.       // server is created and then explodes in the same network update tick.
  866.       // On the client end in NetConnection::ghostReadPacket() the ghost is
  867.       // created and then Projectile::unpackUpdate() is called prior to the
  868.       // projectile being registered.  Within unpackUpdate() the explosion
  869.       // is triggered, but without being registered onAdd() isn't called and
  870.       // the container is not set.  As all we're doing is checking if the
  871.       // given explosion point is within water, we should be able to use the
  872.       // global container here.  We could likely always get away with this,
  873.       // but using the actual defined container when possible is the right
  874.       // thing to do.  DAW
  875.       AssertFatal(isClientObject(), "Server projectile has not been properly added");
  876.       gClientContainer.findObjects( boundsBox, WaterObjectType, findRouter, &info );
  877.    }
  878.  
  879.    return ( info.waterCoverage > 0.0f );
  880. }
  881.  
  882. //----------------------------------------------------------------------------
  883.  
  884. void Projectile::emitParticles(const Point3F& from, const Point3F& to, const Point3F& vel, const U32 ms)
  885. {
  886.    if ( mHasExploded )
  887.       return;
  888.  
  889.    Point3F axis = -vel;
  890.  
  891.    if( axis.isZero() )
  892.       axis.set( 0.0, 0.0, 1.0 );
  893.    else
  894.       axis.normalize();
  895.  
  896.    bool fromWater = pointInWater(from);
  897.    bool toWater   = pointInWater(to);
  898.  
  899.    if (!fromWater && !toWater && bool(mParticleEmitter))                                        // not in water
  900.       mParticleEmitter->emitParticles(from, to, axis, vel, ms);
  901.    else if (fromWater && toWater && bool(mParticleWaterEmitter))                                // in water
  902.       mParticleWaterEmitter->emitParticles(from, to, axis, vel, ms);
  903.    else if (!fromWater && toWater && mDataBlock->splash)     // entering water
  904.    {
  905.       // cast the ray to get the surface point of the water
  906.       RayInfo rInfo;
  907.       if (gClientContainer.castRay(from, to, WaterObjectType, &rInfo))
  908.       {
  909.          MatrixF trans = getTransform();
  910.          trans.setPosition(rInfo.point);
  911.  
  912.          Splash *splash = new Splash();
  913.          splash->onNewDataBlock(mDataBlock->splash, false);
  914.          splash->setTransform(trans);
  915.          splash->setInitialState(trans.getPosition(), Point3F(0.0, 0.0, 1.0));
  916.          if (!splash->registerObject())
  917.          {
  918.             delete splash;
  919.             splash = NULL;
  920.          }
  921.  
  922.          // create an emitter for the particles out of water and the particles in water
  923.          if (mParticleEmitter)
  924.             mParticleEmitter->emitParticles(from, rInfo.point, axis, vel, ms);
  925.  
  926.          if (mParticleWaterEmitter)
  927.             mParticleWaterEmitter->emitParticles(rInfo.point, to, axis, vel, ms);
  928.       }
  929.    }
  930.    else if (fromWater && !toWater && mDataBlock->splash)     // leaving water
  931.    {
  932.       // cast the ray in the opposite direction since that point is out of the water, otherwise
  933.       //  we hit water immediately and wont get the appropriate surface point
  934.       RayInfo rInfo;
  935.       if (gClientContainer.castRay(to, from, WaterObjectType, &rInfo))
  936.       {
  937.          MatrixF trans = getTransform();
  938.          trans.setPosition(rInfo.point);
  939.  
  940.          Splash *splash = new Splash();
  941.          splash->onNewDataBlock(mDataBlock->splash,false);
  942.          splash->setTransform(trans);
  943.          splash->setInitialState(trans.getPosition(), Point3F(0.0, 0.0, 1.0));
  944.          if (!splash->registerObject())
  945.          {
  946.             delete splash;
  947.             splash = NULL;
  948.          }
  949.  
  950.          // create an emitter for the particles out of water and the particles in water
  951.          if (mParticleEmitter)
  952.             mParticleEmitter->emitParticles(rInfo.point, to, axis, vel, ms);
  953.  
  954.          if (mParticleWaterEmitter)
  955.             mParticleWaterEmitter->emitParticles(from, rInfo.point, axis, vel, ms);
  956.       }
  957.    }
  958. }
  959.  
  960. void Projectile::explode( const Point3F &p, const Point3F &n, const U32 collideType )
  961. {
  962.    // Make sure we don't explode twice...
  963.    if ( mHasExploded )
  964.       return;
  965.  
  966.    mHasExploded = true;
  967.  
  968.    // Move the explosion point slightly off the surface to avoid problems with radius damage
  969.    Point3F explodePos = p + n * 0.001f;
  970.  
  971.    if ( isServerObject() )
  972.    {
  973.       // Do what the server needs to do, damage the surrounding objects, etc.
  974.       mExplosionPosition = explodePos;
  975.       mExplosionNormal = n;
  976.       mCollideHitType  = collideType;
  977.  
  978.        mDataBlock->onExplode_callback( this, mExplosionPosition, mFadeValue );
  979.  
  980.       setMaskBits(ExplosionMask);
  981.  
  982.       // Just wait till the timeout to self delete. This
  983.       // gives server object time to get ghosted to the client.
  984.    }
  985.    else
  986.    {
  987.       // Client just plays the explosion at the right place...
  988.       //      
  989.       Explosion* pExplosion = NULL;
  990.  
  991.       if (mDataBlock->waterExplosion && pointInWater(p))
  992.       {
  993.          pExplosion = new Explosion;
  994.          pExplosion->onNewDataBlock(mDataBlock->waterExplosion, false);
  995.       }
  996.       else
  997.       if (mDataBlock->explosion)
  998.       {
  999.          pExplosion = new Explosion;
  1000.          pExplosion->onNewDataBlock(mDataBlock->explosion, false);
  1001.       }
  1002.  
  1003.       if( pExplosion )
  1004.       {
  1005.          MatrixF xform(true);
  1006.          xform.setPosition(explodePos);
  1007.          pExplosion->setTransform(xform);
  1008.          pExplosion->setInitialState(explodePos, n);
  1009.          pExplosion->setCollideType( collideType );
  1010.          if (pExplosion->registerObject() == false)
  1011.          {
  1012.             Con::errorf(ConsoleLogEntry::General, "Projectile(%s)::explode: couldn't register explosion",
  1013.                         mDataBlock->getName() );
  1014.             delete pExplosion;
  1015.             pExplosion = NULL;
  1016.          }
  1017.       }
  1018.  
  1019.       // Client (impact) decal.
  1020.       DecalInstance * decalReturn = NULL;
  1021.       if ( mDataBlock->decal )    
  1022.          decalReturn = gDecalManager->addDecal(p, n, 0.0f, mDataBlock->decal);
  1023.       if(decalReturn)
  1024.       {
  1025.          RayInfo rInfo;
  1026.          Point3F oldPosition = p;
  1027.          Point3F newPosition = p - (n*0.05);
  1028.          // Raycast the abstract PhysicsWorld if a PhysicsPlugin exists.
  1029.          bool hit = false;
  1030.          //disableCollision();
  1031.          //let's ignore bullet physics and go the poor castRay
  1032.          hit = gClientContainer.castRay(oldPosition, newPosition, csmDynamicCollisionMask | csmStaticCollisionMask, &rInfo);
  1033.          //enableCollision();
  1034.          //if(rInfo.object has some quality that enables this check) {
  1035.             if(hit)
  1036.                decalReturn->surfaceObject = (rInfo.object)->getId(); //else, surfaceObject keeps being 0
  1037.          //} ----- closing of  if(rInfo.object has some quality...)
  1038.       }
  1039.      
  1040.       // Client object
  1041.       updateSound();
  1042.    }
  1043.  
  1044.    /*
  1045.    // Client and Server both should apply forces to PhysicsWorld objects
  1046.    // within the explosion.
  1047.    if ( false && mPhysicsWorld )
  1048.    {
  1049.       F32 force = 200.0f;
  1050.       mPhysicsWorld->explosion( p, 15.0f, force );
  1051.    }
  1052.    */
  1053. }
  1054.  
  1055. void Projectile::updateSound()
  1056. {
  1057.    if (!mDataBlock->sound)
  1058.       return;
  1059.  
  1060.    if ( mSound )
  1061.    {
  1062.       if ( mHasExploded )
  1063.          mSound->stop();
  1064.       else
  1065.       {
  1066.          if ( !mSound->isPlaying() )
  1067.             mSound->play();
  1068.  
  1069.          mSound->setVelocity( getVelocity() );
  1070.          mSound->setTransform( getRenderTransform() );
  1071.       }
  1072.    }
  1073. }
  1074.  
  1075. void Projectile::processTick( const Move *move )
  1076. {
  1077.    Parent::processTick( move );
  1078.    mCurrTick++;
  1079.  
  1080.    simulate( TickSec );
  1081. }
  1082.  
  1083. void Projectile::simulate( F32 dt )
  1084. {        
  1085.    if ( isServerObject() && mCurrTick >= mDataBlock->lifetime )
  1086.    {
  1087.       deleteObject();
  1088.       return;
  1089.    }
  1090.    
  1091.    if ( mHasExploded )
  1092.       return;
  1093.  
  1094.    // ... otherwise, we have to do some simulation work.
  1095.    RayInfo rInfo;
  1096.    Point3F oldPosition;
  1097.    Point3F newPosition;
  1098.  
  1099.    oldPosition = mCurrPosition;
  1100.    if ( mDataBlock->isBallistic )
  1101.       mCurrVelocity.z -= 9.81 * mDataBlock->gravityMod * dt;
  1102.  
  1103.    newPosition = oldPosition + mCurrVelocity * dt;
  1104.  
  1105.    // disable the source objects collision reponse for a short time while we
  1106.    // determine if the projectile is capable of moving from the old position
  1107.    // to the new position, otherwise we'll hit ourself
  1108.    bool disableSourceObjCollision = (mSourceObject.isValid() && mCurrTick <= SourceIdTimeoutTicks);
  1109.    if ( disableSourceObjCollision )
  1110.       mSourceObject->disableCollision();
  1111.    disableCollision();
  1112.  
  1113.    // Determine if the projectile is going to hit any object between the previous
  1114.    // position and the new position. This code is executed both on the server
  1115.    // and on the client (for prediction purposes). It is possible that the server
  1116.    // will have registered a collision while the client prediction has not. If this
  1117.    // happens the client will be corrected in the next packet update.
  1118.  
  1119.    // Raycast the abstract PhysicsWorld if a PhysicsPlugin exists.
  1120.    bool hit = false;
  1121.  
  1122.    if ( mPhysicsWorld )
  1123.       hit = mPhysicsWorld->castRay( oldPosition, newPosition, &rInfo, Point3F( newPosition - oldPosition) * mDataBlock->impactForce );            
  1124.    else
  1125.       hit = getContainer()->castRay(oldPosition, newPosition, csmDynamicCollisionMask | csmStaticCollisionMask, &rInfo);
  1126.  
  1127.    if ( hit )
  1128.    {
  1129.       // make sure the client knows to bounce
  1130.       if ( isServerObject() && ( rInfo.object->getTypeMask() & csmStaticCollisionMask ) == 0 )
  1131.          setMaskBits( BounceMask );
  1132.  
  1133.       MatrixF xform( true );
  1134.       xform.setColumn( 3, rInfo.point );
  1135.       setTransform( xform );
  1136.       mCurrPosition    = rInfo.point;
  1137.  
  1138.       // Get the object type before the onCollision call, in case
  1139.       // the object is destroyed.
  1140.       U32 objectType = rInfo.object->getTypeMask();
  1141.  
  1142.       // re-enable the collision response on the source object since
  1143.       // we need to process the onCollision and explode calls
  1144.       if ( disableSourceObjCollision )
  1145.          mSourceObject->enableCollision();
  1146.  
  1147.       // Ok, here is how this works:
  1148.       // onCollision is called to notify the server scripts that a collision has occurred, then
  1149.       // a call to explode is made to start the explosion process. The call to explode is made
  1150.       // twice, once on the server and once on the client.
  1151.       // The server process is responsible for two things:
  1152.       //    1) setting the ExplosionMask network bit to guarantee that the client calls explode
  1153.       //    2) initiate the explosion process on the server scripts
  1154.       // The client process is responsible for only one thing:
  1155.       //    1) drawing the appropriate explosion
  1156.  
  1157.       // It is possible that during the processTick the server may have decided that a hit
  1158.       // has occurred while the client prediction has decided that a hit has not occurred.
  1159.       // In this particular scenario the client will have failed to call onCollision and
  1160.       // explode during the processTick. However, the explode function will be called
  1161.       // during the next packet update, due to the ExplosionMask network bit being set.
  1162.       // onCollision will remain uncalled on the client however, therefore no client
  1163.       // specific code should be placed inside the function!
  1164.       onCollision( rInfo.point, rInfo.normal, rInfo.object );
  1165.       // Next order of business: do we explode on this hit?
  1166.       if ( mCurrTick > mDataBlock->armingDelay || mDataBlock->armingDelay == 0 )
  1167.       {
  1168.          mCurrVelocity    = Point3F::Zero;
  1169.          explode( rInfo.point, rInfo.normal, objectType );
  1170.       }
  1171.  
  1172.       if ( mDataBlock->isBallistic )
  1173.       {
  1174.          // Otherwise, this represents a bounce.  First, reflect our velocity
  1175.          //  around the normal...
  1176.          Point3F bounceVel = mCurrVelocity - rInfo.normal * (mDot( mCurrVelocity, rInfo.normal ) * 2.0);
  1177.          mCurrVelocity = bounceVel;
  1178.  
  1179.          // Add in surface friction...
  1180.          Point3F tangent = bounceVel - rInfo.normal * mDot(bounceVel, rInfo.normal);
  1181.          mCurrVelocity  -= tangent * mDataBlock->bounceFriction;
  1182.  
  1183.          // Now, take elasticity into account for modulating the speed of the grenade
  1184.          mCurrVelocity *= mDataBlock->bounceElasticity;
  1185.  
  1186.          // Set the new position to the impact and the bounce
  1187.          // will apply on the next frame.
  1188.          //F32 timeLeft = 1.0f - rInfo.t;
  1189.          newPosition = oldPosition = rInfo.point + rInfo.normal * 0.05f;
  1190.       }
  1191.       else
  1192.       {
  1193.          mCurrVelocity    = Point3F::Zero;
  1194.       }
  1195.    }
  1196.  
  1197.    // re-enable the collision response on the source object now
  1198.    // that we are done processing the ballistic movement
  1199.    if ( disableSourceObjCollision )
  1200.       mSourceObject->enableCollision();
  1201.    enableCollision();
  1202.  
  1203.    if ( isClientObject() )
  1204.    {
  1205.       emitParticles( mCurrPosition, newPosition, mCurrVelocity, U32( dt * 1000.0f ) );
  1206.       updateSound();
  1207.    }
  1208.  
  1209.    mCurrDeltaBase = newPosition;
  1210.    mCurrBackDelta = mCurrPosition - newPosition;
  1211.    mCurrPosition = newPosition;
  1212.  
  1213.    MatrixF xform( true );
  1214.    xform.setColumn( 3, mCurrPosition );
  1215.    setTransform( xform );
  1216. }
  1217.  
  1218.  
  1219. void Projectile::advanceTime(F32 dt)
  1220. {
  1221.    Parent::advanceTime(dt);
  1222.  
  1223.    if ( mHasExploded || dt == 0.0)
  1224.       return;
  1225.  
  1226.    if (mActivateThread &&
  1227.          mProjectileShape->getDuration(mActivateThread) > mProjectileShape->getTime(mActivateThread) + dt)
  1228.    {
  1229.       mProjectileShape->advanceTime(dt, mActivateThread);
  1230.    }
  1231.    else
  1232.    {
  1233.  
  1234.       if (mMaintainThread)
  1235.       {
  1236.          mProjectileShape->advanceTime(dt, mMaintainThread);
  1237.       }
  1238.       else if (mActivateThread && mDataBlock->maintainSeq != -1)
  1239.       {
  1240.          mMaintainThread = mProjectileShape->addThread();
  1241.          mProjectileShape->setTimeScale(mMaintainThread, 1);
  1242.          mProjectileShape->setSequence(mMaintainThread, mDataBlock->maintainSeq, 0);
  1243.          mProjectileShape->advanceTime(dt, mMaintainThread);
  1244.       }
  1245.    }
  1246. }
  1247.  
  1248. void Projectile::interpolateTick(F32 delta)
  1249. {
  1250.    Parent::interpolateTick(delta);
  1251.  
  1252.    if( mHasExploded )
  1253.       return;
  1254.  
  1255.    Point3F interpPos = mCurrDeltaBase + mCurrBackDelta * delta;
  1256.    Point3F dir = mCurrVelocity;
  1257.    if(dir.isZero())
  1258.       dir.set(0,0,1);
  1259.    else
  1260.       dir.normalize();
  1261.  
  1262.    MatrixF xform(true);
  1263.     xform = MathUtils::createOrientFromDir(dir);
  1264.    xform.setPosition(interpPos);
  1265.    setRenderTransform(xform);
  1266.  
  1267.    // fade out the projectile image
  1268.    S32 time = (S32)(mCurrTick - delta);
  1269.    if(time > mDataBlock->fadeDelay)
  1270.    {
  1271.       F32 fade = F32(time - mDataBlock->fadeDelay);
  1272.       mFadeValue = 1.0 - (fade / F32(mDataBlock->lifetime));
  1273.    }
  1274.    else
  1275.       mFadeValue = 1.0;
  1276.  
  1277.    updateSound();
  1278. }
  1279.  
  1280.  
  1281.  
  1282. //--------------------------------------------------------------------------
  1283. void Projectile::onCollision(const Point3F& hitPosition, const Point3F& hitNormal, SceneObject* hitObject)
  1284. {
  1285.    // No client specific code should be placed or branched from this function
  1286.    if(isClientObject())
  1287.       return;
  1288.  
  1289.    if (hitObject != NULL && isServerObject())
  1290.    {
  1291.        mDataBlock->onCollision_callback( this, hitObject, mFadeValue, hitPosition, hitNormal );
  1292.    }
  1293. }
  1294.  
  1295. //--------------------------------------------------------------------------
  1296. U32 Projectile::packUpdate( NetConnection *con, U32 mask, BitStream *stream )
  1297. {
  1298.    U32 retMask = Parent::packUpdate( con, mask, stream );
  1299.  
  1300.    const bool isInitalUpdate = mask & GameBase::InitialUpdateMask;
  1301.  
  1302.    // InitialUpdateMask
  1303.    if ( stream->writeFlag( isInitalUpdate ) )
  1304.    {
  1305.       stream->writeRangedU32( mCurrTick, 0, MaxLivingTicks );
  1306.  
  1307.       if ( mSourceObject.isValid() )
  1308.       {
  1309.          // Potentially have to write this to the client, let's make sure it has a
  1310.          //  ghost on the other side...
  1311.          S32 ghostIndex = con->getGhostIndex( mSourceObject );
  1312.          if ( stream->writeFlag( ghostIndex != -1 ) )
  1313.          {
  1314.             stream->writeRangedU32( U32(ghostIndex),
  1315.                                     0,
  1316.                                     NetConnection::MaxGhostCount );
  1317.  
  1318.             stream->writeRangedU32( U32(mSourceObjectSlot),
  1319.                                     0,
  1320.                                     ShapeBase::MaxMountedImages - 1 );
  1321.          }
  1322.          else
  1323.             // have not recieved the ghost for the source object yet, try again later
  1324.             retMask |= GameBase::InitialUpdateMask;
  1325.       }
  1326.       else
  1327.          stream->writeFlag( false );
  1328.    }
  1329.  
  1330.    // ExplosionMask
  1331.    //
  1332.    // ExplosionMask will be set during the initial update but hidden is
  1333.    // only true if we have really exploded.
  1334.    if ( stream->writeFlag( ( mask & ExplosionMask ) && mHasExploded ) )
  1335.    {
  1336.       mathWrite(*stream, mExplosionPosition);
  1337.       mathWrite(*stream, mExplosionNormal);
  1338.       stream->write(mCollideHitType);
  1339.    }
  1340.  
  1341.    // BounceMask
  1342.    if ( stream->writeFlag( mask & BounceMask ) )
  1343.    {
  1344.       // Bounce against dynamic object
  1345.       mathWrite(*stream, mCurrPosition);
  1346.       mathWrite(*stream, mCurrVelocity);
  1347.    }
  1348.  
  1349.    return retMask;
  1350. }
  1351.  
  1352. void Projectile::unpackUpdate(NetConnection* con, BitStream* stream)
  1353. {
  1354.    Parent::unpackUpdate(con, stream);
  1355.    
  1356.    if ( stream->readFlag() ) // InitialUpdateMask
  1357.    {
  1358.       mCurrTick = stream->readRangedU32( 0, MaxLivingTicks );
  1359.       if ( stream->readFlag() )
  1360.       {
  1361.          mSourceObjectId   = stream->readRangedU32( 0, NetConnection::MaxGhostCount );
  1362.          mSourceObjectSlot = stream->readRangedU32( 0, ShapeBase::MaxMountedImages - 1 );
  1363.  
  1364.          NetObject* pObject = con->resolveGhost( mSourceObjectId );
  1365.          if ( pObject != NULL )
  1366.             mSourceObject = dynamic_cast<ShapeBase*>( pObject );
  1367.       }
  1368.       else
  1369.       {
  1370.          mSourceObjectId   = -1;
  1371.          mSourceObjectSlot = -1;
  1372.          mSourceObject     = NULL;
  1373.       }
  1374.    }
  1375.    
  1376.    if ( stream->readFlag() ) // ExplosionMask
  1377.    {
  1378.       Point3F explodePoint;
  1379.       Point3F explodeNormal;
  1380.       mathRead( *stream, &explodePoint );
  1381.       mathRead( *stream, &explodeNormal );
  1382.       stream->read( &mCollideHitType );
  1383.  
  1384.       // start the explosion visuals
  1385.       explode( explodePoint, explodeNormal, mCollideHitType );
  1386.    }
  1387.  
  1388.    if ( stream->readFlag() ) // BounceMask
  1389.    {
  1390.       Point3F pos;
  1391.       mathRead( *stream, &pos );
  1392.       mathRead( *stream, &mCurrVelocity );
  1393.  
  1394.       mCurrDeltaBase = pos;
  1395.       mCurrBackDelta = mCurrPosition - pos;
  1396.       mCurrPosition = pos;
  1397.       setPosition( mCurrPosition );
  1398.    }
  1399. }
  1400.  
  1401. //--------------------------------------------------------------------------
  1402. void Projectile::prepRenderImage( SceneRenderState* state )
  1403. {
  1404.    if (mHasExploded || mFadeValue <= (1.0/255.0))
  1405.       return;
  1406.  
  1407.    if ( mDataBlock->lightDesc )
  1408.    {
  1409.       mDataBlock->lightDesc->prepRender( state, &mLightState, getRenderTransform() );
  1410.    }
  1411.  
  1412.    /*
  1413.    if ( mFlareData )
  1414.    {
  1415.       mFlareState.fullBrightness = mDataBlock->lightDesc->mBrightness;
  1416.       mFlareState.scale = mFlareScale;
  1417.       mFlareState.lightInfo = mLight;
  1418.       mFlareState.lightMat = getTransform();
  1419.  
  1420.       mFlareData->prepRender( state, &mFlareState );
  1421.    }
  1422.    */
  1423.  
  1424.    prepBatchRender( state );
  1425. }
  1426.  
  1427. void Projectile::prepBatchRender( SceneRenderState *state )
  1428. {
  1429.    if ( !mProjectileShape )
  1430.       return;
  1431.  
  1432.    GFXTransformSaver saver;
  1433.  
  1434.    // Set up our TS render state.
  1435.    TSRenderState rdata;
  1436.    rdata.setSceneState( state );
  1437.  
  1438.    // We might have some forward lit materials
  1439.    // so pass down a query to gather lights.
  1440.    LightQuery query;
  1441.    query.init( getWorldSphere() );
  1442.    rdata.setLightQuery( &query );
  1443.  
  1444.    MatrixF mat = getRenderTransform();
  1445.    mat.scale( mObjScale );
  1446.    mat.scale( mDataBlock->scale );
  1447.    GFX->setWorldMatrix( mat );
  1448.  
  1449.    mProjectileShape->setDetailFromPosAndScale( state, mat.getPosition(), mObjScale );
  1450.    mProjectileShape->animate();
  1451.  
  1452.    mProjectileShape->render( rdata );
  1453. }
  1454.  
  1455. DefineEngineMethod(Projectile, presimulate, void, (F32 seconds), (1.0f),
  1456.                                        "@brief Updates the projectile's positional and collision information.\n\n"
  1457.                                        "This function will first delete the projectile if it is a server object and is outside it's ProjectileData::lifetime. "
  1458.                                        "Also responsible for applying gravity, determining collisions, triggering explosions, "
  1459.                                        "emitting trail particles, and calculating bounces if necessary."
  1460.                                                 "@param seconds Amount of time, in seconds since the simulation's start, to advance.\n"
  1461.                                                 "@tsexample\n"
  1462.                                                    "// Tell the projectile to process a simulation event, and provide the amount of time\n"
  1463.                                                     "// that has passed since the simulation began.\n"
  1464.                                                     "%seconds = 2.0;\n"
  1465.                                                     "%projectile.presimulate(%seconds);\n"
  1466.                                                 "@endtsexample\n"
  1467.                                        "@note This function is not called if the SimObject::hidden is true.")
  1468. {
  1469.     object->simulate( seconds );
  1470. }
RAW Paste Data
Top