Friday, August 21, 2009

Creating sparks/bolts in Opengl ES

I wanted to create some sparks/lightening/bolts kinda thing on the iPhone/iPod touch using OpenGL ES. I made a quick google and found this Delphi Opengl Project. I adapted it and created a quick spark object. Here is the draw method involved:


-(void) draw
{
#define random ((float)random()/RAND_MAX)
// initialise the start and end points
yDisp[0] = yDisp[STEPS-1] = 0;

// calculate new Y coordinate. new = old + random.
for (int i = 1; i <> yDisp[i-1] + 0.075f) yDisp[i] = yDisp[i-1]+0.075f;
if (yDisp[i] <> yDisp[i+1] + 0.075f) yDisp[i] = yDisp[i+1]+0.075f;
if (yDisp[i] <> 0.5f) yDisp[i] = 0.5f;
if (yDisp[i] < -0.5f) yDisp[i] = -0.5f;
}

// Prepare the vertices as a Triangle strip
float rnd;
for (int j = 0; j < STEPS; j++)
{
rnd = 0.04f*(random-0.5f); //0.4 * random between -0.5 and 0.5
vertices[j*6 + 0] = length*j/STEPS + rnd; //x between 0 and length with some slight randomness
vertices[j*6 + 1] = -halfThickness + (yDisp[j] + rnd) * amplitude; //y
vertices[j*6 + 2] = 0; //rnd; //z

vertices[j*6 + 3] = length*j/STEPS + rnd; //x
vertices[j*6 + 4] = halfThickness + (yDisp[j] + rnd) * amplitude; //y
vertices[j*6 + 5] = 0; //rnd; //z
}

// Draw the vertices
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glDisable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glColor4f(0.4f, 0.3f, 0.8f, 1.0f);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(x,y,0);
glRotatef(angleInDegrees, 0, 0, 1);
glDrawArrays(GL_TRIANGLE_STRIP, 0, STEPS*2);
glPopMatrix();
}


The vertices array and yDisp array would need to be malloced appopriately in the init method (and freed in the dealloc):

vertices = malloc(sizeof(GLfloat) * 3 * STEPS * 2);//3 coordinates for each vertex, 2 vertices for each step
yDisp = malloc(sizeof(float) * STEPS);

Some good values for a decent spark would be length 200, halfWidth 1, amplitude 50.
STEPS was #defined to 40 for now.

This is just the beginning. I need to add more effects like glowing endpoints and subtle particle systems.

No comments: