projectile.cpp 53 KB

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