ParticleEmitterComponent.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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. , m_spatial(this)
  161. {
  162. // Allocate and populate a quad
  163. const U32 vertCount = 4;
  164. const U32 indexCount = 6;
  165. m_quadPositions = UnifiedGeometryBuffer::getSingleton().allocateFormat(kMeshRelatedVertexStreamFormats[VertexStreamId::kPosition], vertCount);
  166. m_quadUvs = UnifiedGeometryBuffer::getSingleton().allocateFormat(kMeshRelatedVertexStreamFormats[VertexStreamId::kUv], vertCount);
  167. m_quadIndices = UnifiedGeometryBuffer::getSingleton().allocateFormat(Format::kR16_Uint, indexCount);
  168. RebarAllocation positionsAlloc;
  169. static_assert(kMeshRelatedVertexStreamFormats[VertexStreamId::kPosition] == Format::kR16G16B16A16_Unorm);
  170. U16Vec4* transientPositions = RebarTransientMemoryPool::getSingleton().allocateFrame<U16Vec4>(vertCount, positionsAlloc);
  171. transientPositions[0] = U16Vec4(0, 0, 0, 0);
  172. transientPositions[1] = U16Vec4(kMaxU16, 0, 0, 0);
  173. transientPositions[2] = U16Vec4(kMaxU16, kMaxU16, 0, 0);
  174. transientPositions[3] = U16Vec4(0, kMaxU16, 0, 0);
  175. RebarAllocation uvsAlloc;
  176. static_assert(kMeshRelatedVertexStreamFormats[VertexStreamId::kUv] == Format::kR32G32_Sfloat);
  177. Vec2* transientUvs = RebarTransientMemoryPool::getSingleton().allocateFrame<Vec2>(vertCount, uvsAlloc);
  178. transientUvs[0] = Vec2(0.0f);
  179. transientUvs[1] = Vec2(1.0f, 0.0f);
  180. transientUvs[2] = Vec2(1.0f, 1.0f);
  181. transientUvs[3] = Vec2(0.0f, 1.0f);
  182. RebarAllocation indicesAlloc;
  183. U16* transientIndices = RebarTransientMemoryPool::getSingleton().allocateFrame<U16>(indexCount, indicesAlloc);
  184. transientIndices[0] = 0;
  185. transientIndices[1] = 1;
  186. transientIndices[2] = 3;
  187. transientIndices[3] = 1;
  188. transientIndices[4] = 2;
  189. transientIndices[5] = 3;
  190. CommandBufferInitInfo cmdbInit("Particle quad upload");
  191. cmdbInit.m_flags |= CommandBufferFlag::kSmallBatch;
  192. CommandBufferPtr cmdb = GrManager::getSingleton().newCommandBuffer(cmdbInit);
  193. Buffer* srcBuff = &RebarTransientMemoryPool::getSingleton().getBuffer();
  194. Buffer* dstBuff = &UnifiedGeometryBuffer::getSingleton().getBuffer();
  195. cmdb->copyBufferToBuffer(srcBuff, positionsAlloc.m_offset, dstBuff, m_quadPositions.getOffset(), positionsAlloc.m_range);
  196. cmdb->copyBufferToBuffer(srcBuff, uvsAlloc.m_offset, dstBuff, m_quadUvs.getOffset(), uvsAlloc.m_range);
  197. cmdb->copyBufferToBuffer(srcBuff, indicesAlloc.m_offset, dstBuff, m_quadIndices.getOffset(), indicesAlloc.m_range);
  198. BufferBarrierInfo barrier;
  199. barrier.m_buffer = dstBuff;
  200. barrier.m_offset = 0;
  201. barrier.m_range = kMaxPtrSize;
  202. barrier.m_previousUsage = BufferUsageBit::kTransferDestination;
  203. barrier.m_nextUsage = dstBuff->getBufferUsage();
  204. cmdb->setPipelineBarrier({}, {&barrier, 1}, {});
  205. cmdb->flush();
  206. }
  207. ParticleEmitterComponent::~ParticleEmitterComponent()
  208. {
  209. m_spatial.removeFromOctree(SceneGraph::getSingleton().getOctree());
  210. }
  211. void ParticleEmitterComponent::loadParticleEmitterResource(CString filename)
  212. {
  213. // Load
  214. ParticleEmitterResourcePtr rsrc;
  215. const Error err = ResourceManager::getSingleton().loadResource(filename, rsrc);
  216. if(err)
  217. {
  218. ANKI_SCENE_LOGE("Failed to load particle emitter");
  219. return;
  220. }
  221. m_particleEmitterResource = std::move(rsrc);
  222. m_props = m_particleEmitterResource->getProperties();
  223. m_resourceUpdated = true;
  224. // Cleanup
  225. m_simpleParticles.destroy();
  226. m_physicsParticles.destroy();
  227. GpuSceneBuffer::getSingleton().deferredFree(m_gpuScenePositions);
  228. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneScales);
  229. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneAlphas);
  230. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneUniforms);
  231. for(RenderStateBucketIndex& idx : m_renderStateBuckets)
  232. {
  233. RenderStateBucketContainer::getSingleton().removeUser(idx);
  234. }
  235. // Init particles
  236. m_simulationType = (m_props.m_usePhysicsEngine) ? SimulationType::kPhysicsEngine : SimulationType::kSimple;
  237. if(m_simulationType == SimulationType::kPhysicsEngine)
  238. {
  239. PhysicsCollisionShapePtr collisionShape = PhysicsWorld::getSingleton().newInstance<PhysicsSphere>(m_props.m_particle.m_minInitialSize / 2.0f);
  240. PhysicsBodyInitInfo binit;
  241. binit.m_shape = std::move(collisionShape);
  242. m_physicsParticles.resizeStorage(m_props.m_maxNumOfParticles);
  243. for(U32 i = 0; i < m_props.m_maxNumOfParticles; i++)
  244. {
  245. binit.m_mass = getRandomRange(m_props.m_particle.m_minMass, m_props.m_particle.m_maxMass);
  246. m_physicsParticles.emplaceBack(binit, this);
  247. }
  248. }
  249. else
  250. {
  251. m_simpleParticles.resize(m_props.m_maxNumOfParticles);
  252. }
  253. // GPU scene allocations
  254. m_gpuScenePositions = GpuSceneBuffer::getSingleton().allocate(sizeof(Vec3) * m_props.m_maxNumOfParticles, alignof(F32));
  255. m_gpuSceneAlphas = GpuSceneBuffer::getSingleton().allocate(sizeof(F32) * m_props.m_maxNumOfParticles, alignof(F32));
  256. m_gpuSceneScales = GpuSceneBuffer::getSingleton().allocate(sizeof(F32) * m_props.m_maxNumOfParticles, alignof(F32));
  257. m_gpuSceneUniforms =
  258. GpuSceneBuffer::getSingleton().allocate(m_particleEmitterResource->getMaterial()->getPrefilledLocalUniforms().getSizeInBytes(), alignof(U32));
  259. // Allocate buckets
  260. for(RenderingTechnique t :
  261. EnumBitsIterable<RenderingTechnique, RenderingTechniqueBit>(m_particleEmitterResource->getMaterial()->getRenderingTechniques()))
  262. {
  263. RenderingKey key;
  264. key.setRenderingTechnique(t);
  265. ShaderProgramPtr prog;
  266. m_particleEmitterResource->getRenderingInfo(key, prog);
  267. RenderStateInfo state;
  268. state.m_program = prog;
  269. state.m_primitiveTopology = PrimitiveTopology::kTriangles;
  270. state.m_indexedDrawcall = false;
  271. m_renderStateBuckets[t] = RenderStateBucketContainer::getSingleton().addUser(state, t);
  272. }
  273. }
  274. Error ParticleEmitterComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  275. {
  276. if(!m_particleEmitterResource.isCreated()) [[unlikely]]
  277. {
  278. updated = false;
  279. return Error::kNone;
  280. }
  281. updated = true;
  282. Vec3* positions;
  283. F32* scales;
  284. F32* alphas;
  285. Aabb aabbWorld;
  286. if(m_simulationType == SimulationType::kSimple)
  287. {
  288. simulate(info.m_previousTime, info.m_currentTime, info.m_node->getWorldTransform(), WeakArray<SimpleParticle>(m_simpleParticles), positions,
  289. scales, alphas, aabbWorld);
  290. }
  291. else
  292. {
  293. ANKI_ASSERT(m_simulationType == SimulationType::kPhysicsEngine);
  294. simulate(info.m_previousTime, info.m_currentTime, info.m_node->getWorldTransform(), WeakArray<PhysicsParticle>(m_physicsParticles), positions,
  295. scales, alphas, aabbWorld);
  296. }
  297. m_spatial.setBoundingShape(aabbWorld);
  298. m_spatial.update(SceneGraph::getSingleton().getOctree());
  299. // Upload particles to the GPU scene
  300. GpuSceneMicroPatcher& patcher = GpuSceneMicroPatcher::getSingleton();
  301. if(m_aliveParticleCount > 0)
  302. {
  303. patcher.newCopy(*info.m_framePool, m_gpuScenePositions, sizeof(Vec3) * m_aliveParticleCount, positions);
  304. patcher.newCopy(*info.m_framePool, m_gpuSceneScales, sizeof(F32) * m_aliveParticleCount, scales);
  305. patcher.newCopy(*info.m_framePool, m_gpuSceneAlphas, sizeof(F32) * m_aliveParticleCount, alphas);
  306. }
  307. if(m_resourceUpdated)
  308. {
  309. // Upload GpuSceneParticleEmitter
  310. GpuSceneParticleEmitter particles = {};
  311. particles.m_vertexOffsets[U32(VertexStreamId::kParticlePosition)] = m_gpuScenePositions.getOffset();
  312. particles.m_vertexOffsets[U32(VertexStreamId::kParticleColor)] = m_gpuSceneAlphas.getOffset();
  313. particles.m_vertexOffsets[U32(VertexStreamId::kParticleScale)] = m_gpuSceneScales.getOffset();
  314. particles.m_aliveParticleCount = m_aliveParticleCount;
  315. if(!m_gpuSceneParticleEmitter.isValid())
  316. {
  317. m_gpuSceneParticleEmitter.allocate();
  318. }
  319. m_gpuSceneParticleEmitter.uploadToGpuScene(particles);
  320. // Upload uniforms
  321. patcher.newCopy(*info.m_framePool, m_gpuSceneUniforms, m_particleEmitterResource->getMaterial()->getPrefilledLocalUniforms().getSizeInBytes(),
  322. m_particleEmitterResource->getMaterial()->getPrefilledLocalUniforms().getBegin());
  323. // Upload mesh LODs
  324. GpuSceneMeshLod meshLod = {};
  325. meshLod.m_vertexOffsets[U32(VertexStreamId::kPosition)] =
  326. m_quadPositions.getOffset() / getFormatInfo(kMeshRelatedVertexStreamFormats[VertexStreamId::kPosition]).m_texelSize;
  327. meshLod.m_vertexOffsets[U32(VertexStreamId::kUv)] =
  328. m_quadUvs.getOffset() / getFormatInfo(kMeshRelatedVertexStreamFormats[VertexStreamId::kUv]).m_texelSize;
  329. meshLod.m_indexCount = 6;
  330. meshLod.m_firstIndex = m_quadIndices.getOffset() / sizeof(U16);
  331. meshLod.m_positionScale = 1.0f;
  332. meshLod.m_positionTranslation = Vec3(-0.5f, -0.5f, 0.0f);
  333. Array<GpuSceneMeshLod, kMaxLodCount> meshLods;
  334. meshLods.fill(meshLod);
  335. if(!m_gpuSceneMeshLods.isValid())
  336. {
  337. m_gpuSceneMeshLods.allocate();
  338. }
  339. m_gpuSceneMeshLods.uploadToGpuScene(meshLods);
  340. // Upload the GpuSceneRenderable
  341. GpuSceneRenderable renderable;
  342. renderable.m_boneTransformsOffset = 0;
  343. renderable.m_uniformsOffset = m_gpuSceneUniforms.getOffset();
  344. renderable.m_meshLodsOffset = m_gpuSceneMeshLods.getGpuSceneOffset();
  345. renderable.m_particleEmitterOffset = m_gpuSceneParticleEmitter.getGpuSceneOffset();
  346. renderable.m_worldTransformsOffset = 0;
  347. if(!m_gpuSceneRenderable.isValid())
  348. {
  349. m_gpuSceneRenderable.allocate();
  350. }
  351. m_gpuSceneRenderable.uploadToGpuScene(renderable);
  352. }
  353. if(!m_resourceUpdated)
  354. {
  355. // Always upload GpuSceneParticleEmitter
  356. GpuSceneParticleEmitter particles = {};
  357. particles.m_vertexOffsets[U32(VertexStreamId::kParticlePosition)] = m_gpuScenePositions.getOffset();
  358. particles.m_vertexOffsets[U32(VertexStreamId::kParticleColor)] = m_gpuSceneAlphas.getOffset();
  359. particles.m_vertexOffsets[U32(VertexStreamId::kParticleScale)] = m_gpuSceneScales.getOffset();
  360. particles.m_aliveParticleCount = m_aliveParticleCount;
  361. if(!m_gpuSceneParticleEmitter.isValid())
  362. {
  363. m_gpuSceneParticleEmitter.allocate();
  364. }
  365. m_gpuSceneParticleEmitter.uploadToGpuScene(particles);
  366. }
  367. // Upload the GpuSceneRenderableAabb always
  368. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  369. {
  370. if(!!(RenderingTechniqueBit(1 << t) & m_particleEmitterResource->getMaterial()->getRenderingTechniques()))
  371. {
  372. const GpuSceneRenderableAabb gpuVolume =
  373. initGpuSceneRenderableAabb(m_spatial.getAabbWorldSpace().getMin().xyz(), m_spatial.getAabbWorldSpace().getMax().xyz(),
  374. m_gpuSceneRenderable.getIndex(), m_renderStateBuckets[t].get());
  375. switch(t)
  376. {
  377. case RenderingTechnique::kGBuffer:
  378. if(!m_gpuSceneRenderableAabbGBuffer.isValid())
  379. {
  380. m_gpuSceneRenderableAabbGBuffer.allocate();
  381. }
  382. m_gpuSceneRenderableAabbGBuffer.uploadToGpuScene(gpuVolume);
  383. break;
  384. case RenderingTechnique::kDepth:
  385. if(!m_gpuSceneRenderableAabbDepth.isValid())
  386. {
  387. m_gpuSceneRenderableAabbDepth.allocate();
  388. }
  389. m_gpuSceneRenderableAabbDepth.uploadToGpuScene(gpuVolume);
  390. break;
  391. case RenderingTechnique::kForward:
  392. if(!m_gpuSceneRenderableAabbForward.isValid())
  393. {
  394. m_gpuSceneRenderableAabbForward.allocate();
  395. }
  396. m_gpuSceneRenderableAabbForward.uploadToGpuScene(gpuVolume);
  397. break;
  398. default:
  399. ANKI_ASSERT(0);
  400. }
  401. }
  402. else if(!!(RenderingTechniqueBit(1 << t) & RenderingTechniqueBit::kAllRt))
  403. {
  404. continue;
  405. }
  406. else
  407. {
  408. switch(t)
  409. {
  410. case RenderingTechnique::kGBuffer:
  411. m_gpuSceneRenderableAabbGBuffer.free();
  412. break;
  413. case RenderingTechnique::kDepth:
  414. m_gpuSceneRenderableAabbDepth.free();
  415. break;
  416. case RenderingTechnique::kForward:
  417. m_gpuSceneRenderableAabbForward.free();
  418. break;
  419. default:
  420. ANKI_ASSERT(0);
  421. }
  422. }
  423. }
  424. m_resourceUpdated = false;
  425. return Error::kNone;
  426. }
  427. template<typename TParticle>
  428. void ParticleEmitterComponent::simulate(Second prevUpdateTime, Second crntTime, const Transform& worldTransform, WeakArray<TParticle> particles,
  429. Vec3*& positions, F32*& scales, F32*& alphas, Aabb& aabbWorld)
  430. {
  431. // - Deactivate the dead particles
  432. // - Calc the AABB
  433. // - Calc the instancing stuff
  434. Vec3 aabbMin(kMaxF32);
  435. Vec3 aabbMax(kMinF32);
  436. m_aliveParticleCount = 0;
  437. positions =
  438. static_cast<Vec3*>(SceneGraph::getSingleton().getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(Vec3), alignof(Vec3)));
  439. scales = static_cast<F32*>(SceneGraph::getSingleton().getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(F32), alignof(F32)));
  440. alphas = static_cast<F32*>(SceneGraph::getSingleton().getFrameMemoryPool().allocate(m_props.m_maxNumOfParticles * sizeof(F32), alignof(F32)));
  441. F32 maxParticleSize = -1.0f;
  442. for(TParticle& particle : particles)
  443. {
  444. if(particle.isDead())
  445. {
  446. // if its already dead so dont deactivate it again
  447. continue;
  448. }
  449. if(particle.m_timeOfDeath < crntTime)
  450. {
  451. // Just died
  452. particle.kill();
  453. }
  454. else
  455. {
  456. // It's alive
  457. // This will calculate a new world transformation
  458. particle.simulate(prevUpdateTime, crntTime);
  459. const Vec3& origin = particle.m_crntPosition;
  460. aabbMin = aabbMin.min(origin);
  461. aabbMax = aabbMax.max(origin);
  462. positions[m_aliveParticleCount] = origin;
  463. scales[m_aliveParticleCount] = particle.m_crntSize;
  464. maxParticleSize = max(maxParticleSize, particle.m_crntSize);
  465. alphas[m_aliveParticleCount] = clamp(particle.m_crntAlpha, 0.0f, 1.0f);
  466. ++m_aliveParticleCount;
  467. }
  468. }
  469. // AABB
  470. if(m_aliveParticleCount != 0)
  471. {
  472. ANKI_ASSERT(maxParticleSize > 0.0f);
  473. const Vec3 min = aabbMin - maxParticleSize;
  474. const Vec3 max = aabbMax + maxParticleSize;
  475. aabbWorld = Aabb(min, max);
  476. }
  477. else
  478. {
  479. aabbWorld = Aabb(Vec3(0.0f), Vec3(0.001f));
  480. positions = nullptr;
  481. alphas = scales = nullptr;
  482. }
  483. //
  484. // Emit new particles
  485. //
  486. if(m_timeLeftForNextEmission <= 0.0)
  487. {
  488. U particleCount = 0; // How many particles I am allowed to emmit
  489. for(TParticle& particle : particles)
  490. {
  491. if(!particle.isDead())
  492. {
  493. // its alive so skip it
  494. continue;
  495. }
  496. particle.revive(m_props, worldTransform, crntTime);
  497. // do the rest
  498. ++particleCount;
  499. if(particleCount >= m_props.m_particlesPerEmission)
  500. {
  501. break;
  502. }
  503. } // end for all particles
  504. m_timeLeftForNextEmission = m_props.m_emissionPeriod;
  505. } // end if can emit
  506. else
  507. {
  508. m_timeLeftForNextEmission -= crntTime - prevUpdateTime;
  509. }
  510. }
  511. void ParticleEmitterComponent::setupRenderableQueueElements(RenderingTechnique technique, WeakArray<RenderableQueueElement>& outRenderables) const
  512. {
  513. if(!(m_particleEmitterResource->getMaterial()->getRenderingTechniques() & RenderingTechniqueBit(1 << technique)) || m_aliveParticleCount == 0)
  514. {
  515. outRenderables.setArray(nullptr, 0);
  516. return;
  517. }
  518. RenderingKey key;
  519. key.setRenderingTechnique(technique);
  520. ShaderProgramPtr prog;
  521. m_particleEmitterResource->getRenderingInfo(key, prog);
  522. RenderableQueueElement* el = static_cast<RenderableQueueElement*>(
  523. SceneGraph::getSingleton().getFrameMemoryPool().allocate(sizeof(RenderableQueueElement), alignof(RenderableQueueElement)));
  524. el->m_mergeKey = 0; // Not mergable
  525. el->m_program = prog.get();
  526. el->m_worldTransformsOffset = 0;
  527. el->m_uniformsOffset = m_gpuSceneUniforms.getOffset();
  528. el->m_meshLodOffset = m_gpuSceneMeshLods.getGpuSceneOffset();
  529. el->m_particleEmitterOffset = m_gpuSceneParticleEmitter.getGpuSceneOffset();
  530. el->m_boneTransformsOffset = 0;
  531. el->m_vertexCount = 6 * m_aliveParticleCount;
  532. el->m_firstVertex = 0;
  533. el->m_indexed = false;
  534. el->m_primitiveTopology = PrimitiveTopology::kTriangles;
  535. el->m_aabbMin = m_spatial.getAabbWorldSpace().getMin().xyz();
  536. el->m_aabbMax = m_spatial.getAabbWorldSpace().getMax().xyz();
  537. outRenderables.setArray(el, 1);
  538. }
  539. } // end namespace anki