particle.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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 "particle.h"
  27. #include "console/consoleTypes.h"
  28. #include "console/typeValidators.h"
  29. #include "core/stream/bitStream.h"
  30. #include "math/mRandom.h"
  31. #include "math/mathIO.h"
  32. #include "console/engineAPI.h"
  33. IMPLEMENT_CO_DATABLOCK_V1( ParticleData );
  34. ConsoleDocClass( ParticleData,
  35. "@brief Contains information for how specific particles should look and react "
  36. "including particle colors, particle imagemap, acceleration value for individual "
  37. "particles and spin information.\n"
  38. "@tsexample\n"
  39. "datablock ParticleData( GLWaterExpSmoke )\n"
  40. "{\n"
  41. " textureName = \"art/shapes/particles/smoke\";\n"
  42. " dragCoefficient = 0.4;\n"
  43. " gravityCoefficient = -0.25;\n"
  44. " inheritedVelFactor = 0.025;\n"
  45. " constantAcceleration = -1.1;\n"
  46. " lifetimeMS = 1250;\n"
  47. " lifetimeVarianceMS = 0;\n"
  48. " useInvAlpha = false;\n"
  49. " spinSpeed = 1;\n"
  50. " spinRandomMin = -200.0;\n"
  51. " spinRandomMax = 200.0;\n\n"
  52. " colors[0] = \"0.1 0.1 1.0 1.0\";\n"
  53. " colors[1] = \"0.4 0.4 1.0 1.0\";\n"
  54. " colors[2] = \"0.4 0.4 1.0 0.0\";\n\n"
  55. " sizes[0] = 2.0;\n"
  56. " sizes[1] = 6.0;\n"
  57. " sizes[2] = 2.0;\n\n"
  58. " times[0] = 0.0;\n"
  59. " times[1] = 0.5;\n"
  60. " times[2] = 1.0;\n"
  61. "};\n"
  62. "@endtsexample\n"
  63. "@ingroup FX\n"
  64. "@see ParticleEmitter\n"
  65. "@see ParticleEmitterData\n"
  66. "@see ParticleEmitterNode\n"
  67. );
  68. static const F32 sgDefaultWindCoefficient = 0.0f;
  69. static const F32 sgDefaultConstantAcceleration = 0.f;
  70. static const F32 sgDefaultSpinSpeed = 1.f;
  71. static const F32 sgDefaultSpinRandomMin = 0.f;
  72. static const F32 sgDefaultSpinRandomMax = 0.f;
  73. static const F32 sgDefaultSpinBias = 1.0f;
  74. static const F32 sgDefaultSizeBias = 1.0f;
  75. //-----------------------------------------------------------------------------
  76. // Constructor
  77. //-----------------------------------------------------------------------------
  78. ParticleData::ParticleData()
  79. {
  80. dragCoefficient = 0.0f;
  81. windCoefficient = sgDefaultWindCoefficient;
  82. gravityCoefficient = 0.0f;
  83. inheritedVelFactor = 0.0f;
  84. constantAcceleration = sgDefaultConstantAcceleration;
  85. lifetimeMS = 1000;
  86. lifetimeVarianceMS = 0;
  87. spinSpeed = sgDefaultSpinSpeed;
  88. spinRandomMin = sgDefaultSpinRandomMin;
  89. spinRandomMax = sgDefaultSpinRandomMax;
  90. useInvAlpha = false;
  91. animateTexture = false;
  92. numFrames = 1;
  93. framesPerSec = numFrames;
  94. S32 i;
  95. for( i=0; i<PDC_NUM_KEYS; i++ )
  96. {
  97. colors[i].set( 1.0, 1.0, 1.0, 1.0 );
  98. sizes[i] = 1.0;
  99. }
  100. times[0] = 0.0f;
  101. times[1] = 1.0f;
  102. for (i = 2; i < PDC_NUM_KEYS; i++)
  103. times[i] = -1.0f;
  104. texCoords[0].set(0.0,0.0); // texture coords at 4 corners
  105. texCoords[1].set(0.0,1.0); // of particle quad
  106. texCoords[2].set(1.0,1.0); // (defaults to entire particle)
  107. texCoords[3].set(1.0,0.0);
  108. animTexTiling.set(0,0); // tiling dimensions
  109. animTexFramesString = NULL; // string of animation frame indices
  110. animTexUVs = NULL; // array of tile vertex UVs
  111. INIT_ASSET(Texture);
  112. INIT_ASSET(TextureExt);
  113. constrain_pos = false;
  114. start_angle = 0.0f;
  115. angle_variance = 0.0f;
  116. sizeBias = sgDefaultSizeBias;
  117. spinBias = sgDefaultSpinBias;
  118. randomizeSpinDir = false;
  119. }
  120. //-----------------------------------------------------------------------------
  121. // Destructor
  122. //-----------------------------------------------------------------------------
  123. FRangeValidator dragCoefFValidator(0.f, 5.f);
  124. FRangeValidator gravCoefFValidator(-10.f, 10.f);
  125. FRangeValidator spinRandFValidator(-1000.f, 1000.f);
  126. //-----------------------------------------------------------------------------
  127. // initPersistFields
  128. //-----------------------------------------------------------------------------
  129. void ParticleData::initPersistFields()
  130. {
  131. addFieldV( "dragCoefficient", TYPEID< F32 >(), Offset(dragCoefficient, ParticleData), &dragCoefFValidator,
  132. "Particle physics drag amount." );
  133. addField( "windCoefficient", TYPEID< F32 >(), Offset(windCoefficient, ParticleData),
  134. "Strength of wind on the particles." );
  135. addFieldV( "gravityCoefficient", TYPEID< F32 >(), Offset(gravityCoefficient, ParticleData), &gravCoefFValidator,
  136. "Strength of gravity on the particles." );
  137. addFieldV( "inheritedVelFactor", TYPEID< F32 >(), Offset(inheritedVelFactor, ParticleData), &CommonValidators::NormalizedFloat,
  138. "Amount of emitter velocity to add to particle initial velocity." );
  139. addField( "constantAcceleration", TYPEID< F32 >(), Offset(constantAcceleration, ParticleData),
  140. "Constant acceleration to apply to this particle." );
  141. addField( "lifetimeMS", TYPEID< S32 >(), Offset(lifetimeMS, ParticleData),
  142. "Time in milliseconds before this particle is destroyed." );
  143. addField( "lifetimeVarianceMS", TYPEID< S32 >(), Offset(lifetimeVarianceMS, ParticleData),
  144. "Variance in lifetime of particle, from 0 - lifetimeMS." );
  145. addField( "spinSpeed", TYPEID< F32 >(), Offset(spinSpeed, ParticleData),
  146. "Speed at which to spin the particle." );
  147. addFieldV( "spinRandomMin", TYPEID< F32 >(), Offset(spinRandomMin, ParticleData), &spinRandFValidator,
  148. "Minimum allowed spin speed of this particle, between -1000 and spinRandomMax." );
  149. addFieldV( "spinRandomMax", TYPEID< F32 >(), Offset(spinRandomMax, ParticleData), &spinRandFValidator,
  150. "Maximum allowed spin speed of this particle, between spinRandomMin and 1000." );
  151. addField( "useInvAlpha", TYPEID< bool >(), Offset(useInvAlpha, ParticleData),
  152. "@brief Controls how particles blend with the scene.\n\n"
  153. "If true, particles blend like ParticleBlendStyle NORMAL, if false, "
  154. "blend like ParticleBlendStyle ADDITIVE.\n"
  155. "@note If ParticleEmitterData::blendStyle is set, it will override this value." );
  156. addField( "animateTexture", TYPEID< bool >(), Offset(animateTexture, ParticleData),
  157. "If true, allow the particle texture to be an animated sprite." );
  158. addField( "framesPerSec", TYPEID< S32 >(), Offset(framesPerSec, ParticleData),
  159. "If animateTexture is true, this defines the frames per second of the "
  160. "sprite animation." );
  161. addField( "textureCoords", TYPEID< Point2F >(), Offset(texCoords, ParticleData), 4,
  162. "@brief 4 element array defining the UV coords into textureName to use "
  163. "for this particle.\n\n"
  164. "Coords should be set for the first tile only when using animTexTiling; "
  165. "coordinates for other tiles will be calculated automatically. \"0 0\" is "
  166. "top left and \"1 1\" is bottom right." );
  167. addField( "animTexTiling", TYPEID< Point2I >(), Offset(animTexTiling, ParticleData),
  168. "@brief The number of frames, in rows and columns stored in textureName "
  169. "(when animateTexture is true).\n\n"
  170. "A maximum of 256 frames can be stored in a single texture when using "
  171. "animTexTiling. Value should be \"NumColumns NumRows\", for example \"4 4\"." );
  172. addField( "animTexFrames", TYPEID< StringTableEntry >(), Offset(animTexFramesString,ParticleData),
  173. "@brief A list of frames and/or frame ranges to use for particle "
  174. "animation if animateTexture is true.\n\n"
  175. "Each frame token must be separated by whitespace. A frame token must be "
  176. "a positive integer frame number or a range of frame numbers separated "
  177. "with a '-'. The range separator, '-', cannot have any whitspace around "
  178. "it.\n\n"
  179. "Ranges can be specified to move through the frames in reverse as well "
  180. "as forward (eg. 19-14). Frame numbers exceeding the number of tiles will "
  181. "wrap.\n"
  182. "@tsexample\n"
  183. "animTexFrames = \"0-16 20 19 18 17 31-21\";\n"
  184. "@endtsexample\n" );
  185. addProtectedField( "textureName", TYPEID< StringTableEntry >(), Offset(mTextureName, ParticleData), _setTextureData, defaultProtectedGetFn,
  186. "Texture file to use for this particle.", AbstractClassRep::FIELD_HideInInspectors );
  187. addField( "animTexName", TYPEID< StringTableEntry >(), Offset(mTextureName, ParticleData),
  188. "@brief Texture file to use for this particle if animateTexture is true.\n\n"
  189. "Deprecated. Use textureName instead.", AbstractClassRep::FIELD_HideInInspectors);
  190. INITPERSISTFIELD_IMAGEASSET(Texture, ParticleData, "Texture to use for this particle.");
  191. // Interpolation variables
  192. addField( "colors", TYPEID< LinearColorF >(), Offset(colors, ParticleData), PDC_NUM_KEYS,
  193. "@brief Particle RGBA color keyframe values.\n\n"
  194. "The particle color will linearly interpolate between the color/time keys "
  195. "over the lifetime of the particle." );
  196. addProtectedField( "sizes", TYPEID< F32 >(), Offset(sizes, ParticleData), &protectedSetSizes,
  197. &defaultProtectedGetFn, PDC_NUM_KEYS,
  198. "@brief Particle size keyframe values.\n\n"
  199. "The particle size will linearly interpolate between the size/time keys "
  200. "over the lifetime of the particle." );
  201. addProtectedField( "times", TYPEID< F32 >(), Offset(times, ParticleData), &protectedSetTimes,
  202. &defaultProtectedGetFn, PDC_NUM_KEYS,
  203. "@brief Time keys used with the colors and sizes keyframes.\n\n"
  204. "Values are from 0.0 (particle creation) to 1.0 (end of lifespace)." );
  205. addGroup("AFX");
  206. addProtectedField("textureExtName", TypeFilename, Offset(mTextureExtName, ParticleData), _setTextureExtData, &defaultProtectedGetFn, "", AbstractClassRep::FIELD_HideInInspectors);
  207. INITPERSISTFIELD_IMAGEASSET(TextureExt, ParticleData, "");
  208. addField("constrainPos", TypeBool, Offset(constrain_pos, ParticleData));
  209. addField("angle", TypeF32, Offset(start_angle, ParticleData));
  210. addField("angleVariance", TypeF32, Offset(angle_variance, ParticleData));
  211. addField("sizeBias", TypeF32, Offset(sizeBias, ParticleData));
  212. addField("spinBias", TypeF32, Offset(spinBias, ParticleData));
  213. addField("randomizeSpinDir", TypeBool, Offset(randomizeSpinDir, ParticleData));
  214. endGroup("AFX");
  215. Parent::initPersistFields();
  216. }
  217. //-----------------------------------------------------------------------------
  218. // Pack data
  219. //-----------------------------------------------------------------------------
  220. void ParticleData::packData(BitStream* stream)
  221. {
  222. Parent::packData(stream);
  223. stream->writeFloat(dragCoefficient / 5, 10);
  224. if( stream->writeFlag(windCoefficient != sgDefaultWindCoefficient ) )
  225. stream->write(windCoefficient);
  226. if (stream->writeFlag(gravityCoefficient != 0.0f))
  227. stream->writeSignedFloat(gravityCoefficient / 10, 12);
  228. stream->writeFloat(inheritedVelFactor, 9);
  229. if( stream->writeFlag( constantAcceleration != sgDefaultConstantAcceleration ) )
  230. stream->write(constantAcceleration);
  231. stream->write( lifetimeMS );
  232. stream->write( lifetimeVarianceMS );
  233. if( stream->writeFlag( spinSpeed != sgDefaultSpinSpeed ) )
  234. stream->write(spinSpeed);
  235. if(stream->writeFlag(spinRandomMin != sgDefaultSpinRandomMin || spinRandomMax != sgDefaultSpinRandomMax))
  236. {
  237. stream->writeInt((S32)(spinRandomMin + 1000), 11);
  238. stream->writeInt((S32)(spinRandomMax + 1000), 11);
  239. }
  240. if(stream->writeFlag(spinBias != sgDefaultSpinBias))
  241. stream->write(spinBias);
  242. stream->writeFlag(randomizeSpinDir);
  243. stream->writeFlag(useInvAlpha);
  244. S32 i, count;
  245. // see how many frames there are:
  246. for(count = 0; count < ParticleData::PDC_NUM_KEYS-1; count++)
  247. if(times[count] >= 1)
  248. break;
  249. count++;
  250. // An extra bit is needed for 8 keys.
  251. stream->writeInt(count-1, 3);
  252. for( i=0; i<count; i++ )
  253. {
  254. stream->writeFloat( colors[i].red, 7);
  255. stream->writeFloat( colors[i].green, 7);
  256. stream->writeFloat( colors[i].blue, 7);
  257. stream->writeFloat( colors[i].alpha, 7);
  258. // AFX bits raised from 14 to 16 to allow larger sizes
  259. stream->writeFloat( sizes[i]/MaxParticleSize, 16);
  260. stream->writeFloat( times[i], 8);
  261. }
  262. PACKDATA_ASSET(Texture);
  263. for (i = 0; i < 4; i++)
  264. mathWrite(*stream, texCoords[i]);
  265. if (stream->writeFlag(animateTexture))
  266. {
  267. if (stream->writeFlag(animTexFramesString && animTexFramesString[0]))
  268. {
  269. stream->writeString(animTexFramesString);
  270. }
  271. mathWrite(*stream, animTexTiling);
  272. stream->writeInt(framesPerSec, 8);
  273. }
  274. PACKDATA_ASSET(TextureExt);
  275. stream->writeFlag(constrain_pos);
  276. stream->writeFloat(start_angle/360.0f, 11);
  277. stream->writeFloat(angle_variance/180.0f, 10);
  278. if(stream->writeFlag(sizeBias != sgDefaultSizeBias))
  279. stream->write(sizeBias);
  280. }
  281. //-----------------------------------------------------------------------------
  282. // Unpack data
  283. //-----------------------------------------------------------------------------
  284. void ParticleData::unpackData(BitStream* stream)
  285. {
  286. Parent::unpackData(stream);
  287. dragCoefficient = stream->readFloat(10) * 5;
  288. if(stream->readFlag())
  289. stream->read(&windCoefficient);
  290. else
  291. windCoefficient = sgDefaultWindCoefficient;
  292. if (stream->readFlag())
  293. gravityCoefficient = stream->readSignedFloat(12)*10;
  294. else
  295. gravityCoefficient = 0.0f;
  296. inheritedVelFactor = stream->readFloat(9);
  297. if(stream->readFlag())
  298. stream->read(&constantAcceleration);
  299. else
  300. constantAcceleration = sgDefaultConstantAcceleration;
  301. stream->read( &lifetimeMS );
  302. stream->read( &lifetimeVarianceMS );
  303. if(stream->readFlag())
  304. stream->read(&spinSpeed);
  305. else
  306. spinSpeed = sgDefaultSpinSpeed;
  307. if(stream->readFlag())
  308. {
  309. spinRandomMin = (F32)(stream->readInt(11) - 1000);
  310. spinRandomMax = (F32)(stream->readInt(11) - 1000);
  311. }
  312. else
  313. {
  314. spinRandomMin = sgDefaultSpinRandomMin;
  315. spinRandomMax = sgDefaultSpinRandomMax;
  316. }
  317. if(stream->readFlag())
  318. stream->read(&spinBias);
  319. else
  320. spinBias = sgDefaultSpinBias;
  321. randomizeSpinDir = stream->readFlag();
  322. useInvAlpha = stream->readFlag();
  323. S32 i;
  324. // An extra bit is needed for 8 keys.
  325. S32 count = stream->readInt(3) + 1;
  326. for(i = 0;i < count; i++)
  327. {
  328. colors[i].red = stream->readFloat(7);
  329. colors[i].green = stream->readFloat(7);
  330. colors[i].blue = stream->readFloat(7);
  331. colors[i].alpha = stream->readFloat(7);
  332. // AFX bits raised from 14 to 16 to allow larger sizes
  333. sizes[i] = stream->readFloat(16) * MaxParticleSize;
  334. times[i] = stream->readFloat(8);
  335. }
  336. UNPACKDATA_ASSET(Texture);
  337. for (i = 0; i < 4; i++)
  338. mathRead(*stream, &texCoords[i]);
  339. animateTexture = stream->readFlag();
  340. if (animateTexture)
  341. {
  342. animTexFramesString = (stream->readFlag()) ? stream->readSTString() : 0;
  343. mathRead(*stream, &animTexTiling);
  344. framesPerSec = stream->readInt(8);
  345. }
  346. UNPACKDATA_ASSET(TextureExt);
  347. constrain_pos = stream->readFlag();
  348. start_angle = 360.0f*stream->readFloat(11);
  349. angle_variance = 180.0f*stream->readFloat(10);
  350. if(stream->readFlag())
  351. stream->read(&sizeBias);
  352. else
  353. sizeBias = sgDefaultSizeBias;
  354. }
  355. bool ParticleData::protectedSetSizes( void *object, const char *index, const char *data)
  356. {
  357. ParticleData *pData = static_cast<ParticleData*>( object );
  358. F32 val = dAtof(data);
  359. U32 i;
  360. if (!index)
  361. return (val >= 0.f && val <= MaxParticleSize);
  362. else
  363. i = dAtoui(index);
  364. pData->sizes[i] = mClampF( val, 0.f, MaxParticleSize );
  365. return false;
  366. }
  367. bool ParticleData::protectedSetTimes( void *object, const char *index, const char *data)
  368. {
  369. ParticleData *pData = static_cast<ParticleData*>( object );
  370. F32 val = dAtof(data);
  371. U32 i;
  372. if (!index)
  373. return (val >= 0.f && val <= 1.f);
  374. else
  375. i = dAtoui(index);
  376. pData->times[i] = mClampF( val, 0.f, 1.f );
  377. return false;
  378. }
  379. //-----------------------------------------------------------------------------
  380. // onAdd
  381. //-----------------------------------------------------------------------------
  382. bool ParticleData::onAdd()
  383. {
  384. if (Parent::onAdd() == false)
  385. return false;
  386. if (dragCoefficient < 0.0) {
  387. Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) drag coeff less than 0", getName());
  388. dragCoefficient = 0.0f;
  389. }
  390. if (lifetimeMS < 1) {
  391. Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) lifetime < 1 ms", getName());
  392. lifetimeMS = 1;
  393. }
  394. if (lifetimeVarianceMS >= lifetimeMS) {
  395. Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) lifetimeVariance >= lifetime", getName());
  396. lifetimeVarianceMS = lifetimeMS - 1;
  397. }
  398. if (spinSpeed > 1000.f || spinSpeed < -1000.f) {
  399. Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) spinSpeed invalid", getName());
  400. return false;
  401. }
  402. if (spinRandomMin > 1000.f || spinRandomMin < -1000.f) {
  403. Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) spinRandomMin invalid", getName());
  404. spinRandomMin = -360.0;
  405. return false;
  406. }
  407. if (spinRandomMin > spinRandomMax) {
  408. Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) spinRandomMin greater than spinRandomMax", getName());
  409. spinRandomMin = spinRandomMax - (spinRandomMin - spinRandomMax );
  410. return false;
  411. }
  412. if (spinRandomMax > 1000.f || spinRandomMax < -1000.f) {
  413. Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) spinRandomMax invalid", getName());
  414. spinRandomMax = 360.0;
  415. return false;
  416. }
  417. if (framesPerSec > 255)
  418. {
  419. Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) framesPerSec > 255, too high", getName());
  420. framesPerSec = 255;
  421. return false;
  422. }
  423. times[0] = 0.0f;
  424. for (U32 i = 1; i < PDC_NUM_KEYS; i++)
  425. {
  426. if (times[i] < 0.0f)
  427. break;
  428. if (times[i] < times[i-1])
  429. {
  430. Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) times[%d] < times[%d]", getName(), i, i-1);
  431. times[i] = times[i-1];
  432. }
  433. }
  434. times[0] = 0.0f;
  435. U32 last_idx = 0;
  436. for (U32 i = 1; i < PDC_NUM_KEYS; i++)
  437. {
  438. if (times[i] < 0.0f)
  439. break;
  440. else
  441. last_idx = i;
  442. }
  443. for (U32 i = last_idx+1; i < PDC_NUM_KEYS; i++)
  444. {
  445. times[i] = times[last_idx];
  446. colors[i] = colors[last_idx];
  447. sizes[i] = sizes[last_idx];
  448. }
  449. // Here we validate parameters
  450. if (animateTexture)
  451. {
  452. // Tiling dimensions must be positive and non-zero
  453. if (animTexTiling.x <= 0 || animTexTiling.y <= 0)
  454. {
  455. Con::warnf(ConsoleLogEntry::General,
  456. "ParticleData(%s) bad value(s) for animTexTiling [%d or %d <= 0], invalid datablock",
  457. animTexTiling.x, animTexTiling.y, getName());
  458. return false;
  459. }
  460. // Indices must fit into a byte so these are also bad
  461. if (animTexTiling.x * animTexTiling.y > 256)
  462. {
  463. Con::warnf(ConsoleLogEntry::General,
  464. "ParticleData(%s) bad values for animTexTiling [%d*%d > %d], invalid datablock",
  465. animTexTiling.x, animTexTiling.y, 256, getName());
  466. return false;
  467. }
  468. // A list of frames is required
  469. if (!animTexFramesString || !animTexFramesString[0])
  470. {
  471. Con::warnf(ConsoleLogEntry::General, "ParticleData(%s) no animTexFrames, invalid datablock", getName());
  472. return false;
  473. }
  474. // The frame list cannot be too long.
  475. if (animTexFramesString && dStrlen(animTexFramesString) > 255)
  476. {
  477. Con::errorf(ConsoleLogEntry::General, "ParticleData(%s) animTexFrames string too long [> 255 chars]", getName());
  478. return false;
  479. }
  480. }
  481. start_angle = mFmod(start_angle, 360.0f);
  482. if (start_angle < 0.0f)
  483. start_angle += 360.0f;
  484. angle_variance = mClampF(angle_variance, -180.0f, 180.0f);
  485. return true;
  486. }
  487. //-----------------------------------------------------------------------------
  488. // preload
  489. //-----------------------------------------------------------------------------
  490. bool ParticleData::preload(bool server, String &errorStr)
  491. {
  492. if (Parent::preload(server, errorStr) == false)
  493. return false;
  494. bool error = false;
  495. if(!server)
  496. {
  497. if (animateTexture)
  498. {
  499. // Here we parse animTexFramesString into byte-size frame numbers in animTexFrames.
  500. // Each frame token must be separated by whitespace.
  501. // A frame token must be a positive integer frame number or a range of frame numbers
  502. // separated with a '-'.
  503. // The range separator, '-', cannot have any whitspace around it.
  504. // Ranges can be specified to move through the frames in reverse as well as forward.
  505. // Frame numbers exceeding the number of tiles will wrap.
  506. // example:
  507. // "0-16 20 19 18 17 31-21"
  508. S32 n_tiles = animTexTiling.x * animTexTiling.y;
  509. AssertFatal(n_tiles > 0 && n_tiles <= 256, "Error, bad animTexTiling setting." );
  510. animTexFrames.clear();
  511. dsize_t tokLen = dStrlen(animTexFramesString) + 1;
  512. char* tokCopy = new char[tokLen];
  513. dStrcpy(tokCopy, animTexFramesString, tokLen);
  514. char* currTok = dStrtok(tokCopy, " \t");
  515. while (currTok != NULL)
  516. {
  517. char* minus = dStrchr(currTok, '-');
  518. if (minus)
  519. {
  520. // add a range of frames
  521. *minus = '\0';
  522. S32 range_a = dAtoi(currTok);
  523. S32 range_b = dAtoi(minus+1);
  524. if (range_b < range_a)
  525. {
  526. // reverse frame range
  527. for (S32 i = range_a; i >= range_b; i--)
  528. animTexFrames.push_back((U8)(i % n_tiles));
  529. }
  530. else
  531. {
  532. // forward frame range
  533. for (S32 i = range_a; i <= range_b; i++)
  534. animTexFrames.push_back((U8)(i % n_tiles));
  535. }
  536. }
  537. else
  538. {
  539. // add one frame
  540. animTexFrames.push_back((U8)(dAtoi(currTok) % n_tiles));
  541. }
  542. currTok = dStrtok(NULL, " \t");
  543. }
  544. // Here we pre-calculate the UVs for each frame tile, which are
  545. // tiled inside the UV region specified by texCoords. Since the
  546. // UVs are calculated using bilinear interpolation, the texCoords
  547. // region does *not* have to be an axis-aligned rectangle.
  548. if (animTexUVs)
  549. delete [] animTexUVs;
  550. animTexUVs = new Point2F[(animTexTiling.x+1)*(animTexTiling.y+1)];
  551. // interpolate points on the left and right edge of the uv quadrangle
  552. Point2F lf_pt = texCoords[0];
  553. Point2F rt_pt = texCoords[3];
  554. // per-row delta for left and right interpolated points
  555. Point2F lf_d = (texCoords[1] - texCoords[0])/(F32)animTexTiling.y;
  556. Point2F rt_d = (texCoords[2] - texCoords[3])/(F32)animTexTiling.y;
  557. S32 idx = 0;
  558. for (S32 yy = 0; yy <= animTexTiling.y; yy++)
  559. {
  560. Point2F p = lf_pt;
  561. Point2F dp = (rt_pt - lf_pt)/(F32)animTexTiling.x;
  562. for (S32 xx = 0; xx <= animTexTiling.x; xx++)
  563. {
  564. animTexUVs[idx++] = p;
  565. p += dp;
  566. }
  567. lf_pt += lf_d;
  568. rt_pt += rt_d;
  569. }
  570. // cleanup
  571. delete [] tokCopy;
  572. numFrames = animTexFrames.size();
  573. }
  574. }
  575. return !error;
  576. }
  577. //-----------------------------------------------------------------------------
  578. // Initialize particle
  579. //-----------------------------------------------------------------------------
  580. void ParticleData::initializeParticle(Particle* init, const Point3F& inheritVelocity)
  581. {
  582. init->dataBlock = this;
  583. // Calculate the constant accleration...
  584. init->vel += inheritVelocity * inheritedVelFactor;
  585. init->acc = init->vel * constantAcceleration;
  586. // Calculate this instance's lifetime...
  587. init->totalLifetime = lifetimeMS;
  588. if (lifetimeVarianceMS != 0)
  589. init->totalLifetime += S32(gRandGen.randI() % (2 * lifetimeVarianceMS + 1)) - S32(lifetimeVarianceMS);
  590. // assign spin amount
  591. init->spinSpeed = spinSpeed * gRandGen.randF( spinRandomMin, spinRandomMax );
  592. // apply spin bias
  593. init->spinSpeed *= spinBias;
  594. // randomize spin direction
  595. if (randomizeSpinDir && (gRandGen.randI( 0, 1 ) == 1))
  596. init->spinSpeed = -init->spinSpeed;
  597. }
  598. bool ParticleData::reload(char errorBuffer[256])
  599. {
  600. bool error = false;
  601. StringTableEntry particleTex = getTexture();
  602. if (!_setTexture(particleTex))
  603. {
  604. dSprintf(errorBuffer, 256, "Missing particle texture: %s", particleTex);
  605. }
  606. /*
  607. numFrames = 0;
  608. for( S32 i=0; i<PDC_MAX_TEX; i++ )
  609. {
  610. if( textureNameList[i] && textureNameList[i][0] )
  611. {
  612. textureList[i] = TextureHandle( textureNameList[i], MeshTexture );
  613. if (!textureList[i].getName())
  614. {
  615. dSprintf(errorBuffer, 256, "Missing particle texture: %s", textureNameList[i]);
  616. error = true;
  617. }
  618. numFrames++;
  619. }
  620. }
  621. */
  622. return !error;
  623. }
  624. DefineEngineMethod(ParticleData, reload, void, (),,
  625. "Reloads this particle.\n"
  626. "@tsexample\n"
  627. "// Get the editor's current particle\n"
  628. "%particle = PE_ParticleEditor.currParticle\n\n"
  629. "// Change a particle value\n"
  630. "%particle.setFieldValue( %propertyField, %value );\n\n"
  631. "// Reload it\n"
  632. "%particle.reload();\n"
  633. "@endtsexample\n" )
  634. {
  635. char errorBuffer[256];
  636. object->reload(errorBuffer);
  637. }
  638. //#define TRACK_PARTICLE_DATA_CLONES
  639. #ifdef TRACK_PARTICLE_DATA_CLONES
  640. static int particle_data_clones = 0;
  641. #endif
  642. ParticleData::ParticleData(const ParticleData& other, bool temp_clone) : SimDataBlock(other, temp_clone)
  643. {
  644. #ifdef TRACK_PARTICLE_DATA_CLONES
  645. particle_data_clones++;
  646. if (particle_data_clones == 1)
  647. Con::errorf("ParticleData -- Clones are on the loose!");
  648. #endif
  649. dragCoefficient = other.dragCoefficient;
  650. windCoefficient = other.windCoefficient;
  651. gravityCoefficient = other.gravityCoefficient;
  652. inheritedVelFactor = other.inheritedVelFactor;
  653. constantAcceleration = other.constantAcceleration;
  654. lifetimeMS = other.lifetimeMS;
  655. lifetimeVarianceMS = other.lifetimeVarianceMS;
  656. spinSpeed = other.spinSpeed;
  657. spinRandomMin = other.spinRandomMin;
  658. spinRandomMax = other.spinRandomMax;
  659. useInvAlpha = other.useInvAlpha;
  660. animateTexture = other.animateTexture;
  661. numFrames = other.numFrames; // -- calc from other fields
  662. framesPerSec = other.framesPerSec;
  663. dMemcpy( colors, other.colors, sizeof( colors ) );
  664. dMemcpy( sizes, other.sizes, sizeof( sizes ) );
  665. dMemcpy( times, other.times, sizeof( times ) );
  666. animTexUVs = other.animTexUVs; // -- calc from other fields
  667. dMemcpy( texCoords, other.texCoords, sizeof( texCoords ) );
  668. animTexTiling = other.animTexTiling;
  669. animTexFramesString = other.animTexFramesString;
  670. animTexFrames = other.animTexFrames; // -- parsed from animTexFramesString
  671. CLONE_ASSET(Texture);
  672. spinBias = other.spinBias;
  673. randomizeSpinDir = other.randomizeSpinDir;
  674. CLONE_ASSET(TextureExt);
  675. constrain_pos = other.constrain_pos;
  676. start_angle = other.start_angle;
  677. angle_variance = other.angle_variance;
  678. sizeBias = other.sizeBias;
  679. }
  680. ParticleData::~ParticleData()
  681. {
  682. if (animTexUVs)
  683. {
  684. delete [] animTexUVs;
  685. }
  686. if (!isTempClone())
  687. return;
  688. #ifdef TRACK_PARTICLE_DATA_CLONES
  689. if (particle_data_clones > 0)
  690. {
  691. particle_data_clones--;
  692. if (particle_data_clones == 0)
  693. Con::errorf("ParticleData -- Clones eliminated!");
  694. }
  695. else
  696. Con::errorf("ParticleData -- Too many clones deleted!");
  697. #endif
  698. }
  699. void ParticleData::onPerformSubstitutions()
  700. {
  701. char errorBuffer[256];
  702. reload(errorBuffer);
  703. }
  704. DEF_ASSET_BINDS(ParticleData, Texture);