particleEmitter.cpp 68 KB

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