projectile.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  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_ASSET(ProjectileShape);
  122. INIT_ASSET(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_ASSET(ProjectileSound);
  179. lightDesc = other.lightDesc;
  180. lightDescId = other.lightDescId; // -- for pack/unpack of lightDesc ptr
  181. CLONE_ASSET(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. _setProjectileSound(getProjectileSound());
  301. if (getProjectileSound() != StringTable->EmptyString())
  302. {
  303. if (!getProjectileSoundProfile())
  304. Con::errorf(ConsoleLogEntry::General, "SplashData::preload: Cant get an sfxProfile for splash.");
  305. }
  306. if (!lightDesc && lightDescId != 0)
  307. if (Sim::findObject(lightDescId, lightDesc) == false)
  308. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockid(lightDesc): %d", lightDescId);
  309. }
  310. if (mProjectileShapeAssetId != StringTable->EmptyString())
  311. {
  312. //If we've got a shapeAsset assigned for our projectile, but we failed to load the shape data itself, report the error
  313. if (!mProjectileShape)
  314. {
  315. errorStr = String::ToString("ProjectileData::load: Couldn't load shape \"%s\"", mProjectileShapeAssetId);
  316. return false;
  317. }
  318. else
  319. {
  320. activateSeq = mProjectileShape->findSequence("activate");
  321. maintainSeq = mProjectileShape->findSequence("maintain");
  322. TSShapeInstance* pDummy = new TSShapeInstance(mProjectileShape, !server);
  323. delete pDummy;
  324. }
  325. }
  326. return true;
  327. }
  328. //--------------------------------------------------------------------------
  329. void ProjectileData::packData(BitStream* stream)
  330. {
  331. Parent::packData(stream);
  332. PACKDATA_ASSET(ProjectileShape);
  333. stream->writeFlag(faceViewer);
  334. if(stream->writeFlag(scale.x != 1 || scale.y != 1 || scale.z != 1))
  335. {
  336. stream->write(scale.x);
  337. stream->write(scale.y);
  338. stream->write(scale.z);
  339. }
  340. if (stream->writeFlag(particleEmitter != NULL))
  341. stream->writeRangedU32(particleEmitter->getId(), DataBlockObjectIdFirst,
  342. DataBlockObjectIdLast);
  343. if (stream->writeFlag(particleWaterEmitter != NULL))
  344. stream->writeRangedU32(particleWaterEmitter->getId(), DataBlockObjectIdFirst,
  345. DataBlockObjectIdLast);
  346. if (stream->writeFlag(explosion != NULL))
  347. stream->writeRangedU32(explosion->getId(), DataBlockObjectIdFirst,
  348. DataBlockObjectIdLast);
  349. if (stream->writeFlag(waterExplosion != NULL))
  350. stream->writeRangedU32(waterExplosion->getId(), DataBlockObjectIdFirst,
  351. DataBlockObjectIdLast);
  352. if (stream->writeFlag(splash != NULL))
  353. stream->writeRangedU32(splash->getId(), DataBlockObjectIdFirst,
  354. DataBlockObjectIdLast);
  355. if (stream->writeFlag(decal != NULL))
  356. stream->writeRangedU32(decal->getId(), DataBlockObjectIdFirst,
  357. DataBlockObjectIdLast);
  358. PACKDATA_ASSET(ProjectileSound);
  359. if ( stream->writeFlag(lightDesc != NULL))
  360. stream->writeRangedU32(lightDesc->getId(), DataBlockObjectIdFirst,
  361. DataBlockObjectIdLast);
  362. stream->write(impactForce);
  363. // stream->writeRangedU32(lifetime, 0, Projectile::MaxLivingTicks);
  364. // stream->writeRangedU32(armingDelay, 0, Projectile::MaxLivingTicks);
  365. // stream->writeRangedU32(fadeDelay, 0, Projectile::MaxLivingTicks);
  366. // [tom, 3/21/2007] Changing these to write all 32 bits as the previous
  367. // code limited these to a max value of 4095.
  368. stream->write(lifetime);
  369. stream->write(armingDelay);
  370. stream->write(fadeDelay);
  371. if(stream->writeFlag(isBallistic))
  372. {
  373. stream->write(gravityMod);
  374. stream->write(bounceElasticity);
  375. stream->write(bounceFriction);
  376. }
  377. }
  378. void ProjectileData::unpackData(BitStream* stream)
  379. {
  380. Parent::unpackData(stream);
  381. UNPACKDATA_ASSET(ProjectileShape);
  382. faceViewer = stream->readFlag();
  383. if(stream->readFlag())
  384. {
  385. stream->read(&scale.x);
  386. stream->read(&scale.y);
  387. stream->read(&scale.z);
  388. }
  389. else
  390. scale.set(1,1,1);
  391. if (stream->readFlag())
  392. particleEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  393. if (stream->readFlag())
  394. particleWaterEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  395. if (stream->readFlag())
  396. explosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  397. if (stream->readFlag())
  398. waterExplosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  399. if (stream->readFlag())
  400. splashId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  401. if (stream->readFlag())
  402. decalId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  403. UNPACKDATA_ASSET(ProjectileSound);
  404. if (stream->readFlag())
  405. lightDescId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  406. // [tom, 3/21/2007] See comment in packData()
  407. // lifetime = stream->readRangedU32(0, Projectile::MaxLivingTicks);
  408. // armingDelay = stream->readRangedU32(0, Projectile::MaxLivingTicks);
  409. // fadeDelay = stream->readRangedU32(0, Projectile::MaxLivingTicks);
  410. stream->read(&impactForce);
  411. stream->read(&lifetime);
  412. stream->read(&armingDelay);
  413. stream->read(&fadeDelay);
  414. isBallistic = stream->readFlag();
  415. if(isBallistic)
  416. {
  417. stream->read(&gravityMod);
  418. stream->read(&bounceElasticity);
  419. stream->read(&bounceFriction);
  420. }
  421. }
  422. bool ProjectileData::setLifetime( void *obj, const char *index, const char *data )
  423. {
  424. S32 value = dAtoi(data);
  425. value = scaleValue(value);
  426. ProjectileData *object = static_cast<ProjectileData*>(obj);
  427. object->lifetime = value;
  428. return false;
  429. }
  430. bool ProjectileData::setArmingDelay( void *obj, const char *index, const char *data )
  431. {
  432. S32 value = dAtoi(data);
  433. value = scaleValue(value);
  434. ProjectileData *object = static_cast<ProjectileData*>(obj);
  435. object->armingDelay = value;
  436. return false;
  437. }
  438. bool ProjectileData::setFadeDelay( void *obj, const char *index, const char *data )
  439. {
  440. S32 value = dAtoi(data);
  441. value = scaleValue(value);
  442. ProjectileData *object = static_cast<ProjectileData*>(obj);
  443. object->fadeDelay = value;
  444. return false;
  445. }
  446. const char *ProjectileData::getScaledValue( void *obj, const char *data)
  447. {
  448. S32 value = dAtoi(data);
  449. value = scaleValue(value, false);
  450. String stringData = String::ToString(value);
  451. char *strBuffer = Con::getReturnBuffer(stringData.size());
  452. dMemcpy( strBuffer, stringData, stringData.size() );
  453. return strBuffer;
  454. }
  455. S32 ProjectileData::scaleValue( S32 value, bool down )
  456. {
  457. S32 minV = 0;
  458. S32 maxV = Projectile::MaxLivingTicks;
  459. // scale down to ticks before we validate
  460. if( down )
  461. value /= TickMs;
  462. if(value < minV || value > maxV)
  463. {
  464. Con::errorf("ProjectileData::scaleValue(S32 value = %d, bool down = %b) - Scaled value must be between %d and %d", value, down, minV, maxV);
  465. if(value < minV)
  466. value = minV;
  467. else if(value > maxV)
  468. value = maxV;
  469. }
  470. // scale up from ticks after we validate
  471. if( !down )
  472. value *= TickMs;
  473. return value;
  474. }
  475. //--------------------------------------------------------------------------
  476. //--------------------------------------
  477. //
  478. Projectile::Projectile()
  479. : mPhysicsWorld( NULL ),
  480. mDataBlock( NULL ),
  481. mParticleEmitter( NULL ),
  482. mParticleWaterEmitter( NULL ),
  483. mSound( NULL ),
  484. mCurrPosition( 0, 0, 0 ),
  485. mCurrVelocity( 0, 0, 1 ),
  486. mSourceObjectId( -1 ),
  487. mSourceObjectSlot( -1 ),
  488. mCurrTick( 0 ),
  489. mProjectileShape( NULL ),
  490. mActivateThread( NULL ),
  491. mMaintainThread( NULL ),
  492. mHasExploded( false ),
  493. mFadeValue( 1.0f )
  494. {
  495. // Todo: ScopeAlways?
  496. mNetFlags.set(Ghostable);
  497. mTypeMask |= ProjectileObjectType | LightObjectType | DynamicShapeObjectType;
  498. mLight = LightManager::createLightInfo();
  499. mLight->setType( LightInfo::Point );
  500. mLightState.clear();
  501. mLightState.setLightInfo( mLight );
  502. mDataBlock = 0;
  503. ignoreSourceTimeout = false;
  504. dynamicCollisionMask = csmDynamicCollisionMask;
  505. staticCollisionMask = csmStaticCollisionMask;
  506. }
  507. Projectile::~Projectile()
  508. {
  509. SAFE_DELETE(mLight);
  510. delete mProjectileShape;
  511. mProjectileShape = NULL;
  512. if (mDataBlock && mDataBlock->isTempClone())
  513. {
  514. delete mDataBlock;
  515. mDataBlock = 0;
  516. }
  517. }
  518. //--------------------------------------------------------------------------
  519. void Projectile::initPersistFields()
  520. {
  521. addGroup("Physics");
  522. addProtectedField("initialPosition", TypePoint3F, Offset(mInitialPosition, Projectile), &_setInitialPosition, &defaultProtectedGetFn,
  523. "@brief Starting position for the projectile.\n\n");
  524. //addField("initialPosition", TypePoint3F, Offset(mCurrPosition, Projectile),
  525. // "@brief Starting position for the projectile.\n\n");
  526. addProtectedField("initialVelocity", TypePoint3F, Offset(mInitialVelocity, Projectile), &_setInitialVelocity, &defaultProtectedGetFn,
  527. "@brief Starting velocity for the projectile.\n\n");
  528. //addField("initialVelocity", TypePoint3F, Offset(mCurrVelocity, Projectile),
  529. // "@brief Starting velocity for the projectile.\n\n");
  530. endGroup("Physics");
  531. addGroup("Source");
  532. addField("sourceObject", TypeS32, Offset(mSourceObjectId, Projectile),
  533. "@brief ID number of the object that fired the projectile.\n\n"
  534. "@note If the projectile was fired by a WeaponImage, sourceObject will be "
  535. "the object that owns the WeaponImage. This is usually the player.");
  536. addField("sourceSlot", TypeS32, Offset(mSourceObjectSlot, Projectile),
  537. "@brief The sourceObject's weapon slot that the projectile originates from.\n\n");
  538. addField("ignoreSourceTimeout", TypeBool, Offset(ignoreSourceTimeout, Projectile));
  539. endGroup("Source");
  540. Parent::initPersistFields();
  541. }
  542. bool Projectile::_setInitialPosition( void *object, const char *index, const char *data )
  543. {
  544. Projectile* p = static_cast<Projectile*>( object );
  545. if ( p )
  546. {
  547. Point3F pos;
  548. S32 count = dSscanf( data, "%f %f %f",
  549. &pos.x, &pos.y, &pos.z);
  550. if ( (count != 3) )
  551. {
  552. Con::printf("Projectile: Failed to parse initial position \"px py pz\" from '%s'", data);
  553. return false;
  554. }
  555. p->setInitialPosition( pos );
  556. }
  557. return false;
  558. }
  559. void Projectile::setInitialPosition( const Point3F& pos )
  560. {
  561. mInitialPosition = pos;
  562. mCurrPosition = pos;
  563. }
  564. bool Projectile::_setInitialVelocity( void *object, const char *index, const char *data )
  565. {
  566. Projectile* p = static_cast<Projectile*>( object );
  567. if ( p )
  568. {
  569. Point3F vel;
  570. S32 count = dSscanf( data, "%f %f %f",
  571. &vel.x, &vel.y, &vel.z);
  572. if ( (count != 3) )
  573. {
  574. Con::printf("Projectile: Failed to parse initial velocity \"vx vy vz\" from '%s'", data);
  575. return false;
  576. }
  577. p->setInitialVelocity( vel );
  578. }
  579. return false;
  580. }
  581. void Projectile::setInitialVelocity( const Point3F& vel )
  582. {
  583. mInitialVelocity = vel;
  584. mCurrVelocity = vel;
  585. }
  586. //--------------------------------------------------------------------------
  587. bool Projectile::calculateImpact(float,
  588. Point3F& pointOfImpact,
  589. float& impactTime)
  590. {
  591. Con::warnf(ConsoleLogEntry::General, "Projectile::calculateImpact: Should never be called");
  592. impactTime = 0;
  593. pointOfImpact.set(0, 0, 0);
  594. return false;
  595. }
  596. //--------------------------------------------------------------------------
  597. F32 Projectile::getUpdatePriority(CameraScopeQuery *camInfo, U32 updateMask, S32 updateSkips)
  598. {
  599. F32 ret = Parent::getUpdatePriority(camInfo, updateMask, updateSkips);
  600. // if the camera "owns" this object, it should have a slightly higher priority
  601. if(mSourceObject == camInfo->camera)
  602. return ret + 0.2;
  603. return ret;
  604. }
  605. bool Projectile::onAdd()
  606. {
  607. if(!Parent::onAdd())
  608. return false;
  609. if( !mDataBlock )
  610. {
  611. Con::errorf("Projectile::onAdd - Fail - Not datablock");
  612. return false;
  613. }
  614. if (isServerObject())
  615. {
  616. ShapeBase* ptr;
  617. if (Sim::findObject(mSourceObjectId, ptr))
  618. {
  619. mSourceObject = ptr;
  620. // Since we later do processAfter( mSourceObject ) we must clearProcessAfter
  621. // if it is deleted. SceneObject already handles this in onDeleteNotify so
  622. // all we need to do is register for the notification.
  623. deleteNotify( ptr );
  624. }
  625. else
  626. {
  627. if (mSourceObjectId != -1)
  628. Con::errorf(ConsoleLogEntry::General, "Projectile::onAdd: mSourceObjectId is invalid");
  629. mSourceObject = NULL;
  630. }
  631. // If we're on the server, we need to inherit some of our parent's velocity
  632. //
  633. mCurrTick = 0;
  634. scriptOnAdd();
  635. }
  636. else
  637. {
  638. if (bool(mDataBlock->mProjectileShape))
  639. {
  640. mProjectileShape = new TSShapeInstance(mDataBlock->mProjectileShape, isClientObject());
  641. if (mDataBlock->activateSeq != -1)
  642. {
  643. mActivateThread = mProjectileShape->addThread();
  644. mProjectileShape->setTimeScale(mActivateThread, 1);
  645. mProjectileShape->setSequence(mActivateThread, mDataBlock->activateSeq, 0);
  646. }
  647. }
  648. if (mDataBlock->particleEmitter != NULL)
  649. {
  650. ParticleEmitter* pEmitter = new ParticleEmitter;
  651. pEmitter->onNewDataBlock(mDataBlock->particleEmitter,false);
  652. if (pEmitter->registerObject() == false)
  653. {
  654. Con::warnf(ConsoleLogEntry::General, "Could not register particle emitter for particle of class: %s", mDataBlock->getName());
  655. delete pEmitter;
  656. pEmitter = NULL;
  657. }
  658. mParticleEmitter = pEmitter;
  659. }
  660. if (mDataBlock->particleWaterEmitter != NULL)
  661. {
  662. ParticleEmitter* pEmitter = new ParticleEmitter;
  663. pEmitter->onNewDataBlock(mDataBlock->particleWaterEmitter,false);
  664. if (pEmitter->registerObject() == false)
  665. {
  666. Con::warnf(ConsoleLogEntry::General, "Could not register particle emitter for particle of class: %s", mDataBlock->getName());
  667. delete pEmitter;
  668. pEmitter = NULL;
  669. }
  670. mParticleWaterEmitter = pEmitter;
  671. }
  672. }
  673. if (mSourceObject.isValid())
  674. processAfter(mSourceObject);
  675. // Setup our bounding box
  676. if (bool(mDataBlock->mProjectileShape) == true)
  677. mObjBox = mDataBlock->mProjectileShape->mBounds;
  678. else
  679. mObjBox = Box3F(Point3F(0, 0, 0), Point3F(0, 0, 0));
  680. MatrixF initialTransform( true );
  681. initialTransform.setPosition( mCurrPosition );
  682. setTransform( initialTransform ); // calls resetWorldBox
  683. addToScene();
  684. if ( PHYSICSMGR )
  685. mPhysicsWorld = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  686. return true;
  687. }
  688. void Projectile::onRemove()
  689. {
  690. if( !mParticleEmitter.isNull() )
  691. {
  692. mParticleEmitter->deleteWhenEmpty();
  693. mParticleEmitter = NULL;
  694. }
  695. if( !mParticleWaterEmitter.isNull() )
  696. {
  697. mParticleWaterEmitter->deleteWhenEmpty();
  698. mParticleWaterEmitter = NULL;
  699. }
  700. SFX_DELETE( mSound );
  701. removeFromScene();
  702. Parent::onRemove();
  703. }
  704. bool Projectile::onNewDataBlock( GameBaseData *dptr, bool reload )
  705. {
  706. mDataBlock = dynamic_cast<ProjectileData*>( dptr );
  707. if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  708. return false;
  709. if ( isGhost() )
  710. {
  711. // Create the sound ahead of time. This reduces runtime
  712. // costs and makes the system easier to understand.
  713. SFX_DELETE( mSound );
  714. if ( mDataBlock->getProjectileSound() )
  715. mSound = SFX->createSource( mDataBlock->getProjectileSoundProfile() );
  716. }
  717. return true;
  718. }
  719. void Projectile::submitLights( LightManager *lm, bool staticLighting )
  720. {
  721. if ( staticLighting || mHasExploded || !mDataBlock->lightDesc )
  722. return;
  723. mDataBlock->lightDesc->submitLight( &mLightState, getRenderTransform(), lm, this );
  724. }
  725. bool Projectile::pointInWater(const Point3F &point)
  726. {
  727. // This is pretty much a hack so we can use the existing ContainerQueryInfo
  728. // and findObject router.
  729. // We only care if we intersect with water at all
  730. // so build a box at the point that has only 1 z extent.
  731. // And test if water coverage is anything other than zero.
  732. Box3F boundsBox( point, point );
  733. boundsBox.maxExtents.z += 1.0f;
  734. ContainerQueryInfo info;
  735. info.box = boundsBox;
  736. info.mass = 0.0f;
  737. // Find and retreive physics info from intersecting WaterObject(s)
  738. if(mContainer != NULL)
  739. {
  740. mContainer->findObjects( boundsBox, WaterObjectType, findRouter, &info );
  741. }
  742. else
  743. {
  744. // Handle special case where the projectile has exploded prior to having
  745. // called onAdd() on the client. This occurs when the projectile on the
  746. // server is created and then explodes in the same network update tick.
  747. // On the client end in NetConnection::ghostReadPacket() the ghost is
  748. // created and then Projectile::unpackUpdate() is called prior to the
  749. // projectile being registered. Within unpackUpdate() the explosion
  750. // is triggered, but without being registered onAdd() isn't called and
  751. // the container is not set. As all we're doing is checking if the
  752. // given explosion point is within water, we should be able to use the
  753. // global container here. We could likely always get away with this,
  754. // but using the actual defined container when possible is the right
  755. // thing to do. DAW
  756. AssertFatal(isClientObject(), "Server projectile has not been properly added");
  757. gClientContainer.findObjects( boundsBox, WaterObjectType, findRouter, &info );
  758. }
  759. return ( info.waterCoverage > 0.0f );
  760. }
  761. //----------------------------------------------------------------------------
  762. void Projectile::emitParticles(const Point3F& from, const Point3F& to, const Point3F& vel, const U32 ms)
  763. {
  764. if ( mHasExploded )
  765. return;
  766. Point3F axis = -vel;
  767. if( axis.isZero() )
  768. axis.set( 0.0, 0.0, 1.0 );
  769. else
  770. axis.normalize();
  771. bool fromWater = pointInWater(from);
  772. bool toWater = pointInWater(to);
  773. if (!fromWater && !toWater && bool(mParticleEmitter)) // not in water
  774. mParticleEmitter->emitParticles(from, to, axis, vel, ms);
  775. else if (fromWater && toWater && bool(mParticleWaterEmitter)) // in water
  776. mParticleWaterEmitter->emitParticles(from, to, axis, vel, ms);
  777. else if (!fromWater && toWater && mDataBlock->splash) // entering water
  778. {
  779. // cast the ray to get the surface point of the water
  780. RayInfo rInfo;
  781. if (gClientContainer.castRay(from, to, WaterObjectType, &rInfo))
  782. {
  783. MatrixF trans = getTransform();
  784. trans.setPosition(rInfo.point);
  785. Splash *splash = new Splash();
  786. splash->onNewDataBlock(mDataBlock->splash, false);
  787. splash->setTransform(trans);
  788. splash->setInitialState(trans.getPosition(), Point3F(0.0, 0.0, 1.0));
  789. if (!splash->registerObject())
  790. {
  791. delete splash;
  792. splash = NULL;
  793. }
  794. // create an emitter for the particles out of water and the particles in water
  795. if (mParticleEmitter)
  796. mParticleEmitter->emitParticles(from, rInfo.point, axis, vel, ms);
  797. if (mParticleWaterEmitter)
  798. mParticleWaterEmitter->emitParticles(rInfo.point, to, axis, vel, ms);
  799. }
  800. }
  801. else if (fromWater && !toWater && mDataBlock->splash) // leaving water
  802. {
  803. // cast the ray in the opposite direction since that point is out of the water, otherwise
  804. // we hit water immediately and wont get the appropriate surface point
  805. RayInfo rInfo;
  806. if (gClientContainer.castRay(to, from, WaterObjectType, &rInfo))
  807. {
  808. MatrixF trans = getTransform();
  809. trans.setPosition(rInfo.point);
  810. Splash *splash = new Splash();
  811. splash->onNewDataBlock(mDataBlock->splash,false);
  812. splash->setTransform(trans);
  813. splash->setInitialState(trans.getPosition(), Point3F(0.0, 0.0, 1.0));
  814. if (!splash->registerObject())
  815. {
  816. delete splash;
  817. splash = NULL;
  818. }
  819. // create an emitter for the particles out of water and the particles in water
  820. if (mParticleEmitter)
  821. mParticleEmitter->emitParticles(rInfo.point, to, axis, vel, ms);
  822. if (mParticleWaterEmitter)
  823. mParticleWaterEmitter->emitParticles(from, rInfo.point, axis, vel, ms);
  824. }
  825. }
  826. }
  827. void Projectile::explode( const Point3F &p, const Point3F &n, const U32 collideType )
  828. {
  829. // Make sure we don't explode twice...
  830. if ( mHasExploded )
  831. return;
  832. mHasExploded = true;
  833. // Move the explosion point slightly off the surface to avoid problems with radius damage
  834. Point3F explodePos = p + n * 0.001f;
  835. if ( isServerObject() )
  836. {
  837. // Do what the server needs to do, damage the surrounding objects, etc.
  838. mExplosionPosition = explodePos;
  839. mExplosionNormal = n;
  840. mCollideHitType = collideType;
  841. mDataBlock->onExplode_callback( this, mExplosionPosition, mFadeValue );
  842. setMaskBits(ExplosionMask);
  843. // Just wait till the timeout to self delete. This
  844. // gives server object time to get ghosted to the client.
  845. }
  846. else
  847. {
  848. // Client just plays the explosion at the right place...
  849. //
  850. Explosion* pExplosion = NULL;
  851. if (mDataBlock->waterExplosion && pointInWater(p))
  852. {
  853. pExplosion = new Explosion;
  854. pExplosion->onNewDataBlock(mDataBlock->waterExplosion, false);
  855. }
  856. else
  857. if (mDataBlock->explosion)
  858. {
  859. pExplosion = new Explosion;
  860. pExplosion->onNewDataBlock(mDataBlock->explosion, false);
  861. }
  862. if( pExplosion )
  863. {
  864. MatrixF xform(true);
  865. xform.setPosition(explodePos);
  866. pExplosion->setTransform(xform);
  867. pExplosion->setInitialState(explodePos, n);
  868. pExplosion->setCollideType( collideType );
  869. if (pExplosion->registerObject() == false)
  870. {
  871. Con::errorf(ConsoleLogEntry::General, "Projectile(%s)::explode: couldn't register explosion",
  872. mDataBlock->getName() );
  873. delete pExplosion;
  874. pExplosion = NULL;
  875. }
  876. }
  877. // Client (impact) decal.
  878. if ( mDataBlock->decal )
  879. gDecalManager->addDecal(p, n, 0.0f, mDataBlock->decal);
  880. // Client object
  881. updateSound();
  882. }
  883. /*
  884. // Client and Server both should apply forces to PhysicsWorld objects
  885. // within the explosion.
  886. if ( false && mPhysicsWorld )
  887. {
  888. F32 force = 200.0f;
  889. mPhysicsWorld->explosion( p, 15.0f, force );
  890. }
  891. */
  892. }
  893. void Projectile::updateSound()
  894. {
  895. if (!mDataBlock->isProjectileSoundValid())
  896. return;
  897. if ( mSound )
  898. {
  899. if ( mHasExploded )
  900. mSound->stop();
  901. else
  902. {
  903. if ( !mSound->isPlaying() )
  904. mSound->play();
  905. mSound->setVelocity( getVelocity() );
  906. mSound->setTransform( getRenderTransform() );
  907. }
  908. }
  909. }
  910. void Projectile::processTick( const Move *move )
  911. {
  912. Parent::processTick( move );
  913. mCurrTick++;
  914. simulate( TickSec );
  915. }
  916. void Projectile::simulate( F32 dt )
  917. {
  918. if ( isServerObject() && mCurrTick >= mDataBlock->lifetime )
  919. {
  920. deleteObject();
  921. return;
  922. }
  923. if ( mHasExploded )
  924. return;
  925. // ... otherwise, we have to do some simulation work.
  926. RayInfo rInfo;
  927. Point3F oldPosition;
  928. Point3F newPosition;
  929. oldPosition = mCurrPosition;
  930. if ( mDataBlock->isBallistic )
  931. mCurrVelocity.z -= 9.81 * mDataBlock->gravityMod * dt;
  932. newPosition = oldPosition + mCurrVelocity * dt;
  933. // disable the source objects collision reponse for a short time while we
  934. // determine if the projectile is capable of moving from the old position
  935. // to the new position, otherwise we'll hit ourself
  936. bool disableSourceObjCollision = (mSourceObject.isValid() && (ignoreSourceTimeout || mCurrTick <= SourceIdTimeoutTicks));
  937. if ( disableSourceObjCollision )
  938. mSourceObject->disableCollision();
  939. disableCollision();
  940. // Determine if the projectile is going to hit any object between the previous
  941. // position and the new position. This code is executed both on the server
  942. // and on the client (for prediction purposes). It is possible that the server
  943. // will have registered a collision while the client prediction has not. If this
  944. // happens the client will be corrected in the next packet update.
  945. // Raycast the abstract PhysicsWorld if a PhysicsPlugin exists.
  946. bool hit = false;
  947. if ( mPhysicsWorld )
  948. hit = mPhysicsWorld->castRay( oldPosition, newPosition, &rInfo, Point3F( newPosition - oldPosition) * mDataBlock->impactForce );
  949. else
  950. hit = getContainer()->castRay(oldPosition, newPosition, dynamicCollisionMask | staticCollisionMask, &rInfo);
  951. if ( hit )
  952. {
  953. // make sure the client knows to bounce
  954. if(isServerObject() && (rInfo.object->getTypeMask() & staticCollisionMask) == 0)
  955. setMaskBits( BounceMask );
  956. MatrixF xform( true );
  957. xform.setColumn( 3, rInfo.point );
  958. setTransform( xform );
  959. mCurrPosition = rInfo.point;
  960. // Get the object type before the onCollision call, in case
  961. // the object is destroyed.
  962. U32 objectType = rInfo.object->getTypeMask();
  963. // re-enable the collision response on the source object since
  964. // we need to process the onCollision and explode calls
  965. if ( disableSourceObjCollision )
  966. mSourceObject->enableCollision();
  967. // Ok, here is how this works:
  968. // onCollision is called to notify the server scripts that a collision has occurred, then
  969. // a call to explode is made to start the explosion process. The call to explode is made
  970. // twice, once on the server and once on the client.
  971. // The server process is responsible for two things:
  972. // 1) setting the ExplosionMask network bit to guarantee that the client calls explode
  973. // 2) initiate the explosion process on the server scripts
  974. // The client process is responsible for only one thing:
  975. // 1) drawing the appropriate explosion
  976. // It is possible that during the processTick the server may have decided that a hit
  977. // has occurred while the client prediction has decided that a hit has not occurred.
  978. // In this particular scenario the client will have failed to call onCollision and
  979. // explode during the processTick. However, the explode function will be called
  980. // during the next packet update, due to the ExplosionMask network bit being set.
  981. // onCollision will remain uncalled on the client however, therefore no client
  982. // specific code should be placed inside the function!
  983. onCollision( rInfo.point, rInfo.normal, rInfo.object );
  984. // Next order of business: do we explode on this hit?
  985. if ( mCurrTick > mDataBlock->armingDelay || mDataBlock->armingDelay == 0 )
  986. {
  987. mCurrVelocity = Point3F::Zero;
  988. explode( rInfo.point, rInfo.normal, objectType );
  989. }
  990. if ( mDataBlock->isBallistic )
  991. {
  992. // Otherwise, this represents a bounce. First, reflect our velocity
  993. // around the normal...
  994. Point3F bounceVel = mCurrVelocity - rInfo.normal * (mDot( mCurrVelocity, rInfo.normal ) * 2.0);
  995. mCurrVelocity = bounceVel;
  996. // Add in surface friction...
  997. Point3F tangent = bounceVel - rInfo.normal * mDot(bounceVel, rInfo.normal);
  998. mCurrVelocity -= tangent * mDataBlock->bounceFriction;
  999. // Now, take elasticity into account for modulating the speed of the grenade
  1000. mCurrVelocity *= mDataBlock->bounceElasticity;
  1001. // Set the new position to the impact and the bounce
  1002. // will apply on the next frame.
  1003. //F32 timeLeft = 1.0f - rInfo.t;
  1004. newPosition = oldPosition = rInfo.point + rInfo.normal * 0.05f;
  1005. }
  1006. else
  1007. {
  1008. mCurrVelocity = Point3F::Zero;
  1009. }
  1010. }
  1011. // re-enable the collision response on the source object now
  1012. // that we are done processing the ballistic movement
  1013. if ( disableSourceObjCollision )
  1014. mSourceObject->enableCollision();
  1015. enableCollision();
  1016. if ( isClientObject() )
  1017. {
  1018. emitParticles( mCurrPosition, newPosition, mCurrVelocity, U32( dt * 1000.0f ) );
  1019. updateSound();
  1020. }
  1021. mCurrDeltaBase = newPosition;
  1022. mCurrBackDelta = mCurrPosition - newPosition;
  1023. mCurrPosition = newPosition;
  1024. MatrixF xform( true );
  1025. xform.setColumn( 3, mCurrPosition );
  1026. setTransform( xform );
  1027. }
  1028. void Projectile::advanceTime(F32 dt)
  1029. {
  1030. Parent::advanceTime(dt);
  1031. if ( mHasExploded || dt == 0.0)
  1032. return;
  1033. if (mActivateThread &&
  1034. mProjectileShape->getDuration(mActivateThread) > mProjectileShape->getTime(mActivateThread) + dt)
  1035. {
  1036. mProjectileShape->advanceTime(dt, mActivateThread);
  1037. }
  1038. else
  1039. {
  1040. if (mMaintainThread)
  1041. {
  1042. mProjectileShape->advanceTime(dt, mMaintainThread);
  1043. }
  1044. else if (mActivateThread && mDataBlock->maintainSeq != -1)
  1045. {
  1046. mMaintainThread = mProjectileShape->addThread();
  1047. mProjectileShape->setTimeScale(mMaintainThread, 1);
  1048. mProjectileShape->setSequence(mMaintainThread, mDataBlock->maintainSeq, 0);
  1049. mProjectileShape->advanceTime(dt, mMaintainThread);
  1050. }
  1051. }
  1052. }
  1053. void Projectile::interpolateTick(F32 delta)
  1054. {
  1055. Parent::interpolateTick(delta);
  1056. if( mHasExploded )
  1057. return;
  1058. Point3F interpPos = mCurrDeltaBase + mCurrBackDelta * delta;
  1059. Point3F dir = mCurrVelocity;
  1060. if(dir.isZero())
  1061. dir.set(0,0,1);
  1062. else
  1063. dir.normalize();
  1064. MatrixF xform(true);
  1065. xform = MathUtils::createOrientFromDir(dir);
  1066. xform.setPosition(interpPos);
  1067. setRenderTransform(xform);
  1068. // fade out the projectile image
  1069. S32 time = (S32)(mCurrTick - delta);
  1070. if(time > mDataBlock->fadeDelay)
  1071. {
  1072. F32 fade = F32(time - mDataBlock->fadeDelay);
  1073. mFadeValue = 1.0 - (fade / F32(mDataBlock->lifetime));
  1074. }
  1075. else
  1076. mFadeValue = 1.0;
  1077. updateSound();
  1078. }
  1079. //--------------------------------------------------------------------------
  1080. void Projectile::onCollision(const Point3F& hitPosition, const Point3F& hitNormal, SceneObject* hitObject)
  1081. {
  1082. // No client specific code should be placed or branched from this function
  1083. if(isClientObject())
  1084. return;
  1085. if (hitObject != NULL && isServerObject())
  1086. {
  1087. mDataBlock->onCollision_callback( this, hitObject, mFadeValue, hitPosition, hitNormal );
  1088. }
  1089. }
  1090. //--------------------------------------------------------------------------
  1091. U32 Projectile::packUpdate( NetConnection *con, U32 mask, BitStream *stream )
  1092. {
  1093. U32 retMask = Parent::packUpdate( con, mask, stream );
  1094. const bool isInitalUpdate = mask & GameBase::InitialUpdateMask;
  1095. // InitialUpdateMask
  1096. if ( stream->writeFlag( isInitalUpdate ) )
  1097. {
  1098. stream->writeRangedU32( mCurrTick, 0, MaxLivingTicks );
  1099. if ( mSourceObject.isValid() )
  1100. {
  1101. // Potentially have to write this to the client, let's make sure it has a
  1102. // ghost on the other side...
  1103. S32 ghostIndex = con->getGhostIndex( mSourceObject );
  1104. if ( stream->writeFlag( ghostIndex != -1 ) )
  1105. {
  1106. stream->writeRangedU32( U32(ghostIndex),
  1107. 0,
  1108. NetConnection::MaxGhostCount );
  1109. stream->writeRangedU32( U32(mSourceObjectSlot),
  1110. 0,
  1111. ShapeBase::MaxMountedImages - 1 );
  1112. stream->writeFlag(ignoreSourceTimeout);
  1113. }
  1114. else
  1115. // have not recieved the ghost for the source object yet, try again later
  1116. retMask |= GameBase::InitialUpdateMask;
  1117. }
  1118. else
  1119. stream->writeFlag( false );
  1120. }
  1121. // ExplosionMask
  1122. //
  1123. // ExplosionMask will be set during the initial update but hidden is
  1124. // only true if we have really exploded.
  1125. if ( stream->writeFlag( ( mask & ExplosionMask ) && mHasExploded ) )
  1126. {
  1127. mathWrite(*stream, mExplosionPosition);
  1128. mathWrite(*stream, mExplosionNormal);
  1129. stream->write(mCollideHitType);
  1130. }
  1131. // BounceMask
  1132. if ( stream->writeFlag( mask & BounceMask ) )
  1133. {
  1134. // Bounce against dynamic object
  1135. mathWrite(*stream, mCurrPosition);
  1136. mathWrite(*stream, mCurrVelocity);
  1137. }
  1138. return retMask;
  1139. }
  1140. void Projectile::unpackUpdate(NetConnection* con, BitStream* stream)
  1141. {
  1142. Parent::unpackUpdate(con, stream);
  1143. if ( stream->readFlag() ) // InitialUpdateMask
  1144. {
  1145. mCurrTick = stream->readRangedU32( 0, MaxLivingTicks );
  1146. if ( stream->readFlag() )
  1147. {
  1148. mSourceObjectId = stream->readRangedU32( 0, NetConnection::MaxGhostCount );
  1149. mSourceObjectSlot = stream->readRangedU32( 0, ShapeBase::MaxMountedImages - 1 );
  1150. ignoreSourceTimeout = stream->readFlag();
  1151. NetObject* pObject = con->resolveGhost( mSourceObjectId );
  1152. if ( pObject != NULL )
  1153. mSourceObject = dynamic_cast<ShapeBase*>( pObject );
  1154. }
  1155. else
  1156. {
  1157. mSourceObjectId = -1;
  1158. mSourceObjectSlot = -1;
  1159. mSourceObject = NULL;
  1160. }
  1161. }
  1162. if ( stream->readFlag() ) // ExplosionMask
  1163. {
  1164. Point3F explodePoint;
  1165. Point3F explodeNormal;
  1166. mathRead( *stream, &explodePoint );
  1167. mathRead( *stream, &explodeNormal );
  1168. stream->read( &mCollideHitType );
  1169. // start the explosion visuals
  1170. explode( explodePoint, explodeNormal, mCollideHitType );
  1171. }
  1172. if ( stream->readFlag() ) // BounceMask
  1173. {
  1174. Point3F pos;
  1175. mathRead( *stream, &pos );
  1176. mathRead( *stream, &mCurrVelocity );
  1177. mCurrDeltaBase = pos;
  1178. mCurrBackDelta = mCurrPosition - pos;
  1179. mCurrPosition = pos;
  1180. setPosition( mCurrPosition );
  1181. }
  1182. }
  1183. //--------------------------------------------------------------------------
  1184. void Projectile::prepRenderImage( SceneRenderState* state )
  1185. {
  1186. if (mHasExploded || mFadeValue <= (1.0/255.0))
  1187. return;
  1188. if ( mDataBlock->lightDesc )
  1189. {
  1190. mDataBlock->lightDesc->prepRender( state, &mLightState, getRenderTransform() );
  1191. }
  1192. /*
  1193. if ( mFlareData )
  1194. {
  1195. mFlareState.fullBrightness = mDataBlock->lightDesc->mBrightness;
  1196. mFlareState.scale = mFlareScale;
  1197. mFlareState.lightInfo = mLight;
  1198. mFlareState.lightMat = getTransform();
  1199. mFlareData->prepRender( state, &mFlareState );
  1200. }
  1201. */
  1202. prepBatchRender( state );
  1203. }
  1204. void Projectile::prepBatchRender( SceneRenderState *state )
  1205. {
  1206. if ( !mProjectileShape )
  1207. return;
  1208. GFXTransformSaver saver;
  1209. // Set up our TS render state.
  1210. TSRenderState rdata;
  1211. rdata.setSceneState( state );
  1212. // We might have some forward lit materials
  1213. // so pass down a query to gather lights.
  1214. LightQuery query;
  1215. query.init( getWorldSphere() );
  1216. rdata.setLightQuery( &query );
  1217. MatrixF mat = getRenderTransform();
  1218. mat.scale( mObjScale );
  1219. mat.scale( mDataBlock->scale );
  1220. GFX->setWorldMatrix( mat );
  1221. mProjectileShape->setDetailFromPosAndScale( state, mat.getPosition(), mObjScale );
  1222. mProjectileShape->animate();
  1223. mProjectileShape->render( rdata );
  1224. }
  1225. DefineEngineMethod(Projectile, presimulate, void, (F32 seconds), (1.0f),
  1226. "@brief Updates the projectile's positional and collision information.\n\n"
  1227. "This function will first delete the projectile if it is a server object and is outside it's ProjectileData::lifetime. "
  1228. "Also responsible for applying gravity, determining collisions, triggering explosions, "
  1229. "emitting trail particles, and calculating bounces if necessary."
  1230. "@param seconds Amount of time, in seconds since the simulation's start, to advance.\n"
  1231. "@tsexample\n"
  1232. "// Tell the projectile to process a simulation event, and provide the amount of time\n"
  1233. "// that has passed since the simulation began.\n"
  1234. "%seconds = 2.0;\n"
  1235. "%projectile.presimulate(%seconds);\n"
  1236. "@endtsexample\n"
  1237. "@note This function is not called if the SimObject::hidden is true.")
  1238. {
  1239. object->simulate( seconds );
  1240. }