particleEmitter.cpp 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "T3D/fx/particleEmitter.h"
  28. #include "scene/sceneManager.h"
  29. #include "scene/sceneRenderState.h"
  30. #include "console/consoleTypes.h"
  31. #include "console/typeValidators.h"
  32. #include "core/stream/bitStream.h"
  33. #include "core/strings/stringUnit.h"
  34. #include "math/mRandom.h"
  35. #include "gfx/gfxDevice.h"
  36. #include "gfx/primBuilder.h"
  37. #include "gfx/gfxStringEnumTranslate.h"
  38. #include "renderInstance/renderPassManager.h"
  39. #include "T3D/gameBase/gameProcess.h"
  40. #include "lighting/lightInfo.h"
  41. #include "console/engineAPI.h"
  42. #if defined(AFX_CAP_PARTICLE_POOLS)
  43. #include "afx/util/afxParticlePool.h"
  44. #endif
  45. Point3F ParticleEmitter::mWindVelocity( 0.0, 0.0, 0.0 );
  46. const F32 ParticleEmitter::AgedSpinToRadians = (1.0f/1000.0f) * (1.0f/360.0f) * M_PI_F * 2.0f;
  47. IMPLEMENT_CO_DATABLOCK_V1(ParticleEmitterData);
  48. IMPLEMENT_CONOBJECT(ParticleEmitter);
  49. ConsoleDocClass( ParticleEmitter,
  50. "@brief This object is responsible for spawning particles.\n\n"
  51. "@note This class is not normally instantiated directly - to place a simple "
  52. "particle emitting object in the scene, use a ParticleEmitterNode instead.\n\n"
  53. "This class is the main interface for creating particles - though it is "
  54. "usually only accessed from within another object like ParticleEmitterNode "
  55. "or WheeledVehicle. If using this object class (via C++) directly, be aware "
  56. "that it does <b>not</b> track changes in source axis or velocity over the "
  57. "course of a single update, so emitParticles should be called at a fairly "
  58. "fine grain. The emitter will potentially track the last particle to be "
  59. "created into the next call to this function in order to create a uniformly "
  60. "random time distribution of the particles.\n\n"
  61. "If the object to which the emitter is attached is in motion, it should try "
  62. "to ensure that for call (n+1) to this function, start is equal to the end "
  63. "from call (n). This will ensure a uniform spatial distribution.\n\n"
  64. "@ingroup FX\n"
  65. "@see ParticleEmitterData\n"
  66. "@see ParticleEmitterNode\n"
  67. );
  68. ConsoleDocClass( ParticleEmitterData,
  69. "@brief Defines particle emission properties such as ejection angle, period "
  70. "and velocity for a ParticleEmitter.\n\n"
  71. "@tsexample\n"
  72. "datablock ParticleEmitterData( GrenadeExpDustEmitter )\n"
  73. "{\n"
  74. " ejectionPeriodMS = 1;\n"
  75. " periodVarianceMS = 0;\n"
  76. " ejectionVelocity = 15;\n"
  77. " velocityVariance = 0.0;\n"
  78. " ejectionOffset = 0.0;\n"
  79. " thetaMin = 85;\n"
  80. " thetaMax = 85;\n"
  81. " thetaVariance = 0;\n"
  82. " phiReferenceVel = 0;\n"
  83. " phiVariance = 360;\n"
  84. " overrideAdvance = false;\n"
  85. " lifetimeMS = 200;\n"
  86. " particles = \"GrenadeExpDust\";\n"
  87. "};\n"
  88. "@endtsexample\n\n"
  89. "@ingroup FX\n"
  90. "@see ParticleEmitter\n"
  91. "@see ParticleData\n"
  92. "@see ParticleEmitterNode\n"
  93. );
  94. static const F32 sgDefaultEjectionOffset = 0.f;
  95. static const F32 sgDefaultPhiReferenceVel = 0.f;
  96. static const F32 sgDefaultPhiVariance = 360.f;
  97. //-----------------------------------------------------------------------------
  98. // ParticleEmitterData
  99. //-----------------------------------------------------------------------------
  100. ParticleEmitterData::ParticleEmitterData()
  101. {
  102. VECTOR_SET_ASSOCIATION(particleDataBlocks);
  103. VECTOR_SET_ASSOCIATION(dataBlockIds);
  104. ejectionPeriodMS = 100; // 10 Particles Per second
  105. periodVarianceMS = 0; // exactly
  106. ejectionVelocity = 2.0f; // From 1.0 - 3.0 meters per sec
  107. velocityVariance = 1.0f;
  108. ejectionOffset = sgDefaultEjectionOffset; // ejection from the emitter point
  109. ejectionOffsetVariance = 0.0f;
  110. thetaMin = 0.0f; // All heights
  111. thetaMax = 90.0f;
  112. thetaVariance = 0.0f;
  113. phiReferenceVel = sgDefaultPhiReferenceVel; // All directions
  114. phiVariance = sgDefaultPhiVariance;
  115. softnessDistance = 1.0f;
  116. ambientFactor = 0.0f;
  117. lifetimeMS = 0;
  118. lifetimeVarianceMS = 0;
  119. overrideAdvance = true;
  120. orientParticles = false;
  121. orientOnVelocity = true;
  122. ribbonParticles = false;
  123. useEmitterSizes = false;
  124. useEmitterColors = false;
  125. particleString = NULL;
  126. partListInitSize = 0;
  127. // These members added for support of user defined blend factors
  128. // and optional particle sorting.
  129. blendStyle = ParticleRenderInst::BlendUndefined;
  130. sortParticles = false;
  131. renderReflection = true;
  132. glow = false;
  133. reverseOrder = false;
  134. textureName = 0;
  135. textureHandle = 0;
  136. highResOnly = true;
  137. alignParticles = false;
  138. alignDirection = Point3F(0.0f, 1.0f, 0.0f);
  139. ejectionInvert = false;
  140. fade_color = false;
  141. fade_alpha = false;
  142. fade_size = false;
  143. parts_per_eject = 1;
  144. use_emitter_xfm = false;
  145. #if defined(AFX_CAP_PARTICLE_POOLS)
  146. pool_datablock = 0;
  147. pool_index = 0;
  148. pool_depth_fade = false;
  149. pool_radial_fade = false;
  150. do_pool_id_convert = false;
  151. #endif
  152. }
  153. // Enum tables used for fields blendStyle, srcBlendFactor, dstBlendFactor.
  154. // Note that the enums for srcBlendFactor and dstBlendFactor are consistent
  155. // with the blending enums used in Torque Game Builder.
  156. typedef ParticleRenderInst::BlendStyle ParticleBlendStyle;
  157. DefineEnumType( ParticleBlendStyle );
  158. ImplementEnumType( ParticleBlendStyle,
  159. "The type of visual blending style to apply to the particles.\n"
  160. "@ingroup FX\n\n")
  161. { ParticleRenderInst::BlendNormal, "NORMAL", "No blending style.\n" },
  162. { ParticleRenderInst::BlendAdditive, "ADDITIVE", "Adds the color of the pixel to the frame buffer with full alpha for each pixel.\n" },
  163. { ParticleRenderInst::BlendSubtractive, "SUBTRACTIVE", "Subtractive Blending. Reverses the color model, causing dark colors to have a stronger visual effect.\n" },
  164. { ParticleRenderInst::BlendPremultAlpha, "PREMULTALPHA", "Color blends with the colors of the imagemap rather than the alpha.\n" },
  165. EndImplementEnumType;
  166. IRangeValidator ejectPeriodIValidator(1, 2047);
  167. IRangeValidator periodVarianceIValidator(0, 2047);
  168. FRangeValidator ejectionFValidator(0.f, 655.35f);
  169. FRangeValidator velVarianceFValidator(0.f, 163.83f);
  170. //-----------------------------------------------------------------------------
  171. // initPersistFields
  172. //-----------------------------------------------------------------------------
  173. void ParticleEmitterData::initPersistFields()
  174. {
  175. docsURL;
  176. addGroup( "ParticleEmitterData" );
  177. addFieldV("ejectionPeriodMS", TypeRangedS32, Offset(ejectionPeriodMS, ParticleEmitterData), &ejectPeriodIValidator,
  178. "Time (in milliseconds) between each particle ejection." );
  179. addFieldV("periodVarianceMS", TypeRangedS32, Offset(periodVarianceMS, ParticleEmitterData), &periodVarianceIValidator,
  180. "Variance in ejection period, from 1 - ejectionPeriodMS." );
  181. addFieldV( "ejectionVelocity", TypeRangedF32, Offset(ejectionVelocity, ParticleEmitterData), &ejectionFValidator,
  182. "Particle ejection velocity." );
  183. addFieldV( "velocityVariance", TypeRangedF32, Offset(velocityVariance, ParticleEmitterData), &velVarianceFValidator,
  184. "Variance for ejection velocity, from 0 - ejectionVelocity." );
  185. addFieldV( "ejectionOffset", TypeRangedF32, Offset(ejectionOffset, ParticleEmitterData), &ejectionFValidator,
  186. "Distance along ejection Z axis from which to eject particles." );
  187. addFieldV( "ejectionOffsetVariance", TypeRangedF32, Offset(ejectionOffsetVariance, ParticleEmitterData), &ejectionFValidator,
  188. "Distance Padding along ejection Z axis from which to eject particles." );
  189. addFieldV( "thetaMin", TypeRangedF32, Offset(thetaMin, ParticleEmitterData), &CommonValidators::PosDegreeRangeHalf,
  190. "Minimum angle, from the horizontal plane, to eject from." );
  191. addFieldV( "thetaMax", TypeRangedF32, Offset(thetaMax, ParticleEmitterData), &CommonValidators::PosDegreeRangeHalf,
  192. "Maximum angle, from the horizontal plane, to eject particles from." );
  193. addFieldV( "thetaVariance", TypeRangedF32, Offset(thetaVariance, ParticleEmitterData), &CommonValidators::PosDegreeRangeHalf,
  194. "Angle variance from the previous particle, from 0 - 180." );
  195. addFieldV( "phiReferenceVel", TypeRangedF32, Offset(phiReferenceVel, ParticleEmitterData), &CommonValidators::PosDegreeRange,
  196. "Reference angle, from the vertical plane, to eject particles from." );
  197. addFieldV( "phiVariance", TypeRangedF32, Offset(phiVariance, ParticleEmitterData), &CommonValidators::PosDegreeRange,
  198. "Variance from the reference angle, from 0 - 360." );
  199. addFieldV( "softnessDistance", TypeRangedF32, Offset(softnessDistance, ParticleEmitterData), &CommonValidators::PositiveFloat,
  200. "For soft particles, the distance (in meters) where particles will be "
  201. "faded based on the difference in depth between the particle and the "
  202. "scene geometry." );
  203. addFieldV( "ambientFactor", TypeRangedF32, Offset(ambientFactor, ParticleEmitterData), &CommonValidators::NormalizedFloat,
  204. "Used to generate the final particle color by controlling interpolation "
  205. "between the particle color and the particle color multiplied by the "
  206. "ambient light color." );
  207. addField( "overrideAdvance", TYPEID< bool >(), Offset(overrideAdvance, ParticleEmitterData),
  208. "If false, particles emitted in the same frame have their positions "
  209. "adjusted. If true, adjustment is skipped and particles will clump "
  210. "together." );
  211. addField( "orientParticles", TYPEID< bool >(), Offset(orientParticles, ParticleEmitterData),
  212. "If true, Particles will always face the camera." );
  213. addField( "orientOnVelocity", TYPEID< bool >(), Offset(orientOnVelocity, ParticleEmitterData),
  214. "If true, particles will be oriented to face in the direction they are moving." );
  215. addField( "ribbonParticles", TYPEID< bool >(), Offset(ribbonParticles, ParticleEmitterData),
  216. "If true, particles are rendered as a continous ribbon." );
  217. addField( "particles", TYPEID< StringTableEntry >(), Offset(particleString, ParticleEmitterData),
  218. "@brief List of space or TAB delimited ParticleData datablock names.\n\n"
  219. "A random one of these datablocks is selected each time a particle is "
  220. "emitted." );
  221. addFieldV( "lifetimeMS", TypeRangedS32, Offset(lifetimeMS, ParticleEmitterData), &CommonValidators::PositiveInt,
  222. "Lifetime of emitted particles (in milliseconds)." );
  223. addFieldV("lifetimeVarianceMS", TypeRangedS32, Offset(lifetimeVarianceMS, ParticleEmitterData), &CommonValidators::PositiveInt,
  224. "Variance in particle lifetime from 0 - lifetimeMS." );
  225. addField( "useEmitterSizes", TYPEID< bool >(), Offset(useEmitterSizes, ParticleEmitterData),
  226. "@brief If true, use emitter specified sizes instead of datablock sizes.\n"
  227. "Useful for Debris particle emitters that control the particle size." );
  228. addField( "useEmitterColors", TYPEID< bool >(), Offset(useEmitterColors, ParticleEmitterData),
  229. "@brief If true, use emitter specified colors instead of datablock colors.\n\n"
  230. "Useful for ShapeBase dust and WheeledVehicle wheel particle emitters that use "
  231. "the current material to control particle color." );
  232. /// These fields added for support of user defined blend factors and optional particle sorting.
  233. //@{
  234. addField( "blendStyle", TYPEID< ParticleRenderInst::BlendStyle >(), Offset(blendStyle, ParticleEmitterData),
  235. "String value that controls how emitted particles blend with the scene." );
  236. addField( "sortParticles", TYPEID< bool >(), Offset(sortParticles, ParticleEmitterData),
  237. "If true, particles are sorted furthest to nearest.");
  238. addField( "reverseOrder", TYPEID< bool >(), Offset(reverseOrder, ParticleEmitterData),
  239. "@brief If true, reverses the normal draw order of particles.\n\n"
  240. "Particles are normally drawn from newest to oldest, or in Z order "
  241. "(furthest first) if sortParticles is true. Setting this field to "
  242. "true will reverse that order: oldest first, or nearest first if "
  243. "sortParticles is true." );
  244. addField( "textureName", TYPEID< StringTableEntry >(), Offset(textureName, ParticleEmitterData),
  245. "Optional texture to override ParticleData::textureName." );
  246. addField( "alignParticles", TYPEID< bool >(), Offset(alignParticles, ParticleEmitterData),
  247. "If true, particles always face along the axis defined by alignDirection." );
  248. addProtectedField( "alignDirection", TYPEID< Point3F>(), Offset(alignDirection, ParticleEmitterData), &ParticleEmitterData::_setAlignDirection, &defaultProtectedGetFn,
  249. "The direction aligned particles should face, only valid if alignParticles is true." );
  250. addField( "highResOnly", TYPEID< bool >(), Offset(highResOnly, ParticleEmitterData),
  251. "This particle system should not use the mixed-resolution renderer. "
  252. "If your particle system has large amounts of overdraw, consider "
  253. "disabling this option." );
  254. addField( "renderReflection", TYPEID< bool >(), Offset(renderReflection, ParticleEmitterData),
  255. "Controls whether particles are rendered onto reflective surfaces like water." );
  256. addField("glow", TYPEID< bool >(), Offset(glow, ParticleEmitterData),
  257. "If true, the particles are rendered to the glow buffer as well.");
  258. //@}
  259. endGroup( "ParticleEmitterData" );
  260. addGroup("AFX");
  261. addField("ejectionInvert", TypeBool, Offset(ejectionInvert, ParticleEmitterData));
  262. addField("fadeColor", TypeBool, Offset(fade_color, ParticleEmitterData));
  263. addField("fadeAlpha", TypeBool, Offset(fade_alpha, ParticleEmitterData));
  264. addField("fadeSize", TypeBool, Offset(fade_size, ParticleEmitterData));
  265. // useEmitterTransform currently does not work in TGEA or T3D
  266. addField("useEmitterTransform", TypeBool, Offset(use_emitter_xfm, ParticleEmitterData));
  267. endGroup("AFX");
  268. #if defined(AFX_CAP_PARTICLE_POOLS)
  269. addGroup("AFX Pooled Particles");
  270. addField("poolData", TYPEID<afxParticlePoolData>(), Offset(pool_datablock, ParticleEmitterData));
  271. addFieldV("poolIndex", TypeRangedS32, Offset(pool_index, ParticleEmitterData), &CommonValidators::PositiveInt);
  272. addField("poolDepthFade", TypeBool, Offset(pool_depth_fade, ParticleEmitterData));
  273. addField("poolRadialFade", TypeBool, Offset(pool_radial_fade, ParticleEmitterData));
  274. endGroup("AFX Pooled Particles");
  275. #endif
  276. // disallow some field substitutions
  277. disableFieldSubstitutions("particles");
  278. onlyKeepClearSubstitutions("poolData"); // subs resolving to "~~", or "~0" are OK
  279. Parent::initPersistFields();
  280. }
  281. bool ParticleEmitterData::_setAlignDirection( void *object, const char *index, const char *data )
  282. {
  283. ParticleEmitterData *p = static_cast<ParticleEmitterData*>( object );
  284. Con::setData( TypePoint3F, &p->alignDirection, 0, 1, &data );
  285. p->alignDirection.normalizeSafe();
  286. // we already set the field
  287. return false;
  288. }
  289. //-----------------------------------------------------------------------------
  290. // packData
  291. //-----------------------------------------------------------------------------
  292. void ParticleEmitterData::packData(BitStream* stream)
  293. {
  294. Parent::packData(stream);
  295. stream->writeInt(ejectionPeriodMS, 11); // must match limit on valid range in ParticleEmitterData::initPersistFields
  296. stream->writeInt(periodVarianceMS, 11);
  297. stream->writeInt((S32)(ejectionVelocity * 100), 16);
  298. stream->writeInt((S32)(velocityVariance * 100), 14);
  299. if( stream->writeFlag( ejectionOffset != sgDefaultEjectionOffset ) )
  300. stream->writeInt((S32)(ejectionOffset * 100), 16);
  301. if( stream->writeFlag( ejectionOffsetVariance != 0.0f ) )
  302. stream->writeInt((S32)(ejectionOffsetVariance * 100), 16);
  303. stream->writeRangedU32((U32)thetaMin, 0, 180);
  304. stream->writeRangedU32((U32)thetaMax, 0, 180);
  305. stream->writeRangedU32((U32)thetaVariance, 0, 180);
  306. if( stream->writeFlag( phiReferenceVel != sgDefaultPhiReferenceVel ) )
  307. stream->writeRangedU32((U32)phiReferenceVel, 0, 360);
  308. if( stream->writeFlag( phiVariance != sgDefaultPhiVariance ) )
  309. stream->writeRangedU32((U32)phiVariance, 0, 360);
  310. stream->write( softnessDistance );
  311. stream->write( ambientFactor );
  312. stream->writeFlag(overrideAdvance);
  313. stream->writeFlag(orientParticles);
  314. stream->writeFlag(orientOnVelocity);
  315. stream->writeFlag(ribbonParticles);
  316. stream->write( lifetimeMS );
  317. stream->write( lifetimeVarianceMS );
  318. stream->writeFlag(useEmitterSizes);
  319. stream->writeFlag(useEmitterColors);
  320. stream->write(dataBlockIds.size());
  321. for (U32 i = 0; i < dataBlockIds.size(); i++)
  322. stream->write(dataBlockIds[i]);
  323. stream->writeFlag(sortParticles);
  324. stream->writeFlag(reverseOrder);
  325. if (stream->writeFlag(textureName != 0))
  326. stream->writeString(textureName);
  327. if (stream->writeFlag(alignParticles))
  328. {
  329. stream->write(alignDirection.x);
  330. stream->write(alignDirection.y);
  331. stream->write(alignDirection.z);
  332. }
  333. stream->writeFlag(highResOnly);
  334. stream->writeFlag(renderReflection);
  335. stream->writeFlag(glow);
  336. stream->writeInt( blendStyle, 4 );
  337. stream->writeFlag(ejectionInvert);
  338. stream->writeFlag(fade_color);
  339. stream->writeFlag(fade_alpha);
  340. stream->writeFlag(fade_size);
  341. stream->writeFlag(use_emitter_xfm);
  342. #if defined(AFX_CAP_PARTICLE_POOLS)
  343. if (stream->writeFlag(pool_datablock))
  344. {
  345. stream->writeRangedU32(mPacked ? SimObjectId((uintptr_t)pool_datablock) : pool_datablock->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast);
  346. stream->write(pool_index);
  347. stream->writeFlag(pool_depth_fade);
  348. stream->writeFlag(pool_radial_fade);
  349. }
  350. #endif
  351. }
  352. //-----------------------------------------------------------------------------
  353. // unpackData
  354. //-----------------------------------------------------------------------------
  355. void ParticleEmitterData::unpackData(BitStream* stream)
  356. {
  357. Parent::unpackData(stream);
  358. ejectionPeriodMS = stream->readInt(11);
  359. periodVarianceMS = stream->readInt(11);
  360. ejectionVelocity = stream->readInt(16) / 100.0f;
  361. velocityVariance = stream->readInt(14) / 100.0f;
  362. if( stream->readFlag() )
  363. ejectionOffset = stream->readInt(16) / 100.0f;
  364. else
  365. ejectionOffset = sgDefaultEjectionOffset;
  366. if( stream->readFlag() )
  367. ejectionOffsetVariance = stream->readInt(16) / 100.0f;
  368. else
  369. ejectionOffsetVariance = 0.0f;
  370. thetaMin = (F32)stream->readRangedU32(0, 180);
  371. thetaMax = (F32)stream->readRangedU32(0, 180);
  372. thetaVariance = (F32)stream->readRangedU32(0, 180);
  373. if( stream->readFlag() )
  374. phiReferenceVel = (F32)stream->readRangedU32(0, 360);
  375. else
  376. phiReferenceVel = sgDefaultPhiReferenceVel;
  377. if( stream->readFlag() )
  378. phiVariance = (F32)stream->readRangedU32(0, 360);
  379. else
  380. phiVariance = sgDefaultPhiVariance;
  381. stream->read( &softnessDistance );
  382. stream->read( &ambientFactor );
  383. overrideAdvance = stream->readFlag();
  384. orientParticles = stream->readFlag();
  385. orientOnVelocity = stream->readFlag();
  386. ribbonParticles = stream->readFlag();
  387. stream->read( &lifetimeMS );
  388. stream->read( &lifetimeVarianceMS );
  389. useEmitterSizes = stream->readFlag();
  390. useEmitterColors = stream->readFlag();
  391. U32 size; stream->read(&size);
  392. dataBlockIds.setSize(size);
  393. for (U32 i = 0; i < dataBlockIds.size(); i++)
  394. stream->read(&dataBlockIds[i]);
  395. sortParticles = stream->readFlag();
  396. reverseOrder = stream->readFlag();
  397. textureName = (stream->readFlag()) ? stream->readSTString() : 0;
  398. alignParticles = stream->readFlag();
  399. if (alignParticles)
  400. {
  401. stream->read(&alignDirection.x);
  402. stream->read(&alignDirection.y);
  403. stream->read(&alignDirection.z);
  404. }
  405. highResOnly = stream->readFlag();
  406. renderReflection = stream->readFlag();
  407. glow = stream->readFlag();
  408. blendStyle = stream->readInt( 4 );
  409. ejectionInvert = stream->readFlag();
  410. fade_color = stream->readFlag();
  411. fade_alpha = stream->readFlag();
  412. fade_size = stream->readFlag();
  413. use_emitter_xfm = stream->readFlag();
  414. #if defined(AFX_CAP_PARTICLE_POOLS)
  415. if (stream->readFlag())
  416. {
  417. pool_datablock = (afxParticlePoolData*)(uintptr_t)stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  418. stream->read(&pool_index);
  419. pool_depth_fade = stream->readFlag();
  420. pool_radial_fade = stream->readFlag();
  421. do_pool_id_convert = true;
  422. }
  423. #endif
  424. }
  425. //-----------------------------------------------------------------------------
  426. // onAdd
  427. //-----------------------------------------------------------------------------
  428. bool ParticleEmitterData::onAdd()
  429. {
  430. if( Parent::onAdd() == false )
  431. return false;
  432. // if (overrideAdvance == true) {
  433. // Con::errorf(ConsoleLogEntry::General, "ParticleEmitterData: Not going to work. Fix it!");
  434. // return false;
  435. // }
  436. // Validate the parameters...
  437. //
  438. if( ejectionPeriodMS < 1 )
  439. {
  440. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) period < 1 ms", getName());
  441. ejectionPeriodMS = 1;
  442. }
  443. if( periodVarianceMS >= ejectionPeriodMS )
  444. {
  445. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) periodVariance >= period", getName());
  446. periodVarianceMS = ejectionPeriodMS - 1;
  447. }
  448. if( ejectionVelocity < 0.0f )
  449. {
  450. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) ejectionVelocity < 0.0f", getName());
  451. ejectionVelocity = 0.0f;
  452. }
  453. if( velocityVariance < 0.0f )
  454. {
  455. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) velocityVariance < 0.0f", getName());
  456. velocityVariance = 0.0f;
  457. }
  458. if( velocityVariance > ejectionVelocity )
  459. {
  460. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) velocityVariance > ejectionVelocity", getName());
  461. velocityVariance = ejectionVelocity;
  462. }
  463. if( ejectionOffset < 0.0f )
  464. {
  465. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) ejectionOffset < 0", getName());
  466. ejectionOffset = 0.0f;
  467. }
  468. if( ejectionOffsetVariance < 0.0f )
  469. {
  470. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) ejectionOffset < 0", getName());
  471. ejectionOffsetVariance = 0.0f;
  472. }
  473. if( thetaMin < 0.0f )
  474. {
  475. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaMin < 0.0", getName());
  476. thetaMin = 0.0f;
  477. }
  478. if( thetaMax > 180.0f )
  479. {
  480. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaMax > 180.0", getName());
  481. thetaMax = 180.0f;
  482. }
  483. if( thetaMin > thetaMax )
  484. {
  485. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaMin > thetaMax", getName());
  486. thetaMin = thetaMax;
  487. }
  488. if( thetaVariance > 180.0f )
  489. {
  490. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaVariance > 180.0", getName());
  491. thetaVariance = 180.0f;
  492. }
  493. if( thetaVariance < 0.0f )
  494. {
  495. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) thetaVariance < 0.0", getName());
  496. thetaVariance = 0.0f;
  497. }
  498. if( phiVariance < 0.0f || phiVariance > 360.0f )
  499. {
  500. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) invalid phiVariance", getName());
  501. phiVariance = phiVariance < 0.0f ? 0.0f : 360.0f;
  502. }
  503. if( thetaVariance < 0.0f || thetaVariance > 180.0f )
  504. {
  505. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) invalid thetaVariance", getName());
  506. thetaVariance = thetaVariance < 0.0f ? 0.0f : 180.0f;
  507. }
  508. if ( softnessDistance < 0.0f )
  509. {
  510. Con::warnf( ConsoleLogEntry::General, "ParticleEmitterData(%s) invalid softnessDistance", getName() );
  511. softnessDistance = 0.0f;
  512. }
  513. if (particleString == NULL && dataBlockIds.size() == 0)
  514. {
  515. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) no particleString, invalid datablock", getName());
  516. return false;
  517. }
  518. if (particleString && particleString[0] == '\0')
  519. {
  520. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) no particleString, invalid datablock", getName());
  521. return false;
  522. }
  523. if (particleString && dStrlen(particleString) > 255)
  524. {
  525. Con::errorf(ConsoleLogEntry::General, "ParticleEmitterData(%s) particle string too long [> 255 chars]", getName());
  526. return false;
  527. }
  528. if( lifetimeMS < 0 )
  529. {
  530. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) lifetimeMS < 0.0f", getName());
  531. lifetimeMS = 0;
  532. }
  533. if( lifetimeVarianceMS > lifetimeMS )
  534. {
  535. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) lifetimeVarianceMS >= lifetimeMS", getName());
  536. lifetimeVarianceMS = lifetimeMS;
  537. }
  538. // load the particle datablocks...
  539. //
  540. if( particleString != NULL )
  541. {
  542. // particleString is once again a list of particle datablocks so it
  543. // must be parsed to extract the particle references.
  544. // First we parse particleString into a list of particle name tokens
  545. Vector<char*> dataBlocks(__FILE__, __LINE__);
  546. dsize_t tokLen = dStrlen(particleString) + 1;
  547. char* tokCopy = new char[tokLen];
  548. dStrcpy(tokCopy, particleString, tokLen);
  549. char* currTok = dStrtok(tokCopy, " \t");
  550. while (currTok != NULL)
  551. {
  552. dataBlocks.push_back(currTok);
  553. currTok = dStrtok(NULL, " \t");
  554. }
  555. if (dataBlocks.size() == 0)
  556. {
  557. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) invalid particles string. No datablocks found", getName());
  558. delete [] tokCopy;
  559. return false;
  560. }
  561. // Now we convert the particle name tokens into particle datablocks and IDs
  562. particleDataBlocks.clear();
  563. dataBlockIds.clear();
  564. for (U32 i = 0; i < dataBlocks.size(); i++)
  565. {
  566. ParticleData* pData = NULL;
  567. if (Sim::findObject(dataBlocks[i], pData) == false)
  568. {
  569. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find particle datablock: %s", getName(), dataBlocks[i]);
  570. }
  571. else
  572. {
  573. particleDataBlocks.push_back(pData);
  574. dataBlockIds.push_back(pData->getId());
  575. }
  576. }
  577. // cleanup
  578. delete [] tokCopy;
  579. // check that we actually found some particle datablocks
  580. if (particleDataBlocks.size() == 0)
  581. {
  582. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find any particle datablocks", getName());
  583. return false;
  584. }
  585. }
  586. return true;
  587. }
  588. //-----------------------------------------------------------------------------
  589. // preload
  590. //-----------------------------------------------------------------------------
  591. bool ParticleEmitterData::preload(bool server, String &errorStr)
  592. {
  593. if( Parent::preload(server, errorStr) == false )
  594. return false;
  595. particleDataBlocks.clear();
  596. for (U32 i = 0; i < dataBlockIds.size(); i++)
  597. {
  598. ParticleData* pData = NULL;
  599. if (Sim::findObject(dataBlockIds[i], pData) == false)
  600. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find particle datablock: %d", getName(), dataBlockIds[i]);
  601. else
  602. particleDataBlocks.push_back(pData);
  603. }
  604. if (!server)
  605. {
  606. #if defined(AFX_CAP_PARTICLE_POOLS)
  607. if (do_pool_id_convert)
  608. {
  609. SimObjectId db_id = (SimObjectId)(uintptr_t)pool_datablock;
  610. if (db_id != 0)
  611. {
  612. // try to convert id to pointer
  613. if (!Sim::findObject(db_id, pool_datablock))
  614. {
  615. Con::errorf("ParticleEmitterData::reload() -- bad datablockId: 0x%x (poolData)", db_id);
  616. }
  617. }
  618. do_pool_id_convert = false;
  619. }
  620. #endif
  621. // load emitter texture if specified
  622. if (textureName && textureName[0])
  623. {
  624. textureHandle = GFXTexHandle(textureName, &GFXStaticTextureSRGBProfile, avar("%s() - textureHandle (line %d)", __FUNCTION__, __LINE__));
  625. if (!textureHandle)
  626. {
  627. errorStr = String::ToString("Missing particle emitter texture: %s", textureName);
  628. return false;
  629. }
  630. }
  631. // otherwise, check that all particles refer to the same texture
  632. else if (particleDataBlocks.size() > 1)
  633. {
  634. StringTableEntry txr_name = particleDataBlocks[0]->getTexture();
  635. for (S32 i = 1; i < particleDataBlocks.size(); i++)
  636. {
  637. // warn if particle textures are inconsistent
  638. if (particleDataBlocks[i]->getTexture() != txr_name)
  639. {
  640. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) particles reference different textures.", getName());
  641. break;
  642. }
  643. }
  644. }
  645. }
  646. // if blend-style is undefined check legacy useInvAlpha settings
  647. if (blendStyle == ParticleRenderInst::BlendUndefined && particleDataBlocks.size() > 0)
  648. {
  649. bool useInvAlpha = particleDataBlocks[0]->useInvAlpha;
  650. for (S32 i = 1; i < particleDataBlocks.size(); i++)
  651. {
  652. // warn if blend-style legacy useInvAlpha settings are inconsistent
  653. if (particleDataBlocks[i]->useInvAlpha != useInvAlpha)
  654. {
  655. Con::warnf(ConsoleLogEntry::General, "ParticleEmitterData(%s) particles have inconsistent useInvAlpha settings.", getName());
  656. break;
  657. }
  658. }
  659. blendStyle = (useInvAlpha) ? ParticleRenderInst::BlendNormal : ParticleRenderInst::BlendAdditive;
  660. }
  661. if( !server )
  662. {
  663. allocPrimBuffer();
  664. }
  665. return true;
  666. }
  667. //-----------------------------------------------------------------------------
  668. // alloc PrimitiveBuffer
  669. // The datablock allocates this static index buffer because it's the same
  670. // for all of the emitters - each particle quad uses the same index ordering
  671. //-----------------------------------------------------------------------------
  672. void ParticleEmitterData::allocPrimBuffer( S32 overrideSize )
  673. {
  674. // calculate particle list size
  675. AssertFatal(particleDataBlocks.size() > 0, "Error, no particles found." );
  676. if (particleDataBlocks.empty()) return;
  677. U32 maxPartLife = particleDataBlocks[0]->lifetimeMS + particleDataBlocks[0]->lifetimeVarianceMS;
  678. for (S32 i = 1; i < particleDataBlocks.size(); i++)
  679. {
  680. U32 mpl = particleDataBlocks[i]->lifetimeMS + particleDataBlocks[i]->lifetimeVarianceMS;
  681. if (mpl > maxPartLife)
  682. maxPartLife = mpl;
  683. }
  684. partListInitSize = maxPartLife / (ejectionPeriodMS - periodVarianceMS);
  685. partListInitSize += 8; // add 8 as "fudge factor" to make sure it doesn't realloc if it goes over by 1
  686. if (parts_per_eject > 1)
  687. partListInitSize *= parts_per_eject;
  688. // if override size is specified, then the emitter overran its buffer and needs a larger allocation
  689. if( overrideSize != -1 )
  690. {
  691. partListInitSize = overrideSize;
  692. }
  693. // create index buffer based on that size
  694. U32 indexListSize = partListInitSize * 6; // 6 indices per particle
  695. U16 *indices = new U16[ indexListSize ];
  696. for( U32 i=0; i<partListInitSize; i++ )
  697. {
  698. // this index ordering should be optimal (hopefully) for the vertex cache
  699. U16 *idx = &indices[i*6];
  700. volatile U32 offset = i * 4; // set to volatile to fix VC6 Release mode compiler bug
  701. idx[0] = 0 + offset;
  702. idx[1] = 1 + offset;
  703. idx[2] = 3 + offset;
  704. idx[3] = 1 + offset;
  705. idx[4] = 3 + offset;
  706. idx[5] = 2 + offset;
  707. }
  708. U16 *ibIndices;
  709. GFXBufferType bufferType = GFXBufferTypeStatic;
  710. primBuff.set( GFX, indexListSize, 0, bufferType );
  711. primBuff.lock( &ibIndices );
  712. dMemcpy( ibIndices, indices, indexListSize * sizeof(U16) );
  713. primBuff.unlock();
  714. delete [] indices;
  715. }
  716. //#define TRACK_PARTICLE_EMITTER_DATA_CLONES
  717. #ifdef TRACK_PARTICLE_EMITTER_DATA_CLONES
  718. static int emitter_data_clones = 0;
  719. #endif
  720. ParticleEmitterData::ParticleEmitterData(const ParticleEmitterData& other, bool temp_clone) : GameBaseData(other, temp_clone)
  721. {
  722. #ifdef TRACK_PARTICLE_EMITTER_DATA_CLONES
  723. emitter_data_clones++;
  724. if (emitter_data_clones == 1)
  725. Con::errorf("ParticleEmitterData -- Clones are on the loose!");
  726. #endif
  727. ejectionPeriodMS = other.ejectionPeriodMS;
  728. periodVarianceMS = other.periodVarianceMS;
  729. ejectionVelocity = other.ejectionVelocity;
  730. velocityVariance = other.velocityVariance;
  731. ejectionOffset = other.ejectionOffset;
  732. ejectionOffsetVariance = other.ejectionOffsetVariance;
  733. thetaMin = other.thetaMin;
  734. thetaMax = other.thetaMax;
  735. thetaVariance = other.thetaVariance;
  736. phiReferenceVel = other.phiReferenceVel;
  737. phiVariance = other.phiVariance;
  738. softnessDistance = other.softnessDistance;
  739. ambientFactor = other.ambientFactor;
  740. lifetimeMS = other.lifetimeMS;
  741. lifetimeVarianceMS = other.lifetimeVarianceMS;
  742. overrideAdvance = other.overrideAdvance;
  743. orientParticles = other.orientParticles;
  744. orientOnVelocity = other.orientOnVelocity;
  745. ribbonParticles = other.ribbonParticles;
  746. useEmitterSizes = other.useEmitterSizes;
  747. useEmitterColors = other.useEmitterColors;
  748. alignParticles = other.alignParticles;
  749. alignDirection = other.alignDirection;
  750. particleString = other.particleString;
  751. particleDataBlocks = other.particleDataBlocks; // -- derived from particleString
  752. dataBlockIds = other.dataBlockIds; // -- derived from particleString
  753. partListInitSize = other.partListInitSize; // -- approx calc from other fields
  754. primBuff = other.primBuff;
  755. blendStyle = other.blendStyle;
  756. sortParticles = other.sortParticles;
  757. reverseOrder = other.reverseOrder;
  758. textureName = other.textureName;
  759. textureHandle = other.textureHandle; // -- TextureHandle loads using textureName
  760. highResOnly = other.highResOnly;
  761. glow = other.glow;
  762. renderReflection = other.renderReflection;
  763. fade_color = other.fade_color;
  764. fade_size = other.fade_size;
  765. fade_alpha = other.fade_alpha;
  766. ejectionInvert = other.ejectionInvert;
  767. parts_per_eject = other.parts_per_eject; // -- set to 1 (used by subclasses)
  768. use_emitter_xfm = other.use_emitter_xfm;
  769. #if defined(AFX_CAP_PARTICLE_POOLS)
  770. pool_datablock = other.pool_datablock;
  771. pool_index = other.pool_index;
  772. pool_depth_fade = other.pool_depth_fade;
  773. pool_radial_fade = other.pool_radial_fade;
  774. do_pool_id_convert = other.do_pool_id_convert; // -- flags pool id conversion need
  775. #endif
  776. }
  777. ParticleEmitterData::~ParticleEmitterData()
  778. {
  779. if (!isTempClone())
  780. return;
  781. for (S32 i = 0; i < particleDataBlocks.size(); i++)
  782. {
  783. if (particleDataBlocks[i] && particleDataBlocks[i]->isTempClone())
  784. {
  785. delete particleDataBlocks[i];
  786. particleDataBlocks[i] = 0;
  787. }
  788. }
  789. #ifdef TRACK_PARTICLE_EMITTER_DATA_CLONES
  790. if (emitter_data_clones > 0)
  791. {
  792. emitter_data_clones--;
  793. if (emitter_data_clones == 0)
  794. Con::errorf("ParticleEmitterData -- Clones eliminated!");
  795. }
  796. else
  797. Con::errorf("ParticleEmitterData -- Too many clones deleted!");
  798. #endif
  799. }
  800. ParticleEmitterData* ParticleEmitterData::cloneAndPerformSubstitutions(const SimObject* owner, S32 index)
  801. {
  802. if (!owner)
  803. return this;
  804. bool clone_parts_db = false;
  805. // note -- this could be checked when the particle blocks are evaluated
  806. for (S32 i = 0; i < this->particleDataBlocks.size(); i++)
  807. {
  808. if (this->particleDataBlocks[i] && (this->particleDataBlocks[i]->getSubstitutionCount() > 0))
  809. {
  810. clone_parts_db = true;
  811. break;
  812. }
  813. }
  814. ParticleEmitterData* sub_emitter_db = this;
  815. if (this->getSubstitutionCount() > 0 || clone_parts_db)
  816. {
  817. sub_emitter_db = new ParticleEmitterData(*this, true);
  818. performSubstitutions(sub_emitter_db, owner, index);
  819. if (clone_parts_db)
  820. {
  821. for (S32 i = 0; i < sub_emitter_db->particleDataBlocks.size(); i++)
  822. {
  823. if (sub_emitter_db->particleDataBlocks[i] && (sub_emitter_db->particleDataBlocks[i]->getSubstitutionCount() > 0))
  824. {
  825. ParticleData* orig_db = sub_emitter_db->particleDataBlocks[i];
  826. sub_emitter_db->particleDataBlocks[i] = new ParticleData(*orig_db, true);
  827. orig_db->performSubstitutions(sub_emitter_db->particleDataBlocks[i], owner, index);
  828. }
  829. }
  830. }
  831. }
  832. return sub_emitter_db;
  833. }
  834. //-----------------------------------------------------------------------------
  835. // ParticleEmitter
  836. //-----------------------------------------------------------------------------
  837. ParticleEmitter::ParticleEmitter()
  838. {
  839. mDeleteWhenEmpty = false;
  840. mDeleteOnTick = false;
  841. mInternalClock = 0;
  842. mNextParticleTime = 0;
  843. mLastPosition.set(0, 0, 0);
  844. mHasLastPosition = false;
  845. mLifetimeMS = 0;
  846. mElapsedTimeMS = 0;
  847. part_store = 0;
  848. part_freelist = NULL;
  849. part_list_head.next = NULL;
  850. n_part_capacity = 0;
  851. n_parts = 0;
  852. mThetaOld = 0;
  853. mPhiOld = 0;
  854. mCurBuffSize = 0;
  855. mDead = false;
  856. mDataBlock = NULL;
  857. // ParticleEmitter should be allocated on the client only.
  858. mNetFlags.set( IsGhost );
  859. fade_amt = 1.0f;
  860. forced_bbox = false;
  861. db_temp_clone = false;
  862. pos_pe.set(0,0,0);
  863. sort_priority = 0;
  864. mDataBlock = 0;
  865. std::fill_n(sizes, ParticleData::PDC_NUM_KEYS, 0.0f);
  866. #if defined(AFX_CAP_PARTICLE_POOLS)
  867. pool = 0;
  868. #endif
  869. }
  870. //-----------------------------------------------------------------------------
  871. // destructor
  872. //-----------------------------------------------------------------------------
  873. ParticleEmitter::~ParticleEmitter()
  874. {
  875. for( S32 i = 0; i < part_store.size(); i++ )
  876. {
  877. delete [] part_store[i];
  878. }
  879. if (db_temp_clone && mDataBlock && mDataBlock->isTempClone())
  880. {
  881. for (S32 i = 0; i < mDataBlock->particleDataBlocks.size(); i++)
  882. {
  883. if (mDataBlock->particleDataBlocks[i] && mDataBlock->particleDataBlocks[i]->isTempClone())
  884. {
  885. delete mDataBlock->particleDataBlocks[i];
  886. mDataBlock->particleDataBlocks[i] = 0;
  887. }
  888. }
  889. delete mDataBlock;
  890. mDataBlock = 0;
  891. }
  892. }
  893. //-----------------------------------------------------------------------------
  894. // onAdd
  895. //-----------------------------------------------------------------------------
  896. bool ParticleEmitter::onAdd()
  897. {
  898. if( !Parent::onAdd() )
  899. return false;
  900. // add to client side mission cleanup
  901. SimGroup *cleanup = dynamic_cast<SimGroup *>( Sim::findObject( "ClientMissionCleanup") );
  902. if( cleanup != NULL )
  903. {
  904. cleanup->addObject( this );
  905. }
  906. removeFromProcessList();
  907. F32 radius = 5.0;
  908. mObjBox.minExtents = Point3F(-radius, -radius, -radius);
  909. mObjBox.maxExtents = Point3F(radius, radius, radius);
  910. resetWorldBox();
  911. #if defined(AFX_CAP_PARTICLE_POOLS)
  912. if (pool)
  913. pool->addParticleEmitter(this);
  914. #endif
  915. return true;
  916. }
  917. //-----------------------------------------------------------------------------
  918. // onRemove
  919. //-----------------------------------------------------------------------------
  920. void ParticleEmitter::onRemove()
  921. {
  922. #if defined(AFX_CAP_PARTICLE_POOLS)
  923. if (pool)
  924. {
  925. pool->removeParticleEmitter(this);
  926. pool = 0;
  927. }
  928. #endif
  929. removeFromScene();
  930. Parent::onRemove();
  931. }
  932. //-----------------------------------------------------------------------------
  933. // onNewDataBlock
  934. //-----------------------------------------------------------------------------
  935. bool ParticleEmitter::onNewDataBlock( GameBaseData *dptr, bool reload )
  936. {
  937. mDataBlock = dynamic_cast<ParticleEmitterData*>( dptr );
  938. if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  939. return false;
  940. mLifetimeMS = mDataBlock->lifetimeMS;
  941. if( mDataBlock->lifetimeVarianceMS )
  942. {
  943. mLifetimeMS += S32( gRandGen.randI() % (2 * mDataBlock->lifetimeVarianceMS + 1)) - S32(mDataBlock->lifetimeVarianceMS );
  944. }
  945. // Allocate particle structures and init the freelist. Member part_store
  946. // is a Vector so that we can allocate more particles if partListInitSize
  947. // turns out to be too small.
  948. //
  949. if (mDataBlock->partListInitSize > 0)
  950. {
  951. for( S32 i = 0; i < part_store.size(); i++ )
  952. {
  953. delete [] part_store[i];
  954. }
  955. part_store.clear();
  956. n_part_capacity = mDataBlock->partListInitSize;
  957. Particle* store_block = new Particle[n_part_capacity];
  958. part_store.push_back(store_block);
  959. part_freelist = store_block;
  960. Particle* last_part = part_freelist;
  961. Particle* part = last_part+1;
  962. for( S32 i = 1; i < n_part_capacity; i++, part++, last_part++ )
  963. {
  964. last_part->next = part;
  965. }
  966. store_block[n_part_capacity-1].next = NULL;
  967. part_list_head.next = NULL;
  968. n_parts = 0;
  969. }
  970. if (mDataBlock->isTempClone())
  971. {
  972. db_temp_clone = true;
  973. return true;
  974. }
  975. scriptOnNewDataBlock();
  976. return true;
  977. }
  978. //-----------------------------------------------------------------------------
  979. // getCollectiveColor
  980. //-----------------------------------------------------------------------------
  981. LinearColorF ParticleEmitter::getCollectiveColor()
  982. {
  983. U32 count = 0;
  984. LinearColorF color = LinearColorF(0.0f, 0.0f, 0.0f);
  985. count = n_parts;
  986. for( Particle* part = part_list_head.next; part != NULL; part = part->next )
  987. {
  988. color += part->color;
  989. }
  990. if(count > 0)
  991. {
  992. color /= F32(count);
  993. }
  994. //if(color.red == 0.0f && color.green == 0.0f && color.blue == 0.0f)
  995. // color = color;
  996. return color;
  997. }
  998. //-----------------------------------------------------------------------------
  999. // prepRenderImage
  1000. //-----------------------------------------------------------------------------
  1001. void ParticleEmitter::prepRenderImage(SceneRenderState* state)
  1002. {
  1003. #if defined(AFX_CAP_PARTICLE_POOLS)
  1004. if (pool)
  1005. return;
  1006. #endif
  1007. if( state->isReflectPass() && !getDataBlock()->renderReflection )
  1008. return;
  1009. // Never render into shadows.
  1010. if (state->isShadowPass())
  1011. return;
  1012. PROFILE_SCOPE(ParticleEmitter_prepRenderImage);
  1013. if ( mDead ||
  1014. n_parts == 0 ||
  1015. part_list_head.next == NULL )
  1016. return;
  1017. RenderPassManager *renderManager = state->getRenderPass();
  1018. const Point3F &camPos = state->getCameraPosition();
  1019. copyToVB( camPos, state->getAmbientLightColor() );
  1020. if (!mVertBuff.isValid())
  1021. return;
  1022. ParticleRenderInst *ri = renderManager->allocInst<ParticleRenderInst>();
  1023. ri->vertBuff = &mVertBuff;
  1024. ri->primBuff = &getDataBlock()->primBuff;
  1025. ri->translucentSort = true;
  1026. ri->type = RenderPassManager::RIT_Particle;
  1027. ri->sortDistSq = getRenderWorldBox().getSqDistanceToPoint( camPos );
  1028. ri->defaultKey = (-sort_priority*100);
  1029. // Draw the system offscreen unless the highResOnly flag is set on the datablock
  1030. ri->systemState = ( getDataBlock()->highResOnly ? PSS_AwaitingHighResDraw : PSS_AwaitingOffscreenDraw );
  1031. ri->modelViewProj = renderManager->allocUniqueXform( GFX->getProjectionMatrix() *
  1032. GFX->getViewMatrix() *
  1033. GFX->getWorldMatrix() );
  1034. // Update position on the matrix before multiplying it
  1035. mBBObjToWorld.setPosition(mLastPosition);
  1036. ri->bbModelViewProj = renderManager->allocUniqueXform( *ri->modelViewProj * mBBObjToWorld );
  1037. ri->wsPosition = getWorldTransform().getPosition();
  1038. ri->count = n_parts;
  1039. ri->blendStyle = mDataBlock->blendStyle;
  1040. ri->glow = mDataBlock->glow;
  1041. // use first particle's texture unless there is an emitter texture to override it
  1042. if (mDataBlock->textureHandle)
  1043. ri->diffuseTex = &*(mDataBlock->textureHandle);
  1044. else
  1045. ri->diffuseTex = &*(part_list_head.next->dataBlock->getTextureResource());
  1046. ri->softnessDistance = mDataBlock->softnessDistance;
  1047. // Sort by texture too.
  1048. ri->defaultKey = ri->diffuseTex ? (uintptr_t)ri->diffuseTex : (uintptr_t)ri->vertBuff;
  1049. renderManager->addInst( ri );
  1050. }
  1051. //-----------------------------------------------------------------------------
  1052. // setSizes
  1053. //-----------------------------------------------------------------------------
  1054. void ParticleEmitter::setSizes( F32 *sizeList )
  1055. {
  1056. for( S32 i=0; i<ParticleData::PDC_NUM_KEYS; i++ )
  1057. {
  1058. sizes[i] = sizeList[i];
  1059. }
  1060. }
  1061. //-----------------------------------------------------------------------------
  1062. // setColors
  1063. //-----------------------------------------------------------------------------
  1064. void ParticleEmitter::setColors( LinearColorF *colorList )
  1065. {
  1066. for( S32 i=0; i<ParticleData::PDC_NUM_KEYS; i++ )
  1067. {
  1068. colors[i] = colorList[i];
  1069. }
  1070. }
  1071. //-----------------------------------------------------------------------------
  1072. // deleteWhenEmpty
  1073. //-----------------------------------------------------------------------------
  1074. void ParticleEmitter::deleteWhenEmpty()
  1075. {
  1076. // if the following asserts fire, there is a reasonable chance that you are trying to delete a particle emitter
  1077. // that has already been deleted (possibly by ClientMissionCleanup). If so, use a SimObjectPtr to the emitter and check it
  1078. // for null before calling this function.
  1079. AssertFatal(isProperlyAdded(), "ParticleEmitter must be registed before calling deleteWhenEmpty");
  1080. AssertFatal(!mDead, "ParticleEmitter already deleted");
  1081. AssertFatal(!isDeleted(), "ParticleEmitter already deleted");
  1082. AssertFatal(!isRemoved(), "ParticleEmitter already removed");
  1083. // this check is for non debug case, so that we don't write in to freed memory
  1084. bool okToDelete = !mDead && isProperlyAdded() && !isDeleted() && !isRemoved();
  1085. if (okToDelete)
  1086. {
  1087. mDeleteWhenEmpty = true;
  1088. if( !n_parts )
  1089. {
  1090. // We're already empty, so delete us now.
  1091. mDead = true;
  1092. deleteObject();
  1093. }
  1094. else
  1095. AssertFatal( getSceneManager() != NULL, "ParticleEmitter not on process list and won't get ticked to death" );
  1096. }
  1097. }
  1098. //-----------------------------------------------------------------------------
  1099. // emitParticles
  1100. //-----------------------------------------------------------------------------
  1101. void ParticleEmitter::emitParticles(const Point3F& point,
  1102. const bool useLastPosition,
  1103. const Point3F& axis,
  1104. const Point3F& velocity,
  1105. const U32 numMilliseconds)
  1106. {
  1107. if( mDead ) return;
  1108. // lifetime over - no more particles
  1109. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  1110. {
  1111. return;
  1112. }
  1113. pos_pe = point;
  1114. Point3F realStart;
  1115. if( useLastPosition && mHasLastPosition )
  1116. realStart = mLastPosition;
  1117. else
  1118. realStart = point;
  1119. emitParticles(realStart, point,
  1120. axis,
  1121. velocity,
  1122. numMilliseconds);
  1123. }
  1124. //-----------------------------------------------------------------------------
  1125. // emitParticles
  1126. //-----------------------------------------------------------------------------
  1127. void ParticleEmitter::emitParticles(const Point3F& start,
  1128. const Point3F& end,
  1129. const Point3F& axis,
  1130. const Point3F& velocity,
  1131. const U32 numMilliseconds)
  1132. {
  1133. if( mDead ) return;
  1134. if( mDataBlock->particleDataBlocks.empty() )
  1135. return;
  1136. // lifetime over - no more particles
  1137. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  1138. {
  1139. return;
  1140. }
  1141. U32 currTime = 0;
  1142. bool particlesAdded = false;
  1143. Point3F axisx;
  1144. if( mFabs(axis.z) < 0.9f )
  1145. mCross(axis, Point3F(0, 0, 1), &axisx);
  1146. else
  1147. mCross(axis, Point3F(0, 1, 0), &axisx);
  1148. axisx.normalize();
  1149. if( mNextParticleTime != 0 )
  1150. {
  1151. // Need to handle next particle
  1152. //
  1153. if( mNextParticleTime > numMilliseconds )
  1154. {
  1155. // Defer to next update
  1156. // (Note that this introduces a potential spatial irregularity if the owning
  1157. // object is accelerating, and updating at a low frequency)
  1158. //
  1159. mNextParticleTime -= numMilliseconds;
  1160. mInternalClock += numMilliseconds;
  1161. mLastPosition = end;
  1162. mHasLastPosition = true;
  1163. return;
  1164. }
  1165. else
  1166. {
  1167. currTime += mNextParticleTime;
  1168. mInternalClock += mNextParticleTime;
  1169. // Emit particle at curr time
  1170. // Create particle at the correct position
  1171. Point3F pos;
  1172. pos.interpolate(start, end, F32(currTime) / F32(numMilliseconds));
  1173. addParticle(pos, axis, velocity, axisx, numMilliseconds-currTime);
  1174. particlesAdded = true;
  1175. mNextParticleTime = 0;
  1176. }
  1177. }
  1178. while( currTime < numMilliseconds )
  1179. {
  1180. S32 nextTime = mDataBlock->ejectionPeriodMS;
  1181. if( mDataBlock->periodVarianceMS != 0 )
  1182. {
  1183. nextTime += S32(gRandGen.randI() % (2 * mDataBlock->periodVarianceMS + 1)) -
  1184. S32(mDataBlock->periodVarianceMS);
  1185. }
  1186. AssertFatal(nextTime > 0, "Error, next particle ejection time must always be greater than 0");
  1187. if( currTime + nextTime > numMilliseconds )
  1188. {
  1189. mNextParticleTime = (currTime + nextTime) - numMilliseconds;
  1190. mInternalClock += numMilliseconds - currTime;
  1191. AssertFatal(mNextParticleTime > 0, "Error, should not have deferred this particle!");
  1192. break;
  1193. }
  1194. currTime += nextTime;
  1195. mInternalClock += nextTime;
  1196. // Create particle at the correct position
  1197. Point3F pos;
  1198. pos.interpolate(start, end, F32(currTime) / F32(numMilliseconds));
  1199. addParticle(pos, axis, velocity, axisx, numMilliseconds-currTime);
  1200. particlesAdded = true;
  1201. // This override-advance code is restored in order to correctly adjust
  1202. // animated parameters of particles allocated within the same frame
  1203. // update. Note that ordering is important and this code correctly
  1204. // adds particles in the same newest-to-oldest ordering of the link-list.
  1205. //
  1206. // NOTE: We are assuming that the just added particle is at the head of our
  1207. // list. If that changes, so must this...
  1208. U32 advanceMS = numMilliseconds - currTime;
  1209. if (mDataBlock->overrideAdvance == false && advanceMS != 0)
  1210. {
  1211. Particle* last_part = part_list_head.next;
  1212. if (advanceMS > last_part->totalLifetime)
  1213. {
  1214. part_list_head.next = last_part->next;
  1215. n_parts--;
  1216. last_part->next = part_freelist;
  1217. part_freelist = last_part;
  1218. }
  1219. else
  1220. {
  1221. if (advanceMS != 0)
  1222. {
  1223. F32 t = F32(advanceMS) / 1000.0;
  1224. Point3F a = last_part->acc;
  1225. a -= last_part->vel * last_part->dataBlock->dragCoefficient;
  1226. a += mWindVelocity * last_part->dataBlock->windCoefficient;
  1227. //a += Point3F(0.0f, 0.0f, -9.81f) * last_part->dataBlock->gravityCoefficient;
  1228. a.z += -9.81f*last_part->dataBlock->gravityCoefficient; // as long as gravity is a constant, this is faster
  1229. last_part->vel += a * t;
  1230. //last_part->pos += last_part->vel * t;
  1231. last_part->pos_local += last_part->vel * t;
  1232. // AFX -- allow subclasses to adjust the particle params here
  1233. sub_particleUpdate(last_part);
  1234. if (last_part->dataBlock->constrain_pos)
  1235. last_part->pos = last_part->pos_local + this->pos_pe;
  1236. else
  1237. last_part->pos = last_part->pos_local;
  1238. updateKeyData( last_part );
  1239. }
  1240. }
  1241. }
  1242. }
  1243. // DMMFIX: Lame and slow...
  1244. if( particlesAdded == true )
  1245. updateBBox();
  1246. if( n_parts > 0 && getSceneManager() == NULL )
  1247. {
  1248. gClientSceneGraph->addObjectToScene(this);
  1249. ClientProcessList::get()->addObject(this);
  1250. }
  1251. mLastPosition = end;
  1252. mHasLastPosition = true;
  1253. }
  1254. //-----------------------------------------------------------------------------
  1255. // emitParticles
  1256. //-----------------------------------------------------------------------------
  1257. void ParticleEmitter::emitParticles(const Point3F& rCenter,
  1258. const Point3F& rNormal,
  1259. const F32 radius,
  1260. const Point3F& velocity,
  1261. S32 count)
  1262. {
  1263. if( mDead ) return;
  1264. // lifetime over - no more particles
  1265. if( mLifetimeMS > 0 && mElapsedTimeMS > mLifetimeMS )
  1266. {
  1267. return;
  1268. }
  1269. Point3F axisx, axisy;
  1270. Point3F axisz = rNormal;
  1271. if( axisz.isZero() )
  1272. {
  1273. axisz.set( 0.0, 0.0, 1.0 );
  1274. }
  1275. if( mFabs(axisz.z) < 0.98 )
  1276. {
  1277. mCross(axisz, Point3F(0, 0, 1), &axisy);
  1278. axisy.normalize();
  1279. }
  1280. else
  1281. {
  1282. mCross(axisz, Point3F(0, 1, 0), &axisy);
  1283. axisy.normalize();
  1284. }
  1285. mCross(axisz, axisy, &axisx);
  1286. axisx.normalize();
  1287. // Should think of a better way to distribute the
  1288. // particles within the hemisphere.
  1289. for( S32 i = 0; i < count; i++ )
  1290. {
  1291. Point3F pos = axisx * (radius * (1 - (2 * gRandGen.randF())));
  1292. pos += axisy * (radius * (1 - (2 * gRandGen.randF())));
  1293. pos += axisz * (radius * gRandGen.randF());
  1294. Point3F axis = pos;
  1295. axis.normalize();
  1296. pos += rCenter;
  1297. addParticle(pos, axis, velocity, axisz, 0);
  1298. }
  1299. // Set world bounding box
  1300. mObjBox.minExtents = rCenter - Point3F(radius, radius, radius);
  1301. mObjBox.maxExtents = rCenter + Point3F(radius, radius, radius);
  1302. resetWorldBox();
  1303. // Make sure we're part of the world
  1304. if( n_parts > 0 && getSceneManager() == NULL )
  1305. {
  1306. gClientSceneGraph->addObjectToScene(this);
  1307. ClientProcessList::get()->addObject(this);
  1308. }
  1309. mHasLastPosition = false;
  1310. }
  1311. //-----------------------------------------------------------------------------
  1312. // updateBBox - SLOW, bad news
  1313. //-----------------------------------------------------------------------------
  1314. void ParticleEmitter::updateBBox()
  1315. {
  1316. if (forced_bbox)
  1317. return;
  1318. Point3F minPt(1e10, 1e10, 1e10);
  1319. Point3F maxPt(-1e10, -1e10, -1e10);
  1320. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1321. {
  1322. Point3F particleSize(part->size * 0.5f);
  1323. F32 motion = getMax((part->vel.len() * part->totalLifetime / 1000.0f), 1.0f);
  1324. minPt.setMin(part->pos - particleSize - Point3F(motion));
  1325. maxPt.setMax(part->pos + particleSize + Point3F(motion));
  1326. }
  1327. mObjBox = Box3F(minPt, maxPt);
  1328. MatrixF temp = getTransform();
  1329. setTransform(temp);
  1330. mBBObjToWorld.identity();
  1331. Point3F boxScale = mObjBox.getExtents();
  1332. boxScale.x = getMax(boxScale.x, 1.0f);
  1333. boxScale.y = getMax(boxScale.y, 1.0f);
  1334. boxScale.z = getMax(boxScale.z, 1.0f);
  1335. mBBObjToWorld.scale(boxScale);
  1336. #if defined(AFX_CAP_PARTICLE_POOLS)
  1337. if (pool)
  1338. pool->updatePoolBBox(this);
  1339. #endif
  1340. }
  1341. //-----------------------------------------------------------------------------
  1342. // addParticle
  1343. //-----------------------------------------------------------------------------
  1344. void ParticleEmitter::addParticle(const Point3F& pos, const Point3F& axis, const Point3F& vel,
  1345. const Point3F& axisx, const U32 age_offset)
  1346. {
  1347. n_parts++;
  1348. if (n_parts > n_part_capacity || n_parts > mDataBlock->partListInitSize)
  1349. {
  1350. // In an emergency we allocate additional particles in blocks of 16.
  1351. // This should happen rarely.
  1352. Particle* store_block = new Particle[16];
  1353. part_store.push_back(store_block);
  1354. n_part_capacity += 16;
  1355. for (S32 i = 0; i < 16; i++)
  1356. {
  1357. store_block[i].next = part_freelist;
  1358. part_freelist = &store_block[i];
  1359. }
  1360. mDataBlock->allocPrimBuffer(n_part_capacity); // allocate larger primitive buffer or will crash
  1361. }
  1362. Particle* pNew = part_freelist;
  1363. part_freelist = pNew->next;
  1364. pNew->next = part_list_head.next;
  1365. part_list_head.next = pNew;
  1366. // for earlier access to constrain_pos, the ParticleData datablock is chosen here instead
  1367. // of later in the method.
  1368. U32 dBlockIndex = gRandGen.randI() % mDataBlock->particleDataBlocks.size();
  1369. ParticleData* part_db = mDataBlock->particleDataBlocks[dBlockIndex];
  1370. // set start position to world or local space
  1371. Point3F pos_start;
  1372. if (part_db->constrain_pos)
  1373. pos_start.set(0,0,0);
  1374. else
  1375. pos_start = pos;
  1376. Point3F ejectionAxis = axis;
  1377. F32 theta = 0.0f;
  1378. F32 thetaTarget = (mDataBlock->thetaMax + mDataBlock->thetaMin) / 2.0f;
  1379. if (mDataBlock->thetaVariance <= 0.0f)
  1380. theta = (mDataBlock->thetaMax - mDataBlock->thetaMin) * gRandGen.randF() + mDataBlock->thetaMin;
  1381. else
  1382. {
  1383. F32 thetaDelta = ( gRandGen.randF() - 0.5f) * mDataBlock->thetaVariance * 2.0f;
  1384. thetaDelta += ( (thetaTarget - mThetaOld) / mDataBlock->thetaMax ) * mDataBlock->thetaVariance * 0.25f;
  1385. theta = mThetaOld + thetaDelta;
  1386. }
  1387. mThetaOld = theta;
  1388. F32 ref = (F32(mInternalClock) / 1000.0) * mDataBlock->phiReferenceVel;
  1389. F32 phi = 0.0f;
  1390. if (mDataBlock->thetaVariance <= 0.0f)
  1391. {
  1392. phi = ref + gRandGen.randF() * mDataBlock->phiVariance;
  1393. }
  1394. else
  1395. {
  1396. F32 phiDelta = (gRandGen.randF() - 0.5f) * mDataBlock->thetaVariance * 2.0f;
  1397. phi = ref + mPhiOld + phiDelta;
  1398. if (phi > mDataBlock->phiVariance)
  1399. phi += fabs(phiDelta) * -2.0f;
  1400. if (phi < 0.0f)
  1401. phi += fabs(phiDelta) * 2.0f;
  1402. }
  1403. mPhiOld = phi;
  1404. // Both phi and theta are in degs. Create axis angles out of them, and create the
  1405. // appropriate rotation matrix...
  1406. AngAxisF thetaRot(axisx, theta * (M_PI / 180.0));
  1407. AngAxisF phiRot(axis, phi * (M_PI / 180.0));
  1408. MatrixF temp(true);
  1409. thetaRot.setMatrix(&temp);
  1410. temp.mulP(ejectionAxis);
  1411. phiRot.setMatrix(&temp);
  1412. temp.mulP(ejectionAxis);
  1413. F32 initialVel = mDataBlock->ejectionVelocity;
  1414. initialVel += (mDataBlock->velocityVariance * 2.0f * gRandGen.randF()) - mDataBlock->velocityVariance;
  1415. pNew->pos = pos_start + (ejectionAxis * (mDataBlock->ejectionOffset + mDataBlock->ejectionOffsetVariance* gRandGen.randF()) );
  1416. pNew->pos_local = pNew->pos;
  1417. pNew->vel = mDataBlock->ejectionInvert ? ejectionAxis * -initialVel : ejectionAxis * initialVel;
  1418. if (mDataBlock->orientParticles)
  1419. pNew->orientDir = ejectionAxis;
  1420. else
  1421. // note -- for non-oriented particles, we use orientDir.x to store the billboard start angle.
  1422. pNew->orientDir.x = mDegToRad(part_db->start_angle + part_db->angle_variance*2.0f*gRandGen.randF() - part_db->angle_variance);
  1423. pNew->acc.set(0, 0, 0);
  1424. pNew->currentAge = age_offset;
  1425. pNew->t_last = 0.0f;
  1426. // ribbon particles only use the first particle
  1427. if(mDataBlock->ribbonParticles)
  1428. {
  1429. mDataBlock->particleDataBlocks[0]->initializeParticle(pNew, vel);
  1430. }
  1431. else
  1432. {
  1433. dBlockIndex = gRandGen.randI() % mDataBlock->particleDataBlocks.size();
  1434. mDataBlock->particleDataBlocks[dBlockIndex]->initializeParticle(pNew, vel);
  1435. }
  1436. updateKeyData( pNew );
  1437. }
  1438. //-----------------------------------------------------------------------------
  1439. // processTick
  1440. //-----------------------------------------------------------------------------
  1441. void ParticleEmitter::processTick(const Move*)
  1442. {
  1443. if( mDeleteOnTick == true )
  1444. {
  1445. mDead = true;
  1446. deleteObject();
  1447. }
  1448. }
  1449. //-----------------------------------------------------------------------------
  1450. // advanceTime
  1451. //-----------------------------------------------------------------------------
  1452. void ParticleEmitter::advanceTime(F32 dt)
  1453. {
  1454. if( dt < 0.00001 ) return;
  1455. Parent::advanceTime(dt);
  1456. if( dt > 0.5 ) dt = 0.5;
  1457. if( mDead ) return;
  1458. mElapsedTimeMS += (S32)(dt * 1000.0f);
  1459. U32 numMSToUpdate = (U32)(dt * 1000.0f);
  1460. if( numMSToUpdate == 0 ) return;
  1461. // TODO: Prefetch
  1462. // remove dead particles
  1463. Particle* last_part = &part_list_head;
  1464. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1465. {
  1466. part->currentAge += numMSToUpdate;
  1467. if (part->currentAge > part->totalLifetime)
  1468. {
  1469. n_parts--;
  1470. last_part->next = part->next;
  1471. part->next = part_freelist;
  1472. part_freelist = part;
  1473. part = last_part;
  1474. }
  1475. else
  1476. {
  1477. last_part = part;
  1478. }
  1479. }
  1480. AssertFatal( n_parts >= 0, "ParticleEmitter: negative part count!" );
  1481. if (n_parts < 1 && mDeleteWhenEmpty)
  1482. {
  1483. mDeleteOnTick = true;
  1484. return;
  1485. }
  1486. if( numMSToUpdate != 0 && n_parts > 0 )
  1487. {
  1488. update( numMSToUpdate );
  1489. }
  1490. }
  1491. //-----------------------------------------------------------------------------
  1492. // Update key related particle data
  1493. //-----------------------------------------------------------------------------
  1494. void ParticleEmitter::updateKeyData( Particle *part )
  1495. {
  1496. //Ensure that our lifetime is never below 0
  1497. if( part->totalLifetime < 1 )
  1498. part->totalLifetime = 1;
  1499. if (part->currentAge > part->totalLifetime)
  1500. part->currentAge = part->totalLifetime;
  1501. F32 t = (F32)part->currentAge / (F32)part->totalLifetime;
  1502. for( U32 i = 1; i < ParticleData::PDC_NUM_KEYS; i++ )
  1503. {
  1504. if( part->dataBlock->times[i] >= t )
  1505. {
  1506. F32 firstPart = t - part->dataBlock->times[i-1];
  1507. F32 total = part->dataBlock->times[i] -
  1508. part->dataBlock->times[i-1];
  1509. firstPart /= total;
  1510. if( mDataBlock->useEmitterColors )
  1511. {
  1512. part->color.interpolate(colors[i-1], colors[i], firstPart);
  1513. }
  1514. else
  1515. {
  1516. part->color.interpolate(part->dataBlock->colors[i-1],
  1517. part->dataBlock->colors[i],
  1518. firstPart);
  1519. }
  1520. if( mDataBlock->useEmitterSizes )
  1521. {
  1522. part->size = (sizes[i-1] * (1.0 - firstPart)) +
  1523. (sizes[i] * firstPart);
  1524. }
  1525. else
  1526. {
  1527. part->size = (part->dataBlock->sizes[i-1] * (1.0 - firstPart)) +
  1528. (part->dataBlock->sizes[i] * firstPart);
  1529. part->size *= part->dataBlock->sizeBias;
  1530. }
  1531. if (mDataBlock->fade_color)
  1532. {
  1533. if (mDataBlock->fade_alpha)
  1534. part->color *= fade_amt;
  1535. else
  1536. {
  1537. part->color.red *= fade_amt;
  1538. part->color.green *= fade_amt;
  1539. part->color.blue *= fade_amt;
  1540. }
  1541. }
  1542. else if (mDataBlock->fade_alpha)
  1543. part->color.alpha *= fade_amt;
  1544. if (mDataBlock->fade_size)
  1545. part->size *= fade_amt;
  1546. break;
  1547. }
  1548. }
  1549. }
  1550. //-----------------------------------------------------------------------------
  1551. // Update particles
  1552. //-----------------------------------------------------------------------------
  1553. // AFX CODE BLOCK (enhanced-emitter) <<
  1554. void ParticleEmitter::update( U32 ms )
  1555. {
  1556. F32 t = F32(ms)/1000.0f; // AFX -- moved outside loop, no need to recalculate this for every particle
  1557. for (Particle* part = part_list_head.next; part != NULL; part = part->next)
  1558. {
  1559. Point3F a = part->acc;
  1560. a -= part->vel * part->dataBlock->dragCoefficient;
  1561. a += mWindVelocity * part->dataBlock->windCoefficient;
  1562. a.z += -9.81f*part->dataBlock->gravityCoefficient; // AFX -- as long as gravity is a constant, this is faster
  1563. part->vel += a * t;
  1564. part->pos_local += part->vel * t;
  1565. // AFX -- allow subclasses to adjust the particle params here
  1566. sub_particleUpdate(part);
  1567. if (part->dataBlock->constrain_pos)
  1568. part->pos = part->pos_local + this->pos_pe;
  1569. else
  1570. part->pos = part->pos_local;
  1571. updateKeyData( part );
  1572. }
  1573. }
  1574. //-----------------------------------------------------------------------------
  1575. // Copy particles to vertex buffer
  1576. //-----------------------------------------------------------------------------
  1577. // structure used for particle sorting.
  1578. struct SortParticle
  1579. {
  1580. Particle* p;
  1581. F32 k;
  1582. };
  1583. // qsort callback function for particle sorting
  1584. S32 QSORT_CALLBACK cmpSortParticles(const void* p1, const void* p2)
  1585. {
  1586. const SortParticle* sp1 = (const SortParticle*)p1;
  1587. const SortParticle* sp2 = (const SortParticle*)p2;
  1588. if (sp2->k > sp1->k)
  1589. return 1;
  1590. else if (sp2->k == sp1->k)
  1591. return 0;
  1592. else
  1593. return -1;
  1594. }
  1595. void ParticleEmitter::copyToVB( const Point3F &camPos, const LinearColorF &ambientColor )
  1596. {
  1597. static Vector<SortParticle> orderedVector(__FILE__, __LINE__);
  1598. PROFILE_START(ParticleEmitter_copyToVB);
  1599. PROFILE_START(ParticleEmitter_copyToVB_Sort);
  1600. // build sorted list of particles (far to near)
  1601. if (mDataBlock->sortParticles)
  1602. {
  1603. orderedVector.clear();
  1604. MatrixF modelview = GFX->getWorldMatrix();
  1605. Point3F viewvec; modelview.getRow(1, &viewvec);
  1606. // add each particle and a distance based sort key to orderedVector
  1607. for (Particle* pp = part_list_head.next; pp != NULL; pp = pp->next)
  1608. {
  1609. orderedVector.increment();
  1610. orderedVector.last().p = pp;
  1611. orderedVector.last().k = mDot(pp->pos, viewvec);
  1612. }
  1613. // qsort the list into far to near ordering
  1614. dQsort(orderedVector.address(), orderedVector.size(), sizeof(SortParticle), cmpSortParticles);
  1615. }
  1616. PROFILE_END();
  1617. static Vector<ParticleVertexType> tempBuff(2048);
  1618. tempBuff.reserve( n_parts*4 + 64); // make sure tempBuff is big enough
  1619. ParticleVertexType *buffPtr = tempBuff.address(); // use direct pointer (faster)
  1620. if (mDataBlock->ribbonParticles)
  1621. {
  1622. PROFILE_START(ParticleEmitter_copyToVB_Ribbon);
  1623. if (mDataBlock->reverseOrder)
  1624. {
  1625. Particle* oldPtr = NULL;
  1626. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr -= 4)
  1627. {
  1628. setupRibbon(partPtr, partPtr->next, oldPtr, camPos, ambientColor, buffPtr);
  1629. oldPtr = partPtr;
  1630. }
  1631. }
  1632. else
  1633. {
  1634. Particle* oldPtr = NULL;
  1635. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr += 4)
  1636. {
  1637. setupRibbon(partPtr, partPtr->next, oldPtr, camPos, ambientColor, buffPtr);
  1638. oldPtr = partPtr;
  1639. }
  1640. }
  1641. PROFILE_END();
  1642. }
  1643. else if (mDataBlock->orientParticles)
  1644. {
  1645. PROFILE_START(ParticleEmitter_copyToVB_Orient);
  1646. if (mDataBlock->reverseOrder)
  1647. {
  1648. buffPtr += 4*(n_parts-1);
  1649. // do sorted-oriented particles
  1650. if (mDataBlock->sortParticles)
  1651. {
  1652. SortParticle* partPtr = orderedVector.address();
  1653. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr-=4 )
  1654. setupOriented(partPtr->p, camPos, ambientColor, buffPtr);
  1655. }
  1656. // do unsorted-oriented particles
  1657. else
  1658. {
  1659. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1660. setupOriented(partPtr, camPos, ambientColor, buffPtr);
  1661. }
  1662. }
  1663. else
  1664. {
  1665. // do sorted-oriented particles
  1666. if (mDataBlock->sortParticles)
  1667. {
  1668. SortParticle* partPtr = orderedVector.address();
  1669. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr+=4 )
  1670. setupOriented(partPtr->p, camPos, ambientColor, buffPtr);
  1671. }
  1672. // do unsorted-oriented particles
  1673. else
  1674. {
  1675. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1676. setupOriented(partPtr, camPos, ambientColor, buffPtr);
  1677. }
  1678. }
  1679. PROFILE_END();
  1680. }
  1681. else if (mDataBlock->alignParticles)
  1682. {
  1683. PROFILE_START(ParticleEmitter_copyToVB_Aligned);
  1684. if (mDataBlock->reverseOrder)
  1685. {
  1686. buffPtr += 4*(n_parts-1);
  1687. // do sorted-oriented particles
  1688. if (mDataBlock->sortParticles)
  1689. {
  1690. SortParticle* partPtr = orderedVector.address();
  1691. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr-=4 )
  1692. setupAligned(partPtr->p, ambientColor, buffPtr);
  1693. }
  1694. // do unsorted-oriented particles
  1695. else
  1696. {
  1697. Particle *partPtr = part_list_head.next;
  1698. for (; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1699. setupAligned(partPtr, ambientColor, buffPtr);
  1700. }
  1701. }
  1702. else
  1703. {
  1704. // do sorted-oriented particles
  1705. if (mDataBlock->sortParticles)
  1706. {
  1707. SortParticle* partPtr = orderedVector.address();
  1708. for (U32 i = 0; i < n_parts; i++, partPtr++, buffPtr+=4 )
  1709. setupAligned(partPtr->p, ambientColor, buffPtr);
  1710. }
  1711. // do unsorted-oriented particles
  1712. else
  1713. {
  1714. Particle *partPtr = part_list_head.next;
  1715. for (; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1716. setupAligned(partPtr, ambientColor, buffPtr);
  1717. }
  1718. }
  1719. PROFILE_END();
  1720. }
  1721. else
  1722. {
  1723. PROFILE_START(ParticleEmitter_copyToVB_NonOriented);
  1724. // somewhat odd ordering so that texture coordinates match the oriented
  1725. // particles
  1726. Point3F basePoints[4];
  1727. basePoints[0] = Point3F(-1.0, 0.0, 1.0);
  1728. basePoints[1] = Point3F(-1.0, 0.0, -1.0);
  1729. basePoints[2] = Point3F( 1.0, 0.0, -1.0);
  1730. basePoints[3] = Point3F( 1.0, 0.0, 1.0);
  1731. MatrixF camView = GFX->getWorldMatrix();
  1732. camView.transpose(); // inverse - this gets the particles facing camera
  1733. if (mDataBlock->reverseOrder)
  1734. {
  1735. buffPtr += 4*(n_parts-1);
  1736. // do sorted-billboard particles
  1737. if (mDataBlock->sortParticles)
  1738. {
  1739. SortParticle *partPtr = orderedVector.address();
  1740. for( U32 i=0; i<n_parts; i++, partPtr++, buffPtr-=4 )
  1741. setupBillboard( partPtr->p, basePoints, camView, ambientColor, buffPtr );
  1742. }
  1743. // do unsorted-billboard particles
  1744. else
  1745. {
  1746. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr-=4)
  1747. setupBillboard( partPtr, basePoints, camView, ambientColor, buffPtr );
  1748. }
  1749. }
  1750. else
  1751. {
  1752. // do sorted-billboard particles
  1753. if (mDataBlock->sortParticles)
  1754. {
  1755. SortParticle *partPtr = orderedVector.address();
  1756. for( U32 i=0; i<n_parts; i++, partPtr++, buffPtr+=4 )
  1757. setupBillboard( partPtr->p, basePoints, camView, ambientColor, buffPtr );
  1758. }
  1759. // do unsorted-billboard particles
  1760. else
  1761. {
  1762. for (Particle* partPtr = part_list_head.next; partPtr != NULL; partPtr = partPtr->next, buffPtr+=4)
  1763. setupBillboard( partPtr, basePoints, camView, ambientColor, buffPtr );
  1764. }
  1765. }
  1766. PROFILE_END();
  1767. }
  1768. PROFILE_START(ParticleEmitter_copyToVB_LockCopy);
  1769. // create new VB if emitter size grows
  1770. if( !mVertBuff || n_parts > mCurBuffSize )
  1771. {
  1772. mCurBuffSize = n_parts;
  1773. mVertBuff.set( GFX, n_parts * 4, GFXBufferTypeDynamic );
  1774. }
  1775. // lock and copy tempBuff to video RAM
  1776. ParticleVertexType *verts = mVertBuff.lock();
  1777. dMemcpy( verts, tempBuff.address(), n_parts * 4 * sizeof(ParticleVertexType) );
  1778. mVertBuff.unlock();
  1779. PROFILE_END();
  1780. PROFILE_END();
  1781. }
  1782. //-----------------------------------------------------------------------------
  1783. // Set up particle for billboard style render
  1784. //-----------------------------------------------------------------------------
  1785. void ParticleEmitter::setupBillboard( Particle *part,
  1786. Point3F *basePts,
  1787. const MatrixF &camView,
  1788. const LinearColorF &ambientColor,
  1789. ParticleVertexType *lVerts )
  1790. {
  1791. F32 width = part->size * 0.5f;
  1792. F32 spinAngle = part->spinSpeed * part->currentAge * AgedSpinToRadians;
  1793. F32 sy, cy;
  1794. mSinCos(spinAngle, sy, cy);
  1795. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1796. LinearColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1797. // fill four verts, use macro and unroll loop
  1798. #define fillVert(){ \
  1799. lVerts->point.x = cy * basePts->x - sy * basePts->z; \
  1800. lVerts->point.y = 0.0f; \
  1801. lVerts->point.z = sy * basePts->x + cy * basePts->z; \
  1802. camView.mulV( lVerts->point ); \
  1803. lVerts->point *= width; \
  1804. lVerts->point += part->pos; \
  1805. lVerts->color = partCol.toColorI(); } \
  1806. // Here we deal with UVs for animated particle (billboard)
  1807. if (part->dataBlock->animateTexture && !part->dataBlock->animTexFrames.empty())
  1808. {
  1809. S32 fm = (S32)(part->currentAge*(1.0/1000.0)*part->dataBlock->framesPerSec);
  1810. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1811. S32 uv[4];
  1812. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1813. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1814. uv[2] = uv[1] + 1;
  1815. uv[3] = uv[0] + 1;
  1816. fillVert();
  1817. // Here and below, we copy UVs from particle datablock's current frame's UVs (billboard)
  1818. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1819. ++lVerts;
  1820. ++basePts;
  1821. fillVert();
  1822. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1823. ++lVerts;
  1824. ++basePts;
  1825. fillVert();
  1826. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  1827. ++lVerts;
  1828. ++basePts;
  1829. fillVert();
  1830. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  1831. ++lVerts;
  1832. ++basePts;
  1833. return;
  1834. }
  1835. fillVert();
  1836. // Here and below, we copy UVs from particle datablock's texCoords (billboard)
  1837. lVerts->texCoord = part->dataBlock->texCoords[0];
  1838. ++lVerts;
  1839. ++basePts;
  1840. fillVert();
  1841. lVerts->texCoord = part->dataBlock->texCoords[1];
  1842. ++lVerts;
  1843. ++basePts;
  1844. fillVert();
  1845. lVerts->texCoord = part->dataBlock->texCoords[2];
  1846. ++lVerts;
  1847. ++basePts;
  1848. fillVert();
  1849. lVerts->texCoord = part->dataBlock->texCoords[3];
  1850. ++lVerts;
  1851. ++basePts;
  1852. }
  1853. //-----------------------------------------------------------------------------
  1854. // Set up oriented particle
  1855. //-----------------------------------------------------------------------------
  1856. void ParticleEmitter::setupOriented( Particle *part,
  1857. const Point3F &camPos,
  1858. const LinearColorF &ambientColor,
  1859. ParticleVertexType *lVerts )
  1860. {
  1861. Point3F dir;
  1862. if( mDataBlock->orientOnVelocity )
  1863. {
  1864. // don't render oriented particle if it has no velocity
  1865. if( part->vel.magnitudeSafe() == 0.0 ) return;
  1866. dir = part->vel;
  1867. }
  1868. else
  1869. {
  1870. dir = part->orientDir;
  1871. }
  1872. Point3F dirFromCam = part->pos - camPos;
  1873. Point3F crossDir;
  1874. mCross( dirFromCam, dir, &crossDir );
  1875. crossDir.normalize();
  1876. dir.normalize();
  1877. F32 width = part->size * 0.5f;
  1878. dir *= width;
  1879. crossDir *= width;
  1880. Point3F start = part->pos - dir;
  1881. Point3F end = part->pos + dir;
  1882. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1883. LinearColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1884. const ColorI color = partCol.toColorI();
  1885. // Here we deal with UVs for animated particle (oriented)
  1886. if (part->dataBlock->animateTexture && !part->dataBlock->animTexFrames.empty())
  1887. {
  1888. // Let particle compute the UV indices for current frame
  1889. S32 fm = (S32)(part->currentAge*(1.0f/1000.0f)*part->dataBlock->framesPerSec);
  1890. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1891. S32 uv[4];
  1892. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1893. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1894. uv[2] = uv[1] + 1;
  1895. uv[3] = uv[0] + 1;
  1896. lVerts->point = start + crossDir;
  1897. lVerts->color = color;
  1898. // Here and below, we copy UVs from particle datablock's current frame's UVs (oriented)
  1899. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1900. ++lVerts;
  1901. lVerts->point = start - crossDir;
  1902. lVerts->color = color;
  1903. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1904. ++lVerts;
  1905. lVerts->point = end - crossDir;
  1906. lVerts->color = color;
  1907. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  1908. ++lVerts;
  1909. lVerts->point = end + crossDir;
  1910. lVerts->color = color;
  1911. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  1912. ++lVerts;
  1913. return;
  1914. }
  1915. lVerts->point = start + crossDir;
  1916. lVerts->color = color;
  1917. // Here and below, we copy UVs from particle datablock's texCoords (oriented)
  1918. lVerts->texCoord = part->dataBlock->texCoords[1];
  1919. ++lVerts;
  1920. lVerts->point = start - crossDir;
  1921. lVerts->color = color;
  1922. lVerts->texCoord = part->dataBlock->texCoords[2];
  1923. ++lVerts;
  1924. lVerts->point = end - crossDir;
  1925. lVerts->color = color;
  1926. lVerts->texCoord = part->dataBlock->texCoords[3];
  1927. ++lVerts;
  1928. lVerts->point = end + crossDir;
  1929. lVerts->color = color;
  1930. lVerts->texCoord = part->dataBlock->texCoords[0];
  1931. ++lVerts;
  1932. }
  1933. void ParticleEmitter::setupAligned( const Particle *part,
  1934. const LinearColorF &ambientColor,
  1935. ParticleVertexType *lVerts )
  1936. {
  1937. // The aligned direction will always be normalized.
  1938. Point3F dir = mDataBlock->alignDirection;
  1939. // Find a right vector for this particle.
  1940. Point3F right;
  1941. if (mFabs(dir.y) > mFabs(dir.z))
  1942. mCross(Point3F::UnitZ, dir, &right);
  1943. else
  1944. mCross(Point3F::UnitY, dir, &right);
  1945. right.normalize();
  1946. // If we have a spin velocity.
  1947. if ( !mIsZero( part->spinSpeed ) )
  1948. {
  1949. F32 spinAngle = part->spinSpeed * part->currentAge * AgedSpinToRadians;
  1950. // This is an inline quaternion vector rotation which
  1951. // is faster that QuatF.mulP(), but generates different
  1952. // results and hence cannot replace it right now.
  1953. F32 sin, qw;
  1954. mSinCos( spinAngle * 0.5f, sin, qw );
  1955. F32 qx = dir.x * sin;
  1956. F32 qy = dir.y * sin;
  1957. F32 qz = dir.z * sin;
  1958. F32 vx = ( right.x * qw ) + ( right.z * qy ) - ( right.y * qz );
  1959. F32 vy = ( right.y * qw ) + ( right.x * qz ) - ( right.z * qx );
  1960. F32 vz = ( right.z * qw ) + ( right.y * qx ) - ( right.x * qy );
  1961. F32 vw = ( right.x * qx ) + ( right.y * qy ) + ( right.z * qz );
  1962. right.x = ( qw * vx ) + ( qx * vw ) + ( qy * vz ) - ( qz * vy );
  1963. right.y = ( qw * vy ) + ( qy * vw ) + ( qz * vx ) - ( qx * vz );
  1964. right.z = ( qw * vz ) + ( qz * vw ) + ( qx * vy ) - ( qy * vx );
  1965. }
  1966. // Get the cross vector.
  1967. Point3F cross;
  1968. mCross(right, dir, &cross);
  1969. F32 width = part->size * 0.5f;
  1970. right *= width;
  1971. cross *= width;
  1972. Point3F start = part->pos - right;
  1973. Point3F end = part->pos + right;
  1974. const F32 ambientLerp = mClampF( mDataBlock->ambientFactor, 0.0f, 1.0f );
  1975. LinearColorF partCol = mLerp( part->color, ( part->color * ambientColor ), ambientLerp );
  1976. const ColorI color = partCol.toColorI();
  1977. // Here we deal with UVs for animated particle
  1978. if (part->dataBlock->animateTexture && !part->dataBlock->animTexFrames.empty())
  1979. {
  1980. // Let particle compute the UV indices for current frame
  1981. S32 fm = (S32)(part->currentAge*(1.0f/1000.0f)*part->dataBlock->framesPerSec);
  1982. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  1983. S32 uv[4];
  1984. uv[0] = fm_tile + fm_tile/part->dataBlock->animTexTiling.x;
  1985. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  1986. uv[2] = uv[1] + 1;
  1987. uv[3] = uv[0] + 1;
  1988. lVerts->point = start + cross;
  1989. lVerts->color = color;
  1990. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  1991. ++lVerts;
  1992. lVerts->point = start - cross;
  1993. lVerts->color = color;
  1994. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  1995. ++lVerts;
  1996. lVerts->point = end - cross;
  1997. lVerts->color = color;
  1998. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  1999. ++lVerts;
  2000. lVerts->point = end + cross;
  2001. lVerts->color = color;
  2002. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  2003. ++lVerts;
  2004. }
  2005. else
  2006. {
  2007. // Here and below, we copy UVs from particle datablock's texCoords
  2008. lVerts->point = start + cross;
  2009. lVerts->color = color;
  2010. lVerts->texCoord = part->dataBlock->texCoords[0];
  2011. ++lVerts;
  2012. lVerts->point = start - cross;
  2013. lVerts->color = color;
  2014. lVerts->texCoord = part->dataBlock->texCoords[1];
  2015. ++lVerts;
  2016. lVerts->point = end - cross;
  2017. lVerts->color = color;
  2018. lVerts->texCoord = part->dataBlock->texCoords[2];
  2019. ++lVerts;
  2020. lVerts->point = end + cross;
  2021. lVerts->color = color;
  2022. lVerts->texCoord = part->dataBlock->texCoords[3];
  2023. ++lVerts;
  2024. }
  2025. }
  2026. void ParticleEmitter::setupRibbon(Particle *part,
  2027. Particle *next,
  2028. Particle *prev,
  2029. const Point3F &camPos,
  2030. const LinearColorF &ambientColor,
  2031. ParticleVertexType *lVerts)
  2032. {
  2033. Point3F dir, dirFromCam;
  2034. Point3F crossDir, crossDirNext;
  2035. Point3F start, end;
  2036. LinearColorF prevCol;
  2037. static Point3F crossDirPrev;
  2038. static int position;
  2039. static F32 alphaMod, alphaModEnd;
  2040. const F32 ambientLerp = mClampF(mDataBlock->ambientFactor, 0.0f, 1.0f);
  2041. LinearColorF partCol = mLerp(part->color, (part->color * ambientColor), ambientLerp);
  2042. if (part->currentAge > part->totalLifetime)
  2043. {
  2044. F32 alphaDeath = (part->currentAge - part->totalLifetime) / 200.0f;
  2045. if (alphaDeath > 1.0f)
  2046. alphaDeath = 1.0f;
  2047. alphaDeath = 1.0f - alphaDeath;
  2048. partCol.alpha *= alphaDeath;
  2049. }
  2050. start = part->pos;
  2051. position++;
  2052. if (next == NULL && prev == NULL) {
  2053. // a ribbon of just one particle
  2054. position = 0;
  2055. if (part->vel.magnitudeSafe() == 0.0)
  2056. dir = part->orientDir;
  2057. else
  2058. dir = part->vel;
  2059. dir.normalize();
  2060. dirFromCam = part->pos - camPos;
  2061. mCross(dirFromCam, dir, &crossDir);
  2062. crossDir.normalize();
  2063. crossDir = crossDir * part->size * 0.5;
  2064. crossDirPrev = crossDir;
  2065. partCol.alpha = 0.0f;
  2066. prevCol = partCol;
  2067. end = part->pos;
  2068. }
  2069. else if (next == NULL && prev != NULL)
  2070. {
  2071. // last link in the chain, also the oldest
  2072. dir = part->pos - prev->pos;
  2073. dir.normalize();
  2074. dirFromCam = part->pos - camPos;
  2075. mCross(dirFromCam, dir, &crossDir);
  2076. crossDir.normalize();
  2077. crossDir = crossDir * part->size * 0.5;
  2078. end = prev->pos;
  2079. partCol.alpha = 0.0f;
  2080. prevCol = mLerp(prev->color, (prev->color * ambientColor), ambientLerp);
  2081. prevCol.alpha *= alphaModEnd;
  2082. }
  2083. else if (next != NULL && prev == NULL)
  2084. {
  2085. // first link in chain, newest particle
  2086. // since we draw from current to previous, this one isn't drawn
  2087. position = 0;
  2088. dir = next->pos - part->pos;
  2089. dir.normalize();
  2090. dirFromCam = part->pos - camPos;
  2091. mCross(dirFromCam, dir, &crossDir);
  2092. crossDir.normalize();
  2093. crossDir = crossDir * part->size * 0.5f;
  2094. crossDirPrev = crossDir;
  2095. partCol.alpha = 0.0f;
  2096. prevCol = partCol;
  2097. alphaModEnd = 0.0f;
  2098. end = part->pos;
  2099. }
  2100. else
  2101. {
  2102. // middle of chain
  2103. dir = next->pos - prev->pos;
  2104. dir.normalize();
  2105. dirFromCam = part->pos - camPos;
  2106. mCross(dirFromCam, dir, &crossDir);
  2107. crossDir.normalize();
  2108. crossDir = crossDir * part->size * 0.5;
  2109. prevCol = mLerp(prev->color, (prev->color * ambientColor), ambientLerp);
  2110. if (position == 1)
  2111. {
  2112. // the second particle has a few tweaks for alpha, to smoothly match the first particle
  2113. // we only want to do this once when the particle first fades in, and avoid a strobing effect
  2114. alphaMod = (float(part->currentAge) / float(part->currentAge - prev->currentAge)) - 1.0f;
  2115. if (alphaMod > 1.0f)
  2116. alphaMod = 1.0f;
  2117. partCol.alpha *= alphaMod;
  2118. prevCol.alpha = 0.0f;
  2119. if (next->next == NULL)
  2120. alphaModEnd = alphaMod;
  2121. //Con::printf("alphaMod: %f", alphaMod );
  2122. }
  2123. else if (position == 2)
  2124. {
  2125. prevCol.alpha *= alphaMod;
  2126. alphaMod = 0.0f;
  2127. }
  2128. if (next->next == NULL && position > 1)
  2129. {
  2130. // next to last particle, start the fade out
  2131. alphaModEnd = (float(next->totalLifetime - next->currentAge)) / (float(part->totalLifetime - part->currentAge));
  2132. alphaModEnd *= 2.0f;
  2133. if (alphaModEnd > 1.0f)
  2134. alphaModEnd = 1.0f;
  2135. partCol.alpha *= alphaModEnd;
  2136. //Con::printf("alphaMod: %f Lifetime: %d Age: %d", alphaMod, part->totalLifetime, part->currentAge );
  2137. }
  2138. end = prev->pos;
  2139. }
  2140. ColorI pCol = partCol.toColorI();
  2141. // Here we deal with UVs for animated particle (oriented)
  2142. if (part->dataBlock->animateTexture && !part->dataBlock->animTexFrames.empty())
  2143. {
  2144. // Let particle compute the UV indices for current frame
  2145. S32 fm = (S32)(part->currentAge*(1.0f / 1000.0f)*part->dataBlock->framesPerSec);
  2146. U8 fm_tile = part->dataBlock->animTexFrames[fm % part->dataBlock->numFrames];
  2147. S32 uv[4];
  2148. uv[0] = fm_tile + fm_tile / part->dataBlock->animTexTiling.x;
  2149. uv[1] = uv[0] + (part->dataBlock->animTexTiling.x + 1);
  2150. uv[2] = uv[1] + 1;
  2151. uv[3] = uv[0] + 1;
  2152. lVerts->point = start + crossDir;
  2153. lVerts->color = pCol;
  2154. // Here and below, we copy UVs from particle datablock's current frame's UVs (oriented)
  2155. lVerts->texCoord = part->dataBlock->animTexUVs[uv[0]];
  2156. ++lVerts;
  2157. lVerts->point = start - crossDir;
  2158. lVerts->color = pCol;
  2159. lVerts->texCoord = part->dataBlock->animTexUVs[uv[1]];
  2160. ++lVerts;
  2161. lVerts->point = end - crossDirPrev;
  2162. lVerts->color = pCol;
  2163. lVerts->texCoord = part->dataBlock->animTexUVs[uv[2]];
  2164. ++lVerts;
  2165. lVerts->point = end + crossDirPrev;
  2166. lVerts->color = pCol;
  2167. lVerts->texCoord = part->dataBlock->animTexUVs[uv[3]];
  2168. ++lVerts;
  2169. crossDirPrev = crossDir;
  2170. return;
  2171. }
  2172. lVerts->point = start + crossDir;
  2173. lVerts->color = pCol;
  2174. // Here and below, we copy UVs from particle datablock's texCoords (oriented)
  2175. lVerts->texCoord = part->dataBlock->texCoords[0];
  2176. ++lVerts;
  2177. lVerts->point = start - crossDir;
  2178. lVerts->color = pCol;
  2179. lVerts->texCoord = part->dataBlock->texCoords[1];
  2180. ++lVerts;
  2181. lVerts->point = end - crossDirPrev;
  2182. lVerts->color = pCol;
  2183. lVerts->texCoord = part->dataBlock->texCoords[2];
  2184. ++lVerts;
  2185. lVerts->point = end + crossDirPrev;
  2186. lVerts->color = pCol;
  2187. lVerts->texCoord = part->dataBlock->texCoords[3];
  2188. ++lVerts;
  2189. crossDirPrev = crossDir;
  2190. }
  2191. bool ParticleEmitterData::reload()
  2192. {
  2193. // Clear out current particle data.
  2194. dataBlockIds.clear();
  2195. particleDataBlocks.clear();
  2196. // Parse out particle string.
  2197. U32 numUnits = 0;
  2198. if( particleString )
  2199. numUnits = StringUnit::getUnitCount( particleString, " \t" );
  2200. if( !particleString || !particleString[ 0 ] || !numUnits )
  2201. {
  2202. Con::errorf( "ParticleEmitterData(%s) has an empty particles string.", getName() );
  2203. mReloadSignal.trigger();
  2204. return false;
  2205. }
  2206. for( U32 i = 0; i < numUnits; ++ i )
  2207. {
  2208. const char* dbName = StringUnit::getUnit( particleString, i, " \t" );
  2209. ParticleData* data = NULL;
  2210. if( !Sim::findObject( dbName, data ) )
  2211. {
  2212. Con::errorf( ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find particle datablock: %s", getName(), dbName );
  2213. continue;
  2214. }
  2215. particleDataBlocks.push_back( data );
  2216. dataBlockIds.push_back( data->getId() );
  2217. }
  2218. // Check that we actually found some particle datablocks.
  2219. if( particleDataBlocks.empty() )
  2220. {
  2221. Con::errorf( ConsoleLogEntry::General, "ParticleEmitterData(%s) unable to find any particle datablocks", getName() );
  2222. mReloadSignal.trigger();
  2223. return false;
  2224. }
  2225. // Trigger reload.
  2226. mReloadSignal.trigger();
  2227. return true;
  2228. }
  2229. DefineEngineMethod(ParticleEmitterData, reload, void,(),,
  2230. "Reloads the ParticleData datablocks and other fields used by this emitter.\n"
  2231. "@tsexample\n"
  2232. "// Get the editor's current particle emitter\n"
  2233. "%emitter = PE_EmitterEditor.currEmitter\n\n"
  2234. "// Change a field value\n"
  2235. "%emitter.setFieldValue( %propertyField, %value );\n\n"
  2236. "// Reload this emitter\n"
  2237. "%emitter.reload();\n"
  2238. "@endtsexample\n")
  2239. {
  2240. object->reload();
  2241. }
  2242. void ParticleEmitter::emitParticlesExt(const MatrixF& xfm, const Point3F& point,
  2243. const Point3F& velocity, const U32 numMilliseconds)
  2244. {
  2245. if (mDataBlock->use_emitter_xfm)
  2246. {
  2247. Point3F zero_point(0.0f, 0.0f, 0.0f);
  2248. this->pos_pe = zero_point;
  2249. this->setTransform(xfm);
  2250. Point3F axis(0.0,0.0,1.0);
  2251. xfm.mulV(axis);
  2252. emitParticles(zero_point, true, axis, velocity, numMilliseconds);
  2253. }
  2254. else
  2255. {
  2256. this->pos_pe = point;
  2257. Point3F axis(0.0,0.0,1.0);
  2258. xfm.mulV(axis);
  2259. emitParticles(point, true, axis, velocity, numMilliseconds);
  2260. }
  2261. }
  2262. void ParticleEmitter::setForcedObjBox(Box3F& box)
  2263. {
  2264. mObjBox = box;
  2265. forced_bbox = true;
  2266. #if defined(AFX_CAP_PARTICLE_POOLS)
  2267. if (pool)
  2268. pool->updatePoolBBox(this);
  2269. #endif
  2270. }
  2271. void ParticleEmitter::setSortPriority(S8 priority)
  2272. {
  2273. sort_priority = (priority == 0) ? 1 : priority;
  2274. #if defined(AFX_CAP_PARTICLE_POOLS)
  2275. if (pool)
  2276. pool->setSortPriority(sort_priority);
  2277. #endif
  2278. }