ParticleEmitterComponent.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. // Copyright (C) 2009-present, 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/Shaders/Include/GpuSceneFunctions.h>
  16. #include <AnKi/Core/GpuMemory/RebarTransientMemoryPool.h>
  17. namespace anki {
  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, Second crntTime)
  51. {
  52. ANKI_ASSERT(isDead());
  53. // life
  54. m_timeOfDeath = crntTime + getRandomRange(props.m_particle.m_minLife, props.m_particle.m_maxLife);
  55. m_timeOfBirth = crntTime;
  56. // Size
  57. m_initialSize = getRandomRange(props.m_particle.m_minInitialSize, props.m_particle.m_maxInitialSize);
  58. m_finalSize = getRandomRange(props.m_particle.m_minFinalSize, props.m_particle.m_maxFinalSize);
  59. // Alpha
  60. m_initialAlpha = getRandomRange(props.m_particle.m_minInitialAlpha, props.m_particle.m_maxInitialAlpha);
  61. m_finalAlpha = getRandomRange(props.m_particle.m_minFinalAlpha, props.m_particle.m_maxFinalAlpha);
  62. }
  63. /// Common sumulation code
  64. void simulateCommon(Second crntTime)
  65. {
  66. const F32 lifeFactor = F32((crntTime - m_timeOfBirth) / (m_timeOfDeath - m_timeOfBirth));
  67. m_crntSize = mix(m_initialSize, m_finalSize, lifeFactor);
  68. m_crntAlpha = mix(m_initialAlpha, m_finalAlpha, lifeFactor);
  69. }
  70. };
  71. /// Simple particle for simple simulation
  72. class ParticleEmitterComponent::SimpleParticle : public ParticleEmitterComponent::ParticleBase
  73. {
  74. public:
  75. Vec3 m_velocity = Vec3(0.0f);
  76. Vec3 m_acceleration = Vec3(0.0f);
  77. void kill()
  78. {
  79. killCommon();
  80. }
  81. void revive(const ParticleEmitterProperties& props, const Transform& trf, Second crntTime)
  82. {
  83. reviveCommon(props, crntTime);
  84. m_velocity = Vec3(0.0f);
  85. m_acceleration = getRandom(props.m_particle.m_minGravity, props.m_particle.m_maxGravity);
  86. // Set the initial position
  87. m_crntPosition = getRandom(props.m_particle.m_minStartingPosition, props.m_particle.m_maxStartingPosition);
  88. m_crntPosition += trf.getOrigin().xyz();
  89. }
  90. void simulate(Second prevUpdateTime, Second crntTime)
  91. {
  92. simulateCommon(crntTime);
  93. const F32 dt = F32(crntTime - prevUpdateTime);
  94. const Vec3 xp = m_crntPosition;
  95. const Vec3 xc = m_acceleration * (dt * dt) + m_velocity * dt + xp;
  96. m_crntPosition = xc;
  97. m_velocity += m_acceleration * dt;
  98. }
  99. };
  100. /// Particle for bullet simulations
  101. class ParticleEmitterComponent::PhysicsParticle : public ParticleEmitterComponent::ParticleBase
  102. {
  103. public:
  104. PhysicsBodyPtr m_body;
  105. PhysicsParticle(const PhysicsBodyInitInfo& init, ParticleEmitterComponent* component)
  106. {
  107. m_body = PhysicsWorld::getSingleton().newInstance<PhysicsBody>(init);
  108. m_body->setUserData(component);
  109. m_body->activate(false);
  110. m_body->setMaterialGroup(PhysicsMaterialBit::kParticle);
  111. m_body->setMaterialMask(PhysicsMaterialBit::kStaticGeometry);
  112. m_body->setAngularFactor(Vec3(0.0f));
  113. }
  114. void kill()
  115. {
  116. killCommon();
  117. m_body->activate(false);
  118. }
  119. void revive(const ParticleEmitterProperties& props, const Transform& trf, Second crntTime)
  120. {
  121. reviveCommon(props, crntTime);
  122. // pre calculate
  123. const Bool forceFlag = props.forceEnabled();
  124. const Bool worldGravFlag = props.wordGravityEnabled();
  125. // Activate it
  126. m_body->activate(true);
  127. m_body->setLinearVelocity(Vec3(0.0f));
  128. m_body->setAngularVelocity(Vec3(0.0f));
  129. m_body->clearForces();
  130. // force
  131. if(forceFlag)
  132. {
  133. Vec3 forceDir = getRandom(props.m_particle.m_minForceDirection, props.m_particle.m_maxForceDirection);
  134. forceDir.normalize();
  135. // The forceDir depends on the particle emitter rotation
  136. forceDir = trf.getRotation().getRotationPart() * forceDir;
  137. const F32 forceMag = getRandomRange(props.m_particle.m_minForceMagnitude, props.m_particle.m_maxForceMagnitude);
  138. m_body->applyForce(forceDir * forceMag, Vec3(0.0f));
  139. }
  140. // gravity
  141. if(!worldGravFlag)
  142. {
  143. m_body->setGravity(getRandom(props.m_particle.m_minGravity, props.m_particle.m_maxGravity));
  144. }
  145. // Starting pos. In local space
  146. Vec3 pos = getRandom(props.m_particle.m_minStartingPosition, props.m_particle.m_maxStartingPosition);
  147. pos = trf.transform(pos);
  148. m_body->setTransform(Transform(pos.xyz0(), trf.getRotation(), Vec4(1.0f, 1.0f, 1.0f, 0.0f)));
  149. m_crntPosition = pos;
  150. }
  151. void simulate([[maybe_unused]] Second prevUpdateTime, Second crntTime)
  152. {
  153. simulateCommon(crntTime);
  154. m_crntPosition = m_body->getTransform().getOrigin().xyz();
  155. }
  156. };
  157. ParticleEmitterComponent::ParticleEmitterComponent(SceneNode* node)
  158. : SceneComponent(node, kClassType)
  159. {
  160. // Allocate and populate a quad
  161. const U32 vertCount = 4;
  162. const U32 indexCount = 6;
  163. m_quadPositions = UnifiedGeometryBuffer::getSingleton().allocateFormat(kMeshRelatedVertexStreamFormats[VertexStreamId::kPosition], vertCount);
  164. m_quadUvs = UnifiedGeometryBuffer::getSingleton().allocateFormat(kMeshRelatedVertexStreamFormats[VertexStreamId::kUv], vertCount);
  165. m_quadIndices = UnifiedGeometryBuffer::getSingleton().allocateFormat(Format::kR16_Uint, indexCount);
  166. static_assert(kMeshRelatedVertexStreamFormats[VertexStreamId::kPosition] == Format::kR16G16B16A16_Unorm);
  167. WeakArray<U16Vec4> transientPositions;
  168. const RebarAllocation positionsAlloc = RebarTransientMemoryPool::getSingleton().allocateFrame(vertCount, transientPositions);
  169. transientPositions[0] = U16Vec4(0, 0, 0, 0);
  170. transientPositions[1] = U16Vec4(kMaxU16, 0, 0, 0);
  171. transientPositions[2] = U16Vec4(kMaxU16, kMaxU16, 0, 0);
  172. transientPositions[3] = U16Vec4(0, kMaxU16, 0, 0);
  173. static_assert(kMeshRelatedVertexStreamFormats[VertexStreamId::kUv] == Format::kR32G32_Sfloat);
  174. WeakArray<Vec2> transientUvs;
  175. const RebarAllocation uvsAlloc = RebarTransientMemoryPool::getSingleton().allocateFrame(vertCount, transientUvs);
  176. transientUvs[0] = Vec2(0.0f);
  177. transientUvs[1] = Vec2(1.0f, 0.0f);
  178. transientUvs[2] = Vec2(1.0f, 1.0f);
  179. transientUvs[3] = Vec2(0.0f, 1.0f);
  180. WeakArray<U16> transientIndices;
  181. const RebarAllocation indicesAlloc = RebarTransientMemoryPool::getSingleton().allocateFrame(indexCount, transientIndices);
  182. transientIndices[0] = 0;
  183. transientIndices[1] = 1;
  184. transientIndices[2] = 3;
  185. transientIndices[3] = 1;
  186. transientIndices[4] = 2;
  187. transientIndices[5] = 3;
  188. CommandBufferInitInfo cmdbInit("Particle quad upload");
  189. cmdbInit.m_flags |= CommandBufferFlag::kSmallBatch;
  190. CommandBufferPtr cmdb = GrManager::getSingleton().newCommandBuffer(cmdbInit);
  191. Buffer* dstBuff = &UnifiedGeometryBuffer::getSingleton().getBuffer();
  192. cmdb->copyBufferToBuffer(positionsAlloc, m_quadPositions);
  193. cmdb->copyBufferToBuffer(uvsAlloc, m_quadUvs);
  194. cmdb->copyBufferToBuffer(indicesAlloc, m_quadIndices);
  195. BufferBarrierInfo barrier;
  196. barrier.m_bufferView = BufferView(dstBuff);
  197. barrier.m_previousUsage = BufferUsageBit::kCopyDestination;
  198. barrier.m_nextUsage = dstBuff->getBufferUsage();
  199. cmdb->setPipelineBarrier({}, {&barrier, 1}, {});
  200. cmdb->endRecording();
  201. GrManager::getSingleton().submit(cmdb.get());
  202. }
  203. ParticleEmitterComponent::~ParticleEmitterComponent()
  204. {
  205. }
  206. void ParticleEmitterComponent::loadParticleEmitterResource(CString filename)
  207. {
  208. // Load
  209. ParticleEmitterResourcePtr rsrc;
  210. const Error err = ResourceManager::getSingleton().loadResource(filename, rsrc);
  211. if(err)
  212. {
  213. ANKI_SCENE_LOGE("Failed to load particle emitter");
  214. return;
  215. }
  216. m_particleEmitterResource = std::move(rsrc);
  217. m_props = m_particleEmitterResource->getProperties();
  218. m_resourceUpdated = true;
  219. // Cleanup
  220. m_simpleParticles.destroy();
  221. m_physicsParticles.destroy();
  222. GpuSceneBuffer::getSingleton().deferredFree(m_gpuScenePositions);
  223. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneScales);
  224. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneAlphas);
  225. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneConstants);
  226. for(RenderStateBucketIndex& idx : m_renderStateBuckets)
  227. {
  228. RenderStateBucketContainer::getSingleton().removeUser(idx);
  229. }
  230. // Init particles
  231. m_simulationType = (m_props.m_usePhysicsEngine) ? SimulationType::kPhysicsEngine : SimulationType::kSimple;
  232. if(m_simulationType == SimulationType::kPhysicsEngine)
  233. {
  234. PhysicsCollisionShapePtr collisionShape = PhysicsWorld::getSingleton().newInstance<PhysicsSphere>(m_props.m_particle.m_minInitialSize / 2.0f);
  235. PhysicsBodyInitInfo binit;
  236. binit.m_shape = std::move(collisionShape);
  237. m_physicsParticles.resizeStorage(m_props.m_maxNumOfParticles);
  238. for(U32 i = 0; i < m_props.m_maxNumOfParticles; i++)
  239. {
  240. binit.m_mass = getRandomRange(m_props.m_particle.m_minMass, m_props.m_particle.m_maxMass);
  241. m_physicsParticles.emplaceBack(binit, this);
  242. }
  243. }
  244. else
  245. {
  246. m_simpleParticles.resize(m_props.m_maxNumOfParticles);
  247. }
  248. // GPU scene allocations
  249. m_gpuScenePositions = GpuSceneBuffer::getSingleton().allocate(sizeof(Vec3) * m_props.m_maxNumOfParticles, alignof(F32));
  250. m_gpuSceneAlphas = GpuSceneBuffer::getSingleton().allocate(sizeof(F32) * m_props.m_maxNumOfParticles, alignof(F32));
  251. m_gpuSceneScales = GpuSceneBuffer::getSingleton().allocate(sizeof(F32) * m_props.m_maxNumOfParticles, alignof(F32));
  252. m_gpuSceneConstants = GpuSceneBuffer::getSingleton().allocate(
  253. m_particleEmitterResource->getMaterial()->getPrefilledLocalConstants().getSizeInBytes(), alignof(U32));
  254. // Allocate buckets
  255. for(RenderingTechnique t :
  256. EnumBitsIterable<RenderingTechnique, RenderingTechniqueBit>(m_particleEmitterResource->getMaterial()->getRenderingTechniques()))
  257. {
  258. RenderingKey key;
  259. key.setRenderingTechnique(t);
  260. ShaderProgramPtr prog;
  261. m_particleEmitterResource->getRenderingInfo(key, prog);
  262. RenderStateInfo state;
  263. state.m_program = prog;
  264. state.m_primitiveTopology = PrimitiveTopology::kTriangles;
  265. state.m_indexedDrawcall = false;
  266. m_renderStateBuckets[t] = RenderStateBucketContainer::getSingleton().addUser(state, t, 0);
  267. }
  268. }
  269. Error ParticleEmitterComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  270. {
  271. if(!m_particleEmitterResource.isCreated()) [[unlikely]]
  272. {
  273. updated = false;
  274. return Error::kNone;
  275. }
  276. updated = true;
  277. Vec3* positions;
  278. F32* scales;
  279. F32* alphas;
  280. Aabb aabbWorld;
  281. if(m_simulationType == SimulationType::kSimple)
  282. {
  283. simulate(info.m_previousTime, info.m_currentTime, info.m_node->getWorldTransform(), WeakArray<SimpleParticle>(m_simpleParticles), positions,
  284. scales, alphas, aabbWorld);
  285. }
  286. else
  287. {
  288. ANKI_ASSERT(m_simulationType == SimulationType::kPhysicsEngine);
  289. simulate(info.m_previousTime, info.m_currentTime, info.m_node->getWorldTransform(), WeakArray<PhysicsParticle>(m_physicsParticles), positions,
  290. scales, alphas, aabbWorld);
  291. }
  292. // Upload particles to the GPU scene
  293. GpuSceneMicroPatcher& patcher = GpuSceneMicroPatcher::getSingleton();
  294. if(m_aliveParticleCount > 0)
  295. {
  296. patcher.newCopy(*info.m_framePool, m_gpuScenePositions, sizeof(Vec3) * m_aliveParticleCount, positions);
  297. patcher.newCopy(*info.m_framePool, m_gpuSceneScales, sizeof(F32) * m_aliveParticleCount, scales);
  298. patcher.newCopy(*info.m_framePool, m_gpuSceneAlphas, sizeof(F32) * m_aliveParticleCount, alphas);
  299. }
  300. if(m_resourceUpdated)
  301. {
  302. // Upload GpuSceneParticleEmitter
  303. GpuSceneParticleEmitter particles = {};
  304. particles.m_vertexOffsets[U32(VertexStreamId::kParticlePosition)] = m_gpuScenePositions.getOffset();
  305. particles.m_vertexOffsets[U32(VertexStreamId::kParticleColor)] = m_gpuSceneAlphas.getOffset();
  306. particles.m_vertexOffsets[U32(VertexStreamId::kParticleScale)] = m_gpuSceneScales.getOffset();
  307. particles.m_aliveParticleCount = m_aliveParticleCount;
  308. if(!m_gpuSceneParticleEmitter.isValid())
  309. {
  310. m_gpuSceneParticleEmitter.allocate();
  311. }
  312. m_gpuSceneParticleEmitter.uploadToGpuScene(particles);
  313. // Upload uniforms
  314. patcher.newCopy(*info.m_framePool, m_gpuSceneConstants,
  315. m_particleEmitterResource->getMaterial()->getPrefilledLocalConstants().getSizeInBytes(),
  316. m_particleEmitterResource->getMaterial()->getPrefilledLocalConstants().getBegin());
  317. // Upload mesh LODs
  318. GpuSceneMeshLod meshLod = {};
  319. meshLod.m_vertexOffsets[U32(VertexStreamId::kPosition)] =
  320. m_quadPositions.getOffset() / getFormatInfo(kMeshRelatedVertexStreamFormats[VertexStreamId::kPosition]).m_texelSize;
  321. meshLod.m_vertexOffsets[U32(VertexStreamId::kUv)] =
  322. m_quadUvs.getOffset() / getFormatInfo(kMeshRelatedVertexStreamFormats[VertexStreamId::kUv]).m_texelSize;
  323. meshLod.m_indexCount = 6;
  324. meshLod.m_firstIndex = m_quadIndices.getOffset() / sizeof(U16);
  325. meshLod.m_positionScale = 1.0f;
  326. meshLod.m_positionTranslation = Vec3(-0.5f, -0.5f, 0.0f);
  327. Array<GpuSceneMeshLod, kMaxLodCount> meshLods;
  328. meshLods.fill(meshLod);
  329. if(!m_gpuSceneMeshLods.isValid())
  330. {
  331. m_gpuSceneMeshLods.allocate();
  332. }
  333. m_gpuSceneMeshLods.uploadToGpuScene(meshLods);
  334. // Upload the GpuSceneRenderable
  335. GpuSceneRenderable renderable = {};
  336. renderable.m_boneTransformsOffset = 0;
  337. renderable.m_constantsOffset = m_gpuSceneConstants.getOffset();
  338. renderable.m_meshLodsIndex = m_gpuSceneMeshLods.getIndex() * kMaxLodCount;
  339. renderable.m_particleEmitterIndex = m_gpuSceneParticleEmitter.getIndex();
  340. renderable.m_worldTransformsIndex = 0;
  341. renderable.m_uuid = SceneGraph::getSingleton().getNewUuid();
  342. if(!m_gpuSceneRenderable.isValid())
  343. {
  344. m_gpuSceneRenderable.allocate();
  345. }
  346. m_gpuSceneRenderable.uploadToGpuScene(renderable);
  347. }
  348. if(!m_resourceUpdated)
  349. {
  350. // Always upload GpuSceneParticleEmitter
  351. GpuSceneParticleEmitter particles = {};
  352. particles.m_vertexOffsets[U32(VertexStreamId::kParticlePosition)] = m_gpuScenePositions.getOffset();
  353. particles.m_vertexOffsets[U32(VertexStreamId::kParticleColor)] = m_gpuSceneAlphas.getOffset();
  354. particles.m_vertexOffsets[U32(VertexStreamId::kParticleScale)] = m_gpuSceneScales.getOffset();
  355. particles.m_aliveParticleCount = m_aliveParticleCount;
  356. if(!m_gpuSceneParticleEmitter.isValid())
  357. {
  358. m_gpuSceneParticleEmitter.allocate();
  359. }
  360. m_gpuSceneParticleEmitter.uploadToGpuScene(particles);
  361. }
  362. // Upload the GpuSceneRenderableBoundingVolume always
  363. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  364. {
  365. if(!!(RenderingTechniqueBit(1 << t) & m_particleEmitterResource->getMaterial()->getRenderingTechniques()))
  366. {
  367. const GpuSceneRenderableBoundingVolume gpuVolume = initGpuSceneRenderableBoundingVolume(
  368. aabbWorld.getMin().xyz(), aabbWorld.getMax().xyz(), m_gpuSceneRenderable.getIndex(), m_renderStateBuckets[t].get());
  369. switch(t)
  370. {
  371. case RenderingTechnique::kGBuffer:
  372. if(!m_gpuSceneRenderableAabbGBuffer.isValid())
  373. {
  374. m_gpuSceneRenderableAabbGBuffer.allocate();
  375. }
  376. m_gpuSceneRenderableAabbGBuffer.uploadToGpuScene(gpuVolume);
  377. break;
  378. case RenderingTechnique::kDepth:
  379. if(!m_gpuSceneRenderableAabbDepth.isValid())
  380. {
  381. m_gpuSceneRenderableAabbDepth.allocate();
  382. }
  383. m_gpuSceneRenderableAabbDepth.uploadToGpuScene(gpuVolume);
  384. break;
  385. case RenderingTechnique::kForward:
  386. if(!m_gpuSceneRenderableAabbForward.isValid())
  387. {
  388. m_gpuSceneRenderableAabbForward.allocate();
  389. }
  390. m_gpuSceneRenderableAabbForward.uploadToGpuScene(gpuVolume);
  391. break;
  392. default:
  393. ANKI_ASSERT(0);
  394. }
  395. }
  396. else if(!!(RenderingTechniqueBit(1 << t) & RenderingTechniqueBit::kAllRt))
  397. {
  398. continue;
  399. }
  400. else
  401. {
  402. switch(t)
  403. {
  404. case RenderingTechnique::kGBuffer:
  405. m_gpuSceneRenderableAabbGBuffer.free();
  406. break;
  407. case RenderingTechnique::kDepth:
  408. m_gpuSceneRenderableAabbDepth.free();
  409. break;
  410. case RenderingTechnique::kForward:
  411. m_gpuSceneRenderableAabbForward.free();
  412. break;
  413. default:
  414. ANKI_ASSERT(0);
  415. }
  416. }
  417. }
  418. m_resourceUpdated = false;
  419. return Error::kNone;
  420. }
  421. template<typename TParticle>
  422. void ParticleEmitterComponent::simulate(Second prevUpdateTime, Second crntTime, const Transform& worldTransform, WeakArray<TParticle> particles,
  423. Vec3*& positions, F32*& scales, F32*& alphas, Aabb& aabbWorld)
  424. {
  425. // - Deactivate the dead particles
  426. // - Calc the AABB
  427. // - Calc the instancing stuff
  428. Vec3 aabbMin(kMaxF32);
  429. Vec3 aabbMax(kMinF32);
  430. m_aliveParticleCount = 0;
  431. positions =
  432. static_cast<Vec3*>(SceneGraph::getSingleton().getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(Vec3), alignof(Vec3)));
  433. scales = static_cast<F32*>(SceneGraph::getSingleton().getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(F32), alignof(F32)));
  434. alphas = static_cast<F32*>(SceneGraph::getSingleton().getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(F32), alignof(F32)));
  435. F32 maxParticleSize = -1.0f;
  436. for(TParticle& particle : particles)
  437. {
  438. if(particle.isDead())
  439. {
  440. // if its already dead so dont deactivate it again
  441. continue;
  442. }
  443. if(particle.m_timeOfDeath < crntTime)
  444. {
  445. // Just died
  446. particle.kill();
  447. }
  448. else
  449. {
  450. // It's alive
  451. // This will calculate a new world transformation
  452. particle.simulate(prevUpdateTime, crntTime);
  453. const Vec3& origin = particle.m_crntPosition;
  454. aabbMin = aabbMin.min(origin);
  455. aabbMax = aabbMax.max(origin);
  456. positions[m_aliveParticleCount] = origin;
  457. scales[m_aliveParticleCount] = particle.m_crntSize;
  458. maxParticleSize = max(maxParticleSize, particle.m_crntSize);
  459. alphas[m_aliveParticleCount] = clamp(particle.m_crntAlpha, 0.0f, 1.0f);
  460. ++m_aliveParticleCount;
  461. }
  462. }
  463. // AABB
  464. if(m_aliveParticleCount != 0)
  465. {
  466. ANKI_ASSERT(maxParticleSize > 0.0f);
  467. const Vec3 min = aabbMin - maxParticleSize;
  468. const Vec3 max = aabbMax + maxParticleSize;
  469. aabbWorld = Aabb(min, max);
  470. }
  471. else
  472. {
  473. aabbWorld = Aabb(Vec3(0.0f), Vec3(0.001f));
  474. positions = nullptr;
  475. alphas = scales = nullptr;
  476. }
  477. //
  478. // Emit new particles
  479. //
  480. if(m_timeLeftForNextEmission <= 0.0)
  481. {
  482. U particleCount = 0; // How many particles I am allowed to emmit
  483. for(TParticle& particle : particles)
  484. {
  485. if(!particle.isDead())
  486. {
  487. // its alive so skip it
  488. continue;
  489. }
  490. particle.revive(m_props, worldTransform, crntTime);
  491. // do the rest
  492. ++particleCount;
  493. if(particleCount >= m_props.m_particlesPerEmission)
  494. {
  495. break;
  496. }
  497. } // end for all particles
  498. m_timeLeftForNextEmission = m_props.m_emissionPeriod;
  499. } // end if can emit
  500. else
  501. {
  502. m_timeLeftForNextEmission -= crntTime - prevUpdateTime;
  503. }
  504. }
  505. } // end namespace anki