ParticleEmitterComponent.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Scene/Components/ParticleEmitterComponent.h>
  6. #include <AnKi/Scene/SceneGraph.h>
  7. #include <AnKi/Scene/SceneNode.h>
  8. #include <AnKi/Scene/Components/RenderComponent.h>
  9. #include <AnKi/Resource/ParticleEmitterResource.h>
  10. #include <AnKi/Resource/ResourceManager.h>
  11. #include <AnKi/Physics/PhysicsBody.h>
  12. #include <AnKi/Physics/PhysicsCollisionShape.h>
  13. #include <AnKi/Physics/PhysicsWorld.h>
  14. #include <AnKi/Math.h>
  15. #include <AnKi/Renderer/RenderQueue.h>
  16. namespace anki {
  17. ANKI_SCENE_COMPONENT_STATICS(ParticleEmitterComponent)
  18. static Vec3 getRandom(const Vec3& min, const Vec3& max)
  19. {
  20. Vec3 out;
  21. out.x() = mix(min.x(), max.x(), getRandomRange(0.0f, 1.0f));
  22. out.y() = mix(min.y(), max.y(), getRandomRange(0.0f, 1.0f));
  23. out.z() = mix(min.z(), max.z(), getRandomRange(0.0f, 1.0f));
  24. return out;
  25. }
  26. /// Particle base
  27. class ParticleEmitterComponent::ParticleBase
  28. {
  29. public:
  30. Second m_timeOfBirth; ///< Keep the time of birth for nice effects
  31. Second m_timeOfDeath = -1.0; ///< Time of death. If < 0.0 then dead
  32. F32 m_initialSize;
  33. F32 m_finalSize;
  34. F32 m_crntSize;
  35. F32 m_initialAlpha;
  36. F32 m_finalAlpha;
  37. F32 m_crntAlpha;
  38. Vec3 m_crntPosition;
  39. Bool isDead() const
  40. {
  41. return m_timeOfDeath < 0.0;
  42. }
  43. /// Kill the particle
  44. void killCommon()
  45. {
  46. ANKI_ASSERT(m_timeOfDeath > 0.0);
  47. m_timeOfDeath = -1.0;
  48. }
  49. /// Revive the particle
  50. void reviveCommon(const ParticleEmitterProperties& props, const Transform& trf, Second prevUpdateTime,
  51. Second crntTime)
  52. {
  53. ANKI_ASSERT(isDead());
  54. // life
  55. m_timeOfDeath = crntTime + getRandomRange(props.m_particle.m_minLife, props.m_particle.m_maxLife);
  56. m_timeOfBirth = crntTime;
  57. // Size
  58. m_initialSize = getRandomRange(props.m_particle.m_minInitialSize, props.m_particle.m_maxInitialSize);
  59. m_finalSize = getRandomRange(props.m_particle.m_minFinalSize, props.m_particle.m_maxFinalSize);
  60. // Alpha
  61. m_initialAlpha = getRandomRange(props.m_particle.m_minInitialAlpha, props.m_particle.m_maxInitialAlpha);
  62. m_finalAlpha = getRandomRange(props.m_particle.m_minFinalAlpha, props.m_particle.m_maxFinalAlpha);
  63. }
  64. /// Common sumulation code
  65. void simulateCommon(Second prevUpdateTime, Second crntTime)
  66. {
  67. const F32 lifeFactor = F32((crntTime - m_timeOfBirth) / (m_timeOfDeath - m_timeOfBirth));
  68. m_crntSize = mix(m_initialSize, m_finalSize, lifeFactor);
  69. m_crntAlpha = mix(m_initialAlpha, m_finalAlpha, lifeFactor);
  70. }
  71. };
  72. /// Simple particle for simple simulation
  73. class ParticleEmitterComponent::SimpleParticle : public ParticleEmitterComponent::ParticleBase
  74. {
  75. public:
  76. Vec3 m_velocity = Vec3(0.0f);
  77. Vec3 m_acceleration = Vec3(0.0f);
  78. void kill()
  79. {
  80. killCommon();
  81. }
  82. void revive(const ParticleEmitterProperties& props, const Transform& trf, Second prevUpdateTime, Second crntTime)
  83. {
  84. reviveCommon(props, trf, prevUpdateTime, crntTime);
  85. m_velocity = Vec3(0.0f);
  86. m_acceleration = getRandom(props.m_particle.m_minGravity, props.m_particle.m_maxGravity);
  87. // Set the initial position
  88. m_crntPosition = getRandom(props.m_particle.m_minStartingPosition, props.m_particle.m_maxStartingPosition);
  89. m_crntPosition += trf.getOrigin().xyz();
  90. }
  91. void simulate(Second prevUpdateTime, Second crntTime)
  92. {
  93. simulateCommon(prevUpdateTime, crntTime);
  94. const F32 dt = F32(crntTime - prevUpdateTime);
  95. const Vec3 xp = m_crntPosition;
  96. const Vec3 xc = m_acceleration * (dt * dt) + m_velocity * dt + xp;
  97. m_crntPosition = xc;
  98. m_velocity += m_acceleration * dt;
  99. }
  100. };
  101. /// Particle for bullet simulations
  102. class ParticleEmitterComponent::PhysicsParticle : public ParticleEmitterComponent::ParticleBase
  103. {
  104. public:
  105. PhysicsBodyPtr m_body;
  106. PhysicsParticle(const PhysicsBodyInitInfo& init, SceneNode* node, ParticleEmitterComponent* component)
  107. {
  108. m_body = node->getSceneGraph().getPhysicsWorld().newInstance<PhysicsBody>(init);
  109. m_body->setUserData(component);
  110. m_body->activate(false);
  111. m_body->setMaterialGroup(PhysicsMaterialBit::PARTICLE);
  112. m_body->setMaterialMask(PhysicsMaterialBit::STATIC_GEOMETRY);
  113. m_body->setAngularFactor(Vec3(0.0f));
  114. }
  115. void kill()
  116. {
  117. killCommon();
  118. m_body->activate(false);
  119. }
  120. void revive(const ParticleEmitterProperties& props, const Transform& trf, Second prevUpdateTime, Second crntTime)
  121. {
  122. reviveCommon(props, trf, prevUpdateTime, crntTime);
  123. // pre calculate
  124. const Bool forceFlag = props.forceEnabled();
  125. const Bool worldGravFlag = props.wordGravityEnabled();
  126. // Activate it
  127. m_body->activate(true);
  128. m_body->setLinearVelocity(Vec3(0.0f));
  129. m_body->setAngularVelocity(Vec3(0.0f));
  130. m_body->clearForces();
  131. // force
  132. if(forceFlag)
  133. {
  134. Vec3 forceDir = getRandom(props.m_particle.m_minForceDirection, props.m_particle.m_maxForceDirection);
  135. forceDir.normalize();
  136. // The forceDir depends on the particle emitter rotation
  137. forceDir = trf.getRotation().getRotationPart() * forceDir;
  138. const F32 forceMag =
  139. getRandomRange(props.m_particle.m_minForceMagnitude, props.m_particle.m_maxForceMagnitude);
  140. m_body->applyForce(forceDir * forceMag, Vec3(0.0f));
  141. }
  142. // gravity
  143. if(!worldGravFlag)
  144. {
  145. m_body->setGravity(getRandom(props.m_particle.m_minGravity, props.m_particle.m_maxGravity));
  146. }
  147. // Starting pos. In local space
  148. Vec3 pos = getRandom(props.m_particle.m_minStartingPosition, props.m_particle.m_maxStartingPosition);
  149. pos = trf.transform(pos);
  150. m_body->setTransform(Transform(pos.xyz0(), trf.getRotation(), 1.0f));
  151. m_crntPosition = pos;
  152. }
  153. void simulate(Second prevUpdateTime, Second crntTime)
  154. {
  155. simulateCommon(prevUpdateTime, crntTime);
  156. m_crntPosition = m_body->getTransform().getOrigin().xyz();
  157. }
  158. };
  159. ParticleEmitterComponent::ParticleEmitterComponent(SceneNode* node)
  160. : SceneComponent(node, getStaticClassId())
  161. , m_node(node)
  162. {
  163. }
  164. ParticleEmitterComponent::~ParticleEmitterComponent()
  165. {
  166. m_simpleParticles.destroy(m_node->getAllocator());
  167. m_physicsParticles.destroy(m_node->getAllocator());
  168. }
  169. Error ParticleEmitterComponent::loadParticleEmitterResource(CString filename)
  170. {
  171. // Create the debug drawer
  172. if(!m_dbgImage.isCreated())
  173. {
  174. ANKI_CHECK(m_node->getSceneGraph().getResourceManager().loadResource("EngineAssets/ParticleEmitter.ankitex",
  175. m_dbgImage));
  176. }
  177. // Load
  178. ANKI_CHECK(m_node->getSceneGraph().getResourceManager().loadResource(filename, m_particleEmitterResource));
  179. m_props = m_particleEmitterResource->getProperties();
  180. // Cleanup
  181. m_simpleParticles.destroy(m_node->getAllocator());
  182. m_physicsParticles.destroy(m_node->getAllocator());
  183. // Init particles
  184. m_simulationType = (m_props.m_usePhysicsEngine) ? SimulationType::PHYSICS_ENGINE : SimulationType::SIMPLE;
  185. if(m_simulationType == SimulationType::PHYSICS_ENGINE)
  186. {
  187. PhysicsCollisionShapePtr collisionShape = m_node->getSceneGraph().getPhysicsWorld().newInstance<PhysicsSphere>(
  188. m_props.m_particle.m_minInitialSize / 2.0f);
  189. PhysicsBodyInitInfo binit;
  190. binit.m_shape = collisionShape;
  191. m_physicsParticles.resizeStorage(m_node->getAllocator(), m_props.m_maxNumOfParticles);
  192. for(U32 i = 0; i < m_props.m_maxNumOfParticles; i++)
  193. {
  194. binit.m_mass = getRandomRange(m_props.m_particle.m_minMass, m_props.m_particle.m_maxMass);
  195. m_physicsParticles.emplaceBack(m_node->getAllocator(), binit, m_node, this);
  196. }
  197. }
  198. else
  199. {
  200. m_simpleParticles.create(m_node->getAllocator(), m_props.m_maxNumOfParticles);
  201. }
  202. m_vertBuffSize = m_props.m_maxNumOfParticles * VERTEX_SIZE;
  203. return Error::NONE;
  204. }
  205. Error ParticleEmitterComponent::update(SceneNode& node, Second prevTime, Second crntTime, Bool& updated)
  206. {
  207. if(ANKI_UNLIKELY(!m_particleEmitterResource.isCreated()))
  208. {
  209. updated = false;
  210. return Error::NONE;
  211. }
  212. updated = true;
  213. if(m_simulationType == SimulationType::SIMPLE)
  214. {
  215. simulate(prevTime, crntTime, WeakArray<SimpleParticle>(m_simpleParticles));
  216. }
  217. else
  218. {
  219. ANKI_ASSERT(m_simulationType == SimulationType::PHYSICS_ENGINE);
  220. simulate(prevTime, crntTime, WeakArray<PhysicsParticle>(m_physicsParticles));
  221. }
  222. return Error::NONE;
  223. }
  224. template<typename TParticle>
  225. void ParticleEmitterComponent::simulate(Second prevUpdateTime, Second crntTime, WeakArray<TParticle> particles)
  226. {
  227. // - Deactivate the dead particles
  228. // - Calc the AABB
  229. // - Calc the instancing stuff
  230. Vec3 aabbMin(MAX_F32);
  231. Vec3 aabbMax(MIN_F32);
  232. m_aliveParticleCount = 0;
  233. F32* verts = reinterpret_cast<F32*>(m_node->getFrameAllocator().allocate(m_vertBuffSize));
  234. m_verts = verts;
  235. F32 maxParticleSize = -1.0f;
  236. for(TParticle& particle : particles)
  237. {
  238. if(particle.isDead())
  239. {
  240. // if its already dead so dont deactivate it again
  241. continue;
  242. }
  243. if(particle.m_timeOfDeath < crntTime)
  244. {
  245. // Just died
  246. particle.kill();
  247. }
  248. else
  249. {
  250. // It's alive
  251. // Do checks
  252. ANKI_ASSERT((ptrToNumber(verts) + VERTEX_SIZE - ptrToNumber(m_verts)) <= m_vertBuffSize);
  253. // This will calculate a new world transformation
  254. particle.simulate(prevUpdateTime, crntTime);
  255. const Vec3& origin = particle.m_crntPosition;
  256. aabbMin = aabbMin.min(origin);
  257. aabbMax = aabbMax.max(origin);
  258. verts[0] = origin.x();
  259. verts[1] = origin.y();
  260. verts[2] = origin.z();
  261. verts[3] = particle.m_crntSize;
  262. maxParticleSize = max(maxParticleSize, particle.m_crntSize);
  263. verts[4] = clamp(particle.m_crntAlpha, 0.0f, 1.0f);
  264. ++m_aliveParticleCount;
  265. verts += 5;
  266. }
  267. }
  268. // AABB
  269. if(m_aliveParticleCount != 0)
  270. {
  271. ANKI_ASSERT(maxParticleSize > 0.0f);
  272. const Vec3 min = aabbMin - maxParticleSize;
  273. const Vec3 max = aabbMax + maxParticleSize;
  274. m_worldBoundingVolume = Aabb(min, max);
  275. }
  276. else
  277. {
  278. m_worldBoundingVolume = Aabb(Vec3(0.0f), Vec3(0.001f));
  279. m_verts = nullptr;
  280. }
  281. //
  282. // Emit new particles
  283. //
  284. if(m_timeLeftForNextEmission <= 0.0)
  285. {
  286. U particleCount = 0; // How many particles I am allowed to emmit
  287. for(TParticle& particle : particles)
  288. {
  289. if(!particle.isDead())
  290. {
  291. // its alive so skip it
  292. continue;
  293. }
  294. particle.revive(m_props, m_transform, prevUpdateTime, crntTime);
  295. // do the rest
  296. ++particleCount;
  297. if(particleCount >= m_props.m_particlesPerEmission)
  298. {
  299. break;
  300. }
  301. } // end for all particles
  302. m_timeLeftForNextEmission = m_props.m_emissionPeriod;
  303. } // end if can emit
  304. else
  305. {
  306. m_timeLeftForNextEmission -= crntTime - prevUpdateTime;
  307. }
  308. }
  309. void ParticleEmitterComponent::draw(RenderQueueDrawContext& ctx) const
  310. {
  311. // Early exit
  312. if(ANKI_UNLIKELY(m_aliveParticleCount == 0))
  313. {
  314. return;
  315. }
  316. CommandBufferPtr& cmdb = ctx.m_commandBuffer;
  317. if(!ctx.m_debugDraw)
  318. {
  319. // Load verts
  320. StagingGpuMemoryToken token;
  321. void* gpuStorage = ctx.m_stagingGpuAllocator->allocateFrame(m_aliveParticleCount * VERTEX_SIZE,
  322. StagingGpuMemoryType::VERTEX, token);
  323. memcpy(gpuStorage, m_verts, m_aliveParticleCount * VERTEX_SIZE);
  324. // Program
  325. ShaderProgramPtr prog;
  326. m_particleEmitterResource->getRenderingInfo(ctx.m_key, prog);
  327. cmdb->bindShaderProgram(prog);
  328. // Vertex attribs
  329. cmdb->setVertexAttribute(U32(VertexAttributeId::POSITION), 0, Format::R32G32B32_SFLOAT, 0);
  330. cmdb->setVertexAttribute(U32(VertexAttributeId::SCALE), 0, Format::R32_SFLOAT, sizeof(Vec3));
  331. cmdb->setVertexAttribute(U32(VertexAttributeId::ALPHA), 0, Format::R32_SFLOAT, sizeof(Vec3) + sizeof(F32));
  332. // Vertex buff
  333. cmdb->bindVertexBuffer(0, token.m_buffer, token.m_offset, VERTEX_SIZE, VertexStepRate::INSTANCE);
  334. // Uniforms
  335. Array<Mat4, 1> trf = {Mat4::getIdentity()};
  336. RenderComponent::allocateAndSetupUniforms(m_particleEmitterResource->getMaterial(), ctx, trf, trf,
  337. *ctx.m_stagingGpuAllocator);
  338. // Draw
  339. cmdb->drawArrays(PrimitiveTopology::TRIANGLE_STRIP, 4, m_aliveParticleCount, 0, 0);
  340. }
  341. else
  342. {
  343. const Vec4 tsl = (m_worldBoundingVolume.getMin() + m_worldBoundingVolume.getMax()) / 2.0f;
  344. const Vec4 scale = (m_worldBoundingVolume.getMax() - m_worldBoundingVolume.getMin()) / 2.0f;
  345. // Set non uniform scale. Add a margin to avoid flickering
  346. Mat3 nonUniScale = Mat3::getZero();
  347. nonUniScale(0, 0) = scale.x();
  348. nonUniScale(1, 1) = scale.y();
  349. nonUniScale(2, 2) = scale.z();
  350. const Mat4 mvp = ctx.m_viewProjectionMatrix * Mat4(tsl.xyz1(), Mat3::getIdentity() * nonUniScale, 1.0f);
  351. const Bool enableDepthTest = ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DEPTH_TEST_ON);
  352. if(enableDepthTest)
  353. {
  354. cmdb->setDepthCompareOperation(CompareOperation::LESS);
  355. }
  356. else
  357. {
  358. cmdb->setDepthCompareOperation(CompareOperation::ALWAYS);
  359. }
  360. m_node->getSceneGraph().getDebugDrawer().drawCubes(
  361. ConstWeakArray<Mat4>(&mvp, 1), Vec4(1.0f, 0.0f, 1.0f, 1.0f), 2.0f,
  362. ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DITHERED_DEPTH_TEST_ON), 2.0f,
  363. *ctx.m_stagingGpuAllocator, cmdb);
  364. const Vec3 pos = m_transform.getOrigin().xyz();
  365. m_node->getSceneGraph().getDebugDrawer().drawBillboardTextures(
  366. ctx.m_projectionMatrix, ctx.m_viewMatrix, ConstWeakArray<Vec3>(&pos, 1), Vec4(1.0f),
  367. ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DITHERED_DEPTH_TEST_ON), m_dbgImage->getTextureView(),
  368. ctx.m_sampler, Vec2(0.75f), *ctx.m_stagingGpuAllocator, ctx.m_commandBuffer);
  369. // Restore state
  370. if(!enableDepthTest)
  371. {
  372. cmdb->setDepthCompareOperation(CompareOperation::LESS);
  373. }
  374. }
  375. }
  376. } // end namespace anki