particleEmitter.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "T3D/fx/particleEmitter.h"
  24. #include "scene/sceneManager.h"
  25. #include "scene/sceneRenderState.h"
  26. #include "console/consoleTypes.h"
  27. #include "core/stream/bitStream.h"
  28. #include "core/strings/stringUnit.h"
  29. #include "math/mRandom.h"
  30. #include "gfx/gfxDevice.h"
  31. #include "gfx/primBuilder.h"
  32. #include "gfx/gfxStringEnumTranslate.h"
  33. #include "renderInstance/renderPassManager.h"
  34. #include "T3D/gameBase/gameProcess.h"
  35. #include "lighting/lightInfo.h"
  36. #include "console/engineAPI.h"
  37. #if defined(TORQUE_OS_XENON)
  38. # include "gfx/D3D9/360/gfx360MemVertexBuffer.h"
  39. #endif
  40. Point3F ParticleEmitter::mWindVelocity( 0.0, 0.0, 0.0 );
  41. const F32 ParticleEmitter::AgedSpinToRadians = (1.0f/1000.0f) * (1.0f/360.0f) * M_PI_F * 2.0f;
  42. IMPLEMENT_CO_DATABLOCK_V1(ParticleEmitterData);
  43. IMPLEMENT_CONOBJECT(ParticleEmitter);
  44. ConsoleDocClass( ParticleEmitter,
  45. "@brief This object is responsible for spawning particles.\n\n"
  46. "@note This class is not normally instantiated directly - to place a simple "
  47. "particle emitting object in the scene, use a ParticleEmitterNode instead.\n\n"
  48. "This class is the main interface for creating particles - though it is "
  49. "usually only accessed from within another object like ParticleEmitterNode "
  50. "or WheeledVehicle. If using this object class (via C++) directly, be aware "
  51. "that it does <b>not</b> track changes in source axis or velocity over the "
  52. "course of a single update, so emitParticles should be called at a fairly "
  53. "fine grain. The emitter will potentially track the last particle to be "
  54. "created into the next call to this function in order to create a uniformly "
  55. "random time distribution of the particles.\n\n"
  56. "If the object to which the emitter is attached is in motion, it should try "
  57. "to ensure that for call (n+1) to this function, start is equal to the end "
  58. "from call (n). This will ensure a uniform spatial distribution.\n\n"
  59. "@ingroup FX\n"
  60. "@see ParticleEmitterData\n"
  61. "@see ParticleEmitterNode\n"
  62. );
  63. ConsoleDocClass( ParticleEmitterData,
  64. "@brief Defines particle emission properties such as ejection angle, period "
  65. "and velocity for a ParticleEmitter.\n\n"
  66. "@tsexample\n"
  67. "datablock ParticleEmitterData( GrenadeExpDustEmitter )\n"
  68. "{\n"
  69. " ejectionPeriodMS = 1;\n"
  70. " periodVarianceMS = 0;\n"
  71. " ejectionVelocity = 15;\n"
  72. " velocityVariance = 0.0;\n"
  73. " ejectionOffset = 0.0;\n"
  74. " thetaMin = 85;\n"
  75. " thetaMax = 85;\n"
  76. " phiReferenceVel = 0;\n"
  77. " phiVariance = 360;\n"
  78. " overrideAdvance = false;\n"
  79. " lifetimeMS = 200;\n"
  80. " particles = \"GrenadeExpDust\";\n"
  81. "};\n"
  82. "@endtsexample\n\n"
  83. "@ingroup FX\n"
  84. "@see ParticleEmitter\n"
  85. "@see ParticleData\n"
  86. "@see ParticleEmitterNode\n"
  87. );
  88. static const float sgDefaultEjectionOffset = 0.f;
  89. static const float sgDefaultPhiReferenceVel = 0.f;
  90. static const float sgDefaultPhiVariance = 360.f;
  91. //-----------------------------------------------------------------------------
  92. // ParticleEmitterData
  93. //-----------------------------------------------------------------------------
  94. ParticleEmitterData::ParticleEmitterData()
  95. {
  96. VECTOR_SET_ASSOCIATION(particleDataBlocks);
  97. VECTOR_SET_ASSOCIATION(dataBlockIds);
  98. ejectionPeriodMS = 100; // 10 Particles Per second
  99. periodVarianceMS = 0; // exactly
  100. ejectionVelocity = 2.0f; // From 1.0 - 3.0 meters per sec
  101. velocityVariance = 1.0f;
  102. ejectionOffset = sgDefaultEjectionOffset; // ejection from the emitter point
  103. thetaMin = 0.0f; // All heights
  104. thetaMax = 90.0f;
  105. phiReferenceVel = sgDefaultPhiReferenceVel; // All directions
  106. phiVariance = sgDefaultPhiVariance;
  107. softnessDistance = 1.0f;
  108. ambientFactor = 0.0f;
  109. lifetimeMS = 0;
  110. lifetimeVarianceMS = 0;
  111. overrideAdvance = true;
  112. orientParticles = false;
  113. orientOnVelocity = true;
  114. useEmitterSizes = false;
  115. useEmitterColors = false;
  116. particleString = NULL;
  117. partListInitSize = 0;
  118. // These members added for support of user defined blend factors
  119. // and optional particle sorting.
  120. blendStyle = ParticleRenderInst::BlendUndefined;
  121. sortParticles = false;
  122. renderReflection = true;
  123. reverseOrder = false;
  124. textureName = 0;
  125. textureHandle = 0;
  126. highResOnly = true;
  127. alignParticles = false;
  128. alignDirection = Point3F(0.0f, 1.0f, 0.0f);
  129. }
  130. // Enum tables used for fields blendStyle, srcBlendFactor, dstBlendFactor.
  131. // Note that the enums for srcBlendFactor and dstBlendFactor are consistent
  132. // with the blending enums used in Torque Game Builder.
  133. typedef ParticleRenderInst::BlendStyle ParticleBlendStyle;
  134. DefineEnumType( ParticleBlendStyle );
  135. ImplementEnumType( ParticleBlendStyle,
  136. "The type of visual blending style to apply to the particles.\n"
  137. "@ingroup FX\n\n")
  138. { ParticleRenderInst::BlendNormal, "NORMAL", "No blending style.\n" },
  139. { ParticleRenderInst::BlendAdditive, "ADDITIVE", "Adds the color of the pixel to the frame buffer with full alpha for each pixel.\n" },
  140. { ParticleRenderInst::BlendSubtractive, "SUBTRACTIVE", "Subtractive Blending. Reverses the color model, causing dark colors to have a stronger visual effect.\n" },
  141. { ParticleRenderInst::BlendPremultAlpha, "PREMULTALPHA", "Color blends with the colors of the imagemap rather than the alpha.\n" },
  142. EndImplementEnumType;
  143. //-----------------------------------------------------------------------------
  144. // initPersistFields
  145. //-----------------------------------------------------------------------------
  146. void ParticleEmitterData::initPersistFields()
  147. {
  148. addGroup( "ParticleEmitterData" );
  149. addField("ejectionPeriodMS", TYPEID< S32 >(), Offset(ejectionPeriodMS, ParticleEmitterData),
  150. "Time (in milliseconds) between each particle ejection." );
  151. addField("periodVarianceMS", TYPEID< S32 >(), Offset(periodVarianceMS, ParticleEmitterData),
  152. "Variance in ejection period, from 1 - ejectionPeriodMS." );
  153. addField( "ejectionVelocity", TYPEID< F32 >(), Offset(ejectionVelocity, ParticleEmitterData),
  154. "Particle ejection velocity." );
  155. addField( "velocityVariance", TYPEID< F32 >(), Offset(velocityVariance, ParticleEmitterData),
  156. "Variance for ejection velocity, from 0 - ejectionVelocity." );
  157. addField( "ejectionOffset", TYPEID< F32 >(), Offset(ejectionOffset, ParticleEmitterData),
  158. "Distance along ejection Z axis from which to eject particles." );
  159. addField( "thetaMin", TYPEID< F32 >(), Offset(thetaMin, ParticleEmitterData),
  160. "Minimum angle, from the horizontal plane, to eject from." );
  161. addField( "thetaMax", TYPEID< F32 >(), Offset(thetaMax, ParticleEmitterData),
  162. "Maximum angle, from the horizontal plane, to eject particles from." );
  163. addField( "phiReferenceVel", TYPEID< F32 >(), Offset(phiReferenceVel, ParticleEmitterData),
  164. "Reference angle, from the vertical plane, to eject particles from." );
  165. addField( "phiVariance", TYPEID< F32 >(), Offset(phiVariance, ParticleEmitterData),
  166. "Variance from the reference angle, from 0 - 360." );
  167. addField( "softnessDistance", TYPEID< F32 >(), Offset(softnessDistance, ParticleEmitterData),
  168. "For soft particles, the distance (in meters) where particles will be "
  169. "faded based on the difference in depth between the particle and the "
  170. "scene geometry." );
  171. addField( "ambientFactor", TYPEID< F32 >(), Offset(ambientFactor, ParticleEmitterData),
  172. "Used to generate the final particle color by controlling interpolation "
  173. "between the particle color and the particle color multiplied by the "
  174. "ambient light color." );
  175. addField( "overrideAdvance", TYPEID< bool >(), Offset(overrideAdvance, ParticleEmitterData),
  176. "If false, particles emitted in the same frame have their positions "
  177. "adjusted. If true, adjustment is skipped and particles will clump "
  178. "together." );
  179. addField( "orientParticles", TYPEID< bool >(), Offset(orientParticles, ParticleEmitterData),
  180. "If true, Particles will always face the camera." );
  181. addField( "orientOnVelocity", TYPEID< bool >(), Offset(orientOnVelocity, ParticleEmitterData),
  182. "If true, particles will be oriented to face in the direction they are moving." );
  183. addField( "particles", TYPEID< StringTableEntry >(), Offset(particleString, ParticleEmitterData),
  184. "@brief List of space or TAB delimited ParticleData datablock names.\n\n"
  185. "A random one of these datablocks is selected each time a particle is "
  186. "emitted." );
  187. addField( "lifetimeMS", TYPEID< S32 >(), Offset(lifetimeMS, ParticleEmitterData),
  188. "Lifetime of emitted particles (in milliseconds)." );
  189. addField("lifetimeVarianceMS", TYPEID< S32 >(), Offset(lifetimeVarianceMS, ParticleEmitterData),
  190. "Variance in particle lifetime from 0 - lifetimeMS." );
  191. addField( "useEmitterSizes", TYPEID< bool >(), Offset(useEmitterSizes, ParticleEmitterData),
  192. "@brief If true, use emitter specified sizes instead of datablock sizes.\n"
  193. "Useful for Debris particle emitters that control the particle size." );
  194. addField( "useEmitterColors", TYPEID< bool >(), Offset(useEmitterColors, ParticleEmitterData),
  195. "@brief If true, use emitter specified colors instead of datablock colors.\n\n"
  196. "Useful for ShapeBase dust and WheeledVehicle wheel particle emitters that use "
  197. "the current material to control particle color." );
  198. /// These fields added for support of user defined blend factors and optional particle sorting.
  199. //@{
  200. addField( "blendStyle", TYPEID< ParticleRenderInst::BlendStyle >(), Offset(blendStyle, ParticleEmitterData),
  201. "String value that controls how emitted particles blend with the scene." );
  202. addField( "sortParticles", TYPEID< bool >(), Offset(sortParticles, ParticleEmitterData),
  203. "If true, particles are sorted furthest to nearest.");
  204. addField( "reverseOrder", TYPEID< bool >(), Offset(reverseOrder, ParticleEmitterData),
  205. "@brief If true, reverses the normal draw order of particles.\n\n"
  206. "Particles are normally drawn from newest to oldest, or in Z order "
  207. "(furthest first) if sortParticles is true. Setting this field to "
  208. "true will reverse that order: oldest first, or nearest first if "
  209. "sortParticles is true." );
  210. addField( "textureName", TYPEID< StringTableEntry >(), Offset(textureName, ParticleEmitterData),
  211. "Optional texture to override ParticleData::textureName." );
  212. addField( "alignParticles", TYPEID< bool >(), Offset(alignParticles, ParticleEmitterData),
  213. "If true, particles always face along the axis defined by alignDirection." );
  214. addProtectedField( "alignDirection", TYPEID< Point3F>(), Offset(alignDirection, ParticleEmitterData), &ParticleEmitterData::_setAlignDirection, &defaultProtectedGetFn,
  215. "The direction aligned particles should face, only valid if alignParticles is true." );
  216. addField( "highResOnly", TYPEID< bool >(), Offset(highResOnly, ParticleEmitterData),
  217. "This particle system should not use the mixed-resolution renderer. "
  218. "If your particle system has large amounts of overdraw, consider "
  219. "disabling this option." );
  220. addField( "renderReflection", TYPEID< bool >(), Offset(renderReflection, ParticleEmitterData),
  221. "Controls whether particles are rendered onto reflective surfaces like water." );
  222. //@}
  223. endGroup( "ParticleEmitterData" );
  224. Parent::initPersistFields();
  225. }
  226. bool ParticleEmitterData::_setAlignDirection( void *object, const char *index, const char *data )
  227. {
  228. ParticleEmitterData *p = static_cast<ParticleEmitterData*>( object );
  229. Con::setData( TypePoint3F, &p->alignDirection, 0, 1, &data );
  230. p->alignDirection.normalizeSafe();
  231. // we already set the field
  232. return false;
  233. }
  234. //-----------------------------------------------------------------------------
  235. // packData
  236. //-----------------------------------------------------------------------------
  237. void ParticleEmitterData::packData(BitStream* stream)
  238. {
  239. Parent::packData(stream);
  240. stream->writeInt(ejectionPeriodMS, 10);
  241. stream->writeInt(periodVarianceMS, 10);
  242. stream->writeInt((S32)(ejectionVelocity * 100), 16);
  243. stream->writeInt((S32)(velocityVariance * 100), 14);
  244. if( stream->writeFlag( ejectionOffset != sgDefaultEjectionOffset ) )
  245. stream->writeInt((S32)(ejectionOffset * 100), 16);
  246. stream->writeRangedU32((U32)thetaMin, 0, 180);
  247. stream->writeRangedU32((U32)thetaMax, 0, 180);
  248. if( stream->writeFlag( phiReferenceVel != sgDefaultPhiReferenceVel ) )
  249. stream->writeRangedU32((U32)phiReferenceVel, 0, 360);
  250. if( stream->writeFlag( phiVariance != sgDefaultPhiVariance ) )
  251. stream->writeRangedU32((U32)phiVariance, 0, 360);
  252. stream->write( softnessDistance );
  253. stream->write( ambientFactor );
  254. stream->writeFlag(overrideAdvance);
  255. stream->writeFlag(orientParticles);
  256. stream->writeFlag(orientOnVelocity);
  257. stream->write( lifetimeMS );
  258. stream->write( lifetimeVarianceMS );
  259. stream->writeFlag(useEmitterSizes);
  260. stream->writeFlag(useEmitterColors);
  261. stream->write(dataBlockIds.size());
  262. for (U32 i = 0; i < dataBlockIds.size(); i++)
  263. stream->write(dataBlockIds[i]);
  264. stream->writeFlag(sortParticles);
  265. stream->writeFlag(reverseOrder);
  266. if (stream->writeFlag(textureName != 0))
  267. stream->writeString(textureName);
  268. if (stream->writeFlag(alignParticles))
  269. {
  270. stream->write(alignDirection.x);
  271. stream->write(alignDirection.y);
  272. stream->write(alignDirection.z);
  273. }
  274. stream->writeFlag(highResOnly);
  275. stream->writeFlag(renderReflection);
  276. stream->writeInt( blendStyle, 4 );
  277. }
  278. //-----------------------------------------------------------------------------
  279. // unpackData
  280. //-----------------------------------------------------------------------------
  281. void ParticleEmitterData::unpackData(BitStream* stream)
  282. {
  283. Parent::unpackData(stream);
  284. ejectionPeriodMS = stream->readInt(10);
  285. periodVarianceMS = stream->readInt(10);
  286. ejectionVelocity = stream->readInt(16) / 100.0f;
  287. velocityVariance = stream->readInt(14) / 100.0f;
  288. if( stream->readFlag() )
  289. ejectionOffset = stream->readInt(16) / 100.0f;
  290. else
  291. ejectionOffset = sgDefaultEjectionOffset;
  292. thetaMin = (F32)stream->readRangedU32(0, 180);
  293. thetaMax = (F32)stream->readRangedU32(0, 180);
  294. if( stream->readFlag() )
  295. phiReferenceVel = (F32)stream->readRangedU32(0, 360);
  296. else
  297. phiReferenceVel = sgDefaultPhiReferenceVel;
  298. if( stream->readFlag() )
  299. phiVariance = (F32)stream->readRangedU32(0, 360);
  300. else
  301. phiVariance = sgDefaultPhiVariance;
  302. stream->read( &softnessDistance );
  303. stream->read( &ambientFactor );
  304. overrideAdvance = stream->readFlag();
  305. orientParticles = stream->readFlag();
  306. orientOnVelocity = stream->readFlag();
  307. stream->read( &lifetimeMS );
  308. stream->read( &lifetimeVarianceMS );
  309. useEmitterSizes = stream->readFlag();
  310. useEmitterColors = stream->readFlag();
  311. U32 size; stream->read(&size);
  312. dataBlockIds.setSize(size);
  313. for (U32 i = 0; i < dataBlockIds.size(); i++)
  314. stream->read(&dataBlockIds[i]);
  315. sortParticles = stream->readFlag();
  316. reverseOrder = stream->readFlag();
  317. textureName = (stream->readFlag()) ? stream->readSTString() : 0;
  318. alignParticles = stream->readFlag();
  319. if (alignParticles)
  320. {
  321. stream->read(&alignDirection.x);
  322. stream->read(&alignDirection.y);
  323. stream->read(&alignDirection.z);
  324. }
  325. highResOnly = stream->readFlag();
  326. renderReflection = stream->readFlag();
  327. blendStyle = stream->readInt( 4 );
  328. }
  329. //-----------------------------------------------------------------------------
  330. // onAdd
  331. //-----------------------------------------------------------------------------
  332. bool ParticleEmitterData::onAdd()
  333. {
  334. if( Parent::onAdd() == false )
  335. return false;
  336. // if (overrideAdvance == true) {
  337. // Con::errorf(ConsoleLogEntry::General, "ParticleEmitterData: Not going to work. Fix it!");
  338. // return false;
  339. // }
  340. // Validate the parameters...
  341. //
  342. if( ejectionPeriodMS < 1 )
  343. {
  344. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) period < 1 ms", getName());
  345. ejectionPeriodMS = 1;
  346. }
  347. if( periodVarianceMS >= ejectionPeriodMS )
  348. {
  349. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) periodVariance >= period", getName());
  350. periodVarianceMS = ejectionPeriodMS - 1;
  351. }
  352. if( ejectionVelocity < 0.0f )
  353. {
  354. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) ejectionVelocity < 0.0f", getName());
  355. ejectionVelocity = 0.0f;
  356. }
  357. if( velocityVariance < 0.0f )
  358. {
  359. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) velocityVariance < 0.0f", getName());
  360. velocityVariance = 0.0f;
  361. }
  362. if( velocityVariance > ejectionVelocity )
  363. {
  364. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) velocityVariance > ejectionVelocity", getName());
  365. velocityVariance = ejectionVelocity;
  366. }
  367. if( ejectionOffset < 0.0f )
  368. {
  369. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) ejectionOffset < 0", getName());
  370. ejectionOffset = 0.0f;
  371. }
  372. if( thetaMin < 0.0f )
  373. {
  374. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaMin < 0.0", getName());
  375. thetaMin = 0.0f;
  376. }
  377. if( thetaMax > 180.0f )
  378. {
  379. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaMax > 180.0", getName());
  380. thetaMax = 180.0f;
  381. }
  382. if( thetaMin > thetaMax )
  383. {
  384. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaMin > thetaMax", getName());
  385. thetaMin = thetaMax;
  386. }
  387. if( phiVariance < 0.0f || phiVariance > 360.0f )
  388. {
  389. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) invalid phiVariance", getName());
  390. phiVariance = phiVariance < 0.0f ? 0.0f : 360.0f;
  391. }
  392. if ( softnessDistance < 0.0f )
  393. {
  394. Con::warnf( ConsoleLogEntry::General, "ParticleEmitterData(%s) invalid softnessDistance", getName() );
  395. softnessDistance = 0.0f;
  396. }
  397. if (particleString == NULL && dataBlockIds.size() == 0)
  398. {
  399. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) no particleString, invalid datablock", getName());
  400. return false;
  401. }
  402. if (particleString && particleString[0] == '\0')
  403. {
  404. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) no particleString, invalid datablock", getName());
  405. return false;
  406. }
  407. if (particleString && dStrlen(particleString) > 255)
  408. {
  409. Con::errorf(ConsoleLogEntry::General, "ParticleEmitterData(%s) particle string too long [> 255 chars]", getName());
  410. return false;
  411. }
  412. if( lifetimeMS < 0 )
  413. {
  414. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) lifetimeMS < 0.0f", getName());
  415. lifetimeMS = 0;
  416. }
  417. if( lifetimeVarianceMS > lifetimeMS )
  418. {
  419. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) lifetimeVarianceMS >= lifetimeMS", getName());
  420. lifetimeVarianceMS = lifetimeMS;
  421. }
  422. // load the particle datablocks...
  423. //
  424. if( particleString != NULL )
  425. {
  426. // particleString is once again a list of particle datablocks so it
  427. // must be parsed to extract the particle references.
  428. // First we parse particleString into a list of particle name tokens
  429. Vector<char*> dataBlocks(__FILE__, __LINE__);
  430. char* tokCopy = new char[dStrlen(particleString) + 1];
  431. dStrcpy(tokCopy, particleString);
  432. char* currTok = dStrtok(tokCopy, " \t");
  433. while (currTok != NULL)
  434. {
  435. dataBlocks.push_back(currTok);
  436. currTok = dStrtok(NULL, " \t");
  437. }
  438. if (dataBlocks.size() == 0)
  439. {
  440. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) invalid particles string. No datablocks found", getName());
  441. delete [] tokCopy;
  442. return false;
  443. }
  444. // Now we convert the particle name tokens into particle datablocks and IDs
  445. particleDataBlocks.clear();
  446. dataBlockIds.clear();
  447. for (U32 i = 0; i < dataBlocks.size(); i++)
  448. {
  449. ParticleData* pData = NULL;
  450. if (Sim::findObject(dataBlocks[i], pData) == false)
  451. {
  452. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find particle datablock: %s", getName(), dataBlocks[i]);
  453. }
  454. else
  455. {
  456. particleDataBlocks.push_back(pData);
  457. dataBlockIds.push_back(pData->getId());
  458. }
  459. }
  460. // cleanup
  461. delete [] tokCopy;
  462. // check that we actually found some particle datablocks
  463. if (particleDataBlocks.size() == 0)
  464. {
  465. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find any particle datablocks", getName());
  466. return false;
  467. }
  468. }
  469. return true;
  470. }
  471. //-----------------------------------------------------------------------------
  472. // preload
  473. //-----------------------------------------------------------------------------
  474. bool ParticleEmitterData::preload(bool server, String &errorStr)
  475. {
  476. if( Parent::preload(server, errorStr) == false )
  477. return false;
  478. particleDataBlocks.clear();
  479. for (U32 i = 0; i < dataBlockIds.size(); i++)
  480. {
  481. ParticleData* pData = NULL;
  482. if (Sim::findObject(dataBlockIds[i], pData) == false)
  483. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find particle datablock: %d", getName(), dataBlockIds[i]);
  484. else
  485. particleDataBlocks.push_back(pData);
  486. }
  487. if (!server)
  488. {
  489. // load emitter texture if specified
  490. if (textureName && textureName[0])
  491. {
  492. textureHandle = GFXTexHandle(textureName, &GFXDefaultStaticDiffuseProfile, avar("%s() - textureHandle (line %d)", __FUNCTION__, __LINE__));
  493. if (!textureHandle)
  494. {
  495. errorStr = String::ToString("Missing particle emitter texture: %s", textureName);
  496. return false;
  497. }
  498. }
  499. // otherwise, check that all particles refer to the same texture
  500. else if (particleDataBlocks.size() > 1)
  501. {
  502. StringTableEntry txr_name = particleDataBlocks[0]->textureName;
  503. for (S32 i = 1; i < particleDataBlocks.size(); i++)
  504. {
  505. // warn if particle textures are inconsistent
  506. if (particleDataBlocks[i]->textureName != txr_name)
  507. {
  508. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) particles reference different textures.", getName());
  509. break;
  510. }
  511. }
  512. }
  513. }
  514. // if blend-style is undefined check legacy useInvAlpha settings
  515. if (blendStyle == ParticleRenderInst::BlendUndefined && particleDataBlocks.size() > 0)
  516. {
  517. bool useInvAlpha = particleDataBlocks[0]->useInvAlpha;
  518. for (S32 i = 1; i < particleDataBlocks.size(); i++)
  519. {
  520. // warn if blend-style legacy useInvAlpha settings are inconsistent
  521. if (particleDataBlocks[i]->useInvAlpha != useInvAlpha)
  522. {
  523. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) particles have inconsistent useInvAlpha settings.", getName());
  524. break;
  525. }
  526. }
  527. blendStyle = (useInvAlpha) ? ParticleRenderInst::BlendNormal : ParticleRenderInst::BlendAdditive;
  528. }
  529. if( !server )
  530. {
  531. allocPrimBuffer();
  532. }
  533. return true;
  534. }
  535. //-----------------------------------------------------------------------------
  536. // alloc PrimitiveBuffer
  537. // The datablock allocates this static index buffer because it's the same
  538. // for all of the emitters - each particle quad uses the same index ordering
  539. //-----------------------------------------------------------------------------
  540. void ParticleEmitterData::allocPrimBuffer( S32 overrideSize )
  541. {
  542. // calculate particle list size
  543. AssertFatal(particleDataBlocks.size() > 0, "Error, no particles found." );
  544. U32 maxPartLife = particleDataBlocks[0]->lifetimeMS + particleDataBlocks[0]->lifetimeVarianceMS;
  545. for (S32 i = 1; i < particleDataBlocks.size(); i++)
  546. {
  547. U32 mpl = particleDataBlocks[i]->lifetimeMS + particleDataBlocks[i]->lifetimeVarianceMS;
  548. if (mpl > maxPartLife)
  549. maxPartLife = mpl;
  550. }
  551. partListInitSize = maxPartLife / (ejectionPeriodMS - periodVarianceMS);
  552. partListInitSize += 8; // add 8 as "fudge factor" to make sure it doesn't realloc if it goes over by 1
  553. // if override size is specified, then the emitter overran its buffer and needs a larger allocation
  554. if( overrideSize != -1 )
  555. {
  556. partListInitSize = overrideSize;
  557. }
  558. // create index buffer based on that size
  559. U32 indexListSize = partListInitSize * 6; // 6 indices per particle
  560. U16 *indices = new U16[ indexListSize ];
  561. for( U32 i=0; i<partListInitSize; i++ )
  562. {
  563. // this index ordering should be optimal (hopefully) for the vertex cache
  564. U16 *idx = &indices[i*6];
  565. volatile U32 offset = i * 4; // set to volatile to fix VC6 Release mode compiler bug
  566. idx[0] = 0 + offset;
  567. idx[1] = 1 + offset;
  568. idx[2] = 3 + offset;
  569. idx[3] = 1 + offset;
  570. idx[4] = 3 + offset;
  571. idx[5] = 2 + offset;
  572. }
  573. U16 *ibIndices;
  574. GFXBufferType bufferType = GFXBufferTypeStatic;
  575. #ifdef TORQUE_OS_XENON
  576. // Because of the way the volatile buffers work on Xenon this is the only
  577. // way to do this.
  578. bufferType = GFXBufferTypeVolatile;
  579. #endif
  580. primBuff.set( GFX, indexListSize, 0, bufferType );
  581. primBuff.lock( &ibIndices );
  582. dMemcpy( ibIndices, indices, indexListSize * sizeof(U16) );
  583. primBuff.unlock();
  584. delete [] indices;
  585. }
  586. //-----------------------------------------------------------------------------
  587. // ParticleEmitter
  588. //-----------------------------------------------------------------------------
  589. ParticleEmitter::ParticleEmitter()
  590. {
  591. mDeleteWhenEmpty = false;
  592. mDeleteOnTick = false;
  593. mInternalClock = 0;
  594. mNextParticleTime = 0;
  595. mLastPosition.set(0, 0, 0);
  596. mHasLastPosition = false;
  597. mLifetimeMS = 0;
  598. mElapsedTimeMS = 0;
  599. part_store = 0;
  600. part_freelist = NULL;
  601. part_list_head.next = NULL;
  602. n_part_capacity = 0;
  603. n_parts = 0;
  604. mCurBuffSize = 0;
  605. mDead = false;
  606. // ParticleEmitter should be allocated on the client only.
  607. mNetFlags.set( IsGhost );
  608. }
  609. //-----------------------------------------------------------------------------
  610. // destructor
  611. //-----------------------------------------------------------------------------
  612. ParticleEmitter::~ParticleEmitter()
  613. {
  614. for( S32 i = 0; i < part_store.size(); i++ )
  615. {
  616. delete [] part_store[i];
  617. }
  618. }
  619. //-----------------------------------------------------------------------------
  620. // onAdd
  621. //-----------------------------------------------------------------------------
  622. bool ParticleEmitter::onAdd()
  623. {
  624. if( !Parent::onAdd() )
  625. return false;
  626. // add to client side mission cleanup
  627. SimGroup *cleanup = dynamic_cast<SimGroup *>( Sim::findObject( "ClientMissionCleanup") );
  628. if( cleanup != NULL )
  629. {
  630. cleanup->addObject( this );
  631. }
  632. else
  633. {
  634. AssertFatal( false, "Error, could not find ClientMissionCleanup group" );
  635. return false;
  636. }
  637. removeFromProcessList();
  638. F32 radius = 5.0;
  639. mObjBox.minExtents = Point3F(-radius, -radius, -radius);
  640. mObjBox.maxExtents = Point3F(radius, radius, radius);
  641. resetWorldBox();
  642. return true;
  643. }
  644. //-----------------------------------------------------------------------------
  645. // onRemove
  646. //-----------------------------------------------------------------------------
  647. void ParticleEmitter::onRemove()
  648. {
  649. removeFromScene();
  650. Parent::onRemove();
  651. }
  652. //-----------------------------------------------------------------------------
  653. // onNewDataBlock
  654. //-----------------------------------------------------------------------------
  655. bool ParticleEmitter::onNewDataBlock( GameBaseData *dptr, bool reload )
  656. {
  657. mDataBlock = dynamic_cast<ParticleEmitterData*>( dptr );
  658. if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  659. return false;
  660. mLifetimeMS = mDataBlock->lifetimeMS;
  661. if( mDataBlock->lifetimeVarianceMS )
  662. {
  663. mLifetimeMS += S32( gRandGen.randI() % (2 * mDataBlock->lifetimeVarianceMS + 1)) - S32(mDataBlock->lifetimeVarianceMS );
  664. }
  665. // Allocate particle structures and init the freelist. Member part_store
  666. // is a Vector so that we can allocate more particles if partListInitSize
  667. // turns out to be too small.
  668. //
  669. if (mDataBlock->partListInitSize > 0)
  670. {
  671. for( S32 i = 0; i < part_store.size(); i++ )
  672. {
  673. delete [] part_store[i];
  674. }
  675. part_store.clear();
  676. n_part_capacity = mDataBlock->partListInitSize;
  677. Particle* store_block = new Particle[n_part_capacity];
  678. part_store.push_back(store_block);
  679. part_freelist = store_block;
  680. Particle* last_part = part_freelist;
  681. Particle* part = last_part+1;
  682. for( S32 i = 1; i < n_part_capacity; i++, part++, last_part++ )
  683. {
  684. last_part->next = part;
  685. }
  686. store_block[n_part_capacity-1].next = NULL;
  687. part_list_head.next = NULL;
  688. n_parts = 0;
  689. }
  690. scriptOnNewDataBlock();
  691. return true;
  692. }
  693. //-----------------------------------------------------------------------------
  694. // getCollectiveColor
  695. //-----------------------------------------------------------------------------
  696. ColorF ParticleEmitter::getCollectiveColor()
  697. {
  698. U32 count = 0;
  699. ColorF color = ColorF(0.0f, 0.0f, 0.0f);
  700. count = n_parts;
  701. for( Particle* part = part_list_head.next; part != NULL; part = part->next )
  702. {
  703. color += part->color;
  704. }
  705. if(count > 0)
  706. {
  707. color /= F32(count);
  708. }
  709. //if(color.red == 0.0f && color.green == 0.0f && color.blue == 0.0f)
  710. // color = color;
  711. return color;
  712. }
  713. //-----------------------------------------------------------------------------
  714. // prepRenderImage
  715. //-----------------------------------------------------------------------------
  716. void ParticleEmitter::prepRenderImage(SceneRenderState* state)
  717. {
  718. if( state->isReflectPass() && !getDataBlock()->renderReflection )
  719. return;
  720. // Never render into shadows.
  721. if (state->isShadowPass())
  722. return;
  723. PROFILE_SCOPE(ParticleEmitter_prepRenderImage);
  724. if ( mDead ||
  725. n_parts == 0 ||
  726. part_list_head.next == NULL )
  727. return;
  728. RenderPassManager *renderManager = state->getRenderPass();
  729. const Point3F &camPos = state->getCameraPosition();
  730. copyToVB( camPos, state->getAmbientLightColor() );
  731. if (!mVertBuff.isValid())
  732. return;
  733. ParticleRenderInst *ri = renderManager->allocInst<ParticleRenderInst>();
  734. ri->vertBuff = &mVertBuff;
  735. ri->primBuff = &getDataBlock()->primBuff;
  736. ri->translucentSort = true;
  737. ri->type = RenderPassManager::RIT_Particle;
  738. ri->sortDistSq = getRenderWorldBox().getSqDistanceToPoint( camPos );
  739. // Draw the system offscreen unless the highResOnly flag is set on the datablock
  740. ri->systemState = ( getDataBlock()->highResOnly ? PSS_AwaitingHighResDraw : PSS_AwaitingOffscreenDraw );
  741. ri->modelViewProj = renderManager->allocUniqueXform( GFX->getProjectionMatrix() *
  742. GFX->getViewMatrix() *
  743. GFX->getWorldMatrix() );
  744. // Update position on the matrix before multiplying it
  745. mBBObjToWorld.setPosition(mLastPosition);
  746. ri->bbModelViewProj = renderManager->allocUniqueXform( *ri->modelViewProj * mBBObjToWorld );
  747. ri->count = n_parts;
  748. ri->blendStyle = mDataBlock->blendStyle;
  749. // use first particle's texture unless there is an emitter texture to override it
  750. if (mDataBlock->textureHandle)
  751. ri->diffuseTex = &*(mDataBlock->textureHandle);
  752. else
  753. ri->diffuseTex = &*(part_list_head.next->dataBlock->textureHandle);
  754. ri->softnessDistance = mDataBlock->softnessDistance;
  755. // Sort by texture too.
  756. ri->defaultKey = ri->diffuseTex ? (U32)ri->diffuseTex : (U32)ri->vertBuff;
  757. renderManager->addInst( ri );
  758. }
  759. //-----------------------------------------------------------------------------
  760. // setSizes
  761. //-----------------------------------------------------------------------------
  762. void ParticleEmitter::setSizes( F32 *sizeList )
  763. {
  764. for( int i=0; i<ParticleData::PDC_NUM_KEYS; i++ )
  765. {
  766. sizes[i] = sizeList[i];
  767. }
  768. }
  769. //-----------------------------------------------------------------------------
  770. // setColors
  771. //-----------------------------------------------------------------------------
  772. void ParticleEmitter::setColors( ColorF *colorList )
  773. {
  774. for( int i=0; i<ParticleData::PDC_NUM_KEYS; i++ )
  775. {
  776. colors[i] = colorList[i];
  777. }
  778. }
  779. //-----------------------------------------------------------------------------
  780. // deleteWhenEmpty
  781. //-----------------------------------------------------------------------------
  782. void ParticleEmitter::deleteWhenEmpty()
  783. {
  784. // if the following asserts fire, there is a reasonable chance that you are trying to delete a particle emitter
  785. // that has already been deleted (possibly by ClientMissionCleanup). If so, use a SimObjectPtr to the emitter and check it
  786. // for null before calling this function.
  787. AssertFatal(isProperlyAdded(), "ParticleEmitter must be registed before calling deleteWhenEmpty");
  788. AssertFatal(!mDead, "ParticleEmitter already deleted");
  789. AssertFatal(!isDeleted(), "ParticleEmitter already deleted");
  790. AssertFatal(!isRemoved(), "ParticleEmitter already removed");
  791. // this check is for non debug case, so that we don't write in to freed memory
  792. bool okToDelete = !mDead && isProperlyAdded() && !isDeleted() && !isRemoved();
  793. if (okToDelete)
  794. {
  795. mDeleteWhenEmpty = true;
  796. if( !n_parts )
  797. {
  798. // We're already empty, so delete us now.
  799. mDead = true;
  800. deleteObject();
  801. }
  802. else
  803. AssertFatal( getSceneManager() != NULL, "ParticleEmitter not on process list and won't get ticked to death" );
  804. }
  805. }
  806. //-----------------------------------------------------------------------------
  807. // emitParticles
  808. //-----------------------------------------------------------------------------
  809. void ParticleEmitter::emitParticles(const Point3F& point,
  810. const bool useLastPosition,
  811. const Point3F& axis,
  812. const Point3F& velocity,
  813. const U32 numMilliseconds)
  814. {
  815. if( mDead ) return;
  816. // lifetime over - no more particles
  817. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  818. {
  819. return;
  820. }
  821. Point3F realStart;
  822. if( useLastPosition && mHasLastPosition )
  823. realStart = mLastPosition;
  824. else
  825. realStart = point;
  826. emitParticles(realStart, point,
  827. axis,
  828. velocity,
  829. numMilliseconds);
  830. }
  831. //-----------------------------------------------------------------------------
  832. // emitParticles
  833. //-----------------------------------------------------------------------------
  834. void ParticleEmitter::emitParticles(const Point3F& start,
  835. const Point3F& end,
  836. const Point3F& axis,
  837. const Point3F& velocity,
  838. const U32 numMilliseconds)
  839. {
  840. if( mDead ) return;
  841. if( mDataBlock->particleDataBlocks.empty() )
  842. return;
  843. // lifetime over - no more particles
  844. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  845. {
  846. return;
  847. }
  848. U32 currTime = 0;
  849. bool particlesAdded = false;
  850. Point3F axisx;
  851. if( mFabs(axis.z) < 0.9f )
  852. mCross(axis, Point3F(0, 0, 1), &axisx);
  853. else
  854. mCross(axis, Point3F(0, 1, 0), &axisx);
  855. axisx.normalize();
  856. if( mNextParticleTime != 0 )
  857. {
  858. // Need to handle next particle
  859. //
  860. if( mNextParticleTime > numMilliseconds )
  861. {
  862. // Defer to next update
  863. // (Note that this introduces a potential spatial irregularity if the owning
  864. // object is accelerating, and updating at a low frequency)
  865. //
  866. mNextParticleTime -= numMilliseconds;
  867. mInternalClock += numMilliseconds;
  868. mLastPosition = end;
  869. mHasLastPosition = true;
  870. return;
  871. }
  872. else
  873. {
  874. currTime += mNextParticleTime;
  875. mInternalClock += mNextParticleTime;
  876. // Emit particle at curr time
  877. // Create particle at the correct position
  878. Point3F pos;
  879. pos.interpolate(start, end, F32(currTime) / F32(numMilliseconds));
  880. addParticle(pos, axis, velocity, axisx);
  881. particlesAdded = true;
  882. mNextParticleTime = 0;
  883. }
  884. }
  885. while( currTime < numMilliseconds )
  886. {
  887. S32 nextTime = mDataBlock->ejectionPeriodMS;
  888. if( mDataBlock->periodVarianceMS != 0 )
  889. {
  890. nextTime += S32(gRandGen.randI() % (2 * mDataBlock->periodVarianceMS + 1)) -
  891. S32(mDataBlock->periodVarianceMS);
  892. }
  893. AssertFatal(nextTime > 0, "Error, next particle ejection time must always be greater than 0");
  894. if( currTime + nextTime > numMilliseconds )
  895. {
  896. mNextParticleTime = (currTime + nextTime) - numMilliseconds;
  897. mInternalClock += numMilliseconds - currTime;
  898. AssertFatal(mNextParticleTime > 0, "Error, should not have deferred this particle!");
  899. break;
  900. }
  901. currTime += nextTime;
  902. mInternalClock += nextTime;
  903. // Create particle at the correct position
  904. Point3F pos;
  905. pos.interpolate(start, end, F32(currTime) / F32(numMilliseconds));
  906. addParticle(pos, axis, velocity, axisx);
  907. particlesAdded = true;
  908. // This override-advance code is restored in order to correctly adjust
  909. // animated parameters of particles allocated within the same frame
  910. // update. Note that ordering is important and this code correctly
  911. // adds particles in the same newest-to-oldest ordering of the link-list.
  912. //
  913. // NOTE: We are assuming that the just added particle is at the head of our
  914. // list. If that changes, so must this...
  915. U32 advanceMS = numMilliseconds - currTime;
  916. if (mDataBlock->overrideAdvance == false && advanceMS != 0)
  917. {
  918. Particle* last_part = part_list_head.next;
  919. if (advanceMS > last_part->totalLifetime)
  920. {
  921. part_list_head.next = last_part->next;
  922. n_parts--;
  923. last_part->next = part_freelist;
  924. part_freelist = last_part;
  925. }
  926. else
  927. {
  928. if (advanceMS != 0)
  929. {
  930. F32 t = F32(advanceMS) / 1000.0;
  931. Point3F a = last_part->acc;
  932. a -= last_part->vel * last_part->dataBlock->dragCoefficient;
  933. a -= mWindVelocity * last_part->dataBlock->windCoefficient;
  934. a += Point3F(0.0f, 0.0f, -9.81f) * last_part->dataBlock->gravityCoefficient;
  935. last_part->vel += a * t;
  936. last_part->pos += last_part->vel * t;
  937. updateKeyData( last_part );
  938. }
  939. }
  940. }
  941. }
  942. // DMMFIX: Lame and slow...
  943. if( particlesAdded == true )
  944. updateBBox();
  945. if( n_parts > 0 && getSceneManager() == NULL )
  946. {
  947. gClientSceneGraph->addObjectToScene(this);
  948. ClientProcessList::get()->addObject(this);
  949. }
  950. mLastPosition = end;
  951. mHasLastPosition = true;
  952. }
  953. //-----------------------------------------------------------------------------
  954. // emitParticles
  955. //-----------------------------------------------------------------------------
  956. void ParticleEmitter::emitParticles(const Point3F& rCenter,
  957. const Point3F& rNormal,
  958. const F32 radius,
  959. const Point3F& velocity,
  960. S32 count)
  961. {
  962. if( mDead ) return;
  963. // lifetime over - no more particles
  964. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  965. {
  966. return;
  967. }
  968. Point3F axisx, axisy;
  969. Point3F axisz = rNormal;
  970. if( axisz.isZero() )
  971. {
  972. axisz.set( 0.0, 0.0, 1.0 );
  973. }
  974. if( mFabs(axisz.z) < 0.98 )
  975. {
  976. mCross(axisz, Point3F(0, 0, 1), &axisy);
  977. axisy.normalize();
  978. }
  979. else
  980. {
  981. mCross(axisz, Point3F(0, 1, 0), &axisy);
  982. axisy.normalize();
  983. }
  984. mCross(axisz, axisy, &axisx);
  985. axisx.normalize();
  986. // Should think of a better way to distribute the
  987. // particles within the hemisphere.
  988. for( S32 i = 0; i < count; i++ )
  989. {
  990. Point3F pos = axisx * (radius * (1 - (2 * gRandGen.randF())));
  991. pos += axisy * (radius * (1 - (2 * gRandGen.randF())));
  992. pos += axisz * (radius * gRandGen.randF());
  993. Point3F axis = pos;
  994. axis.normalize();
  995. pos += rCenter;
  996. addParticle(pos, axis, velocity, axisz);
  997. }
  998. // Set world bounding box
  999. mObjBox.minExtents = rCenter - Point3F(radius, radius, radius);
  1000. mObjBox.maxExtents = rCenter + Point3F(radius, radius, radius);
  1001. resetWorldBox();
  1002. // Make sure we're part of the world
  1003. if( n_parts > 0 && getSceneManager() == NULL )
  1004. {
  1005. gClientSceneGraph->addObjectToScene(this);
  1006. ClientProcessList::get()->addObject(this);
  1007. }
  1008. mHasLastPosition = false;
  1009. }
  1010. //-----------------------------------------------------------------------------
  1011. // updateBBox - SLOW, bad news
  1012. //-----------------------------------------------------------------------------
  1013. void ParticleEmitter::updateBBox()
  1014. {
  1015. Point3F minPt(1e10, 1e10, 1e10);
  1016. Point3F maxPt(-1e10, -1e10, -1e10);
  1017. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1018. {
  1019. Point3F particleSize(part->size * 0.5f, 0.0f, part->size * 0.5f);
  1020. minPt.setMin( part->pos - particleSize );
  1021. maxPt.setMax( part->pos + particleSize );
  1022. }
  1023. mObjBox = Box3F(minPt, maxPt);
  1024. MatrixF temp = getTransform();
  1025. setTransform(temp);
  1026. mBBObjToWorld.identity();
  1027. Point3F boxScale = mObjBox.getExtents();
  1028. boxScale.x = getMax(boxScale.x, 1.0f);
  1029. boxScale.y = getMax(boxScale.y, 1.0f);
  1030. boxScale.z = getMax(boxScale.z, 1.0f);
  1031. mBBObjToWorld.scale(boxScale);
  1032. }
  1033. //-----------------------------------------------------------------------------
  1034. // addParticle
  1035. //-----------------------------------------------------------------------------
  1036. void ParticleEmitter::addParticle(const Point3F& pos,
  1037. const Point3F& axis,
  1038. const Point3F& vel,
  1039. const Point3F& axisx)
  1040. {
  1041. n_parts++;
  1042. if (n_parts > n_part_capacity || n_parts > mDataBlock->partListInitSize)
  1043. {
  1044. // In an emergency we allocate additional particles in blocks of 16.
  1045. // This should happen rarely.
  1046. Particle* store_block = new Particle[16];
  1047. part_store.push_back(store_block);
  1048. n_part_capacity += 16;
  1049. for (S32 i = 0; i < 16; i++)
  1050. {
  1051. store_block[i].next = part_freelist;
  1052. part_freelist = &store_block[i];
  1053. }
  1054. mDataBlock->allocPrimBuffer(n_part_capacity); // allocate larger primitive buffer or will crash
  1055. }
  1056. Particle* pNew = part_freelist;
  1057. part_freelist = pNew->next;
  1058. pNew->next = part_list_head.next;
  1059. part_list_head.next = pNew;
  1060. Point3F ejectionAxis = axis;
  1061. F32 theta = (mDataBlock->thetaMax - mDataBlock->thetaMin) * gRandGen.randF() +
  1062. mDataBlock->thetaMin;
  1063. F32 ref = (F32(mInternalClock) / 1000.0) * mDataBlock->phiReferenceVel;
  1064. F32 phi = ref + gRandGen.randF() * mDataBlock->phiVariance;
  1065. // Both phi and theta are in degs. Create axis angles out of them, and create the
  1066. // appropriate rotation matrix...
  1067. AngAxisF thetaRot(axisx, theta * (M_PI / 180.0));
  1068. AngAxisF phiRot(axis, phi * (M_PI / 180.0));
  1069. MatrixF temp(true);
  1070. thetaRot.setMatrix(&temp);
  1071. temp.mulP(ejectionAxis);
  1072. phiRot.setMatrix(&temp);
  1073. temp.mulP(ejectionAxis);
  1074. F32 initialVel = mDataBlock->ejectionVelocity;
  1075. initialVel += (mDataBlock->velocityVariance * 2.0f * gRandGen.randF()) - mDataBlock->velocityVariance;
  1076. pNew->pos = pos + (ejectionAxis * mDataBlock->ejectionOffset);
  1077. pNew->vel = ejectionAxis * initialVel;
  1078. pNew->orientDir = ejectionAxis;
  1079. pNew->acc.set(0, 0, 0);
  1080. pNew->currentAge = 0;
  1081. // Choose a new particle datablack randomly from the list
  1082. U32 dBlockIndex = gRandGen.randI() % mDataBlock->particleDataBlocks.size();
  1083. mDataBlock->particleDataBlocks[dBlockIndex]->initializeParticle(pNew, vel);
  1084. updateKeyData( pNew );
  1085. }
  1086. //-----------------------------------------------------------------------------
  1087. // processTick
  1088. //-----------------------------------------------------------------------------
  1089. void ParticleEmitter::processTick(const Move*)
  1090. {
  1091. if( mDeleteOnTick == true )
  1092. {
  1093. mDead = true;
  1094. deleteObject();
  1095. }
  1096. }
  1097. //-----------------------------------------------------------------------------
  1098. // advanceTime
  1099. //-----------------------------------------------------------------------------
  1100. void ParticleEmitter::advanceTime(F32 dt)
  1101. {
  1102. if( dt < 0.00001 ) return;
  1103. Parent::advanceTime(dt);
  1104. if( dt > 0.5 ) dt = 0.5;
  1105. if( mDead ) return;
  1106. mElapsedTimeMS += (S32)(dt * 1000.0f);
  1107. U32 numMSToUpdate = (U32)(dt * 1000.0f);
  1108. if( numMSToUpdate == 0 ) return;
  1109. // TODO: Prefetch
  1110. // remove dead particles
  1111. Particle* last_part = &part_list_head;
  1112. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1113. {
  1114. part->currentAge += numMSToUpdate;
  1115. if (part->currentAge > part->totalLifetime)
  1116. {
  1117. n_parts--;
  1118. last_part->next = part->next;
  1119. part->next = part_freelist;
  1120. part_freelist = part;
  1121. part = last_part;
  1122. }
  1123. else
  1124. {
  1125. last_part = part;
  1126. }
  1127. }
  1128. AssertFatal( n_parts >= 0, "ParticleEmitter: negative part count!" );
  1129. if (n_parts < 1 && mDeleteWhenEmpty)
  1130. {
  1131. mDeleteOnTick = true;
  1132. return;
  1133. }
  1134. if( numMSToUpdate != 0 && n_parts > 0 )
  1135. {
  1136. update( numMSToUpdate );
  1137. }
  1138. }
  1139. //-----------------------------------------------------------------------------
  1140. // Update key related particle data
  1141. //-----------------------------------------------------------------------------
  1142. void ParticleEmitter::updateKeyData( Particle *part )
  1143. {
  1144. //Ensure that our lifetime is never below 0
  1145. if( part->totalLifetime < 1 )
  1146. part->totalLifetime = 1;
  1147. F32 t = F32(part->currentAge) / F32(part->totalLifetime);
  1148. AssertFatal(t <= 1.0f, "Out out bounds filter function for particle.");
  1149. for( U32 i = 1; i < ParticleData::PDC_NUM_KEYS; i++ )
  1150. {
  1151. if( part->dataBlock->times[i] >= t )
  1152. {
  1153. F32 firstPart = t - part->dataBlock->times[i-1];
  1154. F32 total = part->dataBlock->times[i] -
  1155. part->dataBlock->times[i-1];
  1156. firstPart /= total;
  1157. if( mDataBlock->useEmitterColors )
  1158. {
  1159. part->color.interpolate(colors[i-1], colors[i], firstPart);
  1160. }
  1161. else
  1162. {
  1163. part->color.interpolate(part->dataBlock->colors[i-1],
  1164. part->dataBlock->colors[i],
  1165. firstPart);
  1166. }
  1167. if( mDataBlock->useEmitterSizes )
  1168. {
  1169. part->size = (sizes[i-1] * (1.0 - firstPart)) +
  1170. (sizes[i] * firstPart);
  1171. }
  1172. else
  1173. {
  1174. part->size = (part->dataBlock->sizes[i-1] * (1.0 - firstPart)) +
  1175. (part->dataBlock->sizes[i] * firstPart);
  1176. }
  1177. break;
  1178. }
  1179. }
  1180. }
  1181. //-----------------------------------------------------------------------------
  1182. // Update particles
  1183. //-----------------------------------------------------------------------------
  1184. void ParticleEmitter::update( U32 ms )
  1185. {
  1186. // TODO: Prefetch
  1187. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1188. {
  1189. F32 t = F32(ms) / 1000.0;
  1190. Point3F a = part->acc;
  1191. a -= part->vel * part->dataBlock->dragCoefficient;
  1192. a -= mWindVelocity * part->dataBlock->windCoefficient;
  1193. a += Point3F(0.0f, 0.0f, -9.81f) * part->dataBlock->gravityCoefficient;
  1194. part->vel += a * t;
  1195. part->pos += part->vel * t;
  1196. updateKeyData( part );
  1197. }
  1198. }
  1199. //-----------------------------------------------------------------------------
  1200. // Copy particles to vertex buffer
  1201. //-----------------------------------------------------------------------------
  1202. // structure used for particle sorting.
  1203. struct SortParticle
  1204. {
  1205. Particle* p;
  1206. F32 k;
  1207. };
  1208. // qsort callback function for particle sorting
  1209. int QSORT_CALLBACK cmpSortParticles(const void* p1, const void* p2)
  1210. {
  1211. const SortParticle* sp1 = (const SortParticle*)p1;
  1212. const SortParticle* sp2 = (const SortParticle*)p2;
  1213. if (sp2->k > sp1->k)
  1214. return 1;
  1215. else if (sp2->k == sp1->k)
  1216. return 0;
  1217. else
  1218. return -1;
  1219. }
  1220. void ParticleEmitter::copyToVB( const Point3F &camPos, const ColorF &ambientColor )
  1221. {
  1222. static Vector<SortParticle> orderedVector(__FILE__, __LINE__);
  1223. PROFILE_START(ParticleEmitter_copyToVB);
  1224. PROFILE_START(ParticleEmitter_copyToVB_Sort);
  1225. // build sorted list of particles (far to near)
  1226. if (mDataBlock->sortParticles)
  1227. {
  1228. orderedVector.clear();
  1229. MatrixF modelview = GFX->getWorldMatrix();
  1230. Point3F viewvec; modelview.getRow(1, &viewvec);
  1231. // add each particle and a distance based sort key to orderedVector
  1232. for (Particle* pp = part_list_head.next; pp != NULL; pp = pp->next)
  1233. {
  1234. orderedVector.increment();
  1235. orderedVector.last().p = pp;
  1236. orderedVector.last().k = mDot(pp->pos, viewvec);
  1237. }
  1238. // qsort the list into far to near ordering
  1239. dQsort(orderedVector.address(), orderedVector.size(), sizeof(SortParticle), cmpSortParticles);
  1240. }
  1241. PROFILE_END();
  1242. #if defined(TORQUE_OS_XENON)
  1243. // Allocate writecombined since we don't read back from this buffer (yay!)
  1244. if(mVertBuff.isNull())
  1245. mVertBuff = new GFX360MemVertexBuffer(GFX, 1, getGFXVertexFormat<ParticleVertexType>(), sizeof(ParticleVertexType), GFXBufferTypeDynamic, PAGE_WRITECOMBINE);
  1246. if( n_parts > mCurBuffSize )
  1247. {
  1248. mCurBuffSize = n_parts;
  1249. mVertBuff.resize(n_parts * 4);
  1250. }
  1251. ParticleVertexType *buffPtr = mVertBuff.lock();
  1252. #else
  1253. static Vector<ParticleVertexType> tempBuff(2048);
  1254. tempBuff.reserve( n_parts*4 + 64); // make sure tempBuff is big enough
  1255. ParticleVertexType *buffPtr = tempBuff.address(); // use direct pointer (faster)
  1256. #endif
  1257. if (mDataBlock->orientParticles)
  1258. {
  1259. PROFILE_START(ParticleEmitter_copyToVB_Orient);
  1260. if (mDataBlock->reverseOrder)
  1261. {
  1262. buffPtr += 4*(n_parts-1);
  1263. // do sorted-oriented particles
  1264. if (mDataBlock->sortParticles)
  1265. {
  1266. SortParticle* partPtr = orderedVector.address();
  1267. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr-=4 )
  1268. setupOriented(partPtr->p, camPos, ambientColor, buffPtr);
  1269. }
  1270. // do unsorted-oriented particles
  1271. else
  1272. {
  1273. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1274. setupOriented(partPtr, camPos, ambientColor, buffPtr);
  1275. }
  1276. }
  1277. else
  1278. {
  1279. // do sorted-oriented particles
  1280. if (mDataBlock->sortParticles)
  1281. {
  1282. SortParticle* partPtr = orderedVector.address();
  1283. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr+=4 )
  1284. setupOriented(partPtr->p, camPos, ambientColor, buffPtr);
  1285. }
  1286. // do unsorted-oriented particles
  1287. else
  1288. {
  1289. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1290. setupOriented(partPtr, camPos, ambientColor, buffPtr);
  1291. }
  1292. }
  1293. PROFILE_END();
  1294. }
  1295. else if (mDataBlock->alignParticles)
  1296. {
  1297. PROFILE_START(ParticleEmitter_copyToVB_Aligned);
  1298. if (mDataBlock->reverseOrder)
  1299. {
  1300. buffPtr += 4*(n_parts-1);
  1301. // do sorted-oriented particles
  1302. if (mDataBlock->sortParticles)
  1303. {
  1304. SortParticle* partPtr = orderedVector.address();
  1305. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr-=4 )
  1306. setupAligned(partPtr->p, ambientColor, buffPtr);
  1307. }
  1308. // do unsorted-oriented particles
  1309. else
  1310. {
  1311. Particle *partPtr = part_list_head.next;
  1312. for (; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1313. setupAligned(partPtr, ambientColor, buffPtr);
  1314. }
  1315. }
  1316. else
  1317. {
  1318. // do sorted-oriented particles
  1319. if (mDataBlock->sortParticles)
  1320. {
  1321. SortParticle* partPtr = orderedVector.address();
  1322. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr+=4 )
  1323. setupAligned(partPtr->p, ambientColor, buffPtr);
  1324. }
  1325. // do unsorted-oriented particles
  1326. else
  1327. {
  1328. Particle *partPtr = part_list_head.next;
  1329. for (; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1330. setupAligned(partPtr, ambientColor, buffPtr);
  1331. }
  1332. }
  1333. PROFILE_END();
  1334. }
  1335. else
  1336. {
  1337. PROFILE_START(ParticleEmitter_copyToVB_NonOriented);
  1338. // somewhat odd ordering so that texture coordinates match the oriented
  1339. // particles
  1340. Point3F basePoints[4];
  1341. basePoints[0] = Point3F(-1.0, 0.0, 1.0);
  1342. basePoints[1] = Point3F(-1.0, 0.0, -1.0);
  1343. basePoints[2] = Point3F( 1.0, 0.0, -1.0);
  1344. basePoints[3] = Point3F( 1.0, 0.0, 1.0);
  1345. MatrixF camView = GFX->getWorldMatrix();
  1346. camView.transpose(); // inverse - this gets the particles facing camera
  1347. if (mDataBlock->reverseOrder)
  1348. {
  1349. buffPtr += 4*(n_parts-1);
  1350. // do sorted-billboard particles
  1351. if (mDataBlock->sortParticles)
  1352. {
  1353. SortParticle *partPtr = orderedVector.address();
  1354. for( U32 i=0; i<n_parts; i++, partPtr++, buffPtr-=4 )
  1355. setupBillboard( partPtr->p, basePoints, camView, ambientColor, buffPtr );
  1356. }
  1357. // do unsorted-billboard particles
  1358. else
  1359. {
  1360. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1361. setupBillboard( partPtr, basePoints, camView, ambientColor, buffPtr );
  1362. }
  1363. }
  1364. else
  1365. {
  1366. // do sorted-billboard particles
  1367. if (mDataBlock->sortParticles)
  1368. {
  1369. SortParticle *partPtr = orderedVector.address();
  1370. for( U32 i=0; i<n_parts; i++, partPtr++, buffPtr+=4 )
  1371. setupBillboard( partPtr->p, basePoints, camView, ambientColor, buffPtr );
  1372. }
  1373. // do unsorted-billboard particles
  1374. else
  1375. {
  1376. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1377. setupBillboard( partPtr, basePoints, camView, ambientColor, buffPtr );
  1378. }
  1379. }
  1380. PROFILE_END();
  1381. }
  1382. #if defined(TORQUE_OS_XENON)
  1383. mVertBuff.unlock();
  1384. #else
  1385. PROFILE_START(ParticleEmitter_copyToVB_LockCopy);
  1386. // create new VB if emitter size grows
  1387. if( !mVertBuff || n_parts > mCurBuffSize )
  1388. {
  1389. mCurBuffSize = n_parts;
  1390. mVertBuff.set( GFX, n_parts * 4, GFXBufferTypeDynamic );
  1391. }
  1392. // lock and copy tempBuff to video RAM
  1393. ParticleVertexType *verts = mVertBuff.lock();
  1394. dMemcpy( verts, tempBuff.address(), n_parts * 4 * sizeof(ParticleVertexType) );
  1395. mVertBuff.unlock();
  1396. PROFILE_END();
  1397. #endif
  1398. PROFILE_END();
  1399. }
  1400. //-----------------------------------------------------------------------------
  1401. // Set up particle for billboard style render
  1402. //-----------------------------------------------------------------------------
  1403. void ParticleEmitter::setupBillboard( Particle *part,
  1404. Point3F *basePts,
  1405. const MatrixF &camView,
  1406. const ColorF &ambientColor,
  1407. ParticleVertexType *lVerts )
  1408. {
  1409. F32 width = part->size * 0.5f;
  1410. F32 spinAngle = part->spinSpeed * part->currentAge * AgedSpinToRadians;
  1411. F32 sy, cy;
  1412. mSinCos(spinAngle, sy, cy);
  1413. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1414. ColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1415. // fill four verts, use macro and unroll loop
  1416. #define fillVert(){ \
  1417. lVerts->point.x = cy * basePts->x - sy * basePts->z; \
  1418. lVerts->point.y = 0.0f; \
  1419. lVerts->point.z = sy * basePts->x + cy * basePts->z; \
  1420. camView.mulV( lVerts->point ); \
  1421. lVerts->point *= width; \
  1422. lVerts->point += part->pos; \
  1423. lVerts->color = partCol; } \
  1424. // Here we deal with UVs for animated particle (billboard)
  1425. if (part->dataBlock->animateTexture)
  1426. {
  1427. S32 fm = (S32)(part->currentAge*(1.0/1000.0)*part->dataBlock->framesPerSec);
  1428. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1429. S32 uv[4];
  1430. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1431. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1432. uv[2] = uv[1] + 1;
  1433. uv[3] = uv[0] + 1;
  1434. fillVert();
  1435. // Here and below, we copy UVs from particle datablock's current frame's UVs (billboard)
  1436. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1437. ++lVerts;
  1438. ++basePts;
  1439. fillVert();
  1440. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1441. ++lVerts;
  1442. ++basePts;
  1443. fillVert();
  1444. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  1445. ++lVerts;
  1446. ++basePts;
  1447. fillVert();
  1448. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  1449. ++lVerts;
  1450. ++basePts;
  1451. return;
  1452. }
  1453. fillVert();
  1454. // Here and below, we copy UVs from particle datablock's texCoords (billboard)
  1455. lVerts->texCoord = part->dataBlock->texCoords[0];
  1456. ++lVerts;
  1457. ++basePts;
  1458. fillVert();
  1459. lVerts->texCoord = part->dataBlock->texCoords[1];
  1460. ++lVerts;
  1461. ++basePts;
  1462. fillVert();
  1463. lVerts->texCoord = part->dataBlock->texCoords[2];
  1464. ++lVerts;
  1465. ++basePts;
  1466. fillVert();
  1467. lVerts->texCoord = part->dataBlock->texCoords[3];
  1468. ++lVerts;
  1469. ++basePts;
  1470. }
  1471. //-----------------------------------------------------------------------------
  1472. // Set up oriented particle
  1473. //-----------------------------------------------------------------------------
  1474. void ParticleEmitter::setupOriented( Particle *part,
  1475. const Point3F &camPos,
  1476. const ColorF &ambientColor,
  1477. ParticleVertexType *lVerts )
  1478. {
  1479. Point3F dir;
  1480. if( mDataBlock->orientOnVelocity )
  1481. {
  1482. // don't render oriented particle if it has no velocity
  1483. if( part->vel.magnitudeSafe() == 0.0 ) return;
  1484. dir = part->vel;
  1485. }
  1486. else
  1487. {
  1488. dir = part->orientDir;
  1489. }
  1490. Point3F dirFromCam = part->pos - camPos;
  1491. Point3F crossDir;
  1492. mCross( dirFromCam, dir, &crossDir );
  1493. crossDir.normalize();
  1494. dir.normalize();
  1495. F32 width = part->size * 0.5f;
  1496. dir *= width;
  1497. crossDir *= width;
  1498. Point3F start = part->pos - dir;
  1499. Point3F end = part->pos + dir;
  1500. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1501. ColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1502. // Here we deal with UVs for animated particle (oriented)
  1503. if (part->dataBlock->animateTexture)
  1504. {
  1505. // Let particle compute the UV indices for current frame
  1506. S32 fm = (S32)(part->currentAge*(1.0f/1000.0f)*part->dataBlock->framesPerSec);
  1507. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1508. S32 uv[4];
  1509. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1510. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1511. uv[2] = uv[1] + 1;
  1512. uv[3] = uv[0] + 1;
  1513. lVerts->point = start + crossDir;
  1514. lVerts->color = partCol;
  1515. // Here and below, we copy UVs from particle datablock's current frame's UVs (oriented)
  1516. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1517. ++lVerts;
  1518. lVerts->point = start - crossDir;
  1519. lVerts->color = partCol;
  1520. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1521. ++lVerts;
  1522. lVerts->point = end - crossDir;
  1523. lVerts->color = partCol;
  1524. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  1525. ++lVerts;
  1526. lVerts->point = end + crossDir;
  1527. lVerts->color = partCol;
  1528. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  1529. ++lVerts;
  1530. return;
  1531. }
  1532. lVerts->point = start + crossDir;
  1533. lVerts->color = partCol;
  1534. // Here and below, we copy UVs from particle datablock's texCoords (oriented)
  1535. lVerts->texCoord = part->dataBlock->texCoords[0];
  1536. ++lVerts;
  1537. lVerts->point = start - crossDir;
  1538. lVerts->color = partCol;
  1539. lVerts->texCoord = part->dataBlock->texCoords[1];
  1540. ++lVerts;
  1541. lVerts->point = end - crossDir;
  1542. lVerts->color = partCol;
  1543. lVerts->texCoord = part->dataBlock->texCoords[2];
  1544. ++lVerts;
  1545. lVerts->point = end + crossDir;
  1546. lVerts->color = partCol;
  1547. lVerts->texCoord = part->dataBlock->texCoords[3];
  1548. ++lVerts;
  1549. }
  1550. void ParticleEmitter::setupAligned( const Particle *part,
  1551. const ColorF &ambientColor,
  1552. ParticleVertexType *lVerts )
  1553. {
  1554. // The aligned direction will always be normalized.
  1555. Point3F dir = mDataBlock->alignDirection;
  1556. // Find a right vector for this particle.
  1557. Point3F right;
  1558. if (mFabs(dir.y) > mFabs(dir.z))
  1559. mCross(Point3F::UnitZ, dir, &right);
  1560. else
  1561. mCross(Point3F::UnitY, dir, &right);
  1562. right.normalize();
  1563. // If we have a spin velocity.
  1564. if ( !mIsZero( part->spinSpeed ) )
  1565. {
  1566. F32 spinAngle = part->spinSpeed * part->currentAge * AgedSpinToRadians;
  1567. // This is an inline quaternion vector rotation which
  1568. // is faster that QuatF.mulP(), but generates different
  1569. // results and hence cannot replace it right now.
  1570. F32 sin, qw;
  1571. mSinCos( spinAngle * 0.5f, sin, qw );
  1572. F32 qx = dir.x * sin;
  1573. F32 qy = dir.y * sin;
  1574. F32 qz = dir.z * sin;
  1575. F32 vx = ( right.x * qw ) + ( right.z * qy ) - ( right.y * qz );
  1576. F32 vy = ( right.y * qw ) + ( right.x * qz ) - ( right.z * qx );
  1577. F32 vz = ( right.z * qw ) + ( right.y * qx ) - ( right.x * qy );
  1578. F32 vw = ( right.x * qx ) + ( right.y * qy ) + ( right.z * qz );
  1579. right.x = ( qw * vx ) + ( qx * vw ) + ( qy * vz ) - ( qz * vy );
  1580. right.y = ( qw * vy ) + ( qy * vw ) + ( qz * vx ) - ( qx * vz );
  1581. right.z = ( qw * vz ) + ( qz * vw ) + ( qx * vy ) - ( qy * vx );
  1582. }
  1583. // Get the cross vector.
  1584. Point3F cross;
  1585. mCross(right, dir, &cross);
  1586. F32 width = part->size * 0.5f;
  1587. right *= width;
  1588. cross *= width;
  1589. Point3F start = part->pos - right;
  1590. Point3F end = part->pos + right;
  1591. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1592. ColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1593. // Here we deal with UVs for animated particle
  1594. if (part->dataBlock->animateTexture)
  1595. {
  1596. // Let particle compute the UV indices for current frame
  1597. S32 fm = (S32)(part->currentAge*(1.0f/1000.0f)*part->dataBlock->framesPerSec);
  1598. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1599. S32 uv[4];
  1600. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1601. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1602. uv[2] = uv[1] + 1;
  1603. uv[3] = uv[0] + 1;
  1604. lVerts->point = start + cross;
  1605. lVerts->color = partCol;
  1606. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1607. ++lVerts;
  1608. lVerts->point = start - cross;
  1609. lVerts->color = partCol;
  1610. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1611. ++lVerts;
  1612. lVerts->point = end - cross;
  1613. lVerts->color = partCol;
  1614. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  1615. ++lVerts;
  1616. lVerts->point = end + cross;
  1617. lVerts->color = partCol;
  1618. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  1619. ++lVerts;
  1620. }
  1621. else
  1622. {
  1623. // Here and below, we copy UVs from particle datablock's texCoords
  1624. lVerts->point = start + cross;
  1625. lVerts->color = partCol;
  1626. lVerts->texCoord = part->dataBlock->texCoords[0];
  1627. ++lVerts;
  1628. lVerts->point = start - cross;
  1629. lVerts->color = partCol;
  1630. lVerts->texCoord = part->dataBlock->texCoords[1];
  1631. ++lVerts;
  1632. lVerts->point = end - cross;
  1633. lVerts->color = partCol;
  1634. lVerts->texCoord = part->dataBlock->texCoords[2];
  1635. ++lVerts;
  1636. lVerts->point = end + cross;
  1637. lVerts->color = partCol;
  1638. lVerts->texCoord = part->dataBlock->texCoords[3];
  1639. ++lVerts;
  1640. }
  1641. }
  1642. bool ParticleEmitterData::reload()
  1643. {
  1644. // Clear out current particle data.
  1645. dataBlockIds.clear();
  1646. particleDataBlocks.clear();
  1647. // Parse out particle string.
  1648. U32 numUnits = 0;
  1649. if( particleString )
  1650. numUnits = StringUnit::getUnitCount( particleString, " \t" );
  1651. if( !particleString || !particleString[ 0 ] || !numUnits )
  1652. {
  1653. Con::errorf( "ParticleEmitterData(%s) has an empty particles string.", getName() );
  1654. mReloadSignal.trigger();
  1655. return false;
  1656. }
  1657. for( U32 i = 0; i < numUnits; ++ i )
  1658. {
  1659. const char* dbName = StringUnit::getUnit( particleString, i, " \t" );
  1660. ParticleData* data = NULL;
  1661. if( !Sim::findObject( dbName, data ) )
  1662. {
  1663. Con::errorf( ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find particle datablock: %s", getName(), dbName );
  1664. continue;
  1665. }
  1666. particleDataBlocks.push_back( data );
  1667. dataBlockIds.push_back( data->getId() );
  1668. }
  1669. // Check that we actually found some particle datablocks.
  1670. if( particleDataBlocks.empty() )
  1671. {
  1672. Con::errorf( ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find any particle datablocks", getName() );
  1673. mReloadSignal.trigger();
  1674. return false;
  1675. }
  1676. // Trigger reload.
  1677. mReloadSignal.trigger();
  1678. return true;
  1679. }
  1680. DefineEngineMethod(ParticleEmitterData, reload, void,(),,
  1681. "Reloads the ParticleData datablocks and other fields used by this emitter.\n"
  1682. "@tsexample\n"
  1683. "// Get the editor's current particle emitter\n"
  1684. "%emitter = PE_EmitterEditor.currEmitter\n\n"
  1685. "// Change a field value\n"
  1686. "%emitter.setFieldValue( %propertyField, %value );\n\n"
  1687. "// Reload this emitter\n"
  1688. "%emitter.reload();\n"
  1689. "@endtsexample\n")
  1690. {
  1691. object->reload();
  1692. }