## Thursday, March 10, 2016

### Dual Rotating Triangle

In VTU 6th Sem Syllabus COMPUTER GRAPHICS AND VISUALIZATION Lab, Student have to do a project using the OpenGL and C++. Many of the student have made a great mark by submitting some good projects like 3D Animated Robot. Many of student want to have simple program, hence today we have came with very simple program for you.

### Dual Rotating Triangle

As you may understand with the name of project, there is two triangle and they are rotating. We have used the simple code for developing this project. Let start doing it. First we have defined a global variable for angle.
`int GAngle=0;`

The whole program is divided into three parts - Display, Timer and Main. We will code each of them one by one. First We will define the Display Function, where we are going to use simple primitive opengl function for drawing triangle GL_TRIANGLE. We use the global GAngle variable to rotate the drawn triangle. You can experiment with the angle and try how it turn out to be. You can also experiments with the vertices coordinate which draw triangles.

```void Display(void)
{
glClear(GL_COLOR_BUFFER_BIT);

glRotated(GAngle,0,1,0);

// Anti-Clockwise Winding
glBegin(GL_TRIANGLES);
glColor3f(1,0,0);
glVertex3f(-1,0,0);
glVertex3f(1,0,0);
glVertex3f(0,1,0);

glColor3f(0,1,0);
glVertex3f(-1,0,0.5);
glVertex3f(1,0,0.5);
glVertex3f(0,1,0.5);

glEnd();

GAngle = GAngle + 4;

glFlush();

glutSwapBuffers();
}
```

Now We add the Timer Function to let the Triangle turn on that time. Code is given below-

```void Timer(int extra)
{
glutPostRedisplay();
glutTimerFunc(30,Timer,0);
}
```
Add main function and execute the program to get the output below.
```int main(void)
{
// Init to double buffering

glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutCreateWindow("Dual Rotating Triangle");
glutDisplayFunc(Display);
glutTimerFunc(0,Timer,0);
glMatrixMode(GL_PROJECTION);
glFrustum(-1,1,-1,1,1,3);
glTranslated(0,0,-2);
glMatrixMode(GL_MODELVIEW);
glutMainLoop();
return 0;
}
```

Below is Full Source code for this Project, Just Copy Paste and run it. Before that there are few points for future enchantments -
• Add Keyboard/Mouse Interaction to start and stop rotation of Triangles.
• Use Keyboard/Mouse Interaction to Change the Color of the Triangles.

```#include <stdio.h>

#include "glut.h"
int GAngle=0;
void Display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glRotated(GAngle,0,1,0);

// Anti-Clockwise Winding

glBegin(GL_TRIANGLES);
glColor3f(1,0,0);
glVertex3f(-1,0,0);
glVertex3f(1,0,0);
glVertex3f(0,1,0);
glColor3f(0,1,0);
glVertex3f(-1,0,0.5);
glVertex3f(1,0,0.5);
glVertex3f(0,1,0.5);
glEnd();

GAngle = GAngle + 4;

glFlush();

glutSwapBuffers();

}

void Timer(int extra)
{
glutPostRedisplay();
glutTimerFunc(30,Timer,0);
}

int main(void)
{
// Init to double buffering

glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutCreateWindow("Dual Rotating Triangle");
glutDisplayFunc(Display);
glutTimerFunc(0,Timer,0);
glMatrixMode(GL_PROJECTION);