particle.cpp 28 KB

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