explosion.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  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/fx/explosion.h"
  28. #include "core/resourceManager.h"
  29. #include "console/consoleTypes.h"
  30. #include "console/typeValidators.h"
  31. #include "sfx/sfxSystem.h"
  32. #include "sfx/sfxTrack.h"
  33. #include "sfx/sfxTypes.h"
  34. #include "scene/sceneManager.h"
  35. #include "scene/sceneRenderState.h"
  36. #include "lighting/lightInfo.h"
  37. #include "lighting/lightManager.h"
  38. #include "core/stream/bitStream.h"
  39. #include "sim/netConnection.h"
  40. #include "ts/tsShape.h"
  41. #include "ts/tsShapeInstance.h"
  42. #include "math/mRandom.h"
  43. #include "math/mathIO.h"
  44. #include "math/mathUtils.h"
  45. #include "T3D/debris.h"
  46. #include "T3D/gameBase/gameConnection.h"
  47. #include "T3D/fx/particleEmitter.h"
  48. #include "T3D/fx/cameraFXMgr.h"
  49. #include "T3D/debris.h"
  50. #include "T3D/shapeBase.h"
  51. #include "T3D/gameBase/gameProcess.h"
  52. #include "renderInstance/renderPassManager.h"
  53. #include "console/engineAPI.h"
  54. #include "sfx/sfxProfile.h"
  55. IMPLEMENT_CONOBJECT(Explosion);
  56. ConsoleDocClass( Explosion,
  57. "@brief The emitter for an explosion effect, with properties defined by a "
  58. "ExplosionData object.\n\n"
  59. "@ingroup FX\n"
  60. "The object will initiate the explosion effects automatically after being "
  61. "added to the simulation.\n"
  62. "@tsexample\n"
  63. "datablock ExplosionData( GrenadeSubExplosion )\n"
  64. "{\n"
  65. " offset = 0.25;\n"
  66. " emitter[0] = GrenadeExpSparkEmitter;\n\n"
  67. " lightStartRadius = 4.0;\n"
  68. " lightEndRadius = 0.0;\n"
  69. " lightStartColor = \"0.9 0.7 0.7\";\n"
  70. " lightEndColor = \"0.9 0.7 0.7\";\n"
  71. " lightStartBrightness = 2.0;\n"
  72. " lightEndBrightness = 0.0;\n"
  73. "};\n\n"
  74. "datablock ExplosionData( GrenadeLauncherExplosion )\n"
  75. "{\n"
  76. " soundProfile = GrenadeLauncherExplosionSound;\n"
  77. " lifeTimeMS = 400; // Quick flash, short burn, and moderate dispersal\n\n"
  78. " // Volume particles\n"
  79. " particleEmitter = GrenadeExpFireEmitter;\n"
  80. " particleDensity = 75;\n"
  81. " particleRadius = 2.25;\n\n"
  82. " // Point emission\n"
  83. " emitter[0] = GrenadeExpDustEmitter;\n"
  84. " emitter[1] = GrenadeExpSparksEmitter;\n"
  85. " emitter[2] = GrenadeExpSmokeEmitter;\n\n"
  86. " // Sub explosion objects\n"
  87. " subExplosion[0] = GrenadeSubExplosion;\n\n"
  88. " // Camera Shaking\n"
  89. " shakeCamera = true;\n"
  90. " camShakeFreq = \"10.0 11.0 9.0\";\n"
  91. " camShakeAmp = \"15.0 15.0 15.0\";\n"
  92. " camShakeDuration = 1.5;\n"
  93. " camShakeRadius = 20;\n\n"
  94. " // Exploding debris\n"
  95. " debris = GrenadeDebris;\n"
  96. " debrisThetaMin = 10;\n"
  97. " debrisThetaMax = 60;\n"
  98. " debrisNum = 4;\n"
  99. " debrisNumVariance = 2;\n"
  100. " debrisVelocity = 25;\n"
  101. " debrisVelocityVariance = 5;\n\n"
  102. " lightStartRadius = 4.0;\n"
  103. " lightEndRadius = 0.0;\n"
  104. " lightStartColor = \"1.0 1.0 1.0\";\n"
  105. " lightEndColor = \"1.0 1.0 1.0\";\n"
  106. " lightStartBrightness = 4.0;\n"
  107. " lightEndBrightness = 0.0;\n"
  108. " lightNormalOffset = 2.0;\n"
  109. "};\n\n"
  110. "function ServerPlayExplosion(%position, %datablock)\n"
  111. "{\n"
  112. " // Play the given explosion on every client.\n"
  113. " // The explosion will be transmitted as an event, not attached to any object.\n"
  114. " for(%idx = 0; %idx < ClientGroup.getCount(); %idx++)\n"
  115. " {\n"
  116. " %client = ClientGroup.getObject(%idx);\n"
  117. " commandToClient(%client, 'PlayExplosion', %position, %datablock.getId());\n"
  118. " }\n"
  119. "}\n\n"
  120. "function clientCmdPlayExplosion(%position, %effectDataBlock)\n"
  121. "{\n"
  122. " // Play an explosion sent by the server. Make sure this function is defined\n"
  123. " // on the client.\n"
  124. " if (isObject(%effectDataBlock))\n"
  125. " {\n"
  126. " new Explosion()\n"
  127. " {\n"
  128. " position = %position;\n"
  129. " dataBlock = %effectDataBlock;\n"
  130. " };\n"
  131. " }\n"
  132. "}\n\n"
  133. "// schedule an explosion\n"
  134. "schedule(1000, 0, ServerPlayExplosion, \"0 0 0\", GrenadeLauncherExplosion);\n"
  135. "@endtsexample"
  136. );
  137. #define MaxLightRadius 20
  138. MRandomLCG sgRandom(0xdeadbeef);
  139. //WLE - Vince - The defaults are bad, the whole point of calling this function\
  140. //is to determine the explosion coverage on a object. Why would you want them
  141. //To call this with a null for the ID? In fact, it just returns a 1f if
  142. //it can't find the object. Seems useless to me. Cause how can I apply
  143. //damage to a object that doesn't exist?
  144. //I could possible see a use with passing in a null covMask, but even that
  145. //sounds flaky because it will be 100 percent if your saying not to take
  146. //any thing in consideration for coverage. So I'm removing these defaults they are just bad.
  147. DefineEngineFunction(calcExplosionCoverage, F32, (Point3F pos, S32 id, U32 covMask),,
  148. "@brief Calculates how much an explosion effects a specific object.\n\n"
  149. "Use this to determine how much damage to apply to objects based on their "
  150. "distance from the explosion's center point, and whether the explosion is "
  151. "blocked by other objects.\n\n"
  152. "@param pos Center position of the explosion.\n"
  153. "@param id Id of the object of which to check coverage.\n"
  154. "@param covMask Mask of object types that may block the explosion.\n"
  155. "@return Coverage value from 0 (not affected by the explosion) to 1 (fully affected)\n\n"
  156. "@tsexample\n"
  157. "// Get the position of the explosion.\n"
  158. "%position = %explosion.getPosition();\n\n"
  159. "// Set a list of TypeMasks (defined in gameFunctioncs.cpp), seperated by the | character.\n"
  160. "%TypeMasks = $TypeMasks::StaticObjectType | $TypeMasks::ItemObjectType\n\n"
  161. "// Acquire the damage value from 0.0f - 1.0f.\n"
  162. "%coverage = calcExplosionCoverage( %position, %sceneObject, %TypeMasks );\n\n"
  163. "// Apply damage to object\n"
  164. "%sceneObject.applyDamage( %coverage * 20 );\n"
  165. "@endtsexample\n"
  166. "@ingroup FX")
  167. {
  168. Point3F center;
  169. SceneObject* sceneObject = NULL;
  170. if (Sim::findObject(id, sceneObject) == false) {
  171. Con::warnf(ConsoleLogEntry::General, "calcExplosionCoverage: couldn't find object: %d", id);
  172. return 1.0f;
  173. }
  174. if (sceneObject->isClientObject() || sceneObject->getContainer() == NULL) {
  175. Con::warnf(ConsoleLogEntry::General, "calcExplosionCoverage: object is on the client, or not in the container system");
  176. return 1.0f;
  177. }
  178. sceneObject->getObjBox().getCenter(&center);
  179. center.convolve(sceneObject->getScale());
  180. sceneObject->getTransform().mulP(center);
  181. RayInfo rayInfo;
  182. sceneObject->disableCollision();
  183. if (sceneObject->getContainer()->castRay(pos, center, covMask, &rayInfo) == true) {
  184. // Try casting up and then out
  185. if (sceneObject->getContainer()->castRay(pos, pos + Point3F(0.0f, 0.0f, 1.0f), covMask, &rayInfo) == false)
  186. {
  187. if (sceneObject->getContainer()->castRay(pos + Point3F(0.0f, 0.0f, 1.0f), center, covMask, &rayInfo) == false)
  188. {
  189. sceneObject->enableCollision();
  190. return 1.0f;
  191. }
  192. }
  193. sceneObject->enableCollision();
  194. return 0.0f;
  195. } else {
  196. sceneObject->enableCollision();
  197. return 1.0f;
  198. }
  199. }
  200. //----------------------------------------------------------------------------
  201. //
  202. IMPLEMENT_CO_DATABLOCK_V1(ExplosionData);
  203. ConsoleDocClass( ExplosionData,
  204. "@brief Defines the attributes of an Explosion: particleEmitters, debris, "
  205. "lighting and camera shake effects.\n"
  206. "@ingroup FX\n"
  207. );
  208. ExplosionData::ExplosionData()
  209. {
  210. particleDensity = 10;
  211. particleRadius = 1.0f;
  212. faceViewer = false;
  213. INIT_ASSET(Sound);
  214. //soundProfile = NULL;
  215. particleEmitter = NULL;
  216. particleEmitterId = 0;
  217. explosionScale.set(1.0f, 1.0f, 1.0f);
  218. playSpeed = 1.0f;
  219. INIT_ASSET(ExplosionShape);
  220. explosionAnimation = -1;
  221. dMemset( emitterList, 0, sizeof( emitterList ) );
  222. dMemset( emitterIDList, 0, sizeof( emitterIDList ) );
  223. dMemset( debrisList, 0, sizeof( debrisList ) );
  224. dMemset( debrisIDList, 0, sizeof( debrisIDList ) );
  225. debrisThetaMin = 0.0f;
  226. debrisThetaMax = 90.0f;
  227. debrisPhiMin = 0.0f;
  228. debrisPhiMax = 360.0f;
  229. debrisNum = 1;
  230. debrisNumVariance = 0;
  231. debrisVelocity = 2.0f;
  232. debrisVelocityVariance = 0.0f;
  233. dMemset( explosionList, 0, sizeof( explosionList ) );
  234. dMemset( explosionIDList, 0, sizeof( explosionIDList ) );
  235. delayMS = 0;
  236. delayVariance = 0;
  237. lifetimeMS = 1000;
  238. lifetimeVariance = 0;
  239. offset = 0.0f;
  240. shakeCamera = false;
  241. camShakeFreq.set( 10.0f, 10.0f, 10.0f );
  242. camShakeAmp.set( 1.0f, 1.0f, 1.0f );
  243. camShakeDuration = 1.5f;
  244. camShakeRadius = 10.0f;
  245. camShakeFalloff = 10.0f;
  246. for( U32 i=0; i<EC_NUM_TIME_KEYS; i++ )
  247. {
  248. times[i] = 1.0f;
  249. }
  250. times[0] = 0.0f;
  251. for( U32 j=0; j<EC_NUM_TIME_KEYS; j++ )
  252. {
  253. sizes[j].set( 1.0f, 1.0f, 1.0f );
  254. }
  255. //
  256. lightStartRadius = lightEndRadius = 0.0f;
  257. lightStartColor.set(1.0f,1.0f,1.0f);
  258. lightEndColor.set(1.0f,1.0f,1.0f);
  259. lightStartBrightness = 1.0f;
  260. lightEndBrightness = 1.0f;
  261. lightNormalOffset = 0.1f;
  262. }
  263. //#define TRACK_EXPLOSION_DATA_CLONES
  264. #ifdef TRACK_EXPLOSION_DATA_CLONES
  265. static int explosion_data_clones = 0;
  266. #endif
  267. ExplosionData::ExplosionData(const ExplosionData& other, bool temp_clone) : GameBaseData(other, temp_clone)
  268. {
  269. #ifdef TRACK_EXPLOSION_DATA_CLONES
  270. explosion_data_clones++;
  271. if (explosion_data_clones == 1)
  272. Con::errorf("ExplosionData -- Clones are on the loose!");
  273. #endif
  274. faceViewer = other.faceViewer;
  275. particleDensity = other.particleDensity;
  276. particleRadius = other.particleRadius;
  277. CLONE_ASSET(Sound);
  278. particleEmitter = other.particleEmitter;
  279. particleEmitterId = other.particleEmitterId; // -- for pack/unpack of particleEmitter ptr
  280. explosionScale = other.explosionScale;
  281. playSpeed = other.playSpeed;
  282. CLONE_ASSET(ExplosionShape);
  283. explosionAnimation = other.explosionAnimation; // -- from explosionShape sequence "ambient"
  284. dMemcpy( emitterList, other.emitterList, sizeof( emitterList ) );
  285. dMemcpy( emitterIDList, other.emitterIDList, sizeof( emitterIDList ) ); // -- for pack/unpack of emitterList ptrs
  286. dMemcpy( debrisList, other.debrisList, sizeof( debrisList ) );
  287. dMemcpy( debrisIDList, other.debrisIDList, sizeof( debrisIDList ) ); // -- for pack/unpack of debrisList ptrs
  288. debrisThetaMin = other.debrisThetaMin;
  289. debrisThetaMax = other.debrisThetaMax;
  290. debrisPhiMin = other.debrisPhiMin;
  291. debrisPhiMax = other.debrisPhiMax;
  292. debrisNum = other.debrisNum;
  293. debrisNumVariance = other.debrisNumVariance;
  294. debrisVelocity = other.debrisVelocity;
  295. debrisVelocityVariance = other.debrisVelocityVariance;
  296. dMemcpy( explosionList, other.explosionList, sizeof( explosionList ) );
  297. dMemcpy( explosionIDList, other.explosionIDList, sizeof( explosionIDList ) ); // -- for pack/unpack of explosionList ptrs
  298. delayMS = other.delayMS;
  299. delayVariance = other.delayVariance;
  300. lifetimeMS = other.lifetimeMS;
  301. lifetimeVariance = other.lifetimeVariance;
  302. offset = other.offset;
  303. dMemcpy( sizes, other.times, sizeof( sizes ) );
  304. dMemcpy( times, other.times, sizeof( times ) );
  305. shakeCamera = other.shakeCamera;
  306. camShakeFreq = other.camShakeFreq;
  307. camShakeAmp = other.camShakeAmp;
  308. camShakeDuration = other.camShakeDuration;
  309. camShakeRadius = other.camShakeRadius;
  310. camShakeFalloff = other.camShakeFalloff;
  311. lightStartRadius = other.lightStartRadius;
  312. lightEndRadius = other.lightEndRadius;
  313. lightStartColor = other.lightStartColor;
  314. lightEndColor = other.lightEndColor;
  315. lightStartBrightness = other.lightStartBrightness;
  316. lightEndBrightness = other.lightEndBrightness;
  317. lightNormalOffset = other.lightNormalOffset;
  318. // Note - Explosion calls mDataBlock->getName() in warning messages but
  319. // that should be safe.
  320. }
  321. ExplosionData::~ExplosionData()
  322. {
  323. if (!isTempClone())
  324. return;
  325. // particleEmitter, emitterList[*], debrisList[*], explosionList[*] will delete themselves
  326. #ifdef TRACK_EXPLOSION_DATA_CLONES
  327. if (explosion_data_clones > 0)
  328. {
  329. explosion_data_clones--;
  330. if (explosion_data_clones == 0)
  331. Con::errorf("ExplosionData -- Clones eliminated!");
  332. }
  333. else
  334. Con::errorf("ExplosionData -- Too many clones deleted!");
  335. #endif
  336. }
  337. ExplosionData* ExplosionData::cloneAndPerformSubstitutions(const SimObject* owner, S32 index)
  338. {
  339. if (!owner || getSubstitutionCount() == 0)
  340. return this;
  341. ExplosionData* sub_explosion_db = new ExplosionData(*this, true);
  342. performSubstitutions(sub_explosion_db, owner, index);
  343. return sub_explosion_db;
  344. }
  345. void ExplosionData::initPersistFields()
  346. {
  347. INITPERSISTFIELD_SHAPEASSET(ExplosionShape, ExplosionData, "@brief Optional shape asset to place at the center of the explosion.\n\n"
  348. "The <i>ambient</i> animation of this model will be played automatically at the start of the explosion.");
  349. addField( "explosionScale", TypePoint3F, Offset(explosionScale, ExplosionData),
  350. "\"X Y Z\" scale factor applied to the explosionShape model at the start "
  351. "of the explosion." );
  352. addField( "playSpeed", TypeF32, Offset(playSpeed, ExplosionData),
  353. "Time scale at which to play the explosionShape <i>ambient</i> sequence." );
  354. INITPERSISTFIELD_SOUNDASSET(Sound, ExplosionData, "Sound to play when this explosion explodes.");
  355. addField( "faceViewer", TypeBool, Offset(faceViewer, ExplosionData),
  356. "Controls whether the visual effects of the explosion always face the camera." );
  357. addField( "particleEmitter", TYPEID< ParticleEmitterData >(), Offset(particleEmitter, ExplosionData),
  358. "@brief Emitter used to generate a cloud of particles at the start of the explosion.\n\n"
  359. "Explosions can generate two different particle effects. The first is a "
  360. "single burst of particles at the start of the explosion emitted in a "
  361. "spherical cloud using particleEmitter.\n\n"
  362. "The second effect spawns the list of ParticleEmitters given by the emitter[] "
  363. "field. These emitters generate particles in the normal way throughout the "
  364. "lifetime of the explosion." );
  365. addField( "particleDensity", TypeS32, Offset(particleDensity, ExplosionData),
  366. "@brief Density of the particle cloud created at the start of the explosion.\n\n"
  367. "@see particleEmitter" );
  368. addField( "particleRadius", TypeF32, Offset(particleRadius, ExplosionData),
  369. "@brief Radial distance from the explosion center at which cloud particles "
  370. "are emitted.\n\n"
  371. "@see particleEmitter" );
  372. addField( "emitter", TYPEID< ParticleEmitterData >(), Offset(emitterList, ExplosionData), EC_NUM_EMITTERS,
  373. "@brief List of additional ParticleEmitterData objects to spawn with this "
  374. "explosion.\n\n"
  375. "@see particleEmitter" );
  376. addField( "debris", TYPEID< DebrisData >(), Offset(debrisList, ExplosionData), EC_NUM_DEBRIS_TYPES,
  377. "List of DebrisData objects to spawn with this explosion." );
  378. addField( "debrisThetaMin", TypeF32, Offset(debrisThetaMin, ExplosionData),
  379. "Minimum angle, from the horizontal plane, to eject debris from." );
  380. addField( "debrisThetaMax", TypeF32, Offset(debrisThetaMax, ExplosionData),
  381. "Maximum angle, from the horizontal plane, to eject debris from." );
  382. addField( "debrisPhiMin", TypeF32, Offset(debrisPhiMin, ExplosionData),
  383. "Minimum reference angle, from the vertical plane, to eject debris from." );
  384. addField( "debrisPhiMax", TypeF32, Offset(debrisPhiMax, ExplosionData),
  385. "Maximum reference angle, from the vertical plane, to eject debris from." );
  386. addField( "debrisNum", TypeS32, Offset(debrisNum, ExplosionData),
  387. "Number of debris objects to create." );
  388. addField( "debrisNumVariance", TypeS32, Offset(debrisNumVariance, ExplosionData),
  389. "Variance in the number of debris objects to create (must be from 0 - debrisNum)." );
  390. addField( "debrisVelocity", TypeF32, Offset(debrisVelocity, ExplosionData),
  391. "Velocity to toss debris at." );
  392. addField( "debrisVelocityVariance", TypeF32, Offset(debrisVelocityVariance, ExplosionData),
  393. "Variance in the debris initial velocity (must be >= 0)." );
  394. addField( "subExplosion", TYPEID< ExplosionData >(), Offset(explosionList, ExplosionData), EC_MAX_SUB_EXPLOSIONS,
  395. "List of additional ExplosionData objects to create at the start of the "
  396. "explosion." );
  397. addField( "delayMS", TypeS32, Offset(delayMS, ExplosionData),
  398. "Amount of time, in milliseconds, to delay the start of the explosion effect "
  399. "from the creation of the Explosion object." );
  400. addField( "delayVariance", TypeS32, Offset(delayVariance, ExplosionData),
  401. "Variance, in milliseconds, of delayMS." );
  402. addField( "lifetimeMS", TypeS32, Offset(lifetimeMS, ExplosionData),
  403. "@brief Lifetime, in milliseconds, of the Explosion object.\n\n"
  404. "@note If explosionShape is defined and contains an <i>ambient</i> animation, "
  405. "this field is ignored, and the playSpeed scaled duration of the animation "
  406. "is used instead." );
  407. addField( "lifetimeVariance", TypeS32, Offset(lifetimeVariance, ExplosionData),
  408. "Variance, in milliseconds, of the lifetimeMS of the Explosion object.\n" );
  409. addField( "offset", TypeF32, Offset(offset, ExplosionData),
  410. "@brief Offset distance (in a random direction) of the center of the explosion "
  411. "from the Explosion object position.\n\n"
  412. "Most often used to create some variance in position for subExplosion effects." );
  413. addField( "times", TypeF32, Offset(times, ExplosionData), EC_NUM_TIME_KEYS,
  414. "@brief Time keyframes used to scale the explosionShape model.\n\n"
  415. "Values should be in increasing order from 0.0 - 1.0, and correspond to "
  416. "the life of the Explosion where 0 is the beginning and 1 is the end of "
  417. "the explosion lifetime.\n"
  418. "@see lifetimeMS" );
  419. addField( "sizes", TypePoint3F, Offset(sizes, ExplosionData), EC_NUM_TIME_KEYS,
  420. "@brief \"X Y Z\" size keyframes used to scale the explosionShape model.\n\n"
  421. "The explosionShape (if defined) will be scaled using the times/sizes "
  422. "keyframes over the lifetime of the explosion.\n"
  423. "@see lifetimeMS" );
  424. addField( "shakeCamera", TypeBool, Offset(shakeCamera, ExplosionData),
  425. "Controls whether the camera shakes during this explosion." );
  426. addField( "camShakeFreq", TypePoint3F, Offset(camShakeFreq, ExplosionData),
  427. "Frequency of camera shaking, defined in the \"X Y Z\" axes." );
  428. addField( "camShakeAmp", TypePoint3F, Offset(camShakeAmp, ExplosionData),
  429. "@brief Amplitude of camera shaking, defined in the \"X Y Z\" axes.\n\n"
  430. "Set any value to 0 to disable shaking in that axis." );
  431. addField( "camShakeDuration", TypeF32, Offset(camShakeDuration, ExplosionData),
  432. "Duration (in seconds) to shake the camera." );
  433. addField( "camShakeRadius", TypeF32, Offset(camShakeRadius, ExplosionData),
  434. "Radial distance that a camera's position must be within relative to the "
  435. "center of the explosion to be shaken." );
  436. addField( "camShakeFalloff", TypeF32, Offset(camShakeFalloff, ExplosionData),
  437. "Falloff value for the camera shake." );
  438. addField( "lightStartRadius", TypeF32, Offset(lightStartRadius, ExplosionData),
  439. "@brief Initial radius of the PointLight created by this explosion.\n\n"
  440. "Radius is linearly interpolated from lightStartRadius to lightEndRadius "
  441. "over the lifetime of the explosion.\n"
  442. "@see lifetimeMS" );
  443. addField( "lightEndRadius", TypeF32, Offset(lightEndRadius, ExplosionData),
  444. "@brief Final radius of the PointLight created by this explosion.\n\n"
  445. "@see lightStartRadius" );
  446. addField( "lightStartColor", TypeColorF, Offset(lightStartColor, ExplosionData),
  447. "@brief Initial color of the PointLight created by this explosion.\n\n"
  448. "Color is linearly interpolated from lightStartColor to lightEndColor "
  449. "over the lifetime of the explosion.\n"
  450. "@see lifetimeMS" );
  451. addField( "lightEndColor", TypeColorF, Offset(lightEndColor, ExplosionData),
  452. "@brief Final color of the PointLight created by this explosion.\n\n"
  453. "@see lightStartColor" );
  454. addField( "lightStartBrightness", TypeF32, Offset(lightStartBrightness, ExplosionData),
  455. "@brief Initial brightness of the PointLight created by this explosion.\n\n"
  456. "Brightness is linearly interpolated from lightStartBrightness to "
  457. "lightEndBrightness over the lifetime of the explosion.\n"
  458. "@see lifetimeMS" );
  459. addField("lightEndBrightness", TypeF32, Offset(lightEndBrightness, ExplosionData),
  460. "@brief Final brightness of the PointLight created by this explosion.\n\n"
  461. "@see lightStartBrightness" );
  462. addField( "lightNormalOffset", TypeF32, Offset(lightNormalOffset, ExplosionData),
  463. "Distance (in the explosion normal direction) of the PointLight position "
  464. "from the explosion center." );
  465. // disallow some field substitutions
  466. onlyKeepClearSubstitutions("debris"); // subs resolving to "~~", or "~0" are OK
  467. onlyKeepClearSubstitutions("emitter");
  468. onlyKeepClearSubstitutions("particleEmitter");
  469. onlyKeepClearSubstitutions("subExplosion");
  470. Parent::initPersistFields();
  471. }
  472. bool ExplosionData::onAdd()
  473. {
  474. if (Parent::onAdd() == false)
  475. return false;
  476. if (explosionScale.x < 0.01f || explosionScale.y < 0.01f || explosionScale.z < 0.01f)
  477. {
  478. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s)::onAdd: ExplosionScale components must be >= 0.01", getName());
  479. explosionScale.x = explosionScale.x < 0.01f ? 0.01f : explosionScale.x;
  480. explosionScale.y = explosionScale.y < 0.01f ? 0.01f : explosionScale.y;
  481. explosionScale.z = explosionScale.z < 0.01f ? 0.01f : explosionScale.z;
  482. }
  483. if (debrisThetaMin < 0.0f)
  484. {
  485. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisThetaMin < 0.0", getName());
  486. debrisThetaMin = 0.0f;
  487. }
  488. if (debrisThetaMax > 180.0f)
  489. {
  490. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisThetaMax > 180.0", getName());
  491. debrisThetaMax = 180.0f;
  492. }
  493. if (debrisThetaMin > debrisThetaMax) {
  494. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisThetaMin > debrisThetaMax", getName());
  495. debrisThetaMin = debrisThetaMax;
  496. }
  497. if (debrisPhiMin < 0.0f)
  498. {
  499. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisPhiMin < 0.0", getName());
  500. debrisPhiMin = 0.0f;
  501. }
  502. if (debrisPhiMax > 360.0f)
  503. {
  504. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisPhiMax > 360.0", getName());
  505. debrisPhiMax = 360.0f;
  506. }
  507. if (debrisPhiMin > debrisPhiMax) {
  508. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisPhiMin > debrisPhiMax", getName());
  509. debrisPhiMin = debrisPhiMax;
  510. }
  511. if (debrisNum > 1000) {
  512. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisNum > 1000", getName());
  513. debrisNum = 1000;
  514. }
  515. if (debrisNumVariance > 1000) {
  516. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisNumVariance > 1000", getName());
  517. debrisNumVariance = 1000;
  518. }
  519. if (debrisVelocity < 0.1f)
  520. {
  521. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisVelocity < 0.1", getName());
  522. debrisVelocity = 0.1f;
  523. }
  524. if (debrisVelocityVariance > 1000) {
  525. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisVelocityVariance > 1000", getName());
  526. debrisVelocityVariance = 1000;
  527. }
  528. if (playSpeed < 0.05f)
  529. {
  530. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) playSpeed < 0.05", getName());
  531. playSpeed = 0.05f;
  532. }
  533. if (lifetimeMS < 1) {
  534. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) lifetimeMS < 1", getName());
  535. lifetimeMS = 1;
  536. }
  537. if (lifetimeVariance > lifetimeMS) {
  538. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) lifetimeVariance > lifetimeMS", getName());
  539. lifetimeVariance = lifetimeMS;
  540. }
  541. if (delayMS < 0) {
  542. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) delayMS < 0", getName());
  543. delayMS = 0;
  544. }
  545. if (delayVariance > delayMS) {
  546. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) delayVariance > delayMS", getName());
  547. delayVariance = delayMS;
  548. }
  549. if (offset < 0.0f)
  550. {
  551. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) offset < 0.0", getName());
  552. offset = 0.0f;
  553. }
  554. S32 i;
  555. for( i=0; i<EC_NUM_DEBRIS_TYPES; i++ )
  556. {
  557. if( !debrisList[i] && debrisIDList[i] != 0 )
  558. {
  559. if( !Sim::findObject( debrisIDList[i], debrisList[i] ) )
  560. {
  561. Con::errorf( ConsoleLogEntry::General, "ExplosionData::onAdd: Invalid packet, bad datablockId(debris): 0x%x", debrisIDList[i] );
  562. }
  563. }
  564. }
  565. for( i=0; i<EC_NUM_EMITTERS; i++ )
  566. {
  567. if( !emitterList[i] && emitterIDList[i] != 0 )
  568. {
  569. if( Sim::findObject( emitterIDList[i], emitterList[i] ) == false)
  570. {
  571. Con::errorf( ConsoleLogEntry::General, "ExplosionData::onAdd: Invalid packet, bad datablockId(particle emitter): 0x%x", emitterIDList[i] );
  572. }
  573. }
  574. }
  575. for( S32 k=0; k<EC_MAX_SUB_EXPLOSIONS; k++ )
  576. {
  577. if( !explosionList[k] && explosionIDList[k] != 0 )
  578. {
  579. if( Sim::findObject( explosionIDList[k], explosionList[k] ) == false)
  580. {
  581. Con::errorf( ConsoleLogEntry::General, "ExplosionData::onAdd: Invalid packet, bad datablockId(explosion): 0x%x", explosionIDList[k] );
  582. }
  583. }
  584. }
  585. return true;
  586. }
  587. void ExplosionData::packData(BitStream* stream)
  588. {
  589. Parent::packData(stream);
  590. PACKDATA_ASSET(ExplosionShape);
  591. PACKDATA_ASSET(Sound);
  592. if (stream->writeFlag(particleEmitter))
  593. stream->writeRangedU32(particleEmitter->getId(),DataBlockObjectIdFirst,DataBlockObjectIdLast);
  594. stream->writeInt(particleDensity, 14);
  595. stream->write(particleRadius);
  596. stream->writeFlag(faceViewer);
  597. if(stream->writeFlag(explosionScale.x != 1 || explosionScale.y != 1 || explosionScale.z != 1))
  598. {
  599. stream->writeInt((S32)(explosionScale.x * 100), 16);
  600. stream->writeInt((S32)(explosionScale.y * 100), 16);
  601. stream->writeInt((S32)(explosionScale.z * 100), 16);
  602. }
  603. stream->writeInt((S32)(playSpeed * 20), 14);
  604. stream->writeRangedU32((U32)debrisThetaMin, 0, 180);
  605. stream->writeRangedU32((U32)debrisThetaMax, 0, 180);
  606. stream->writeRangedU32((U32)debrisPhiMin, 0, 360);
  607. stream->writeRangedU32((U32)debrisPhiMax, 0, 360);
  608. stream->writeRangedU32((U32)debrisNum, 0, 1000);
  609. stream->writeRangedU32(debrisNumVariance, 0, 1000);
  610. stream->writeInt((S32)(debrisVelocity * 10), 14);
  611. stream->writeRangedU32((U32)(debrisVelocityVariance * 10), 0, 10000);
  612. stream->writeInt(delayMS >> 5, 16);
  613. stream->writeInt(delayVariance >> 5, 16);
  614. stream->writeInt(lifetimeMS >> 5, 16);
  615. stream->writeInt(lifetimeVariance >> 5, 16);
  616. stream->write(offset);
  617. stream->writeFlag( shakeCamera );
  618. stream->write(camShakeFreq.x);
  619. stream->write(camShakeFreq.y);
  620. stream->write(camShakeFreq.z);
  621. stream->write(camShakeAmp.x);
  622. stream->write(camShakeAmp.y);
  623. stream->write(camShakeAmp.z);
  624. stream->write(camShakeDuration);
  625. stream->write(camShakeRadius);
  626. stream->write(camShakeFalloff);
  627. for( S32 j=0; j<EC_NUM_DEBRIS_TYPES; j++ )
  628. {
  629. if( stream->writeFlag( debrisList[j] ) )
  630. {
  631. stream->writeRangedU32( debrisList[j]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  632. }
  633. }
  634. S32 i;
  635. for( i=0; i<EC_NUM_EMITTERS; i++ )
  636. {
  637. if( stream->writeFlag( emitterList[i] != NULL ) )
  638. {
  639. stream->writeRangedU32( emitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  640. }
  641. }
  642. for( i=0; i<EC_MAX_SUB_EXPLOSIONS; i++ )
  643. {
  644. if( stream->writeFlag( explosionList[i] != NULL ) )
  645. {
  646. stream->writeRangedU32( explosionList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  647. }
  648. }
  649. U32 count;
  650. for(count = 0; count < EC_NUM_TIME_KEYS; count++)
  651. if(times[count] >= 1)
  652. break;
  653. count++;
  654. if(count > EC_NUM_TIME_KEYS)
  655. count = EC_NUM_TIME_KEYS;
  656. stream->writeRangedU32(count, 0, EC_NUM_TIME_KEYS);
  657. for( i=0; i<count; i++ )
  658. stream->writeFloat( times[i], 8 );
  659. for( i=0; i<count; i++ )
  660. {
  661. stream->writeRangedU32((U32)(sizes[i].x * 100), 0, 16000);
  662. stream->writeRangedU32((U32)(sizes[i].y * 100), 0, 16000);
  663. stream->writeRangedU32((U32)(sizes[i].z * 100), 0, 16000);
  664. }
  665. // Dynamic light info
  666. stream->writeFloat(lightStartRadius/MaxLightRadius, 8);
  667. stream->writeFloat(lightEndRadius/MaxLightRadius, 8);
  668. stream->writeFloat(lightStartColor.red,7);
  669. stream->writeFloat(lightStartColor.green,7);
  670. stream->writeFloat(lightStartColor.blue,7);
  671. stream->writeFloat(lightEndColor.red,7);
  672. stream->writeFloat(lightEndColor.green,7);
  673. stream->writeFloat(lightEndColor.blue,7);
  674. stream->writeFloat(lightStartBrightness/MaxLightRadius, 8);
  675. stream->writeFloat(lightEndBrightness/MaxLightRadius, 8);
  676. stream->write(lightNormalOffset);
  677. }
  678. void ExplosionData::unpackData(BitStream* stream)
  679. {
  680. Parent::unpackData(stream);
  681. UNPACKDATA_ASSET(ExplosionShape);
  682. UNPACKDATA_ASSET(Sound);
  683. if (stream->readFlag())
  684. particleEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  685. else
  686. particleEmitterId = 0;
  687. particleDensity = stream->readInt(14);
  688. stream->read(&particleRadius);
  689. faceViewer = stream->readFlag();
  690. if(stream->readFlag())
  691. {
  692. explosionScale.x = stream->readInt(16) / 100.0f;
  693. explosionScale.y = stream->readInt(16) / 100.0f;
  694. explosionScale.z = stream->readInt(16) / 100.0f;
  695. }
  696. else
  697. explosionScale.set(1,1,1);
  698. playSpeed = stream->readInt(14) / 20.0f;
  699. debrisThetaMin = stream->readRangedU32(0, 180);
  700. debrisThetaMax = stream->readRangedU32(0, 180);
  701. debrisPhiMin = stream->readRangedU32(0, 360);
  702. debrisPhiMax = stream->readRangedU32(0, 360);
  703. debrisNum = stream->readRangedU32(0, 1000);
  704. debrisNumVariance = stream->readRangedU32(0, 1000);
  705. debrisVelocity = stream->readInt(14) / 10.0f;
  706. debrisVelocityVariance = stream->readRangedU32(0, 10000) / 10.0f;
  707. delayMS = stream->readInt(16) << 5;
  708. delayVariance = stream->readInt(16) << 5;
  709. lifetimeMS = stream->readInt(16) << 5;
  710. lifetimeVariance = stream->readInt(16) << 5;
  711. stream->read(&offset);
  712. shakeCamera = stream->readFlag();
  713. stream->read(&camShakeFreq.x);
  714. stream->read(&camShakeFreq.y);
  715. stream->read(&camShakeFreq.z);
  716. stream->read(&camShakeAmp.x);
  717. stream->read(&camShakeAmp.y);
  718. stream->read(&camShakeAmp.z);
  719. stream->read(&camShakeDuration);
  720. stream->read(&camShakeRadius);
  721. stream->read(&camShakeFalloff);
  722. for( S32 j=0; j<EC_NUM_DEBRIS_TYPES; j++ )
  723. {
  724. if( stream->readFlag() )
  725. {
  726. debrisIDList[j] = (S32) stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  727. }
  728. }
  729. U32 i;
  730. for( i=0; i<EC_NUM_EMITTERS; i++ )
  731. {
  732. if( stream->readFlag() )
  733. {
  734. emitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  735. }
  736. }
  737. for( S32 k=0; k<EC_MAX_SUB_EXPLOSIONS; k++ )
  738. {
  739. if( stream->readFlag() )
  740. {
  741. explosionIDList[k] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  742. }
  743. }
  744. U32 count = stream->readRangedU32(0, EC_NUM_TIME_KEYS);
  745. for( i=0; i<count; i++ )
  746. times[i] = stream->readFloat(8);
  747. for( i=0; i<count; i++ )
  748. {
  749. sizes[i].x = stream->readRangedU32(0, 16000) / 100.0f;
  750. sizes[i].y = stream->readRangedU32(0, 16000) / 100.0f;
  751. sizes[i].z = stream->readRangedU32(0, 16000) / 100.0f;
  752. }
  753. //
  754. lightStartRadius = stream->readFloat(8) * MaxLightRadius;
  755. lightEndRadius = stream->readFloat(8) * MaxLightRadius;
  756. lightStartColor.red = stream->readFloat(7);
  757. lightStartColor.green = stream->readFloat(7);
  758. lightStartColor.blue = stream->readFloat(7);
  759. lightEndColor.red = stream->readFloat(7);
  760. lightEndColor.green = stream->readFloat(7);
  761. lightEndColor.blue = stream->readFloat(7);
  762. lightStartBrightness = stream->readFloat(8) * MaxLightRadius;
  763. lightEndBrightness = stream->readFloat(8) * MaxLightRadius;
  764. stream->read( &lightNormalOffset );
  765. }
  766. bool ExplosionData::preload(bool server, String &errorStr)
  767. {
  768. if (Parent::preload(server, errorStr) == false)
  769. return false;
  770. if (!server && !getSoundProfile())
  771. return false;
  772. if( !server )
  773. {
  774. if (getSound() != StringTable->EmptyString())
  775. {
  776. _setSound(getSound());
  777. if (!getSoundProfile())
  778. Con::errorf(ConsoleLogEntry::General, "SplashData::preload: Cant get an sfxProfile for splash.");
  779. }
  780. if (!particleEmitter && particleEmitterId != 0)
  781. if (Sim::findObject(particleEmitterId, particleEmitter) == false)
  782. Con::errorf(ConsoleLogEntry::General, "Error, unable to load particle emitter for explosion datablock");
  783. }
  784. if (mExplosionShapeAsset.notNull()) {
  785. // Resolve animations
  786. explosionAnimation = mExplosionShape->findSequence("ambient");
  787. // Preload textures with a dummy instance...
  788. TSShapeInstance* pDummy = new TSShapeInstance(mExplosionShape, !server);
  789. delete pDummy;
  790. } else {
  791. explosionAnimation = -1;
  792. }
  793. return true;
  794. }
  795. //--------------------------------------------------------------------------
  796. //--------------------------------------
  797. //
  798. Explosion::Explosion()
  799. : mDataBlock( NULL )
  800. {
  801. mTypeMask |= ExplosionObjectType | LightObjectType;
  802. mExplosionInstance = NULL;
  803. mExplosionThread = NULL;
  804. dMemset( mEmitterList, 0, sizeof( mEmitterList ) );
  805. mMainEmitter = NULL;
  806. mFade = 1;
  807. mDelayMS = 0;
  808. mCurrMS = 0;
  809. mEndingMS = 1000;
  810. mActive = false;
  811. mCollideType = 0;
  812. mInitialNormal.set( 0.0f, 0.0f, 1.0f );
  813. mRandAngle = sgRandom.randF( 0.0f, 1.0f ) * M_PI_F * 2.0f;
  814. mLight = LIGHTMGR->createLightInfo();
  815. mNetFlags.set( IsGhost );
  816. ss_object = 0;
  817. ss_index = 0;
  818. mDataBlock = 0;
  819. soundProfile_clone = 0;
  820. mRandomVal = 0;
  821. }
  822. Explosion::~Explosion()
  823. {
  824. if( mExplosionInstance )
  825. {
  826. delete mExplosionInstance;
  827. mExplosionInstance = NULL;
  828. mExplosionThread = NULL;
  829. }
  830. SAFE_DELETE(mLight);
  831. if (soundProfile_clone)
  832. {
  833. delete soundProfile_clone;
  834. soundProfile_clone = 0;
  835. }
  836. if (mDataBlock && mDataBlock->isTempClone())
  837. {
  838. delete mDataBlock;
  839. mDataBlock = 0;
  840. }
  841. }
  842. void Explosion::setInitialState(const Point3F& point, const Point3F& normal, const F32 fade)
  843. {
  844. setPosition(point);
  845. mInitialNormal = normal;
  846. mFade = fade;
  847. }
  848. //--------------------------------------------------------------------------
  849. void Explosion::initPersistFields()
  850. {
  851. Parent::initPersistFields();
  852. addField("initialNormal", TypePoint3F, Offset(mInitialNormal, Explosion), "Initial starting Normal.");
  853. //
  854. }
  855. //--------------------------------------------------------------------------
  856. bool Explosion::onAdd()
  857. {
  858. // first check if we have a server connection, if we dont then this is on the server
  859. // and we should exit, then check if the parent fails to add the object
  860. GameConnection *conn = GameConnection::getConnectionToServer();
  861. if ( !conn || !Parent::onAdd() )
  862. return false;
  863. if( !mDataBlock )
  864. {
  865. Con::errorf("Explosion::onAdd - Fail - No datablok");
  866. return false;
  867. }
  868. mDelayMS = mDataBlock->delayMS + sgRandom.randI( -mDataBlock->delayVariance, mDataBlock->delayVariance );
  869. mEndingMS = mDataBlock->lifetimeMS + sgRandom.randI( -mDataBlock->lifetimeVariance, mDataBlock->lifetimeVariance );
  870. if( mFabs( mDataBlock->offset ) > 0.001f )
  871. {
  872. MatrixF axisOrient = MathUtils::createOrientFromDir( mInitialNormal );
  873. MatrixF trans = getTransform();
  874. Point3F randVec;
  875. randVec.x = sgRandom.randF( -1.0f, 1.0f );
  876. randVec.y = sgRandom.randF( 0.0f, 1.0f );
  877. randVec.z = sgRandom.randF( -1.0f, 1.0f );
  878. randVec.normalize();
  879. randVec *= mDataBlock->offset;
  880. axisOrient.mulV( randVec );
  881. trans.setPosition( trans.getPosition() + randVec );
  882. setTransform( trans );
  883. }
  884. // shake camera
  885. if( mDataBlock->shakeCamera )
  886. {
  887. // first check if explosion is near player
  888. GameConnection* connection = GameConnection::getConnectionToServer();
  889. ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject());
  890. bool applyShake = true;
  891. if( obj )
  892. {
  893. ShapeBase* cObj = obj;
  894. while((cObj = cObj->getControlObject()) != 0)
  895. {
  896. if(cObj->useObjsEyePoint())
  897. {
  898. applyShake = false;
  899. break;
  900. }
  901. }
  902. }
  903. if( applyShake && obj )
  904. {
  905. VectorF diff = obj->getPosition() - getPosition();
  906. F32 dist = diff.len();
  907. if( dist < mDataBlock->camShakeRadius )
  908. {
  909. CameraShake *camShake = new CameraShake;
  910. camShake->setDuration( mDataBlock->camShakeDuration );
  911. camShake->setFrequency( mDataBlock->camShakeFreq );
  912. F32 falloff = dist / mDataBlock->camShakeRadius;
  913. falloff = 1.0f + falloff * 10.0f;
  914. falloff = 1.0f / (falloff * falloff);
  915. VectorF shakeAmp = mDataBlock->camShakeAmp * falloff;
  916. camShake->setAmplitude( shakeAmp );
  917. camShake->setFalloff( mDataBlock->camShakeFalloff );
  918. camShake->init();
  919. gCamFXMgr.addFX( camShake );
  920. }
  921. }
  922. }
  923. if( mDelayMS == 0 )
  924. {
  925. if( !explode() )
  926. {
  927. return false;
  928. }
  929. }
  930. gClientSceneGraph->addObjectToScene(this);
  931. removeFromProcessList();
  932. ClientProcessList::get()->addObject(this);
  933. mRandomVal = sgRandom.randF();
  934. NetConnection* pNC = NetConnection::getConnectionToServer();
  935. AssertFatal(pNC != NULL, "Error, must have a connection to the server!");
  936. pNC->addObject(this);
  937. // Initialize the light structure and register as a dynamic light
  938. if (mDataBlock->lightStartRadius != 0.0f || mDataBlock->lightEndRadius)
  939. {
  940. mLight->setType( LightInfo::Point );
  941. mLight->setRange( mDataBlock->lightStartRadius );
  942. mLight->setColor( mDataBlock->lightStartColor );
  943. }
  944. return true;
  945. }
  946. void Explosion::onRemove()
  947. {
  948. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  949. {
  950. if( mEmitterList[i] )
  951. {
  952. mEmitterList[i]->deleteWhenEmpty();
  953. mEmitterList[i] = NULL;
  954. }
  955. }
  956. if( mMainEmitter )
  957. {
  958. mMainEmitter->deleteWhenEmpty();
  959. mMainEmitter = NULL;
  960. }
  961. removeFromScene();
  962. Parent::onRemove();
  963. }
  964. bool Explosion::onNewDataBlock( GameBaseData *dptr, bool reload )
  965. {
  966. mDataBlock = dynamic_cast<ExplosionData*>( dptr );
  967. if (!mDataBlock || !Parent::onNewDataBlock( dptr, reload ))
  968. return false;
  969. if (mDataBlock->isTempClone())
  970. return true;
  971. scriptOnNewDataBlock();
  972. return true;
  973. }
  974. //--------------------------------------------------------------------------
  975. void Explosion::prepRenderImage( SceneRenderState* state )
  976. {
  977. prepBatchRender( state );
  978. }
  979. void Explosion::setCurrentScale()
  980. {
  981. F32 t = F32(mCurrMS) / F32(mEndingMS);
  982. for( U32 i = 1; i < ExplosionData::EC_NUM_TIME_KEYS; i++ )
  983. {
  984. if( mDataBlock->times[i] >= t )
  985. {
  986. F32 firstPart = t - mDataBlock->times[i-1];
  987. F32 total = mDataBlock->times[i] -
  988. mDataBlock->times[i-1];
  989. firstPart /= total;
  990. mObjScale = (mDataBlock->sizes[i-1] * (1.0f - firstPart)) +
  991. (mDataBlock->sizes[i] * firstPart);
  992. return;
  993. }
  994. }
  995. }
  996. //--------------------------------------------------------------------------
  997. // Make the explosion face the viewer (if desired)
  998. //--------------------------------------------------------------------------
  999. void Explosion::prepModelView(SceneRenderState* state)
  1000. {
  1001. MatrixF rotMatrix( true );
  1002. Point3F targetVector;
  1003. if( mDataBlock->faceViewer )
  1004. {
  1005. targetVector = getPosition() - state->getCameraPosition();
  1006. targetVector.normalize();
  1007. // rotate explosion each time so it's a little different
  1008. rotMatrix.set( EulerF( 0.0f, mRandAngle, 0.0f ) );
  1009. }
  1010. else
  1011. {
  1012. targetVector = mInitialNormal;
  1013. }
  1014. MatrixF explOrient = MathUtils::createOrientFromDir( targetVector );
  1015. explOrient.mul( rotMatrix );
  1016. explOrient.setPosition( getPosition() );
  1017. setCurrentScale();
  1018. explOrient.scale( mObjScale );
  1019. GFX->setWorldMatrix( explOrient );
  1020. }
  1021. //--------------------------------------------------------------------------
  1022. // Render object
  1023. //--------------------------------------------------------------------------
  1024. void Explosion::prepBatchRender(SceneRenderState* state)
  1025. {
  1026. if ( !mExplosionInstance )
  1027. return;
  1028. MatrixF proj = GFX->getProjectionMatrix();
  1029. RectI viewport = GFX->getViewport();
  1030. // Set up our TS render state here.
  1031. TSRenderState rdata;
  1032. rdata.setSceneState( state );
  1033. // We might have some forward lit materials
  1034. // so pass down a query to gather lights.
  1035. LightQuery query;
  1036. query.init( getWorldSphere() );
  1037. rdata.setLightQuery( &query );
  1038. // render mesh
  1039. GFX->pushWorldMatrix();
  1040. prepModelView( state );
  1041. mExplosionInstance->animate();
  1042. mExplosionInstance->render( rdata );
  1043. GFX->popWorldMatrix();
  1044. GFX->setProjectionMatrix( proj );
  1045. GFX->setViewport( viewport );
  1046. }
  1047. void Explosion::submitLights( LightManager *lm, bool staticLighting )
  1048. {
  1049. if ( staticLighting )
  1050. return;
  1051. // Update the light's info and add it to the scene, the light will
  1052. // only be visible for this current frame.
  1053. mLight->setPosition( getRenderTransform().getPosition() + mInitialNormal * mDataBlock->lightNormalOffset );
  1054. F32 t = F32(mCurrMS) / F32(mEndingMS);
  1055. mLight->setRange( mDataBlock->lightStartRadius +
  1056. (mDataBlock->lightEndRadius - mDataBlock->lightStartRadius) * t );
  1057. mLight->setColor( mDataBlock->lightStartColor +
  1058. (mDataBlock->lightEndColor - mDataBlock->lightStartColor) * t );
  1059. mLight->setBrightness( mDataBlock->lightStartBrightness +
  1060. (mDataBlock->lightEndBrightness - mDataBlock->lightStartBrightness) * t );
  1061. lm->registerGlobalLight( mLight, this );
  1062. }
  1063. //--------------------------------------------------------------------------
  1064. void Explosion::processTick(const Move*)
  1065. {
  1066. mCurrMS += TickMs;
  1067. if( mCurrMS >= mEndingMS )
  1068. {
  1069. deleteObject();
  1070. return;
  1071. }
  1072. if( (mCurrMS > mDelayMS) && !mActive )
  1073. explode();
  1074. }
  1075. void Explosion::advanceTime(F32 dt)
  1076. {
  1077. if (dt == 0.0f)
  1078. return;
  1079. GameConnection* conn = GameConnection::getConnectionToServer();
  1080. if(!conn)
  1081. return;
  1082. updateEmitters( dt );
  1083. if( mExplosionInstance )
  1084. mExplosionInstance->advanceTime(dt, mExplosionThread);
  1085. }
  1086. //----------------------------------------------------------------------------
  1087. // Update emitters
  1088. //----------------------------------------------------------------------------
  1089. void Explosion::updateEmitters( F32 dt )
  1090. {
  1091. Point3F pos = getPosition();
  1092. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  1093. {
  1094. if( mEmitterList[i] )
  1095. {
  1096. mEmitterList[i]->emitParticles( pos, pos, mInitialNormal, Point3F( 0.0f, 0.0f, 0.0f ), (U32)(dt * 1000));
  1097. }
  1098. }
  1099. }
  1100. //----------------------------------------------------------------------------
  1101. // Launch Debris
  1102. //----------------------------------------------------------------------------
  1103. void Explosion::launchDebris( Point3F &axis )
  1104. {
  1105. GameConnection* conn = GameConnection::getConnectionToServer();
  1106. if(!conn)
  1107. return;
  1108. bool hasDebris = false;
  1109. for( S32 j=0; j<ExplosionData::EC_NUM_DEBRIS_TYPES; j++ )
  1110. {
  1111. if( mDataBlock->debrisList[j] )
  1112. {
  1113. hasDebris = true;
  1114. break;
  1115. }
  1116. }
  1117. if( !hasDebris )
  1118. {
  1119. return;
  1120. }
  1121. Point3F axisx;
  1122. if (mFabs(axis.z) < 0.999f)
  1123. mCross(axis, Point3F(0.0f, 0.0f, 1.0f), &axisx);
  1124. else
  1125. mCross(axis, Point3F(0.0f, 1.0f, 0.0f), &axisx);
  1126. axisx.normalize();
  1127. Point3F pos( 0.0f, 0.0f, 0.5f );
  1128. pos += getPosition();
  1129. U32 numDebris = mDataBlock->debrisNum + sgRandom.randI( -mDataBlock->debrisNumVariance, mDataBlock->debrisNumVariance );
  1130. for( S32 i=0; i<numDebris; i++ )
  1131. {
  1132. Point3F launchDir = MathUtils::randomDir( axis, mDataBlock->debrisThetaMin, mDataBlock->debrisThetaMax,
  1133. mDataBlock->debrisPhiMin, mDataBlock->debrisPhiMax );
  1134. F32 debrisVel = mDataBlock->debrisVelocity + mDataBlock->debrisVelocityVariance * sgRandom.randF( -1.0f, 1.0f );
  1135. launchDir *= debrisVel;
  1136. Debris *debris = new Debris;
  1137. debris->setSubstitutionData(ss_object, ss_index);
  1138. debris->setDataBlock(mDataBlock->debrisList[0]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1139. debris->setTransform( getTransform() );
  1140. debris->init( pos, launchDir );
  1141. if( !debris->registerObject() )
  1142. {
  1143. Con::warnf( ConsoleLogEntry::General, "Could not register debris for class: %s", mDataBlock->getName() );
  1144. delete debris;
  1145. debris = NULL;
  1146. }
  1147. }
  1148. }
  1149. //----------------------------------------------------------------------------
  1150. // Spawn sub explosions
  1151. //----------------------------------------------------------------------------
  1152. void Explosion::spawnSubExplosions()
  1153. {
  1154. GameConnection* conn = GameConnection::getConnectionToServer();
  1155. if(!conn)
  1156. return;
  1157. for( S32 i=0; i<ExplosionData::EC_MAX_SUB_EXPLOSIONS; i++ )
  1158. {
  1159. if( mDataBlock->explosionList[i] )
  1160. {
  1161. MatrixF trans = getTransform();
  1162. Explosion* pExplosion = new Explosion;
  1163. pExplosion->setSubstitutionData(ss_object, ss_index);
  1164. pExplosion->setDataBlock(mDataBlock->explosionList[i]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1165. pExplosion->setTransform( trans );
  1166. pExplosion->setInitialState( trans.getPosition(), mInitialNormal, 1);
  1167. if (!pExplosion->registerObject())
  1168. delete pExplosion;
  1169. }
  1170. }
  1171. }
  1172. //----------------------------------------------------------------------------
  1173. // Explode
  1174. //----------------------------------------------------------------------------
  1175. bool Explosion::explode()
  1176. {
  1177. mActive = true;
  1178. GameConnection* conn = GameConnection::getConnectionToServer();
  1179. if(!conn)
  1180. return false;
  1181. launchDebris( mInitialNormal );
  1182. spawnSubExplosions();
  1183. if (bool(mDataBlock->mExplosionShape) && mDataBlock->explosionAnimation != -1) {
  1184. mExplosionInstance = new TSShapeInstance(mDataBlock->mExplosionShape, true);
  1185. mExplosionThread = mExplosionInstance->addThread();
  1186. mExplosionInstance->setSequence(mExplosionThread, mDataBlock->explosionAnimation, 0);
  1187. mExplosionInstance->setTimeScale(mExplosionThread, mDataBlock->playSpeed);
  1188. mCurrMS = 0;
  1189. mEndingMS = U32(mExplosionInstance->getScaledDuration(mExplosionThread) * 1000.0f);
  1190. mObjScale.convolve(mDataBlock->explosionScale);
  1191. mObjBox = mDataBlock->mExplosionShape->mBounds;
  1192. resetWorldBox();
  1193. }
  1194. SFXProfile* sound_prof = mDataBlock->getSoundProfile();
  1195. if (sound_prof)
  1196. {
  1197. soundProfile_clone = sound_prof->cloneAndPerformSubstitutions(ss_object, ss_index);
  1198. SFX->playOnce( soundProfile_clone, &getTransform() );
  1199. if (!soundProfile_clone->isTempClone())
  1200. soundProfile_clone = 0;
  1201. }
  1202. if (mDataBlock->particleEmitter) {
  1203. mMainEmitter = new ParticleEmitter;
  1204. mMainEmitter->setDataBlock(mDataBlock->particleEmitter->cloneAndPerformSubstitutions(ss_object, ss_index));
  1205. mMainEmitter->registerObject();
  1206. mMainEmitter->emitParticles(getPosition(), mInitialNormal, mDataBlock->particleRadius,
  1207. Point3F::Zero, U32(mDataBlock->particleDensity * mFade));
  1208. }
  1209. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  1210. {
  1211. if( mDataBlock->emitterList[i] != NULL )
  1212. {
  1213. ParticleEmitter * pEmitter = new ParticleEmitter;
  1214. pEmitter->setDataBlock(mDataBlock->emitterList[i]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1215. if( !pEmitter->registerObject() )
  1216. {
  1217. Con::warnf( ConsoleLogEntry::General, "Could not register emitter for particle of class: %s", mDataBlock->getName() );
  1218. SAFE_DELETE(pEmitter);
  1219. }
  1220. mEmitterList[i] = pEmitter;
  1221. }
  1222. }
  1223. return true;
  1224. }