ParticleEmitterComponent.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. // Copyright (C) 2009-2023, 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/MoveComponent.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. #include <AnKi/Shaders/Include/GpuSceneFunctions.h>
  17. #include <AnKi/Core/GpuMemory/RebarTransientMemoryPool.h>
  18. namespace anki {
  19. static Vec3 getRandom(const Vec3& min, const Vec3& max)
  20. {
  21. Vec3 out;
  22. out.x() = mix(min.x(), max.x(), getRandomRange(0.0f, 1.0f));
  23. out.y() = mix(min.y(), max.y(), getRandomRange(0.0f, 1.0f));
  24. out.z() = mix(min.z(), max.z(), getRandomRange(0.0f, 1.0f));
  25. return out;
  26. }
  27. /// Particle base
  28. class ParticleEmitterComponent::ParticleBase
  29. {
  30. public:
  31. Second m_timeOfBirth; ///< Keep the time of birth for nice effects
  32. Second m_timeOfDeath = -1.0; ///< Time of death. If < 0.0 then dead
  33. F32 m_initialSize;
  34. F32 m_finalSize;
  35. F32 m_crntSize;
  36. F32 m_initialAlpha;
  37. F32 m_finalAlpha;
  38. F32 m_crntAlpha;
  39. Vec3 m_crntPosition;
  40. Bool isDead() const
  41. {
  42. return m_timeOfDeath < 0.0;
  43. }
  44. /// Kill the particle
  45. void killCommon()
  46. {
  47. ANKI_ASSERT(m_timeOfDeath > 0.0);
  48. m_timeOfDeath = -1.0;
  49. }
  50. /// Revive the particle
  51. void reviveCommon(const ParticleEmitterProperties& props, 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 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 crntTime)
  83. {
  84. reviveCommon(props, 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(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, ParticleEmitterComponent* component)
  107. {
  108. m_body = PhysicsWorld::getSingleton().newInstance<PhysicsBody>(init);
  109. m_body->setUserData(component);
  110. m_body->activate(false);
  111. m_body->setMaterialGroup(PhysicsMaterialBit::kParticle);
  112. m_body->setMaterialMask(PhysicsMaterialBit::kStaticGeometry);
  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 crntTime)
  121. {
  122. reviveCommon(props, 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 = getRandomRange(props.m_particle.m_minForceMagnitude, props.m_particle.m_maxForceMagnitude);
  139. m_body->applyForce(forceDir * forceMag, Vec3(0.0f));
  140. }
  141. // gravity
  142. if(!worldGravFlag)
  143. {
  144. m_body->setGravity(getRandom(props.m_particle.m_minGravity, props.m_particle.m_maxGravity));
  145. }
  146. // Starting pos. In local space
  147. Vec3 pos = getRandom(props.m_particle.m_minStartingPosition, props.m_particle.m_maxStartingPosition);
  148. pos = trf.transform(pos);
  149. m_body->setTransform(Transform(pos.xyz0(), trf.getRotation(), 1.0f));
  150. m_crntPosition = pos;
  151. }
  152. void simulate([[maybe_unused]] Second prevUpdateTime, Second crntTime)
  153. {
  154. simulateCommon(crntTime);
  155. m_crntPosition = m_body->getTransform().getOrigin().xyz();
  156. }
  157. };
  158. ParticleEmitterComponent::ParticleEmitterComponent(SceneNode* node)
  159. : SceneComponent(node, kClassType)
  160. {
  161. // Allocate and populate a quad
  162. const U32 vertCount = 4;
  163. const U32 indexCount = 6;
  164. m_quadPositions = UnifiedGeometryBuffer::getSingleton().allocateFormat(kMeshRelatedVertexStreamFormats[VertexStreamId::kPosition], vertCount);
  165. m_quadUvs = UnifiedGeometryBuffer::getSingleton().allocateFormat(kMeshRelatedVertexStreamFormats[VertexStreamId::kUv], vertCount);
  166. m_quadIndices = UnifiedGeometryBuffer::getSingleton().allocateFormat(Format::kR16_Uint, indexCount);
  167. static_assert(kMeshRelatedVertexStreamFormats[VertexStreamId::kPosition] == Format::kR16G16B16A16_Unorm);
  168. WeakArray<U16Vec4> transientPositions;
  169. const RebarAllocation positionsAlloc = RebarTransientMemoryPool::getSingleton().allocateFrame(vertCount, transientPositions);
  170. transientPositions[0] = U16Vec4(0, 0, 0, 0);
  171. transientPositions[1] = U16Vec4(kMaxU16, 0, 0, 0);
  172. transientPositions[2] = U16Vec4(kMaxU16, kMaxU16, 0, 0);
  173. transientPositions[3] = U16Vec4(0, kMaxU16, 0, 0);
  174. static_assert(kMeshRelatedVertexStreamFormats[VertexStreamId::kUv] == Format::kR32G32_Sfloat);
  175. WeakArray<Vec2> transientUvs;
  176. const RebarAllocation uvsAlloc = RebarTransientMemoryPool::getSingleton().allocateFrame(vertCount, transientUvs);
  177. transientUvs[0] = Vec2(0.0f);
  178. transientUvs[1] = Vec2(1.0f, 0.0f);
  179. transientUvs[2] = Vec2(1.0f, 1.0f);
  180. transientUvs[3] = Vec2(0.0f, 1.0f);
  181. WeakArray<U16> transientIndices;
  182. const RebarAllocation indicesAlloc = RebarTransientMemoryPool::getSingleton().allocateFrame(indexCount, transientIndices);
  183. transientIndices[0] = 0;
  184. transientIndices[1] = 1;
  185. transientIndices[2] = 3;
  186. transientIndices[3] = 1;
  187. transientIndices[4] = 2;
  188. transientIndices[5] = 3;
  189. CommandBufferInitInfo cmdbInit("Particle quad upload");
  190. cmdbInit.m_flags |= CommandBufferFlag::kSmallBatch;
  191. CommandBufferPtr cmdb = GrManager::getSingleton().newCommandBuffer(cmdbInit);
  192. Buffer* srcBuff = &RebarTransientMemoryPool::getSingleton().getBuffer();
  193. Buffer* dstBuff = &UnifiedGeometryBuffer::getSingleton().getBuffer();
  194. cmdb->copyBufferToBuffer(srcBuff, positionsAlloc.getOffset(), dstBuff, m_quadPositions.getOffset(), positionsAlloc.getRange());
  195. cmdb->copyBufferToBuffer(srcBuff, uvsAlloc.getOffset(), dstBuff, m_quadUvs.getOffset(), uvsAlloc.getRange());
  196. cmdb->copyBufferToBuffer(srcBuff, indicesAlloc.getOffset(), dstBuff, m_quadIndices.getOffset(), indicesAlloc.getRange());
  197. BufferBarrierInfo barrier;
  198. barrier.m_buffer = dstBuff;
  199. barrier.m_offset = 0;
  200. barrier.m_range = kMaxPtrSize;
  201. barrier.m_previousUsage = BufferUsageBit::kTransferDestination;
  202. barrier.m_nextUsage = dstBuff->getBufferUsage();
  203. cmdb->setPipelineBarrier({}, {&barrier, 1}, {});
  204. cmdb->flush();
  205. }
  206. ParticleEmitterComponent::~ParticleEmitterComponent()
  207. {
  208. }
  209. void ParticleEmitterComponent::loadParticleEmitterResource(CString filename)
  210. {
  211. // Load
  212. ParticleEmitterResourcePtr rsrc;
  213. const Error err = ResourceManager::getSingleton().loadResource(filename, rsrc);
  214. if(err)
  215. {
  216. ANKI_SCENE_LOGE("Failed to load particle emitter");
  217. return;
  218. }
  219. m_particleEmitterResource = std::move(rsrc);
  220. m_props = m_particleEmitterResource->getProperties();
  221. m_resourceUpdated = true;
  222. // Cleanup
  223. m_simpleParticles.destroy();
  224. m_physicsParticles.destroy();
  225. GpuSceneBuffer::getSingleton().deferredFree(m_gpuScenePositions);
  226. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneScales);
  227. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneAlphas);
  228. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneUniforms);
  229. for(RenderStateBucketIndex& idx : m_renderStateBuckets)
  230. {
  231. RenderStateBucketContainer::getSingleton().removeUser(idx);
  232. }
  233. // Init particles
  234. m_simulationType = (m_props.m_usePhysicsEngine) ? SimulationType::kPhysicsEngine : SimulationType::kSimple;
  235. if(m_simulationType == SimulationType::kPhysicsEngine)
  236. {
  237. PhysicsCollisionShapePtr collisionShape = PhysicsWorld::getSingleton().newInstance<PhysicsSphere>(m_props.m_particle.m_minInitialSize / 2.0f);
  238. PhysicsBodyInitInfo binit;
  239. binit.m_shape = std::move(collisionShape);
  240. m_physicsParticles.resizeStorage(m_props.m_maxNumOfParticles);
  241. for(U32 i = 0; i < m_props.m_maxNumOfParticles; i++)
  242. {
  243. binit.m_mass = getRandomRange(m_props.m_particle.m_minMass, m_props.m_particle.m_maxMass);
  244. m_physicsParticles.emplaceBack(binit, this);
  245. }
  246. }
  247. else
  248. {
  249. m_simpleParticles.resize(m_props.m_maxNumOfParticles);
  250. }
  251. // GPU scene allocations
  252. m_gpuScenePositions = GpuSceneBuffer::getSingleton().allocate(sizeof(Vec3) * m_props.m_maxNumOfParticles, alignof(F32));
  253. m_gpuSceneAlphas = GpuSceneBuffer::getSingleton().allocate(sizeof(F32) * m_props.m_maxNumOfParticles, alignof(F32));
  254. m_gpuSceneScales = GpuSceneBuffer::getSingleton().allocate(sizeof(F32) * m_props.m_maxNumOfParticles, alignof(F32));
  255. m_gpuSceneUniforms =
  256. GpuSceneBuffer::getSingleton().allocate(m_particleEmitterResource->getMaterial()->getPrefilledLocalUniforms().getSizeInBytes(), alignof(U32));
  257. // Allocate buckets
  258. for(RenderingTechnique t :
  259. EnumBitsIterable<RenderingTechnique, RenderingTechniqueBit>(m_particleEmitterResource->getMaterial()->getRenderingTechniques()))
  260. {
  261. RenderingKey key;
  262. key.setRenderingTechnique(t);
  263. ShaderProgramPtr prog;
  264. m_particleEmitterResource->getRenderingInfo(key, prog);
  265. RenderStateInfo state;
  266. state.m_program = prog;
  267. state.m_primitiveTopology = PrimitiveTopology::kTriangles;
  268. state.m_indexedDrawcall = false;
  269. m_renderStateBuckets[t] = RenderStateBucketContainer::getSingleton().addUser(state, t);
  270. }
  271. }
  272. Error ParticleEmitterComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  273. {
  274. if(!m_particleEmitterResource.isCreated()) [[unlikely]]
  275. {
  276. updated = false;
  277. return Error::kNone;
  278. }
  279. updated = true;
  280. Vec3* positions;
  281. F32* scales;
  282. F32* alphas;
  283. Aabb aabbWorld;
  284. if(m_simulationType == SimulationType::kSimple)
  285. {
  286. simulate(info.m_previousTime, info.m_currentTime, info.m_node->getWorldTransform(), WeakArray<SimpleParticle>(m_simpleParticles), positions,
  287. scales, alphas, aabbWorld);
  288. }
  289. else
  290. {
  291. ANKI_ASSERT(m_simulationType == SimulationType::kPhysicsEngine);
  292. simulate(info.m_previousTime, info.m_currentTime, info.m_node->getWorldTransform(), WeakArray<PhysicsParticle>(m_physicsParticles), positions,
  293. scales, alphas, aabbWorld);
  294. }
  295. // Upload particles to the GPU scene
  296. GpuSceneMicroPatcher& patcher = GpuSceneMicroPatcher::getSingleton();
  297. if(m_aliveParticleCount > 0)
  298. {
  299. patcher.newCopy(*info.m_framePool, m_gpuScenePositions, sizeof(Vec3) * m_aliveParticleCount, positions);
  300. patcher.newCopy(*info.m_framePool, m_gpuSceneScales, sizeof(F32) * m_aliveParticleCount, scales);
  301. patcher.newCopy(*info.m_framePool, m_gpuSceneAlphas, sizeof(F32) * m_aliveParticleCount, alphas);
  302. }
  303. if(m_resourceUpdated)
  304. {
  305. // Upload GpuSceneParticleEmitter
  306. GpuSceneParticleEmitter particles = {};
  307. particles.m_vertexOffsets[U32(VertexStreamId::kParticlePosition)] = m_gpuScenePositions.getOffset();
  308. particles.m_vertexOffsets[U32(VertexStreamId::kParticleColor)] = m_gpuSceneAlphas.getOffset();
  309. particles.m_vertexOffsets[U32(VertexStreamId::kParticleScale)] = m_gpuSceneScales.getOffset();
  310. particles.m_aliveParticleCount = m_aliveParticleCount;
  311. if(!m_gpuSceneParticleEmitter.isValid())
  312. {
  313. m_gpuSceneParticleEmitter.allocate();
  314. }
  315. m_gpuSceneParticleEmitter.uploadToGpuScene(particles);
  316. // Upload uniforms
  317. patcher.newCopy(*info.m_framePool, m_gpuSceneUniforms, m_particleEmitterResource->getMaterial()->getPrefilledLocalUniforms().getSizeInBytes(),
  318. m_particleEmitterResource->getMaterial()->getPrefilledLocalUniforms().getBegin());
  319. // Upload mesh LODs
  320. GpuSceneMeshLod meshLod = {};
  321. meshLod.m_vertexOffsets[U32(VertexStreamId::kPosition)] =
  322. m_quadPositions.getOffset() / getFormatInfo(kMeshRelatedVertexStreamFormats[VertexStreamId::kPosition]).m_texelSize;
  323. meshLod.m_vertexOffsets[U32(VertexStreamId::kUv)] =
  324. m_quadUvs.getOffset() / getFormatInfo(kMeshRelatedVertexStreamFormats[VertexStreamId::kUv]).m_texelSize;
  325. meshLod.m_indexCount = 6;
  326. meshLod.m_firstIndex = m_quadIndices.getOffset() / sizeof(U16);
  327. meshLod.m_positionScale = 1.0f;
  328. meshLod.m_positionTranslation = Vec3(-0.5f, -0.5f, 0.0f);
  329. Array<GpuSceneMeshLod, kMaxLodCount> meshLods;
  330. meshLods.fill(meshLod);
  331. if(!m_gpuSceneMeshLods.isValid())
  332. {
  333. m_gpuSceneMeshLods.allocate();
  334. }
  335. m_gpuSceneMeshLods.uploadToGpuScene(meshLods);
  336. // Upload the GpuSceneRenderable
  337. GpuSceneRenderable renderable;
  338. renderable.m_boneTransformsOffset = 0;
  339. renderable.m_uniformsOffset = m_gpuSceneUniforms.getOffset();
  340. renderable.m_meshLodsOffset = m_gpuSceneMeshLods.getGpuSceneOffset();
  341. renderable.m_particleEmitterOffset = m_gpuSceneParticleEmitter.getGpuSceneOffset();
  342. renderable.m_worldTransformsOffset = 0;
  343. if(!m_gpuSceneRenderable.isValid())
  344. {
  345. m_gpuSceneRenderable.allocate();
  346. }
  347. m_gpuSceneRenderable.uploadToGpuScene(renderable);
  348. }
  349. if(!m_resourceUpdated)
  350. {
  351. // Always upload GpuSceneParticleEmitter
  352. GpuSceneParticleEmitter particles = {};
  353. particles.m_vertexOffsets[U32(VertexStreamId::kParticlePosition)] = m_gpuScenePositions.getOffset();
  354. particles.m_vertexOffsets[U32(VertexStreamId::kParticleColor)] = m_gpuSceneAlphas.getOffset();
  355. particles.m_vertexOffsets[U32(VertexStreamId::kParticleScale)] = m_gpuSceneScales.getOffset();
  356. particles.m_aliveParticleCount = m_aliveParticleCount;
  357. if(!m_gpuSceneParticleEmitter.isValid())
  358. {
  359. m_gpuSceneParticleEmitter.allocate();
  360. }
  361. m_gpuSceneParticleEmitter.uploadToGpuScene(particles);
  362. }
  363. // Upload the GpuSceneRenderableAabb always
  364. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  365. {
  366. if(!!(RenderingTechniqueBit(1 << t) & m_particleEmitterResource->getMaterial()->getRenderingTechniques()))
  367. {
  368. const GpuSceneRenderableAabb gpuVolume = initGpuSceneRenderableAabb(aabbWorld.getMin().xyz(), aabbWorld.getMax().xyz(),
  369. m_gpuSceneRenderable.getIndex(), m_renderStateBuckets[t].get());
  370. switch(t)
  371. {
  372. case RenderingTechnique::kGBuffer:
  373. if(!m_gpuSceneRenderableAabbGBuffer.isValid())
  374. {
  375. m_gpuSceneRenderableAabbGBuffer.allocate();
  376. }
  377. m_gpuSceneRenderableAabbGBuffer.uploadToGpuScene(gpuVolume);
  378. break;
  379. case RenderingTechnique::kDepth:
  380. if(!m_gpuSceneRenderableAabbDepth.isValid())
  381. {
  382. m_gpuSceneRenderableAabbDepth.allocate();
  383. }
  384. m_gpuSceneRenderableAabbDepth.uploadToGpuScene(gpuVolume);
  385. break;
  386. case RenderingTechnique::kForward:
  387. if(!m_gpuSceneRenderableAabbForward.isValid())
  388. {
  389. m_gpuSceneRenderableAabbForward.allocate();
  390. }
  391. m_gpuSceneRenderableAabbForward.uploadToGpuScene(gpuVolume);
  392. break;
  393. default:
  394. ANKI_ASSERT(0);
  395. }
  396. }
  397. else if(!!(RenderingTechniqueBit(1 << t) & RenderingTechniqueBit::kAllRt))
  398. {
  399. continue;
  400. }
  401. else
  402. {
  403. switch(t)
  404. {
  405. case RenderingTechnique::kGBuffer:
  406. m_gpuSceneRenderableAabbGBuffer.free();
  407. break;
  408. case RenderingTechnique::kDepth:
  409. m_gpuSceneRenderableAabbDepth.free();
  410. break;
  411. case RenderingTechnique::kForward:
  412. m_gpuSceneRenderableAabbForward.free();
  413. break;
  414. default:
  415. ANKI_ASSERT(0);
  416. }
  417. }
  418. }
  419. m_resourceUpdated = false;
  420. return Error::kNone;
  421. }
  422. template<typename TParticle>
  423. void ParticleEmitterComponent::simulate(Second prevUpdateTime, Second crntTime, const Transform& worldTransform, WeakArray<TParticle> particles,
  424. Vec3*& positions, F32*& scales, F32*& alphas, Aabb& aabbWorld)
  425. {
  426. // - Deactivate the dead particles
  427. // - Calc the AABB
  428. // - Calc the instancing stuff
  429. Vec3 aabbMin(kMaxF32);
  430. Vec3 aabbMax(kMinF32);
  431. m_aliveParticleCount = 0;
  432. positions =
  433. static_cast<Vec3*>(SceneGraph::getSingleton().getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(Vec3), alignof(Vec3)));
  434. scales = static_cast<F32*>(SceneGraph::getSingleton().getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(F32), alignof(F32)));
  435. alphas = static_cast<F32*>(SceneGraph::getSingleton().getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(F32), alignof(F32)));
  436. F32 maxParticleSize = -1.0f;
  437. for(TParticle& particle : particles)
  438. {
  439. if(particle.isDead())
  440. {
  441. // if its already dead so dont deactivate it again
  442. continue;
  443. }
  444. if(particle.m_timeOfDeath < crntTime)
  445. {
  446. // Just died
  447. particle.kill();
  448. }
  449. else
  450. {
  451. // It's alive
  452. // This will calculate a new world transformation
  453. particle.simulate(prevUpdateTime, crntTime);
  454. const Vec3& origin = particle.m_crntPosition;
  455. aabbMin = aabbMin.min(origin);
  456. aabbMax = aabbMax.max(origin);
  457. positions[m_aliveParticleCount] = origin;
  458. scales[m_aliveParticleCount] = particle.m_crntSize;
  459. maxParticleSize = max(maxParticleSize, particle.m_crntSize);
  460. alphas[m_aliveParticleCount] = clamp(particle.m_crntAlpha, 0.0f, 1.0f);
  461. ++m_aliveParticleCount;
  462. }
  463. }
  464. // AABB
  465. if(m_aliveParticleCount != 0)
  466. {
  467. ANKI_ASSERT(maxParticleSize > 0.0f);
  468. const Vec3 min = aabbMin - maxParticleSize;
  469. const Vec3 max = aabbMax + maxParticleSize;
  470. aabbWorld = Aabb(min, max);
  471. }
  472. else
  473. {
  474. aabbWorld = Aabb(Vec3(0.0f), Vec3(0.001f));
  475. positions = nullptr;
  476. alphas = scales = nullptr;
  477. }
  478. //
  479. // Emit new particles
  480. //
  481. if(m_timeLeftForNextEmission <= 0.0)
  482. {
  483. U particleCount = 0; // How many particles I am allowed to emmit
  484. for(TParticle& particle : particles)
  485. {
  486. if(!particle.isDead())
  487. {
  488. // its alive so skip it
  489. continue;
  490. }
  491. particle.revive(m_props, worldTransform, crntTime);
  492. // do the rest
  493. ++particleCount;
  494. if(particleCount >= m_props.m_particlesPerEmission)
  495. {
  496. break;
  497. }
  498. } // end for all particles
  499. m_timeLeftForNextEmission = m_props.m_emissionPeriod;
  500. } // end if can emit
  501. else
  502. {
  503. m_timeLeftForNextEmission -= crntTime - prevUpdateTime;
  504. }
  505. }
  506. } // end namespace anki