particleEmitter.cpp 67 KB

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