ParticleEmitter.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  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 deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // 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 FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "ParticleEffect.h"
  25. #include "ParticleEmitter.h"
  26. #include "Profiler.h"
  27. #include "ResourceCache.h"
  28. #include "ResourceEvents.h"
  29. #include "Scene.h"
  30. #include "SceneEvents.h"
  31. #include "DebugNew.h"
  32. namespace Urho3D
  33. {
  34. extern const char* GEOMETRY_CATEGORY;
  35. extern const char* faceCameraModeNames[];
  36. static const unsigned MAX_PARTICLES_IN_FRAME = 100;
  37. ParticleEmitter::ParticleEmitter(Context* context) :
  38. BillboardSet(context),
  39. periodTimer_(0.0f),
  40. emissionTimer_(0.0f),
  41. lastTimeStep_(0.0f),
  42. lastUpdateFrameNumber_(M_MAX_UNSIGNED)
  43. {
  44. SetNumParticles(DEFAULT_NUM_PARTICLES);
  45. }
  46. ParticleEmitter::~ParticleEmitter()
  47. {
  48. }
  49. void ParticleEmitter::RegisterObject(Context* context)
  50. {
  51. context->RegisterFactory<ParticleEmitter>(GEOMETRY_CATEGORY);
  52. ACCESSOR_ATTRIBUTE(ParticleEmitter, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  53. ACCESSOR_ATTRIBUTE(ParticleEmitter, VAR_RESOURCEREF, "Effect", GetEffectAttr, SetEffectAttr, ResourceRef, ResourceRef(ParticleEffect::GetTypeStatic()), AM_DEFAULT);
  54. ENUM_ATTRIBUTE(ParticleEmitter, "Face Camera Mode", faceCameraMode_, faceCameraModeNames, FC_ROTATE_XYZ, AM_DEFAULT);
  55. ACCESSOR_ATTRIBUTE(ParticleEmitter, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  56. ATTRIBUTE(ParticleEmitter, VAR_BOOL, "Cast Shadows", castShadows_, false, AM_DEFAULT);
  57. ACCESSOR_ATTRIBUTE(ParticleEmitter, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  58. ACCESSOR_ATTRIBUTE(ParticleEmitter, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  59. ACCESSOR_ATTRIBUTE(ParticleEmitter, VAR_FLOAT, "Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  60. ATTRIBUTE(ParticleEmitter, VAR_BOOL, "Is Emitting", emitting_, true, AM_FILE);
  61. ATTRIBUTE(ParticleEmitter, VAR_FLOAT, "Period Timer", periodTimer_, 0.0f, AM_FILE | AM_NOEDIT);
  62. ATTRIBUTE(ParticleEmitter, VAR_FLOAT, "Emission Timer", emissionTimer_, 0.0f, AM_FILE | AM_NOEDIT);
  63. ACCESSOR_ATTRIBUTE(ParticleEmitter, VAR_VARIANTVECTOR, "Particles", GetParticlesAttr, SetParticlesAttr, VariantVector, Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  64. ACCESSOR_ATTRIBUTE(ParticleEmitter, VAR_VARIANTVECTOR, "Billboards", GetBillboardsAttr, SetBillboardsAttr, VariantVector, Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  65. }
  66. void ParticleEmitter::OnSetEnabled()
  67. {
  68. BillboardSet::OnSetEnabled();
  69. Scene* scene = GetScene();
  70. if (scene)
  71. {
  72. if (IsEnabledEffective())
  73. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(ParticleEmitter, HandleScenePostUpdate));
  74. else
  75. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  76. }
  77. }
  78. void ParticleEmitter::Update(const FrameInfo& frame)
  79. {
  80. if (!effect_)
  81. return;
  82. // Cancel update if has only moved but does not actually need to animate the particles
  83. if (!needUpdate_)
  84. return;
  85. // If there is an amount mismatch between particles and billboards, correct it
  86. if (particles_.Size() != billboards_.Size())
  87. SetNumBillboards(particles_.Size());
  88. bool needCommit = false;
  89. // Check active/inactive period switching
  90. periodTimer_ += lastTimeStep_;
  91. if (emitting_)
  92. {
  93. float activeTime = effect_->GetActiveTime();
  94. if (activeTime && periodTimer_ >= activeTime)
  95. {
  96. emitting_ = false;
  97. periodTimer_ -= activeTime;
  98. }
  99. }
  100. else
  101. {
  102. float inactiveTime = effect_->GetInactiveTime();
  103. if (inactiveTime && periodTimer_ >= inactiveTime)
  104. {
  105. emitting_ = true;
  106. periodTimer_ -= inactiveTime;
  107. }
  108. // If emitter has an indefinite stop interval, keep period timer reset to allow restarting emission in the editor
  109. if (inactiveTime == 0.0f)
  110. periodTimer_ = 0.0f;
  111. }
  112. // Check for emitting new particles
  113. if (emitting_)
  114. {
  115. emissionTimer_ += lastTimeStep_;
  116. float intervalMin = 1.0f / effect_->GetMaxEmissionRate();
  117. float intervalMax = 1.0f / effect_->GetMinEmissionRate();
  118. // If emission timer has a longer delay than max. interval, clamp it
  119. if (emissionTimer_ < -intervalMax)
  120. emissionTimer_ = -intervalMax;
  121. unsigned counter = MAX_PARTICLES_IN_FRAME;
  122. while (emissionTimer_ > 0.0f && counter)
  123. {
  124. emissionTimer_ -= Lerp(intervalMin, intervalMax, Random(1.0f));
  125. if (EmitNewParticle())
  126. {
  127. --counter;
  128. needCommit = true;
  129. }
  130. else
  131. break;
  132. }
  133. }
  134. // Update existing particles
  135. Vector3 relativeConstantForce = node_->GetWorldRotation().Inverse() * effect_->GetConstantForce();
  136. // If billboards are not relative, apply scaling to the position update
  137. Vector3 scaleVector = Vector3::ONE;
  138. if (scaled_ && !relative_)
  139. scaleVector = node_->GetWorldScale();
  140. for (unsigned i = 0; i < particles_.Size(); ++i)
  141. {
  142. Particle& particle = particles_[i];
  143. Billboard& billboard = billboards_[i];
  144. if (billboard.enabled_)
  145. {
  146. needCommit = true;
  147. // Time to live
  148. if (particle.timer_ >= particle.timeToLive_)
  149. {
  150. billboard.enabled_ = false;
  151. continue;
  152. }
  153. particle.timer_ += lastTimeStep_;
  154. // Velocity & position
  155. const Vector3& constantForce = effect_->GetConstantForce();
  156. if (constantForce != Vector3::ZERO)
  157. {
  158. if (relative_)
  159. particle.velocity_ += lastTimeStep_ * relativeConstantForce;
  160. else
  161. particle.velocity_ += lastTimeStep_ * constantForce;
  162. }
  163. float dampingForce = effect_->GetDampingForce();
  164. if (dampingForce != 0.0f)
  165. {
  166. Vector3 force = -dampingForce * particle.velocity_;
  167. particle.velocity_ += lastTimeStep_ * force;
  168. }
  169. billboard.position_ += lastTimeStep_ * particle.velocity_ * scaleVector;
  170. // Rotation
  171. billboard.rotation_ += lastTimeStep_ * particle.rotationSpeed_;
  172. // Scaling
  173. float sizeAdd = effect_->GetSizeAdd();
  174. float sizeMul = effect_->GetSizeMul();
  175. if (sizeAdd != 0.0f || sizeMul != 1.0f)
  176. {
  177. particle.scale_ += lastTimeStep_ * sizeAdd;
  178. if (sizeMul != 1.0f)
  179. particle.scale_ *= (lastTimeStep_ * (sizeMul - 1.0f)) + 1.0f;
  180. billboard.size_ = particle.size_ * particle.scale_;
  181. }
  182. // Color interpolation
  183. unsigned& index = particle.colorIndex_;
  184. const Vector<ColorFrame>& colorFrames_ = effect_->GetColorFrames();
  185. if (index < colorFrames_.Size())
  186. {
  187. if (index < colorFrames_.Size() - 1)
  188. {
  189. if (particle.timer_ >= colorFrames_[index + 1].time_)
  190. ++index;
  191. }
  192. if (index < colorFrames_.Size() - 1)
  193. billboard.color_ = colorFrames_[index].Interpolate(colorFrames_[index + 1], particle.timer_);
  194. else
  195. billboard.color_ = colorFrames_[index].color_;
  196. }
  197. // Texture animation
  198. unsigned& texIndex = particle.texIndex_;
  199. const Vector<TextureFrame>& textureFrames_ = effect_->GetTextureFrames();
  200. if (textureFrames_.Size() && texIndex < textureFrames_.Size() - 1)
  201. {
  202. if (particle.timer_ >= textureFrames_[texIndex + 1].time_)
  203. {
  204. billboard.uv_ = textureFrames_[texIndex + 1].uv_;
  205. ++texIndex;
  206. }
  207. }
  208. }
  209. }
  210. if (needCommit)
  211. Commit();
  212. needUpdate_ = false;
  213. }
  214. void ParticleEmitter::SetEffect(ParticleEffect* effect)
  215. {
  216. if (effect == effect_)
  217. return;
  218. Reset();
  219. // Unsubscribe from the reload event of previous effect (if any), then subscribe to the new
  220. if (effect_)
  221. UnsubscribeFromEvent(effect_, E_RELOADFINISHED);
  222. effect_ = effect;
  223. if (effect_)
  224. SubscribeToEvent(effect_, E_RELOADFINISHED, HANDLER(ParticleEmitter, HandleEffectReloadFinished));
  225. ApplyEffect();
  226. MarkNetworkUpdate();
  227. }
  228. void ParticleEmitter::SetNumParticles(unsigned num)
  229. {
  230. // Prevent negative value being assigned from the editor
  231. if (num > M_MAX_INT)
  232. num = 0;
  233. if (num > MAX_BILLBOARDS)
  234. num = MAX_BILLBOARDS;
  235. particles_.Resize(num);
  236. SetNumBillboards(num);
  237. }
  238. void ParticleEmitter::SetEmitting(bool enable)
  239. {
  240. if (enable != emitting_)
  241. {
  242. emitting_ = enable;
  243. periodTimer_ = 0.0f;
  244. MarkNetworkUpdate();
  245. }
  246. }
  247. void ParticleEmitter::ResetEmissionTimer()
  248. {
  249. emissionTimer_ = 0.0f;
  250. }
  251. void ParticleEmitter::RemoveAllParticles()
  252. {
  253. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  254. i->enabled_ = false;
  255. Commit();
  256. }
  257. void ParticleEmitter::Reset()
  258. {
  259. RemoveAllParticles();
  260. ResetEmissionTimer();
  261. SetEmitting(true);
  262. }
  263. void ParticleEmitter::ApplyEffect()
  264. {
  265. if (!effect_)
  266. return;
  267. SetMaterial(effect_->GetMaterial());
  268. SetNumParticles(effect_->GetNumParticles());
  269. SetRelative(effect_->IsRelative());
  270. SetScaled(effect_->IsScaled());
  271. SetSorted(effect_->IsSorted());
  272. SetAnimationLodBias(effect_->GetAnimationLodBias());
  273. }
  274. void ParticleEmitter::SetEffectAttr(ResourceRef value)
  275. {
  276. ResourceCache* cache = GetSubsystem<ResourceCache>();
  277. SetEffect(cache->GetResource<ParticleEffect>(value.name_));
  278. }
  279. ResourceRef ParticleEmitter::GetEffectAttr() const
  280. {
  281. return GetResourceRef(effect_, ParticleEffect::GetTypeStatic());
  282. }
  283. void ParticleEmitter::SetParticlesAttr(VariantVector value)
  284. {
  285. unsigned index = 0;
  286. SetNumParticles(index < value.Size() ? value[index++].GetUInt() : 0);
  287. for (PODVector<Particle>::Iterator i = particles_.Begin(); i != particles_.End() && index < value.Size(); ++i)
  288. {
  289. i->velocity_ = value[index++].GetVector3();
  290. i->size_ = value[index++].GetVector2();
  291. i->timer_ = value[index++].GetFloat();
  292. i->timeToLive_ = value[index++].GetFloat();
  293. i->scale_ = value[index++].GetFloat();
  294. i->rotationSpeed_ = value[index++].GetFloat();
  295. i->colorIndex_ = value[index++].GetInt();
  296. i->texIndex_ = value[index++].GetInt();
  297. }
  298. }
  299. VariantVector ParticleEmitter::GetParticlesAttr() const
  300. {
  301. VariantVector ret;
  302. ret.Reserve(particles_.Size() * 8 + 1);
  303. ret.Push(particles_.Size());
  304. for (PODVector<Particle>::ConstIterator i = particles_.Begin(); i != particles_.End(); ++i)
  305. {
  306. ret.Push(i->velocity_);
  307. ret.Push(i->size_);
  308. ret.Push(i->timer_);
  309. ret.Push(i->timeToLive_);
  310. ret.Push(i->scale_);
  311. ret.Push(i->rotationSpeed_);
  312. ret.Push(i->colorIndex_);
  313. ret.Push(i->texIndex_);
  314. }
  315. return ret;
  316. }
  317. void ParticleEmitter::OnNodeSet(Node* node)
  318. {
  319. BillboardSet::OnNodeSet(node);
  320. if (node)
  321. {
  322. Scene* scene = GetScene();
  323. if (scene && IsEnabledEffective())
  324. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(ParticleEmitter, HandleScenePostUpdate));
  325. }
  326. }
  327. bool ParticleEmitter::EmitNewParticle()
  328. {
  329. unsigned index = GetFreeParticle();
  330. if (index == M_MAX_UNSIGNED)
  331. return false;
  332. assert(index < particles_.Size());
  333. Particle& particle = particles_[index];
  334. Billboard& billboard = billboards_[index];
  335. Vector3 startPos;
  336. Vector3 startDir;
  337. switch (effect_->GetEmitterType())
  338. {
  339. case EMITTER_SPHERE:
  340. {
  341. Vector3 dir(
  342. Random(2.0f) - 1.0f,
  343. Random(2.0f) - 1.0f,
  344. Random(2.0f) - 1.0f
  345. );
  346. dir.Normalize();
  347. startPos = effect_->GetEmitterSize() * dir * 0.5f;
  348. }
  349. break;
  350. case EMITTER_BOX:
  351. {
  352. const Vector3& emitterSize = effect_->GetEmitterSize();
  353. startPos = Vector3(
  354. Random(emitterSize.x_) - emitterSize.x_ * 0.5f,
  355. Random(emitterSize.y_) - emitterSize.y_ * 0.5f,
  356. Random(emitterSize.z_) - emitterSize.z_ * 0.5f
  357. );
  358. }
  359. break;
  360. }
  361. startDir = effect_->GetRandomDirection();
  362. startDir.Normalize();
  363. if (!relative_)
  364. {
  365. startPos = node_->GetWorldTransform() * startPos;
  366. startDir = node_->GetWorldRotation() * startDir;
  367. };
  368. particle.velocity_ = effect_->GetRandomVelocity() * startDir;
  369. particle.size_ = effect_->GetRandomSize();
  370. particle.timer_ = 0.0f;
  371. particle.timeToLive_ = effect_->GetRandomTimeToLive();
  372. particle.scale_ = 1.0f;
  373. particle.rotationSpeed_ = effect_->GetRandomRotationSpeed();
  374. particle.colorIndex_ = 0;
  375. particle.texIndex_ = 0;
  376. billboard.position_ = startPos;
  377. billboard.size_ = particles_[index].size_;
  378. const Vector<TextureFrame>& textureFrames_ = effect_->GetTextureFrames();
  379. billboard.uv_ = textureFrames_.Size() ? textureFrames_[0].uv_ : Rect::POSITIVE;
  380. billboard.rotation_ = effect_->GetRandomRotation();
  381. const Vector<ColorFrame>& colorFrames_ = effect_->GetColorFrames();
  382. billboard.color_ = colorFrames_[0].color_;
  383. billboard.enabled_ = true;
  384. return true;
  385. }
  386. unsigned ParticleEmitter::GetFreeParticle() const
  387. {
  388. for (unsigned i = 0; i < billboards_.Size(); ++i)
  389. {
  390. if (!billboards_[i].enabled_)
  391. return i;
  392. }
  393. return M_MAX_UNSIGNED;
  394. }
  395. void ParticleEmitter::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  396. {
  397. // Store scene's timestep and use it instead of global timestep, as time scale may be other than 1
  398. using namespace ScenePostUpdate;
  399. lastTimeStep_ = eventData[P_TIMESTEP].GetFloat();
  400. // If no invisible update, check that the billboardset is in view (framenumber has changed)
  401. if ((effect_ && effect_->GetUpdateInvisible()) || viewFrameNumber_ != lastUpdateFrameNumber_)
  402. {
  403. lastUpdateFrameNumber_ = viewFrameNumber_;
  404. needUpdate_ = true;
  405. MarkForUpdate();
  406. }
  407. }
  408. void ParticleEmitter::HandleEffectReloadFinished(StringHash eventType, VariantMap& eventData)
  409. {
  410. // When particle effect file is live-edited, remove existing particles and reapply the effect parameters
  411. Reset();
  412. ApplyEffect();
  413. }
  414. }