Wednesday, September 24, 2014

Tetra Turns into a Sphere and Viceversa

You may be aware of how a tetrahedron looks like. It is a polyhedra made up of four equilateral triangles.
 In this program all the equilateral triangles have a sierpinski gasket on them. Sierpinski gasket is a fractal drawn recursively by dividing the edges of the triangle and then inscribing a triangle with vertices at the center of each edge. Except the inscribed triangle all other triangles are repeatedly subdivided. Here is how a Sierpinski gasket looks like...
In my program that is the first one where the tetra turns into a sphere....i have colored the triangles inside the tetrahedron using Red, Green, Blue and Black Colors.
I will show a snippet of code which is doing this magic.
Here is the source.
 In the function normalize i have added the following code:(See comments)
void normalize(GLfloat *p)
{ double d=0.0;
int i;
for(i=0;i<3;i++) d+=p[i]*p[i]; //find the length of the vector
d=sqrt(d); // starting from origin to face of tetra
d=d+(1-d)*sf; // sf(scaling factor) has abs of sine wave 
                           // which is set in idle function
 if(max<d) max=d; // this statement i guess is not needed
if(d>0.0)
for(i=0;i<3;i++) p[i]/=d;//divide the vector components by the
}                                            // newly required length in d
Here is the idle function
void idle()
{ sf=fabs(sin(angle)); // as mentioned abs of sine wave
angle+=0.0004; // increment angle
if(angle>=360) angle=0; // if angle overflows
glutPostRedisplay(); // call display every possible moment
}
Happy Coding!
Small modification now the up and down arrow increases or decreases the angle and hence the scaling factor which decides the difference between the tetra and the sphere. Here is the modified code.

No comments:

Post a Comment