explosion.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  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 )
  771. {
  772. if (getSound() != StringTable->EmptyString())
  773. {
  774. _setSound(getSound());
  775. if (!getSoundProfile())
  776. {
  777. Con::errorf(ConsoleLogEntry::General, "SplashData::preload: Cant get an sfxProfile for splash.");
  778. return false;
  779. }
  780. }
  781. if (!particleEmitter && particleEmitterId != 0)
  782. if (Sim::findObject(particleEmitterId, particleEmitter) == false)
  783. {
  784. Con::errorf(ConsoleLogEntry::General, "Error, unable to load particle emitter for explosion datablock");
  785. return false;
  786. }
  787. }
  788. if (mExplosionShapeAsset.notNull()) {
  789. // Resolve animations
  790. explosionAnimation = mExplosionShape->findSequence("ambient");
  791. // Preload textures with a dummy instance...
  792. TSShapeInstance* pDummy = new TSShapeInstance(mExplosionShape, !server);
  793. delete pDummy;
  794. } else {
  795. explosionAnimation = -1;
  796. }
  797. return true;
  798. }
  799. //--------------------------------------------------------------------------
  800. //--------------------------------------
  801. //
  802. Explosion::Explosion()
  803. : mDataBlock( NULL )
  804. {
  805. mTypeMask |= ExplosionObjectType | LightObjectType;
  806. mExplosionInstance = NULL;
  807. mExplosionThread = NULL;
  808. dMemset( mEmitterList, 0, sizeof( mEmitterList ) );
  809. mMainEmitter = NULL;
  810. mFade = 1;
  811. mDelayMS = 0;
  812. mCurrMS = 0;
  813. mEndingMS = 1000;
  814. mActive = false;
  815. mCollideType = 0;
  816. mInitialNormal.set( 0.0f, 0.0f, 1.0f );
  817. mRandAngle = sgRandom.randF( 0.0f, 1.0f ) * M_PI_F * 2.0f;
  818. mLight = LIGHTMGR->createLightInfo();
  819. mNetFlags.set( IsGhost );
  820. ss_object = 0;
  821. ss_index = 0;
  822. mDataBlock = 0;
  823. soundProfile_clone = 0;
  824. mRandomVal = 0;
  825. }
  826. Explosion::~Explosion()
  827. {
  828. if( mExplosionInstance )
  829. {
  830. delete mExplosionInstance;
  831. mExplosionInstance = NULL;
  832. mExplosionThread = NULL;
  833. }
  834. SAFE_DELETE(mLight);
  835. if (soundProfile_clone)
  836. {
  837. delete soundProfile_clone;
  838. soundProfile_clone = 0;
  839. }
  840. if (mDataBlock && mDataBlock->isTempClone())
  841. {
  842. delete mDataBlock;
  843. mDataBlock = 0;
  844. }
  845. }
  846. void Explosion::setInitialState(const Point3F& point, const Point3F& normal, const F32 fade)
  847. {
  848. setPosition(point);
  849. mInitialNormal = normal;
  850. mFade = fade;
  851. }
  852. //--------------------------------------------------------------------------
  853. void Explosion::initPersistFields()
  854. {
  855. Parent::initPersistFields();
  856. addField("initialNormal", TypePoint3F, Offset(mInitialNormal, Explosion), "Initial starting Normal.");
  857. //
  858. }
  859. //--------------------------------------------------------------------------
  860. bool Explosion::onAdd()
  861. {
  862. // first check if we have a server connection, if we dont then this is on the server
  863. // and we should exit, then check if the parent fails to add the object
  864. GameConnection *conn = GameConnection::getConnectionToServer();
  865. if ( !conn || !Parent::onAdd() )
  866. return false;
  867. if( !mDataBlock )
  868. {
  869. Con::errorf("Explosion::onAdd - Fail - No datablok");
  870. return false;
  871. }
  872. mDelayMS = mDataBlock->delayMS + sgRandom.randI( -mDataBlock->delayVariance, mDataBlock->delayVariance );
  873. mEndingMS = mDataBlock->lifetimeMS + sgRandom.randI( -mDataBlock->lifetimeVariance, mDataBlock->lifetimeVariance );
  874. if( mFabs( mDataBlock->offset ) > 0.001f )
  875. {
  876. MatrixF axisOrient = MathUtils::createOrientFromDir( mInitialNormal );
  877. MatrixF trans = getTransform();
  878. Point3F randVec;
  879. randVec.x = sgRandom.randF( -1.0f, 1.0f );
  880. randVec.y = sgRandom.randF( 0.0f, 1.0f );
  881. randVec.z = sgRandom.randF( -1.0f, 1.0f );
  882. randVec.normalize();
  883. randVec *= mDataBlock->offset;
  884. axisOrient.mulV( randVec );
  885. trans.setPosition( trans.getPosition() + randVec );
  886. setTransform( trans );
  887. }
  888. // shake camera
  889. if( mDataBlock->shakeCamera )
  890. {
  891. // first check if explosion is near player
  892. GameConnection* connection = GameConnection::getConnectionToServer();
  893. ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject());
  894. bool applyShake = true;
  895. if( obj )
  896. {
  897. ShapeBase* cObj = obj;
  898. while((cObj = cObj->getControlObject()) != 0)
  899. {
  900. if(cObj->useObjsEyePoint())
  901. {
  902. applyShake = false;
  903. break;
  904. }
  905. }
  906. }
  907. if( applyShake && obj )
  908. {
  909. VectorF diff = obj->getPosition() - getPosition();
  910. F32 dist = diff.len();
  911. if( dist < mDataBlock->camShakeRadius )
  912. {
  913. CameraShake *camShake = new CameraShake;
  914. camShake->setDuration( mDataBlock->camShakeDuration );
  915. camShake->setFrequency( mDataBlock->camShakeFreq );
  916. F32 falloff = dist / mDataBlock->camShakeRadius;
  917. falloff = 1.0f + falloff * 10.0f;
  918. falloff = 1.0f / (falloff * falloff);
  919. VectorF shakeAmp = mDataBlock->camShakeAmp * falloff;
  920. camShake->setAmplitude( shakeAmp );
  921. camShake->setFalloff( mDataBlock->camShakeFalloff );
  922. camShake->init();
  923. gCamFXMgr.addFX( camShake );
  924. }
  925. }
  926. }
  927. if( mDelayMS == 0 )
  928. {
  929. if( !explode() )
  930. {
  931. return false;
  932. }
  933. }
  934. gClientSceneGraph->addObjectToScene(this);
  935. removeFromProcessList();
  936. ClientProcessList::get()->addObject(this);
  937. mRandomVal = sgRandom.randF();
  938. NetConnection* pNC = NetConnection::getConnectionToServer();
  939. AssertFatal(pNC != NULL, "Error, must have a connection to the server!");
  940. pNC->addObject(this);
  941. // Initialize the light structure and register as a dynamic light
  942. if (mDataBlock->lightStartRadius != 0.0f || mDataBlock->lightEndRadius)
  943. {
  944. mLight->setType( LightInfo::Point );
  945. mLight->setRange( mDataBlock->lightStartRadius );
  946. mLight->setColor( mDataBlock->lightStartColor );
  947. }
  948. return true;
  949. }
  950. void Explosion::onRemove()
  951. {
  952. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  953. {
  954. if( mEmitterList[i] )
  955. {
  956. mEmitterList[i]->deleteWhenEmpty();
  957. mEmitterList[i] = NULL;
  958. }
  959. }
  960. if( mMainEmitter )
  961. {
  962. mMainEmitter->deleteWhenEmpty();
  963. mMainEmitter = NULL;
  964. }
  965. removeFromScene();
  966. Parent::onRemove();
  967. }
  968. bool Explosion::onNewDataBlock( GameBaseData *dptr, bool reload )
  969. {
  970. mDataBlock = dynamic_cast<ExplosionData*>( dptr );
  971. if (!mDataBlock || !Parent::onNewDataBlock( dptr, reload ))
  972. return false;
  973. if (mDataBlock->isTempClone())
  974. return true;
  975. scriptOnNewDataBlock();
  976. return true;
  977. }
  978. //--------------------------------------------------------------------------
  979. void Explosion::prepRenderImage( SceneRenderState* state )
  980. {
  981. prepBatchRender( state );
  982. }
  983. void Explosion::setCurrentScale()
  984. {
  985. F32 t = F32(mCurrMS) / F32(mEndingMS);
  986. for( U32 i = 1; i < ExplosionData::EC_NUM_TIME_KEYS; i++ )
  987. {
  988. if( mDataBlock->times[i] >= t )
  989. {
  990. F32 firstPart = t - mDataBlock->times[i-1];
  991. F32 total = mDataBlock->times[i] -
  992. mDataBlock->times[i-1];
  993. firstPart /= total;
  994. mObjScale = (mDataBlock->sizes[i-1] * (1.0f - firstPart)) +
  995. (mDataBlock->sizes[i] * firstPart);
  996. return;
  997. }
  998. }
  999. }
  1000. //--------------------------------------------------------------------------
  1001. // Make the explosion face the viewer (if desired)
  1002. //--------------------------------------------------------------------------
  1003. void Explosion::prepModelView(SceneRenderState* state)
  1004. {
  1005. MatrixF rotMatrix( true );
  1006. Point3F targetVector;
  1007. if( mDataBlock->faceViewer )
  1008. {
  1009. targetVector = getPosition() - state->getCameraPosition();
  1010. targetVector.normalize();
  1011. // rotate explosion each time so it's a little different
  1012. rotMatrix.set( EulerF( 0.0f, mRandAngle, 0.0f ) );
  1013. }
  1014. else
  1015. {
  1016. targetVector = mInitialNormal;
  1017. }
  1018. MatrixF explOrient = MathUtils::createOrientFromDir( targetVector );
  1019. explOrient.mul( rotMatrix );
  1020. explOrient.setPosition( getPosition() );
  1021. setCurrentScale();
  1022. explOrient.scale( mObjScale );
  1023. GFX->setWorldMatrix( explOrient );
  1024. }
  1025. //--------------------------------------------------------------------------
  1026. // Render object
  1027. //--------------------------------------------------------------------------
  1028. void Explosion::prepBatchRender(SceneRenderState* state)
  1029. {
  1030. if ( !mExplosionInstance )
  1031. return;
  1032. MatrixF proj = GFX->getProjectionMatrix();
  1033. RectI viewport = GFX->getViewport();
  1034. // Set up our TS render state here.
  1035. TSRenderState rdata;
  1036. rdata.setSceneState( state );
  1037. // We might have some forward lit materials
  1038. // so pass down a query to gather lights.
  1039. LightQuery query;
  1040. query.init( getWorldSphere() );
  1041. rdata.setLightQuery( &query );
  1042. // render mesh
  1043. GFX->pushWorldMatrix();
  1044. prepModelView( state );
  1045. mExplosionInstance->animate();
  1046. mExplosionInstance->render( rdata );
  1047. GFX->popWorldMatrix();
  1048. GFX->setProjectionMatrix( proj );
  1049. GFX->setViewport( viewport );
  1050. }
  1051. void Explosion::submitLights( LightManager *lm, bool staticLighting )
  1052. {
  1053. if ( staticLighting )
  1054. return;
  1055. // Update the light's info and add it to the scene, the light will
  1056. // only be visible for this current frame.
  1057. mLight->setPosition( getRenderTransform().getPosition() + mInitialNormal * mDataBlock->lightNormalOffset );
  1058. F32 t = F32(mCurrMS) / F32(mEndingMS);
  1059. mLight->setRange( mDataBlock->lightStartRadius +
  1060. (mDataBlock->lightEndRadius - mDataBlock->lightStartRadius) * t );
  1061. mLight->setColor( mDataBlock->lightStartColor +
  1062. (mDataBlock->lightEndColor - mDataBlock->lightStartColor) * t );
  1063. mLight->setBrightness( mDataBlock->lightStartBrightness +
  1064. (mDataBlock->lightEndBrightness - mDataBlock->lightStartBrightness) * t );
  1065. lm->registerGlobalLight( mLight, this );
  1066. }
  1067. //--------------------------------------------------------------------------
  1068. void Explosion::processTick(const Move*)
  1069. {
  1070. mCurrMS += TickMs;
  1071. if( mCurrMS >= mEndingMS )
  1072. {
  1073. deleteObject();
  1074. return;
  1075. }
  1076. if( (mCurrMS > mDelayMS) && !mActive )
  1077. explode();
  1078. }
  1079. void Explosion::advanceTime(F32 dt)
  1080. {
  1081. if (dt == 0.0f)
  1082. return;
  1083. GameConnection* conn = GameConnection::getConnectionToServer();
  1084. if(!conn)
  1085. return;
  1086. updateEmitters( dt );
  1087. if( mExplosionInstance )
  1088. mExplosionInstance->advanceTime(dt, mExplosionThread);
  1089. }
  1090. //----------------------------------------------------------------------------
  1091. // Update emitters
  1092. //----------------------------------------------------------------------------
  1093. void Explosion::updateEmitters( F32 dt )
  1094. {
  1095. Point3F pos = getPosition();
  1096. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  1097. {
  1098. if( mEmitterList[i] )
  1099. {
  1100. mEmitterList[i]->emitParticles( pos, pos, mInitialNormal, Point3F( 0.0f, 0.0f, 0.0f ), (U32)(dt * 1000));
  1101. }
  1102. }
  1103. }
  1104. //----------------------------------------------------------------------------
  1105. // Launch Debris
  1106. //----------------------------------------------------------------------------
  1107. void Explosion::launchDebris( Point3F &axis )
  1108. {
  1109. GameConnection* conn = GameConnection::getConnectionToServer();
  1110. if(!conn)
  1111. return;
  1112. bool hasDebris = false;
  1113. for( S32 j=0; j<ExplosionData::EC_NUM_DEBRIS_TYPES; j++ )
  1114. {
  1115. if( mDataBlock->debrisList[j] )
  1116. {
  1117. hasDebris = true;
  1118. break;
  1119. }
  1120. }
  1121. if( !hasDebris )
  1122. {
  1123. return;
  1124. }
  1125. Point3F axisx;
  1126. if (mFabs(axis.z) < 0.999f)
  1127. mCross(axis, Point3F(0.0f, 0.0f, 1.0f), &axisx);
  1128. else
  1129. mCross(axis, Point3F(0.0f, 1.0f, 0.0f), &axisx);
  1130. axisx.normalize();
  1131. Point3F pos( 0.0f, 0.0f, 0.5f );
  1132. pos += getPosition();
  1133. U32 numDebris = mDataBlock->debrisNum + sgRandom.randI( -mDataBlock->debrisNumVariance, mDataBlock->debrisNumVariance );
  1134. for( S32 i=0; i<numDebris; i++ )
  1135. {
  1136. Point3F launchDir = MathUtils::randomDir( axis, mDataBlock->debrisThetaMin, mDataBlock->debrisThetaMax,
  1137. mDataBlock->debrisPhiMin, mDataBlock->debrisPhiMax );
  1138. F32 debrisVel = mDataBlock->debrisVelocity + mDataBlock->debrisVelocityVariance * sgRandom.randF( -1.0f, 1.0f );
  1139. launchDir *= debrisVel;
  1140. Debris *debris = new Debris;
  1141. debris->setSubstitutionData(ss_object, ss_index);
  1142. debris->setDataBlock(mDataBlock->debrisList[0]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1143. debris->setTransform( getTransform() );
  1144. debris->init( pos, launchDir );
  1145. if( !debris->registerObject() )
  1146. {
  1147. Con::warnf( ConsoleLogEntry::General, "Could not register debris for class: %s", mDataBlock->getName() );
  1148. delete debris;
  1149. debris = NULL;
  1150. }
  1151. }
  1152. }
  1153. //----------------------------------------------------------------------------
  1154. // Spawn sub explosions
  1155. //----------------------------------------------------------------------------
  1156. void Explosion::spawnSubExplosions()
  1157. {
  1158. GameConnection* conn = GameConnection::getConnectionToServer();
  1159. if(!conn)
  1160. return;
  1161. for( S32 i=0; i<ExplosionData::EC_MAX_SUB_EXPLOSIONS; i++ )
  1162. {
  1163. if( mDataBlock->explosionList[i] )
  1164. {
  1165. MatrixF trans = getTransform();
  1166. Explosion* pExplosion = new Explosion;
  1167. pExplosion->setSubstitutionData(ss_object, ss_index);
  1168. pExplosion->setDataBlock(mDataBlock->explosionList[i]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1169. pExplosion->setTransform( trans );
  1170. pExplosion->setInitialState( trans.getPosition(), mInitialNormal, 1);
  1171. if (!pExplosion->registerObject())
  1172. delete pExplosion;
  1173. }
  1174. }
  1175. }
  1176. //----------------------------------------------------------------------------
  1177. // Explode
  1178. //----------------------------------------------------------------------------
  1179. bool Explosion::explode()
  1180. {
  1181. mActive = true;
  1182. GameConnection* conn = GameConnection::getConnectionToServer();
  1183. if(!conn)
  1184. return false;
  1185. launchDebris( mInitialNormal );
  1186. spawnSubExplosions();
  1187. if (bool(mDataBlock->mExplosionShape) && mDataBlock->explosionAnimation != -1) {
  1188. mExplosionInstance = new TSShapeInstance(mDataBlock->mExplosionShape, true);
  1189. mExplosionThread = mExplosionInstance->addThread();
  1190. mExplosionInstance->setSequence(mExplosionThread, mDataBlock->explosionAnimation, 0);
  1191. mExplosionInstance->setTimeScale(mExplosionThread, mDataBlock->playSpeed);
  1192. mCurrMS = 0;
  1193. mEndingMS = U32(mExplosionInstance->getScaledDuration(mExplosionThread) * 1000.0f);
  1194. mObjScale.convolve(mDataBlock->explosionScale);
  1195. mObjBox = mDataBlock->mExplosionShape->mBounds;
  1196. resetWorldBox();
  1197. }
  1198. SFXProfile* sound_prof = mDataBlock->getSoundProfile();
  1199. if (sound_prof)
  1200. {
  1201. soundProfile_clone = sound_prof->cloneAndPerformSubstitutions(ss_object, ss_index);
  1202. SFX->playOnce( soundProfile_clone, &getTransform() );
  1203. if (!soundProfile_clone->isTempClone())
  1204. soundProfile_clone = 0;
  1205. }
  1206. if (mDataBlock->particleEmitter) {
  1207. mMainEmitter = new ParticleEmitter;
  1208. mMainEmitter->setDataBlock(mDataBlock->particleEmitter->cloneAndPerformSubstitutions(ss_object, ss_index));
  1209. mMainEmitter->registerObject();
  1210. mMainEmitter->emitParticles(getPosition(), mInitialNormal, mDataBlock->particleRadius,
  1211. Point3F::Zero, U32(mDataBlock->particleDensity * mFade));
  1212. }
  1213. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  1214. {
  1215. if( mDataBlock->emitterList[i] != NULL )
  1216. {
  1217. ParticleEmitter * pEmitter = new ParticleEmitter;
  1218. pEmitter->setDataBlock(mDataBlock->emitterList[i]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1219. if( !pEmitter->registerObject() )
  1220. {
  1221. Con::warnf( ConsoleLogEntry::General, "Could not register emitter for particle of class: %s", mDataBlock->getName() );
  1222. SAFE_DELETE(pEmitter);
  1223. }
  1224. mEmitterList[i] = pEmitter;
  1225. }
  1226. }
  1227. return true;
  1228. }