particleEmitter.cpp 67 KB

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