ParticleEmitter.cpp 17 KB

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