explosion.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  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. mExplosionShapeAsset.registerRefreshNotify(this);
  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. mExplosionShapeAsset = other.mExplosionShapeAsset;
  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. mExplosionShapeAsset.unregisterRefreshNotify();
  326. // particleEmitter, emitterList[*], debrisList[*], explosionList[*] will delete themselves
  327. #ifdef TRACK_EXPLOSION_DATA_CLONES
  328. if (explosion_data_clones > 0)
  329. {
  330. explosion_data_clones--;
  331. if (explosion_data_clones == 0)
  332. Con::errorf("ExplosionData -- Clones eliminated!");
  333. }
  334. else
  335. Con::errorf("ExplosionData -- Too many clones deleted!");
  336. #endif
  337. }
  338. ExplosionData* ExplosionData::cloneAndPerformSubstitutions(const SimObject* owner, S32 index)
  339. {
  340. if (!owner || getSubstitutionCount() == 0)
  341. return this;
  342. ExplosionData* sub_explosion_db = new ExplosionData(*this, true);
  343. performSubstitutions(sub_explosion_db, owner, index);
  344. return sub_explosion_db;
  345. }
  346. IRangeValidator expPartDensityRange(0, 1<<14);
  347. IRangeValidator expDebrisNumRange(0, 1000);
  348. FRangeValidator expPlaySpeedRange(0.05f, FLT_MAX);
  349. FRangeValidator expLightRadiusRange(0.0f, MaxLightRadius,1<<8);
  350. FRangeValidator expTimeRange(0.0f, 1.0f, 1 << 8);
  351. void ExplosionData::initPersistFields()
  352. {
  353. docsURL;
  354. addGroup("Shapes");
  355. INITPERSISTFIELD_SHAPEASSET_REFACTOR(ExplosionShape, ExplosionData, "@brief Optional shape asset to place at the center of the explosion.\n\n"
  356. "The <i>ambient</i> animation of this model will be played automatically at the start of the explosion.");
  357. endGroup("Shapes");
  358. addGroup("Sounds");
  359. INITPERSISTFIELD_SOUNDASSET(Sound, ExplosionData, "Sound to play when this explosion explodes.");
  360. endGroup("Sounds");
  361. addGroup("Particle Effects");
  362. addField( "faceViewer", TypeBool, Offset(faceViewer, ExplosionData),
  363. "Controls whether the visual effects of the explosion always face the camera." );
  364. addField( "particleEmitter", TYPEID< ParticleEmitterData >(), Offset(particleEmitter, ExplosionData),
  365. "@brief Emitter used to generate a cloud of particles at the start of the explosion.\n\n"
  366. "Explosions can generate two different particle effects. The first is a "
  367. "single burst of particles at the start of the explosion emitted in a "
  368. "spherical cloud using particleEmitter.\n\n"
  369. "The second effect spawns the list of ParticleEmitters given by the emitter[] "
  370. "field. These emitters generate particles in the normal way throughout the "
  371. "lifetime of the explosion." );
  372. addFieldV( "particleDensity", TypeRangedS32, Offset(particleDensity, ExplosionData), &expPartDensityRange,
  373. "@brief Density of the particle cloud created at the start of the explosion.\n\n"
  374. "@see particleEmitter" );
  375. addFieldV( "particleRadius", TypeRangedF32, Offset(particleRadius, ExplosionData),&CommonValidators::PositiveFloat,
  376. "@brief Radial distance from the explosion center at which cloud particles "
  377. "are emitted.\n\n"
  378. "@see particleEmitter" );
  379. addField( "emitter", TYPEID< ParticleEmitterData >(), Offset(emitterList, ExplosionData), EC_NUM_EMITTERS,
  380. "@brief List of additional ParticleEmitterData objects to spawn with this "
  381. "explosion.\n\n"
  382. "@see particleEmitter" );
  383. endGroup("Particle Effects");
  384. addGroup("Debris");
  385. addField( "debris", TYPEID< DebrisData >(), Offset(debrisList, ExplosionData), EC_NUM_DEBRIS_TYPES,
  386. "List of DebrisData objects to spawn with this explosion." );
  387. addFieldV( "debrisThetaMin", TypeRangedF32, Offset(debrisThetaMin, ExplosionData), &CommonValidators::PosDegreeRangeHalf,
  388. "Minimum angle, from the horizontal plane, to eject debris from." );
  389. addFieldV( "debrisThetaMax", TypeRangedF32, Offset(debrisThetaMax, ExplosionData), &CommonValidators::PosDegreeRangeHalf,
  390. "Maximum angle, from the horizontal plane, to eject debris from." );
  391. addFieldV( "debrisPhiMin", TypeRangedF32, Offset(debrisPhiMin, ExplosionData), &CommonValidators::PosDegreeRange,
  392. "Minimum reference angle, from the vertical plane, to eject debris from." );
  393. addFieldV( "debrisPhiMax", TypeRangedF32, Offset(debrisPhiMax, ExplosionData), &CommonValidators::PosDegreeRange,
  394. "Maximum reference angle, from the vertical plane, to eject debris from." );
  395. addFieldV( "debrisNum", TypeRangedS32, Offset(debrisNum, ExplosionData), &expDebrisNumRange,
  396. "Number of debris objects to create." );
  397. addFieldV( "debrisNumVariance", TypeRangedS32, Offset(debrisNumVariance, ExplosionData), &expDebrisNumRange,
  398. "Variance in the number of debris objects to create (must be from 0 - debrisNum)." );
  399. addFieldV( "debrisVelocity", TypeRangedF32, Offset(debrisVelocity, ExplosionData), &CommonValidators::PositiveFloat,
  400. "Velocity to toss debris at." );
  401. addFieldV( "debrisVelocityVariance", TypeRangedF32, Offset(debrisVelocityVariance, ExplosionData), &CommonValidators::PositiveFloat,
  402. "Variance in the debris initial velocity (must be >= 0)." );
  403. addField( "subExplosion", TYPEID< ExplosionData >(), Offset(explosionList, ExplosionData), EC_MAX_SUB_EXPLOSIONS,
  404. "List of additional ExplosionData objects to create at the start of the explosion." );
  405. endGroup("Debris");
  406. addGroup("Animation");
  407. addField("explosionScale", TypePoint3F, Offset(explosionScale, ExplosionData),
  408. "\"X Y Z\" scale factor applied to the explosionShape model at the start "
  409. "of the explosion.");
  410. addFieldV("playSpeed", TypeRangedF32, Offset(playSpeed, ExplosionData),&expPlaySpeedRange,
  411. "Time scale at which to play the explosionShape <i>ambient</i> sequence.");
  412. addFieldV( "delayMS", TypeRangedS32, Offset(delayMS, ExplosionData), &CommonValidators::PositiveInt,
  413. "Amount of time, in milliseconds, to delay the start of the explosion effect "
  414. "from the creation of the Explosion object." );
  415. addFieldV( "delayVariance", TypeRangedS32, Offset(delayVariance, ExplosionData), &CommonValidators::PositiveInt,
  416. "Variance, in milliseconds, of delayMS." );
  417. addFieldV( "lifetimeMS", TypeRangedS32, Offset(lifetimeMS, ExplosionData), &CommonValidators::PositiveInt,
  418. "@brief Lifetime, in milliseconds, of the Explosion object.\n\n"
  419. "@note If explosionShape is defined and contains an <i>ambient</i> animation, "
  420. "this field is ignored, and the playSpeed scaled duration of the animation "
  421. "is used instead." );
  422. addFieldV( "lifetimeVariance", TypeRangedS32, Offset(lifetimeVariance, ExplosionData), &CommonValidators::PositiveInt,
  423. "Variance, in milliseconds, of the lifetimeMS of the Explosion object.\n" );
  424. addFieldV( "offset", TypeRangedF32, Offset(offset, ExplosionData), &CommonValidators::PositiveFloat,
  425. "@brief Offset distance (in a random direction) of the center of the explosion "
  426. "from the Explosion object position.\n\n"
  427. "Most often used to create some variance in position for subExplosion effects." );
  428. addFieldV( "times", TypeRangedF32, Offset(times, ExplosionData), &expTimeRange, EC_NUM_TIME_KEYS,
  429. "@brief Time keyframes used to scale the explosionShape model.\n\n"
  430. "Values should be in increasing order from 0.0 - 1.0, and correspond to "
  431. "the life of the Explosion where 0 is the beginning and 1 is the end of "
  432. "the explosion lifetime.\n"
  433. "@see lifetimeMS" );
  434. addField( "sizes", TypePoint3F, Offset(sizes, ExplosionData), EC_NUM_TIME_KEYS,
  435. "@brief \"X Y Z\" size keyframes used to scale the explosionShape model.\n\n"
  436. "The explosionShape (if defined) will be scaled using the times/sizes "
  437. "keyframes over the lifetime of the explosion.\n"
  438. "@see lifetimeMS" );
  439. endGroup("Animation");
  440. addGroup("Camera Shake");
  441. addField( "shakeCamera", TypeBool, Offset(shakeCamera, ExplosionData),
  442. "Controls whether the camera shakes during this explosion." );
  443. addField( "camShakeFreq", TypePoint3F, Offset(camShakeFreq, ExplosionData),
  444. "Frequency of camera shaking, defined in the \"X Y Z\" axes." );
  445. addField( "camShakeAmp", TypePoint3F, Offset(camShakeAmp, ExplosionData),
  446. "@brief Amplitude of camera shaking, defined in the \"X Y Z\" axes.\n\n"
  447. "Set any value to 0 to disable shaking in that axis." );
  448. addFieldV( "camShakeDuration", TypeRangedF32, Offset(camShakeDuration, ExplosionData), &CommonValidators::PositiveFloat,
  449. "Duration (in seconds) to shake the camera." );
  450. addFieldV( "camShakeRadius", TypeRangedF32, Offset(camShakeRadius, ExplosionData), &CommonValidators::PositiveFloat,
  451. "Radial distance that a camera's position must be within relative to the "
  452. "center of the explosion to be shaken." );
  453. addFieldV( "camShakeFalloff", TypeRangedF32, Offset(camShakeFalloff, ExplosionData), &CommonValidators::PositiveFloat,
  454. "Falloff value for the camera shake." );
  455. endGroup("Camera Shake");
  456. addGroup("Light Emitter");
  457. addFieldV( "lightStartRadius", TypeRangedF32, Offset(lightStartRadius, ExplosionData), &expLightRadiusRange,
  458. "@brief Initial radius of the PointLight created by this explosion.\n\n"
  459. "Radius is linearly interpolated from lightStartRadius to lightEndRadius "
  460. "over the lifetime of the explosion.\n"
  461. "@see lifetimeMS" );
  462. addFieldV( "lightEndRadius", TypeRangedF32, Offset(lightEndRadius, ExplosionData), &expLightRadiusRange,
  463. "@brief Final radius of the PointLight created by this explosion.\n\n"
  464. "@see lightStartRadius" );
  465. addField( "lightStartColor", TypeColorF, Offset(lightStartColor, ExplosionData),
  466. "@brief Initial color of the PointLight created by this explosion.\n\n"
  467. "Color is linearly interpolated from lightStartColor to lightEndColor "
  468. "over the lifetime of the explosion.\n"
  469. "@see lifetimeMS" );
  470. addField( "lightEndColor", TypeColorF, Offset(lightEndColor, ExplosionData),
  471. "@brief Final color of the PointLight created by this explosion.\n\n"
  472. "@see lightStartColor" );
  473. addFieldV( "lightStartBrightness", TypeRangedF32, Offset(lightStartBrightness, ExplosionData), &expLightRadiusRange,
  474. "@brief Initial brightness of the PointLight created by this explosion.\n\n"
  475. "Brightness is linearly interpolated from lightStartBrightness to "
  476. "lightEndBrightness over the lifetime of the explosion.\n"
  477. "@see lifetimeMS" );
  478. addFieldV("lightEndBrightness", TypeRangedF32, Offset(lightEndBrightness, ExplosionData), &expLightRadiusRange,
  479. "@brief Final brightness of the PointLight created by this explosion.\n\n"
  480. "@see lightStartBrightness" );
  481. addFieldV( "lightNormalOffset", TypeRangedF32, Offset(lightNormalOffset, ExplosionData), &CommonValidators::PositiveFloat,
  482. "Distance (in the explosion normal direction) of the PointLight position "
  483. "from the explosion center." );
  484. endGroup("Light Emitter");
  485. // disallow some field substitutions
  486. onlyKeepClearSubstitutions("debris"); // subs resolving to "~~", or "~0" are OK
  487. onlyKeepClearSubstitutions("emitter");
  488. onlyKeepClearSubstitutions("particleEmitter");
  489. onlyKeepClearSubstitutions("subExplosion");
  490. Parent::initPersistFields();
  491. }
  492. bool ExplosionData::onAdd()
  493. {
  494. if (Parent::onAdd() == false)
  495. return false;
  496. if (explosionScale.x < 0.01f || explosionScale.y < 0.01f || explosionScale.z < 0.01f)
  497. {
  498. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s)::onAdd: ExplosionScale components must be >= 0.01", getName());
  499. explosionScale.x = explosionScale.x < 0.01f ? 0.01f : explosionScale.x;
  500. explosionScale.y = explosionScale.y < 0.01f ? 0.01f : explosionScale.y;
  501. explosionScale.z = explosionScale.z < 0.01f ? 0.01f : explosionScale.z;
  502. }
  503. if (debrisThetaMin < 0.0f)
  504. {
  505. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisThetaMin < 0.0", getName());
  506. debrisThetaMin = 0.0f;
  507. }
  508. if (debrisThetaMax > 180.0f)
  509. {
  510. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisThetaMax > 180.0", getName());
  511. debrisThetaMax = 180.0f;
  512. }
  513. if (debrisThetaMin > debrisThetaMax) {
  514. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisThetaMin > debrisThetaMax", getName());
  515. debrisThetaMin = debrisThetaMax;
  516. }
  517. if (debrisPhiMin < 0.0f)
  518. {
  519. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisPhiMin < 0.0", getName());
  520. debrisPhiMin = 0.0f;
  521. }
  522. if (debrisPhiMax > 360.0f)
  523. {
  524. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisPhiMax > 360.0", getName());
  525. debrisPhiMax = 360.0f;
  526. }
  527. if (debrisPhiMin > debrisPhiMax) {
  528. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisPhiMin > debrisPhiMax", getName());
  529. debrisPhiMin = debrisPhiMax;
  530. }
  531. if (debrisNum > 1000) {
  532. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisNum > 1000", getName());
  533. debrisNum = 1000;
  534. }
  535. if (debrisNumVariance > 1000) {
  536. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisNumVariance > 1000", getName());
  537. debrisNumVariance = 1000;
  538. }
  539. if (debrisVelocity < 0.1f)
  540. {
  541. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisVelocity < 0.1", getName());
  542. debrisVelocity = 0.1f;
  543. }
  544. if (debrisVelocityVariance > 1000) {
  545. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) debrisVelocityVariance > 1000", getName());
  546. debrisVelocityVariance = 1000;
  547. }
  548. if (playSpeed < 0.05f)
  549. {
  550. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) playSpeed < 0.05", getName());
  551. playSpeed = 0.05f;
  552. }
  553. if (lifetimeMS < 1) {
  554. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) lifetimeMS < 1", getName());
  555. lifetimeMS = 1;
  556. }
  557. if (lifetimeVariance > lifetimeMS) {
  558. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) lifetimeVariance > lifetimeMS", getName());
  559. lifetimeVariance = lifetimeMS;
  560. }
  561. if (delayMS < 0) {
  562. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) delayMS < 0", getName());
  563. delayMS = 0;
  564. }
  565. if (delayVariance > delayMS) {
  566. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) delayVariance > delayMS", getName());
  567. delayVariance = delayMS;
  568. }
  569. if (offset < 0.0f)
  570. {
  571. Con::warnf(ConsoleLogEntry::General, "ExplosionData(%s) offset < 0.0", getName());
  572. offset = 0.0f;
  573. }
  574. S32 i;
  575. for( i=0; i<EC_NUM_DEBRIS_TYPES; i++ )
  576. {
  577. if( !debrisList[i] && debrisIDList[i] != 0 )
  578. {
  579. if( !Sim::findObject( debrisIDList[i], debrisList[i] ) )
  580. {
  581. Con::errorf( ConsoleLogEntry::General, "ExplosionData::onAdd: Invalid packet, bad datablockId(debris): 0x%x", debrisIDList[i] );
  582. }
  583. }
  584. }
  585. for( i=0; i<EC_NUM_EMITTERS; i++ )
  586. {
  587. if( !emitterList[i] && emitterIDList[i] != 0 )
  588. {
  589. if( Sim::findObject( emitterIDList[i], emitterList[i] ) == false)
  590. {
  591. Con::errorf( ConsoleLogEntry::General, "ExplosionData::onAdd: Invalid packet, bad datablockId(particle emitter): 0x%x", emitterIDList[i] );
  592. }
  593. }
  594. }
  595. for( S32 k=0; k<EC_MAX_SUB_EXPLOSIONS; k++ )
  596. {
  597. if( !explosionList[k] && explosionIDList[k] != 0 )
  598. {
  599. if( Sim::findObject( explosionIDList[k], explosionList[k] ) == false)
  600. {
  601. Con::errorf( ConsoleLogEntry::General, "ExplosionData::onAdd: Invalid packet, bad datablockId(explosion): 0x%x", explosionIDList[k] );
  602. }
  603. }
  604. }
  605. return true;
  606. }
  607. void ExplosionData::packData(BitStream* stream)
  608. {
  609. Parent::packData(stream);
  610. PACKDATA_ASSET_REFACTOR(ExplosionShape);
  611. //PACKDATA_SOUNDASSET(Sound);
  612. PACKDATA_ASSET(Sound);
  613. if (stream->writeFlag(particleEmitter))
  614. stream->writeRangedU32(particleEmitter->getId(),DataBlockObjectIdFirst,DataBlockObjectIdLast);
  615. stream->writeInt(particleDensity, 14);
  616. stream->write(particleRadius);
  617. stream->writeFlag(faceViewer);
  618. if(stream->writeFlag(explosionScale.x != 1 || explosionScale.y != 1 || explosionScale.z != 1))
  619. {
  620. stream->writeInt((S32)(explosionScale.x * 100), 16);
  621. stream->writeInt((S32)(explosionScale.y * 100), 16);
  622. stream->writeInt((S32)(explosionScale.z * 100), 16);
  623. }
  624. stream->writeInt((S32)(playSpeed * 20), 14);
  625. stream->writeRangedU32((U32)debrisThetaMin, 0, 180);
  626. stream->writeRangedU32((U32)debrisThetaMax, 0, 180);
  627. stream->writeRangedU32((U32)debrisPhiMin, 0, 360);
  628. stream->writeRangedU32((U32)debrisPhiMax, 0, 360);
  629. stream->writeRangedU32((U32)debrisNum, 0, 1000);
  630. stream->writeRangedU32(debrisNumVariance, 0, 1000);
  631. stream->writeInt((S32)(debrisVelocity * 10), 14);
  632. stream->writeRangedU32((U32)(debrisVelocityVariance * 10), 0, 10000);
  633. stream->writeInt(delayMS >> 5, 16);
  634. stream->writeInt(delayVariance >> 5, 16);
  635. stream->writeInt(lifetimeMS >> 5, 16);
  636. stream->writeInt(lifetimeVariance >> 5, 16);
  637. stream->write(offset);
  638. stream->writeFlag( shakeCamera );
  639. stream->write(camShakeFreq.x);
  640. stream->write(camShakeFreq.y);
  641. stream->write(camShakeFreq.z);
  642. stream->write(camShakeAmp.x);
  643. stream->write(camShakeAmp.y);
  644. stream->write(camShakeAmp.z);
  645. stream->write(camShakeDuration);
  646. stream->write(camShakeRadius);
  647. stream->write(camShakeFalloff);
  648. for( S32 j=0; j<EC_NUM_DEBRIS_TYPES; j++ )
  649. {
  650. if( stream->writeFlag( debrisList[j] ) )
  651. {
  652. stream->writeRangedU32( debrisList[j]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  653. }
  654. }
  655. S32 i;
  656. for( i=0; i<EC_NUM_EMITTERS; i++ )
  657. {
  658. if( stream->writeFlag( emitterList[i] != NULL ) )
  659. {
  660. stream->writeRangedU32( emitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  661. }
  662. }
  663. for( i=0; i<EC_MAX_SUB_EXPLOSIONS; i++ )
  664. {
  665. if( stream->writeFlag( explosionList[i] != NULL ) )
  666. {
  667. stream->writeRangedU32( explosionList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  668. }
  669. }
  670. U32 count;
  671. for(count = 0; count < EC_NUM_TIME_KEYS; count++)
  672. if(times[count] >= 1)
  673. break;
  674. count++;
  675. if(count > EC_NUM_TIME_KEYS)
  676. count = EC_NUM_TIME_KEYS;
  677. stream->writeRangedU32(count, 0, EC_NUM_TIME_KEYS);
  678. for( i=0; i<count; i++ )
  679. stream->writeFloat( times[i], 8 );
  680. for( i=0; i<count; i++ )
  681. {
  682. stream->writeRangedU32((U32)(sizes[i].x * 100), 0, 16000);
  683. stream->writeRangedU32((U32)(sizes[i].y * 100), 0, 16000);
  684. stream->writeRangedU32((U32)(sizes[i].z * 100), 0, 16000);
  685. }
  686. // Dynamic light info
  687. stream->writeFloat(lightStartRadius/MaxLightRadius, 8);
  688. stream->writeFloat(lightEndRadius/MaxLightRadius, 8);
  689. stream->writeFloat(lightStartColor.red,8);
  690. stream->writeFloat(lightStartColor.green,8);
  691. stream->writeFloat(lightStartColor.blue,8);
  692. stream->writeFloat(lightEndColor.red,8);
  693. stream->writeFloat(lightEndColor.green,8);
  694. stream->writeFloat(lightEndColor.blue,8);
  695. stream->writeFloat(lightStartBrightness/MaxLightRadius, 8);
  696. stream->writeFloat(lightEndBrightness/MaxLightRadius, 8);
  697. stream->write(lightNormalOffset);
  698. }
  699. void ExplosionData::unpackData(BitStream* stream)
  700. {
  701. Parent::unpackData(stream);
  702. UNPACKDATA_ASSET_REFACTOR(ExplosionShape);
  703. UNPACKDATA_ASSET(Sound);
  704. if (stream->readFlag())
  705. particleEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  706. else
  707. particleEmitterId = 0;
  708. particleDensity = stream->readInt(14);
  709. stream->read(&particleRadius);
  710. faceViewer = stream->readFlag();
  711. if(stream->readFlag())
  712. {
  713. explosionScale.x = stream->readInt(16) / 100.0f;
  714. explosionScale.y = stream->readInt(16) / 100.0f;
  715. explosionScale.z = stream->readInt(16) / 100.0f;
  716. }
  717. else
  718. explosionScale.set(1,1,1);
  719. playSpeed = stream->readInt(14) / 20.0f;
  720. debrisThetaMin = stream->readRangedU32(0, 180);
  721. debrisThetaMax = stream->readRangedU32(0, 180);
  722. debrisPhiMin = stream->readRangedU32(0, 360);
  723. debrisPhiMax = stream->readRangedU32(0, 360);
  724. debrisNum = stream->readRangedU32(0, 1000);
  725. debrisNumVariance = stream->readRangedU32(0, 1000);
  726. debrisVelocity = stream->readInt(14) / 10.0f;
  727. debrisVelocityVariance = stream->readRangedU32(0, 10000) / 10.0f;
  728. delayMS = stream->readInt(16) << 5;
  729. delayVariance = stream->readInt(16) << 5;
  730. lifetimeMS = stream->readInt(16) << 5;
  731. lifetimeVariance = stream->readInt(16) << 5;
  732. stream->read(&offset);
  733. shakeCamera = stream->readFlag();
  734. stream->read(&camShakeFreq.x);
  735. stream->read(&camShakeFreq.y);
  736. stream->read(&camShakeFreq.z);
  737. stream->read(&camShakeAmp.x);
  738. stream->read(&camShakeAmp.y);
  739. stream->read(&camShakeAmp.z);
  740. stream->read(&camShakeDuration);
  741. stream->read(&camShakeRadius);
  742. stream->read(&camShakeFalloff);
  743. for( S32 j=0; j<EC_NUM_DEBRIS_TYPES; j++ )
  744. {
  745. if( stream->readFlag() )
  746. {
  747. debrisIDList[j] = (S32) stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  748. }
  749. }
  750. U32 i;
  751. for( i=0; i<EC_NUM_EMITTERS; i++ )
  752. {
  753. if( stream->readFlag() )
  754. {
  755. emitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  756. }
  757. }
  758. for( S32 k=0; k<EC_MAX_SUB_EXPLOSIONS; k++ )
  759. {
  760. if( stream->readFlag() )
  761. {
  762. explosionIDList[k] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  763. }
  764. }
  765. U32 count = stream->readRangedU32(0, EC_NUM_TIME_KEYS);
  766. for( i=0; i<count; i++ )
  767. times[i] = stream->readFloat(8);
  768. for( i=0; i<count; i++ )
  769. {
  770. sizes[i].x = stream->readRangedU32(0, 16000) / 100.0f;
  771. sizes[i].y = stream->readRangedU32(0, 16000) / 100.0f;
  772. sizes[i].z = stream->readRangedU32(0, 16000) / 100.0f;
  773. }
  774. //
  775. lightStartRadius = stream->readFloat(8) * MaxLightRadius;
  776. lightEndRadius = stream->readFloat(8) * MaxLightRadius;
  777. lightStartColor.red = stream->readFloat(8);
  778. lightStartColor.green = stream->readFloat(8);
  779. lightStartColor.blue = stream->readFloat(8);
  780. lightEndColor.red = stream->readFloat(8);
  781. lightEndColor.green = stream->readFloat(8);
  782. lightEndColor.blue = stream->readFloat(8);
  783. lightStartBrightness = stream->readFloat(8) * MaxLightRadius;
  784. lightEndBrightness = stream->readFloat(8) * MaxLightRadius;
  785. stream->read( &lightNormalOffset );
  786. }
  787. bool ExplosionData::preload(bool server, String &errorStr)
  788. {
  789. if (Parent::preload(server, errorStr) == false)
  790. return false;
  791. if( !server )
  792. {
  793. if (!isSoundValid())
  794. {
  795. //return false; -TODO: trigger asset download
  796. }
  797. if (!particleEmitter && particleEmitterId != 0)
  798. if (Sim::findObject(particleEmitterId, particleEmitter) == false)
  799. {
  800. Con::errorf(ConsoleLogEntry::General, "Error, unable to load particle emitter for explosion datablock");
  801. return false;
  802. }
  803. }
  804. if (getExplosionShape()) {
  805. // Resolve animations
  806. explosionAnimation = getExplosionShape()->findSequence("ambient");
  807. // Preload textures with a dummy instance...
  808. TSShapeInstance* pDummy = new TSShapeInstance(getExplosionShape(), !server);
  809. delete pDummy;
  810. }
  811. else if (mExplosionShapeAsset.notNull())
  812. {
  813. errorStr = String::ToString("ExplosionData::preload: Couldn't load shape \"%s\"", _getExplosionShapeAssetId());
  814. return false;
  815. }
  816. else {
  817. explosionAnimation = -1;
  818. }
  819. return true;
  820. }
  821. //--------------------------------------------------------------------------
  822. //--------------------------------------
  823. //
  824. Explosion::Explosion()
  825. : mDataBlock( NULL )
  826. {
  827. mTypeMask |= ExplosionObjectType | LightObjectType;
  828. mExplosionInstance = NULL;
  829. mExplosionThread = NULL;
  830. dMemset( mEmitterList, 0, sizeof( mEmitterList ) );
  831. mMainEmitter = NULL;
  832. mFade = 1;
  833. mDelayMS = 0;
  834. mCurrMS = 0;
  835. mEndingMS = 1000;
  836. mActive = false;
  837. mCollideType = 0;
  838. mInitialNormal.set( 0.0f, 0.0f, 1.0f );
  839. mRandAngle = sgRandom.randF( 0.0f, 1.0f ) * M_PI_F * 2.0f;
  840. mLight = LIGHTMGR->createLightInfo();
  841. mNetFlags.set( IsGhost );
  842. ss_object = 0;
  843. ss_index = 0;
  844. mDataBlock = 0;
  845. soundProfile_clone = 0;
  846. mRandomVal = 0;
  847. }
  848. Explosion::~Explosion()
  849. {
  850. if( mExplosionInstance )
  851. {
  852. delete mExplosionInstance;
  853. mExplosionInstance = NULL;
  854. mExplosionThread = NULL;
  855. }
  856. SAFE_DELETE(mLight);
  857. if (soundProfile_clone)
  858. {
  859. delete soundProfile_clone;
  860. soundProfile_clone = 0;
  861. }
  862. if (mDataBlock && mDataBlock->isTempClone())
  863. {
  864. delete mDataBlock;
  865. mDataBlock = 0;
  866. }
  867. }
  868. void Explosion::setInitialState(const Point3F& point, const Point3F& normal, const F32 fade)
  869. {
  870. setPosition(point);
  871. mInitialNormal = normal;
  872. mFade = fade;
  873. }
  874. //--------------------------------------------------------------------------
  875. void Explosion::initPersistFields()
  876. {
  877. docsURL;
  878. Parent::initPersistFields();
  879. addField("initialNormal", TypePoint3F, Offset(mInitialNormal, Explosion), "Initial starting Normal.");
  880. //
  881. }
  882. //--------------------------------------------------------------------------
  883. bool Explosion::onAdd()
  884. {
  885. // first check if we have a server connection, if we dont then this is on the server
  886. // and we should exit, then check if the parent fails to add the object
  887. GameConnection *conn = GameConnection::getConnectionToServer();
  888. if ( !conn || !Parent::onAdd() )
  889. return false;
  890. if( !mDataBlock )
  891. {
  892. Con::errorf("Explosion::onAdd - Fail - No datablok");
  893. return false;
  894. }
  895. mDelayMS = mDataBlock->delayMS + sgRandom.randI( -mDataBlock->delayVariance, mDataBlock->delayVariance );
  896. mEndingMS = mDataBlock->lifetimeMS + sgRandom.randI( -mDataBlock->lifetimeVariance, mDataBlock->lifetimeVariance );
  897. if( mFabs( mDataBlock->offset ) > 0.001f )
  898. {
  899. MatrixF axisOrient = MathUtils::createOrientFromDir( mInitialNormal );
  900. MatrixF trans = getTransform();
  901. Point3F randVec;
  902. randVec.x = sgRandom.randF( -1.0f, 1.0f );
  903. randVec.y = sgRandom.randF( 0.0f, 1.0f );
  904. randVec.z = sgRandom.randF( -1.0f, 1.0f );
  905. randVec.normalize();
  906. randVec *= mDataBlock->offset;
  907. axisOrient.mulV( randVec );
  908. trans.setPosition( trans.getPosition() + randVec );
  909. setTransform( trans );
  910. }
  911. // shake camera
  912. if( mDataBlock->shakeCamera )
  913. {
  914. // first check if explosion is near player
  915. GameConnection* connection = GameConnection::getConnectionToServer();
  916. ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject());
  917. bool applyShake = true;
  918. if( obj )
  919. {
  920. ShapeBase* cObj = obj;
  921. while((cObj = cObj->getControlObject()) != 0)
  922. {
  923. if(cObj->useObjsEyePoint())
  924. {
  925. applyShake = false;
  926. break;
  927. }
  928. }
  929. }
  930. if( applyShake && obj )
  931. {
  932. VectorF diff = obj->getPosition() - getPosition();
  933. F32 dist = diff.len();
  934. if( dist < mDataBlock->camShakeRadius )
  935. {
  936. CameraShake *camShake = new CameraShake;
  937. camShake->setDuration( mDataBlock->camShakeDuration );
  938. camShake->setFrequency( mDataBlock->camShakeFreq );
  939. F32 falloff = dist / mDataBlock->camShakeRadius;
  940. falloff = 1.0f + falloff * 10.0f;
  941. falloff = 1.0f / (falloff * falloff);
  942. VectorF shakeAmp = mDataBlock->camShakeAmp * falloff;
  943. camShake->setAmplitude( shakeAmp );
  944. camShake->setFalloff( mDataBlock->camShakeFalloff );
  945. camShake->init();
  946. gCamFXMgr.addFX( camShake );
  947. }
  948. }
  949. }
  950. if( mDelayMS == 0 )
  951. {
  952. if( !explode() )
  953. {
  954. return false;
  955. }
  956. }
  957. gClientSceneGraph->addObjectToScene(this);
  958. removeFromProcessList();
  959. ClientProcessList::get()->addObject(this);
  960. mRandomVal = sgRandom.randF();
  961. NetConnection* pNC = NetConnection::getConnectionToServer();
  962. AssertFatal(pNC != NULL, "Error, must have a connection to the server!");
  963. pNC->addObject(this);
  964. // Initialize the light structure and register as a dynamic light
  965. if (mDataBlock->lightStartRadius != 0.0f || mDataBlock->lightEndRadius)
  966. {
  967. mLight->setType( LightInfo::Point );
  968. mLight->setRange( mDataBlock->lightStartRadius );
  969. mLight->setColor( mDataBlock->lightStartColor );
  970. }
  971. return true;
  972. }
  973. void Explosion::onRemove()
  974. {
  975. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  976. {
  977. if( mEmitterList[i] )
  978. {
  979. mEmitterList[i]->deleteWhenEmpty();
  980. mEmitterList[i] = NULL;
  981. }
  982. }
  983. if( mMainEmitter )
  984. {
  985. mMainEmitter->deleteWhenEmpty();
  986. mMainEmitter = NULL;
  987. }
  988. removeFromScene();
  989. Parent::onRemove();
  990. }
  991. bool Explosion::onNewDataBlock( GameBaseData *dptr, bool reload )
  992. {
  993. mDataBlock = dynamic_cast<ExplosionData*>( dptr );
  994. if (!mDataBlock || !Parent::onNewDataBlock( dptr, reload ))
  995. return false;
  996. if (mDataBlock->isTempClone())
  997. return true;
  998. scriptOnNewDataBlock(reload);
  999. return true;
  1000. }
  1001. //--------------------------------------------------------------------------
  1002. void Explosion::prepRenderImage( SceneRenderState* state )
  1003. {
  1004. prepBatchRender( state );
  1005. }
  1006. void Explosion::setCurrentScale()
  1007. {
  1008. F32 t = F32(mCurrMS) / F32(mEndingMS);
  1009. for( U32 i = 1; i < ExplosionData::EC_NUM_TIME_KEYS; i++ )
  1010. {
  1011. if( mDataBlock->times[i] >= t )
  1012. {
  1013. F32 firstPart = t - mDataBlock->times[i-1];
  1014. F32 total = mDataBlock->times[i] -
  1015. mDataBlock->times[i-1];
  1016. firstPart /= total;
  1017. mObjScale = (mDataBlock->sizes[i-1] * (1.0f - firstPart)) +
  1018. (mDataBlock->sizes[i] * firstPart);
  1019. return;
  1020. }
  1021. }
  1022. }
  1023. //--------------------------------------------------------------------------
  1024. // Make the explosion face the viewer (if desired)
  1025. //--------------------------------------------------------------------------
  1026. void Explosion::prepModelView(SceneRenderState* state)
  1027. {
  1028. MatrixF rotMatrix( true );
  1029. Point3F targetVector;
  1030. if( mDataBlock->faceViewer )
  1031. {
  1032. targetVector = getPosition() - state->getCameraPosition();
  1033. targetVector.normalize();
  1034. // rotate explosion each time so it's a little different
  1035. rotMatrix.set( EulerF( 0.0f, mRandAngle, 0.0f ) );
  1036. }
  1037. else
  1038. {
  1039. targetVector = mInitialNormal;
  1040. }
  1041. MatrixF explOrient = MathUtils::createOrientFromDir( targetVector );
  1042. explOrient.mul( rotMatrix );
  1043. explOrient.setPosition( getPosition() );
  1044. setCurrentScale();
  1045. explOrient.scale( mObjScale );
  1046. GFX->setWorldMatrix( explOrient );
  1047. }
  1048. //--------------------------------------------------------------------------
  1049. // Render object
  1050. //--------------------------------------------------------------------------
  1051. void Explosion::prepBatchRender(SceneRenderState* state)
  1052. {
  1053. if ( !mExplosionInstance )
  1054. return;
  1055. MatrixF proj = GFX->getProjectionMatrix();
  1056. RectI viewport = GFX->getViewport();
  1057. // Set up our TS render state here.
  1058. TSRenderState rdata;
  1059. rdata.setSceneState( state );
  1060. // We might have some forward lit materials
  1061. // so pass down a query to gather lights.
  1062. LightQuery query;
  1063. query.init( getWorldSphere() );
  1064. rdata.setLightQuery( &query );
  1065. // render mesh
  1066. GFX->pushWorldMatrix();
  1067. prepModelView( state );
  1068. mExplosionInstance->animate();
  1069. mExplosionInstance->render( rdata );
  1070. GFX->popWorldMatrix();
  1071. GFX->setProjectionMatrix( proj );
  1072. GFX->setViewport( viewport );
  1073. }
  1074. void Explosion::submitLights( LightManager *lm, bool staticLighting )
  1075. {
  1076. if ( staticLighting )
  1077. return;
  1078. // Update the light's info and add it to the scene, the light will
  1079. // only be visible for this current frame.
  1080. mLight->setPosition( getRenderTransform().getPosition() + mInitialNormal * mDataBlock->lightNormalOffset );
  1081. F32 t = F32(mCurrMS) / F32(mEndingMS);
  1082. mLight->setRange( mDataBlock->lightStartRadius +
  1083. (mDataBlock->lightEndRadius - mDataBlock->lightStartRadius) * t );
  1084. mLight->setColor( mDataBlock->lightStartColor +
  1085. (mDataBlock->lightEndColor - mDataBlock->lightStartColor) * t );
  1086. mLight->setBrightness( mDataBlock->lightStartBrightness +
  1087. (mDataBlock->lightEndBrightness - mDataBlock->lightStartBrightness) * t );
  1088. lm->registerGlobalLight( mLight, this );
  1089. }
  1090. //--------------------------------------------------------------------------
  1091. void Explosion::processTick(const Move*)
  1092. {
  1093. mCurrMS += TickMs;
  1094. if( mCurrMS >= mEndingMS )
  1095. {
  1096. deleteObject();
  1097. return;
  1098. }
  1099. if( (mCurrMS > mDelayMS) && !mActive )
  1100. explode();
  1101. }
  1102. void Explosion::advanceTime(F32 dt)
  1103. {
  1104. if (dt == 0.0f)
  1105. return;
  1106. GameConnection* conn = GameConnection::getConnectionToServer();
  1107. if(!conn)
  1108. return;
  1109. updateEmitters( dt );
  1110. if( mExplosionInstance )
  1111. mExplosionInstance->advanceTime(dt, mExplosionThread);
  1112. }
  1113. //----------------------------------------------------------------------------
  1114. // Update emitters
  1115. //----------------------------------------------------------------------------
  1116. void Explosion::updateEmitters( F32 dt )
  1117. {
  1118. Point3F pos = getPosition();
  1119. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  1120. {
  1121. if( mEmitterList[i] )
  1122. {
  1123. mEmitterList[i]->emitParticles( pos, pos, mInitialNormal, Point3F( 0.0f, 0.0f, 0.0f ), (U32)(dt * 1000));
  1124. }
  1125. }
  1126. }
  1127. //----------------------------------------------------------------------------
  1128. // Launch Debris
  1129. //----------------------------------------------------------------------------
  1130. void Explosion::launchDebris( Point3F &axis )
  1131. {
  1132. GameConnection* conn = GameConnection::getConnectionToServer();
  1133. if(!conn)
  1134. return;
  1135. bool hasDebris = false;
  1136. for( S32 j=0; j<ExplosionData::EC_NUM_DEBRIS_TYPES; j++ )
  1137. {
  1138. if( mDataBlock->debrisList[j] )
  1139. {
  1140. hasDebris = true;
  1141. break;
  1142. }
  1143. }
  1144. if( !hasDebris )
  1145. {
  1146. return;
  1147. }
  1148. Point3F axisx;
  1149. if (mFabs(axis.z) < 0.999f)
  1150. mCross(axis, Point3F(0.0f, 0.0f, 1.0f), &axisx);
  1151. else
  1152. mCross(axis, Point3F(0.0f, 1.0f, 0.0f), &axisx);
  1153. axisx.normalize();
  1154. Point3F pos( 0.0f, 0.0f, 0.5f );
  1155. pos += getPosition();
  1156. U32 numDebris = mDataBlock->debrisNum + sgRandom.randI( -mDataBlock->debrisNumVariance, mDataBlock->debrisNumVariance );
  1157. for( S32 i=0; i<numDebris; i++ )
  1158. {
  1159. Point3F launchDir = MathUtils::randomDir( axis, mDataBlock->debrisThetaMin, mDataBlock->debrisThetaMax,
  1160. mDataBlock->debrisPhiMin, mDataBlock->debrisPhiMax );
  1161. F32 debrisVel = mDataBlock->debrisVelocity + mDataBlock->debrisVelocityVariance * sgRandom.randF( -1.0f, 1.0f );
  1162. launchDir *= debrisVel;
  1163. Debris *debris = new Debris;
  1164. debris->setSubstitutionData(ss_object, ss_index);
  1165. debris->setDataBlock(mDataBlock->debrisList[0]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1166. debris->setTransform( getTransform() );
  1167. debris->init( pos, launchDir );
  1168. if( !debris->registerObject() )
  1169. {
  1170. Con::warnf( ConsoleLogEntry::General, "Could not register debris for class: %s", mDataBlock->getName() );
  1171. delete debris;
  1172. debris = NULL;
  1173. }
  1174. }
  1175. }
  1176. //----------------------------------------------------------------------------
  1177. // Spawn sub explosions
  1178. //----------------------------------------------------------------------------
  1179. void Explosion::spawnSubExplosions()
  1180. {
  1181. GameConnection* conn = GameConnection::getConnectionToServer();
  1182. if(!conn)
  1183. return;
  1184. for( S32 i=0; i<ExplosionData::EC_MAX_SUB_EXPLOSIONS; i++ )
  1185. {
  1186. if( mDataBlock->explosionList[i] )
  1187. {
  1188. MatrixF trans = getTransform();
  1189. Explosion* pExplosion = new Explosion;
  1190. pExplosion->setSubstitutionData(ss_object, ss_index);
  1191. pExplosion->setDataBlock(mDataBlock->explosionList[i]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1192. pExplosion->setTransform( trans );
  1193. pExplosion->setInitialState( trans.getPosition(), mInitialNormal, 1);
  1194. if (!pExplosion->registerObject())
  1195. delete pExplosion;
  1196. }
  1197. }
  1198. }
  1199. //----------------------------------------------------------------------------
  1200. // Explode
  1201. //----------------------------------------------------------------------------
  1202. bool Explosion::explode()
  1203. {
  1204. mActive = true;
  1205. GameConnection* conn = GameConnection::getConnectionToServer();
  1206. if(!conn)
  1207. return false;
  1208. launchDebris( mInitialNormal );
  1209. spawnSubExplosions();
  1210. if (bool(mDataBlock->getExplosionShape()) && mDataBlock->explosionAnimation != -1) {
  1211. mExplosionInstance = new TSShapeInstance(mDataBlock->getExplosionShape(), true);
  1212. mExplosionThread = mExplosionInstance->addThread();
  1213. mExplosionInstance->setSequence(mExplosionThread, mDataBlock->explosionAnimation, 0);
  1214. mExplosionInstance->setTimeScale(mExplosionThread, mDataBlock->playSpeed);
  1215. mCurrMS = 0;
  1216. mEndingMS = U32(mExplosionInstance->getScaledDuration(mExplosionThread) * 1000.0f);
  1217. mObjScale.convolve(mDataBlock->explosionScale);
  1218. mObjBox = mDataBlock->getExplosionShape()->mBounds;
  1219. resetWorldBox();
  1220. }
  1221. SFXProfile* sound_prof = static_cast<SFXProfile*>(mDataBlock->getSoundProfile());
  1222. if (sound_prof)
  1223. {
  1224. soundProfile_clone = sound_prof->cloneAndPerformSubstitutions(ss_object, ss_index);
  1225. SFX->playOnce( soundProfile_clone, &getTransform() );
  1226. if (!soundProfile_clone->isTempClone())
  1227. soundProfile_clone = 0;
  1228. }
  1229. if (mDataBlock->particleEmitter) {
  1230. mMainEmitter = new ParticleEmitter;
  1231. mMainEmitter->setDataBlock(mDataBlock->particleEmitter->cloneAndPerformSubstitutions(ss_object, ss_index));
  1232. mMainEmitter->registerObject();
  1233. mMainEmitter->emitParticles(getPosition(), mInitialNormal, mDataBlock->particleRadius,
  1234. Point3F::Zero, U32(mDataBlock->particleDensity * mFade));
  1235. }
  1236. for( S32 i=0; i<ExplosionData::EC_NUM_EMITTERS; i++ )
  1237. {
  1238. if( mDataBlock->emitterList[i] != NULL )
  1239. {
  1240. ParticleEmitter * pEmitter = new ParticleEmitter;
  1241. pEmitter->setDataBlock(mDataBlock->emitterList[i]->cloneAndPerformSubstitutions(ss_object, ss_index));
  1242. if( !pEmitter->registerObject() )
  1243. {
  1244. Con::warnf( ConsoleLogEntry::General, "Could not register emitter for particle of class: %s", mDataBlock->getName() );
  1245. SAFE_DELETE(pEmitter);
  1246. }
  1247. mEmitterList[i] = pEmitter;
  1248. }
  1249. }
  1250. return true;
  1251. }