ParticleEmitter.cpp 18 KB

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