ParticleEmitter.cpp 18 KB

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