projectile.cpp 51 KB

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