forked from Barnold1953/GraphicsTutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParticleBatch2D.cpp
More file actions
83 lines (68 loc) · 2.46 KB
/
Copy pathParticleBatch2D.cpp
File metadata and controls
83 lines (68 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "ParticleBatch2D.h"
namespace Bengine {
ParticleBatch2D::ParticleBatch2D() {
// Empty
}
ParticleBatch2D::~ParticleBatch2D() {
delete[] m_particles;
}
void ParticleBatch2D::init(int maxParticles,
float decayRate,
GLTexture texture,
std::function<void(Particle2D&, float)> updateFunc /* = defaultParticleUpdate */) {
m_maxParticles = maxParticles;
m_particles = new Particle2D[maxParticles];
m_decayRate = decayRate;
m_texture = texture;
m_updateFunc = updateFunc;
}
void ParticleBatch2D::update(float deltaTime) {
for (int i = 0; i < m_maxParticles; i++) {
// Check if it is active
if (m_particles[i].life > 0.0f) {
// Update using function pointer
m_updateFunc(m_particles[i], deltaTime);
m_particles[i].life -= m_decayRate * deltaTime;
}
}
}
void ParticleBatch2D::draw(SpriteBatch* spriteBatch) {
glm::vec4 uvRect(0.0f, 0.0f, 1.0f, 1.0f);
for (int i = 0; i < m_maxParticles; i++) {
// Check if it is active
auto& p = m_particles[i];
if (p.life > 0.0f) {
glm::vec4 destRect(p.position.x, p.position.y, p.width, p.width);
spriteBatch->draw(destRect, uvRect, m_texture.id, 0.0f, p.color);
}
}
}
void ParticleBatch2D::addParticle(const glm::vec2& position,
const glm::vec2& velocity,
const ColorRGBA8& color,
float width) {
int particleIndex = findFreeParticle();
auto& p = m_particles[particleIndex];
p.life = 1.0f;
p.position = position;
p.velocity = velocity;
p.color = color;
p.width = width;
}
int ParticleBatch2D::findFreeParticle() {
for (int i = m_lastFreeParticle; i < m_maxParticles; i++) {
if (m_particles[i].life <= 0.0f) {
m_lastFreeParticle = i;
return i;
}
}
for (int i = 0; i < m_lastFreeParticle; i++) {
if (m_particles[i].life <= 0.0f) {
m_lastFreeParticle = i;
return i;
}
}
// No particles are free, overwrite first particle
return 0;
}
}