ParticleEmitter.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. //
  2. // Copyright (c) 2008-2017 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 "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/DrawableEvents.h"
  26. #include "../Graphics/ParticleEffect.h"
  27. #include "../Graphics/ParticleEmitter.h"
  28. #include "../Resource/ResourceCache.h"
  29. #include "../Resource/ResourceEvents.h"
  30. #include "../Scene/Scene.h"
  31. #include "../Scene/SceneEvents.h"
  32. #include "../DebugNew.h"
  33. namespace Atomic
  34. {
  35. extern const char* GEOMETRY_CATEGORY;
  36. extern const char* faceCameraModeNames[];
  37. static const unsigned MAX_PARTICLES_IN_FRAME = 100;
  38. extern const char* autoRemoveModeNames[];
  39. ParticleEmitter::ParticleEmitter(Context* context) :
  40. BillboardSet(context),
  41. periodTimer_(0.0f),
  42. emissionTimer_(0.0f),
  43. lastTimeStep_(0.0f),
  44. lastUpdateFrameNumber_(M_MAX_UNSIGNED),
  45. emitting_(true),
  46. needUpdate_(false),
  47. serializeParticles_(true),
  48. sendFinishedEvent_(true),
  49. autoRemove_(REMOVE_DISABLED)
  50. {
  51. SetNumParticles(DEFAULT_NUM_PARTICLES);
  52. }
  53. ParticleEmitter::~ParticleEmitter()
  54. {
  55. }
  56. void ParticleEmitter::RegisterObject(Context* context)
  57. {
  58. context->RegisterFactory<ParticleEmitter>(GEOMETRY_CATEGORY);
  59. ATOMIC_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  60. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Effect", GetEffectAttr, SetEffectAttr, ResourceRef, ResourceRef(ParticleEffect::GetTypeStatic()),
  61. AM_DEFAULT);
  62. ATOMIC_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  63. ATOMIC_ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  64. ATOMIC_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  65. ATOMIC_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  66. ATOMIC_ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  67. ATOMIC_ATTRIBUTE("Is Emitting", bool, emitting_, true, AM_FILE);
  68. ATOMIC_ATTRIBUTE("Period Timer", float, periodTimer_, 0.0f, AM_FILE | AM_NOEDIT);
  69. ATOMIC_ATTRIBUTE("Emission Timer", float, emissionTimer_, 0.0f, AM_FILE | AM_NOEDIT);
  70. ATOMIC_ENUM_ATTRIBUTE("Autoremove Mode", autoRemove_, autoRemoveModeNames, REMOVE_DISABLED, AM_DEFAULT);
  71. ATOMIC_COPY_BASE_ATTRIBUTES(Drawable);
  72. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Particles", GetParticlesAttr, SetParticlesAttr, VariantVector, Variant::emptyVariantVector,
  73. AM_FILE | AM_NOEDIT);
  74. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Billboards", GetParticleBillboardsAttr, SetBillboardsAttr, VariantVector, Variant::emptyVariantVector,
  75. AM_FILE | AM_NOEDIT);
  76. ATOMIC_ATTRIBUTE("Serialize Particles", bool, serializeParticles_, true, AM_FILE);
  77. }
  78. void ParticleEmitter::OnSetEnabled()
  79. {
  80. BillboardSet::OnSetEnabled();
  81. Scene* scene = GetScene();
  82. if (scene)
  83. {
  84. if (IsEnabledEffective())
  85. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, ATOMIC_HANDLER(ParticleEmitter, HandleScenePostUpdate));
  86. else
  87. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  88. }
  89. }
  90. void ParticleEmitter::Update(const FrameInfo& frame)
  91. {
  92. if (!effect_)
  93. return;
  94. // Cancel update if has only moved but does not actually need to animate the particles
  95. if (!needUpdate_)
  96. return;
  97. // If there is an amount mismatch between particles and billboards, correct it
  98. if (particles_.Size() != billboards_.Size())
  99. SetNumBillboards(particles_.Size());
  100. bool needCommit = false;
  101. // Check active/inactive period switching
  102. periodTimer_ += lastTimeStep_;
  103. if (emitting_)
  104. {
  105. float activeTime = effect_->GetActiveTime();
  106. if (activeTime && periodTimer_ >= activeTime)
  107. {
  108. emitting_ = false;
  109. periodTimer_ -= activeTime;
  110. }
  111. }
  112. else
  113. {
  114. float inactiveTime = effect_->GetInactiveTime();
  115. if (inactiveTime && periodTimer_ >= inactiveTime)
  116. {
  117. emitting_ = true;
  118. sendFinishedEvent_ = true;
  119. periodTimer_ -= inactiveTime;
  120. }
  121. // If emitter has an indefinite stop interval, keep period timer reset to allow restarting emission in the editor
  122. if (inactiveTime == 0.0f)
  123. periodTimer_ = 0.0f;
  124. }
  125. // Check for emitting new particles
  126. if (emitting_)
  127. {
  128. emissionTimer_ += lastTimeStep_;
  129. float intervalMin = 1.0f / effect_->GetMaxEmissionRate();
  130. float intervalMax = 1.0f / effect_->GetMinEmissionRate();
  131. // If emission timer has a longer delay than max. interval, clamp it
  132. if (emissionTimer_ < -intervalMax)
  133. emissionTimer_ = -intervalMax;
  134. unsigned counter = MAX_PARTICLES_IN_FRAME;
  135. while (emissionTimer_ > 0.0f && counter)
  136. {
  137. emissionTimer_ -= Lerp(intervalMin, intervalMax, Random(1.0f));
  138. if (EmitNewParticle())
  139. {
  140. --counter;
  141. needCommit = true;
  142. }
  143. else
  144. break;
  145. }
  146. }
  147. // Update existing particles
  148. Vector3 relativeConstantForce = node_->GetWorldRotation().Inverse() * effect_->GetConstantForce();
  149. // If billboards are not relative, apply scaling to the position update
  150. Vector3 scaleVector = Vector3::ONE;
  151. if (scaled_ && !relative_)
  152. scaleVector = node_->GetWorldScale();
  153. for (unsigned i = 0; i < particles_.Size(); ++i)
  154. {
  155. Particle& particle = particles_[i];
  156. Billboard& billboard = *billboards_[i];
  157. if (billboard.enabled_)
  158. {
  159. needCommit = true;
  160. // Time to live
  161. if (particle.timer_ >= particle.timeToLive_)
  162. {
  163. billboard.enabled_ = false;
  164. continue;
  165. }
  166. particle.timer_ += lastTimeStep_;
  167. // Velocity & position
  168. const Vector3& constantForce = effect_->GetConstantForce();
  169. if (constantForce != Vector3::ZERO)
  170. {
  171. if (relative_)
  172. particle.velocity_ += lastTimeStep_ * relativeConstantForce;
  173. else
  174. particle.velocity_ += lastTimeStep_ * constantForce;
  175. }
  176. float dampingForce = effect_->GetDampingForce();
  177. if (dampingForce != 0.0f)
  178. {
  179. Vector3 force = -dampingForce * particle.velocity_;
  180. particle.velocity_ += lastTimeStep_ * force;
  181. }
  182. billboard.position_ += lastTimeStep_ * particle.velocity_ * scaleVector;
  183. billboard.direction_ = particle.velocity_.Normalized();
  184. // Rotation
  185. billboard.rotation_ += lastTimeStep_ * particle.rotationSpeed_;
  186. // Scaling
  187. float sizeAdd = effect_->GetSizeAdd();
  188. float sizeMul = effect_->GetSizeMul();
  189. if (sizeAdd != 0.0f || sizeMul != 1.0f)
  190. {
  191. particle.scale_ += lastTimeStep_ * sizeAdd;
  192. if (particle.scale_ < 0.0f)
  193. particle.scale_ = 0.0f;
  194. if (sizeMul != 1.0f)
  195. particle.scale_ *= (lastTimeStep_ * (sizeMul - 1.0f)) + 1.0f;
  196. billboard.size_ = particle.size_ * particle.scale_;
  197. }
  198. // Color interpolation
  199. unsigned& index = particle.colorIndex_;
  200. const Vector<ColorFrame>& colorFrames_ = effect_->GetColorFrames();
  201. if (index < colorFrames_.Size())
  202. {
  203. if (index < colorFrames_.Size() - 1)
  204. {
  205. if (particle.timer_ >= colorFrames_[index + 1].time_)
  206. ++index;
  207. }
  208. if (index < colorFrames_.Size() - 1)
  209. billboard.color_ = colorFrames_[index].Interpolate(colorFrames_[index + 1], particle.timer_);
  210. else
  211. billboard.color_ = colorFrames_[index].color_;
  212. }
  213. // Texture animation
  214. unsigned& texIndex = particle.texIndex_;
  215. const Vector<TextureFrame>& textureFrames_ = effect_->GetTextureFrames();
  216. if (textureFrames_.Size() && texIndex < textureFrames_.Size() - 1)
  217. {
  218. if (particle.timer_ >= textureFrames_[texIndex + 1].time_)
  219. {
  220. billboard.uv_ = textureFrames_[texIndex + 1].uv_;
  221. ++texIndex;
  222. }
  223. }
  224. }
  225. }
  226. if (needCommit)
  227. Commit();
  228. needUpdate_ = false;
  229. }
  230. void ParticleEmitter::SetEffect(ParticleEffect* effect)
  231. {
  232. if (effect == effect_)
  233. return;
  234. Reset();
  235. // Unsubscribe from the reload event of previous effect (if any), then subscribe to the new
  236. if (effect_)
  237. UnsubscribeFromEvent(effect_, E_RELOADFINISHED);
  238. effect_ = effect;
  239. if (effect_)
  240. SubscribeToEvent(effect_, E_RELOADFINISHED, ATOMIC_HANDLER(ParticleEmitter, HandleEffectReloadFinished));
  241. ApplyEffect();
  242. MarkNetworkUpdate();
  243. }
  244. void ParticleEmitter::SetNumParticles(unsigned num)
  245. {
  246. // Prevent negative value being assigned from the editor
  247. if (num > M_MAX_INT)
  248. num = 0;
  249. particles_.Resize(num);
  250. SetNumBillboards(num);
  251. }
  252. void ParticleEmitter::SetEmitting(bool enable)
  253. {
  254. if (enable != emitting_)
  255. {
  256. emitting_ = enable;
  257. // If stopping emission now, and there are active particles, send finish event once they are gone
  258. sendFinishedEvent_ = enable || CheckActiveParticles();
  259. periodTimer_ = 0.0f;
  260. // Note: network update does not need to be marked as this is a file only attribute
  261. }
  262. }
  263. void ParticleEmitter::SetSerializeParticles(bool enable)
  264. {
  265. serializeParticles_ = enable;
  266. // Note: network update does not need to be marked as this is a file only attribute
  267. }
  268. void ParticleEmitter::SetAutoRemoveMode(AutoRemoveMode mode)
  269. {
  270. autoRemove_ = mode;
  271. MarkNetworkUpdate();
  272. }
  273. void ParticleEmitter::ResetEmissionTimer()
  274. {
  275. emissionTimer_ = 0.0f;
  276. }
  277. void ParticleEmitter::RemoveAllParticles()
  278. {
  279. for (Vector<SharedPtr<Billboard>>::Iterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  280. (*i)->enabled_ = false;
  281. Commit();
  282. }
  283. void ParticleEmitter::Reset()
  284. {
  285. RemoveAllParticles();
  286. ResetEmissionTimer();
  287. SetEmitting(true);
  288. }
  289. void ParticleEmitter::ApplyEffect()
  290. {
  291. if (!effect_)
  292. return;
  293. SetMaterial(effect_->GetMaterial());
  294. SetNumParticles(effect_->GetNumParticles());
  295. SetRelative(effect_->IsRelative());
  296. SetScaled(effect_->IsScaled());
  297. SetSorted(effect_->IsSorted());
  298. SetFixedScreenSize(effect_->IsFixedScreenSize());
  299. SetAnimationLodBias(effect_->GetAnimationLodBias());
  300. SetFaceCameraMode(effect_->GetFaceCameraMode());
  301. }
  302. ParticleEffect* ParticleEmitter::GetEffect() const
  303. {
  304. return effect_;
  305. }
  306. void ParticleEmitter::SetEffectAttr(const ResourceRef& value)
  307. {
  308. ResourceCache* cache = GetSubsystem<ResourceCache>();
  309. SetEffect(cache->GetResource<ParticleEffect>(value.name_));
  310. }
  311. ResourceRef ParticleEmitter::GetEffectAttr() const
  312. {
  313. return GetResourceRef(effect_, ParticleEffect::GetTypeStatic());
  314. }
  315. void ParticleEmitter::SetParticlesAttr(const VariantVector& value)
  316. {
  317. unsigned index = 0;
  318. SetNumParticles(index < value.Size() ? value[index++].GetUInt() : 0);
  319. for (PODVector<Particle>::Iterator i = particles_.Begin(); i != particles_.End() && index < value.Size(); ++i)
  320. {
  321. i->velocity_ = value[index++].GetVector3();
  322. i->size_ = value[index++].GetVector2();
  323. i->timer_ = value[index++].GetFloat();
  324. i->timeToLive_ = value[index++].GetFloat();
  325. i->scale_ = value[index++].GetFloat();
  326. i->rotationSpeed_ = value[index++].GetFloat();
  327. i->colorIndex_ = (unsigned)value[index++].GetInt();
  328. i->texIndex_ = (unsigned)value[index++].GetInt();
  329. }
  330. }
  331. VariantVector ParticleEmitter::GetParticlesAttr() const
  332. {
  333. VariantVector ret;
  334. if (!serializeParticles_)
  335. {
  336. ret.Push(particles_.Size());
  337. return ret;
  338. }
  339. ret.Reserve(particles_.Size() * 8 + 1);
  340. ret.Push(particles_.Size());
  341. for (PODVector<Particle>::ConstIterator i = particles_.Begin(); i != particles_.End(); ++i)
  342. {
  343. ret.Push(i->velocity_);
  344. ret.Push(i->size_);
  345. ret.Push(i->timer_);
  346. ret.Push(i->timeToLive_);
  347. ret.Push(i->scale_);
  348. ret.Push(i->rotationSpeed_);
  349. ret.Push(i->colorIndex_);
  350. ret.Push(i->texIndex_);
  351. }
  352. return ret;
  353. }
  354. VariantVector ParticleEmitter::GetParticleBillboardsAttr() const
  355. {
  356. VariantVector ret;
  357. if (!serializeParticles_)
  358. {
  359. ret.Push(billboards_.Size());
  360. return ret;
  361. }
  362. ret.Reserve(billboards_.Size() * 7 + 1);
  363. ret.Push(billboards_.Size());
  364. for (Vector<SharedPtr<Billboard>>::ConstIterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  365. {
  366. ret.Push((*i)->position_);
  367. ret.Push((*i)->size_);
  368. ret.Push(Vector4((*i)->uv_.min_.x_, (*i)->uv_.min_.y_, (*i)->uv_.max_.x_, (*i)->uv_.max_.y_));
  369. ret.Push((*i)->color_);
  370. ret.Push((*i)->rotation_);
  371. ret.Push((*i)->direction_);
  372. ret.Push((*i)->enabled_);
  373. }
  374. return ret;
  375. }
  376. void ParticleEmitter::OnSceneSet(Scene* scene)
  377. {
  378. BillboardSet::OnSceneSet(scene);
  379. if (scene && IsEnabledEffective())
  380. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, ATOMIC_HANDLER(ParticleEmitter, HandleScenePostUpdate));
  381. else if (!scene)
  382. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  383. }
  384. bool ParticleEmitter::EmitNewParticle()
  385. {
  386. unsigned index = GetFreeParticle();
  387. if (index == M_MAX_UNSIGNED)
  388. return false;
  389. assert(index < particles_.Size());
  390. Particle& particle = particles_[index];
  391. Billboard* billboard = billboards_[index];
  392. Vector3 startDir;
  393. Vector3 startPos;
  394. startDir = effect_->GetRandomDirection();
  395. startDir.Normalize();
  396. switch (effect_->GetEmitterType())
  397. {
  398. case EMITTER_SPHERE:
  399. {
  400. Vector3 dir(
  401. Random(2.0f) - 1.0f,
  402. Random(2.0f) - 1.0f,
  403. Random(2.0f) - 1.0f
  404. );
  405. dir.Normalize();
  406. startPos = effect_->GetEmitterSize() * dir * 0.5f;
  407. }
  408. break;
  409. case EMITTER_BOX:
  410. {
  411. const Vector3& emitterSize = effect_->GetEmitterSize();
  412. startPos = Vector3(
  413. Random(emitterSize.x_) - emitterSize.x_ * 0.5f,
  414. Random(emitterSize.y_) - emitterSize.y_ * 0.5f,
  415. Random(emitterSize.z_) - emitterSize.z_ * 0.5f
  416. );
  417. }
  418. break;
  419. }
  420. particle.size_ = effect_->GetRandomSize();
  421. particle.timer_ = 0.0f;
  422. particle.timeToLive_ = effect_->GetRandomTimeToLive();
  423. particle.scale_ = 1.0f;
  424. particle.rotationSpeed_ = effect_->GetRandomRotationSpeed();
  425. particle.colorIndex_ = 0;
  426. particle.texIndex_ = 0;
  427. if (faceCameraMode_ == FC_DIRECTION)
  428. {
  429. startPos += startDir * particle.size_.y_;
  430. }
  431. if (!relative_)
  432. {
  433. startPos = node_->GetWorldTransform() * startPos;
  434. startDir = node_->GetWorldRotation() * startDir;
  435. };
  436. particle.velocity_ = effect_->GetRandomVelocity() * startDir;
  437. billboard->position_ = startPos;
  438. billboard->size_ = particles_[index].size_;
  439. const Vector<TextureFrame>& textureFrames_ = effect_->GetTextureFrames();
  440. billboard->uv_ = textureFrames_.Size() ? textureFrames_[0].uv_ : Rect::POSITIVE;
  441. billboard->rotation_ = effect_->GetRandomRotation();
  442. const Vector<ColorFrame>& colorFrames_ = effect_->GetColorFrames();
  443. billboard->color_ = colorFrames_.Size() ? colorFrames_[0].color_ : Color();
  444. billboard->enabled_ = true;
  445. billboard->direction_ = startDir;
  446. return true;
  447. }
  448. unsigned ParticleEmitter::GetFreeParticle() const
  449. {
  450. for (unsigned i = 0; i < billboards_.Size(); ++i)
  451. {
  452. if (!billboards_[i]->enabled_)
  453. return i;
  454. }
  455. return M_MAX_UNSIGNED;
  456. }
  457. bool ParticleEmitter::CheckActiveParticles() const
  458. {
  459. for (unsigned i = 0; i < billboards_.Size(); ++i)
  460. {
  461. if (billboards_[i]->enabled_)
  462. {
  463. return true;
  464. break;
  465. }
  466. }
  467. return false;
  468. }
  469. void ParticleEmitter::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  470. {
  471. // Store scene's timestep and use it instead of global timestep, as time scale may be other than 1
  472. using namespace ScenePostUpdate;
  473. lastTimeStep_ = eventData[P_TIMESTEP].GetFloat();
  474. // If no invisible update, check that the billboardset is in view (framenumber has changed)
  475. if ((effect_ && effect_->GetUpdateInvisible()) || viewFrameNumber_ != lastUpdateFrameNumber_)
  476. {
  477. lastUpdateFrameNumber_ = viewFrameNumber_;
  478. needUpdate_ = true;
  479. MarkForUpdate();
  480. }
  481. // Send finished event only once all particles are gone
  482. if (node_ && !emitting_ && sendFinishedEvent_ && !CheckActiveParticles())
  483. {
  484. sendFinishedEvent_ = false;
  485. // Make a weak pointer to self to check for destruction during event handling
  486. WeakPtr<ParticleEmitter> self(this);
  487. using namespace ParticleEffectFinished;
  488. VariantMap& eventData = GetEventDataMap();
  489. eventData[P_NODE] = node_;
  490. eventData[P_EFFECT] = effect_;
  491. node_->SendEvent(E_PARTICLEEFFECTFINISHED, eventData);
  492. if (self.Expired())
  493. return;
  494. DoAutoRemove(autoRemove_);
  495. }
  496. }
  497. void ParticleEmitter::HandleEffectReloadFinished(StringHash eventType, VariantMap& eventData)
  498. {
  499. // When particle effect file is live-edited, remove existing particles and reapply the effect parameters
  500. Reset();
  501. ApplyEffect();
  502. }
  503. }