particle.cpp 29 KB

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