projectile.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  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. // Next order of business: do we explode on this hit?
  893. if ( mCurrTick > mDataBlock->armingDelay || mDataBlock->armingDelay == 0 )
  894. {
  895. MatrixF xform( true );
  896. xform.setColumn( 3, rInfo.point );
  897. setTransform( xform );
  898. mCurrPosition = rInfo.point;
  899. mCurrVelocity = Point3F::Zero;
  900. // Get the object type before the onCollision call, in case
  901. // the object is destroyed.
  902. U32 objectType = rInfo.object->getTypeMask();
  903. // re-enable the collision response on the source object since
  904. // we need to process the onCollision and explode calls
  905. if ( disableSourceObjCollision )
  906. mSourceObject->enableCollision();
  907. // Ok, here is how this works:
  908. // onCollision is called to notify the server scripts that a collision has occurred, then
  909. // a call to explode is made to start the explosion process. The call to explode is made
  910. // twice, once on the server and once on the client.
  911. // The server process is responsible for two things:
  912. // 1) setting the ExplosionMask network bit to guarantee that the client calls explode
  913. // 2) initiate the explosion process on the server scripts
  914. // The client process is responsible for only one thing:
  915. // 1) drawing the appropriate explosion
  916. // It is possible that during the processTick the server may have decided that a hit
  917. // has occurred while the client prediction has decided that a hit has not occurred.
  918. // In this particular scenario the client will have failed to call onCollision and
  919. // explode during the processTick. However, the explode function will be called
  920. // during the next packet update, due to the ExplosionMask network bit being set.
  921. // onCollision will remain uncalled on the client however, therefore no client
  922. // specific code should be placed inside the function!
  923. onCollision( rInfo.point, rInfo.normal, rInfo.object );
  924. explode( rInfo.point, rInfo.normal, objectType );
  925. // break out of the collision check, since we've exploded
  926. // we don't want to mess with the position and velocity
  927. }
  928. else
  929. {
  930. if ( mDataBlock->isBallistic )
  931. {
  932. // Otherwise, this represents a bounce. First, reflect our velocity
  933. // around the normal...
  934. Point3F bounceVel = mCurrVelocity - rInfo.normal * (mDot( mCurrVelocity, rInfo.normal ) * 2.0);
  935. mCurrVelocity = bounceVel;
  936. // Add in surface friction...
  937. Point3F tangent = bounceVel - rInfo.normal * mDot(bounceVel, rInfo.normal);
  938. mCurrVelocity -= tangent * mDataBlock->bounceFriction;
  939. // Now, take elasticity into account for modulating the speed of the grenade
  940. mCurrVelocity *= mDataBlock->bounceElasticity;
  941. // Set the new position to the impact and the bounce
  942. // will apply on the next frame.
  943. //F32 timeLeft = 1.0f - rInfo.t;
  944. newPosition = oldPosition = rInfo.point + rInfo.normal * 0.05f;
  945. }
  946. }
  947. }
  948. // re-enable the collision response on the source object now
  949. // that we are done processing the ballistic movement
  950. if ( disableSourceObjCollision )
  951. mSourceObject->enableCollision();
  952. enableCollision();
  953. if ( isClientObject() )
  954. {
  955. emitParticles( mCurrPosition, newPosition, mCurrVelocity, U32( dt * 1000.0f ) );
  956. updateSound();
  957. }
  958. mCurrDeltaBase = newPosition;
  959. mCurrBackDelta = mCurrPosition - newPosition;
  960. mCurrPosition = newPosition;
  961. MatrixF xform( true );
  962. xform.setColumn( 3, mCurrPosition );
  963. setTransform( xform );
  964. }
  965. void Projectile::advanceTime(F32 dt)
  966. {
  967. Parent::advanceTime(dt);
  968. if ( mHasExploded || dt == 0.0)
  969. return;
  970. if (mActivateThread &&
  971. mProjectileShape->getDuration(mActivateThread) > mProjectileShape->getTime(mActivateThread) + dt)
  972. {
  973. mProjectileShape->advanceTime(dt, mActivateThread);
  974. }
  975. else
  976. {
  977. if (mMaintainThread)
  978. {
  979. mProjectileShape->advanceTime(dt, mMaintainThread);
  980. }
  981. else if (mActivateThread && mDataBlock->maintainSeq != -1)
  982. {
  983. mMaintainThread = mProjectileShape->addThread();
  984. mProjectileShape->setTimeScale(mMaintainThread, 1);
  985. mProjectileShape->setSequence(mMaintainThread, mDataBlock->maintainSeq, 0);
  986. mProjectileShape->advanceTime(dt, mMaintainThread);
  987. }
  988. }
  989. }
  990. void Projectile::interpolateTick(F32 delta)
  991. {
  992. Parent::interpolateTick(delta);
  993. if( mHasExploded )
  994. return;
  995. Point3F interpPos = mCurrDeltaBase + mCurrBackDelta * delta;
  996. Point3F dir = mCurrVelocity;
  997. if(dir.isZero())
  998. dir.set(0,0,1);
  999. else
  1000. dir.normalize();
  1001. MatrixF xform(true);
  1002. xform = MathUtils::createOrientFromDir(dir);
  1003. xform.setPosition(interpPos);
  1004. setRenderTransform(xform);
  1005. // fade out the projectile image
  1006. S32 time = (S32)(mCurrTick - delta);
  1007. if(time > mDataBlock->fadeDelay)
  1008. {
  1009. F32 fade = F32(time - mDataBlock->fadeDelay);
  1010. mFadeValue = 1.0 - (fade / F32(mDataBlock->lifetime));
  1011. }
  1012. else
  1013. mFadeValue = 1.0;
  1014. updateSound();
  1015. }
  1016. //--------------------------------------------------------------------------
  1017. void Projectile::onCollision(const Point3F& hitPosition, const Point3F& hitNormal, SceneObject* hitObject)
  1018. {
  1019. // No client specific code should be placed or branched from this function
  1020. if(isClientObject())
  1021. return;
  1022. if (hitObject != NULL && isServerObject())
  1023. {
  1024. mDataBlock->onCollision_callback( this, hitObject, mFadeValue, hitPosition, hitNormal );
  1025. }
  1026. }
  1027. //--------------------------------------------------------------------------
  1028. U32 Projectile::packUpdate( NetConnection *con, U32 mask, BitStream *stream )
  1029. {
  1030. U32 retMask = Parent::packUpdate( con, mask, stream );
  1031. const bool isInitalUpdate = mask & GameBase::InitialUpdateMask;
  1032. // InitialUpdateMask
  1033. if ( stream->writeFlag( isInitalUpdate ) )
  1034. {
  1035. stream->writeRangedU32( mCurrTick, 0, MaxLivingTicks );
  1036. if ( mSourceObject.isValid() )
  1037. {
  1038. // Potentially have to write this to the client, let's make sure it has a
  1039. // ghost on the other side...
  1040. S32 ghostIndex = con->getGhostIndex( mSourceObject );
  1041. if ( stream->writeFlag( ghostIndex != -1 ) )
  1042. {
  1043. stream->writeRangedU32( U32(ghostIndex),
  1044. 0,
  1045. NetConnection::MaxGhostCount );
  1046. stream->writeRangedU32( U32(mSourceObjectSlot),
  1047. 0,
  1048. ShapeBase::MaxMountedImages - 1 );
  1049. }
  1050. else
  1051. // have not recieved the ghost for the source object yet, try again later
  1052. retMask |= GameBase::InitialUpdateMask;
  1053. }
  1054. else
  1055. stream->writeFlag( false );
  1056. }
  1057. // ExplosionMask
  1058. //
  1059. // ExplosionMask will be set during the initial update but hidden is
  1060. // only true if we have really exploded.
  1061. if ( stream->writeFlag( ( mask & ExplosionMask ) && mHasExploded ) )
  1062. {
  1063. mathWrite(*stream, mExplosionPosition);
  1064. mathWrite(*stream, mExplosionNormal);
  1065. stream->write(mCollideHitType);
  1066. }
  1067. // BounceMask
  1068. if ( stream->writeFlag( mask & BounceMask ) )
  1069. {
  1070. // Bounce against dynamic object
  1071. mathWrite(*stream, mCurrPosition);
  1072. mathWrite(*stream, mCurrVelocity);
  1073. }
  1074. return retMask;
  1075. }
  1076. void Projectile::unpackUpdate(NetConnection* con, BitStream* stream)
  1077. {
  1078. Parent::unpackUpdate(con, stream);
  1079. if ( stream->readFlag() ) // InitialUpdateMask
  1080. {
  1081. mCurrTick = stream->readRangedU32( 0, MaxLivingTicks );
  1082. if ( stream->readFlag() )
  1083. {
  1084. mSourceObjectId = stream->readRangedU32( 0, NetConnection::MaxGhostCount );
  1085. mSourceObjectSlot = stream->readRangedU32( 0, ShapeBase::MaxMountedImages - 1 );
  1086. NetObject* pObject = con->resolveGhost( mSourceObjectId );
  1087. if ( pObject != NULL )
  1088. mSourceObject = dynamic_cast<ShapeBase*>( pObject );
  1089. }
  1090. else
  1091. {
  1092. mSourceObjectId = -1;
  1093. mSourceObjectSlot = -1;
  1094. mSourceObject = NULL;
  1095. }
  1096. }
  1097. if ( stream->readFlag() ) // ExplosionMask
  1098. {
  1099. Point3F explodePoint;
  1100. Point3F explodeNormal;
  1101. mathRead( *stream, &explodePoint );
  1102. mathRead( *stream, &explodeNormal );
  1103. stream->read( &mCollideHitType );
  1104. // start the explosion visuals
  1105. explode( explodePoint, explodeNormal, mCollideHitType );
  1106. }
  1107. if ( stream->readFlag() ) // BounceMask
  1108. {
  1109. Point3F pos;
  1110. mathRead( *stream, &pos );
  1111. mathRead( *stream, &mCurrVelocity );
  1112. mCurrDeltaBase = pos;
  1113. mCurrBackDelta = mCurrPosition - pos;
  1114. mCurrPosition = pos;
  1115. setPosition( mCurrPosition );
  1116. }
  1117. }
  1118. //--------------------------------------------------------------------------
  1119. void Projectile::prepRenderImage( SceneRenderState* state )
  1120. {
  1121. if (mHasExploded || mFadeValue <= (1.0/255.0))
  1122. return;
  1123. if ( mDataBlock->lightDesc )
  1124. {
  1125. mDataBlock->lightDesc->prepRender( state, &mLightState, getRenderTransform() );
  1126. }
  1127. /*
  1128. if ( mFlareData )
  1129. {
  1130. mFlareState.fullBrightness = mDataBlock->lightDesc->mBrightness;
  1131. mFlareState.scale = mFlareScale;
  1132. mFlareState.lightInfo = mLight;
  1133. mFlareState.lightMat = getTransform();
  1134. mFlareData->prepRender( state, &mFlareState );
  1135. }
  1136. */
  1137. prepBatchRender( state );
  1138. }
  1139. void Projectile::prepBatchRender( SceneRenderState *state )
  1140. {
  1141. if ( !mProjectileShape )
  1142. return;
  1143. GFXTransformSaver saver;
  1144. // Set up our TS render state.
  1145. TSRenderState rdata;
  1146. rdata.setSceneState( state );
  1147. // We might have some forward lit materials
  1148. // so pass down a query to gather lights.
  1149. LightQuery query;
  1150. query.init( getWorldSphere() );
  1151. rdata.setLightQuery( &query );
  1152. MatrixF mat = getRenderTransform();
  1153. mat.scale( mObjScale );
  1154. mat.scale( mDataBlock->scale );
  1155. GFX->setWorldMatrix( mat );
  1156. mProjectileShape->setDetailFromPosAndScale( state, mat.getPosition(), mObjScale );
  1157. mProjectileShape->animate();
  1158. mProjectileShape->render( rdata );
  1159. }
  1160. DefineEngineMethod(Projectile, presimulate, void, (F32 seconds), (1.0f),
  1161. "@brief Updates the projectile's positional and collision information.\n\n"
  1162. "This function will first delete the projectile if it is a server object and is outside it's ProjectileData::lifetime. "
  1163. "Also responsible for applying gravity, determining collisions, triggering explosions, "
  1164. "emitting trail particles, and calculating bounces if necessary."
  1165. "@param seconds Amount of time, in seconds since the simulation's start, to advance.\n"
  1166. "@tsexample\n"
  1167. "// Tell the projectile to process a simulation event, and provide the amount of time\n"
  1168. "// that has passed since the simulation began.\n"
  1169. "%seconds = 2.0;\n"
  1170. "%projectile.presimulate(%seconds);\n"
  1171. "@endtsexample\n"
  1172. "@note This function is not called if the SimObject::hidden is true.")
  1173. {
  1174. object->simulate( seconds );
  1175. }