projectile.cpp 48 KB

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