You are on page 1of 2

//Create and rotate a triangle about the origin and a fixed point.

#include <stdio.h>
#include <math.h>
#include <glut.h>

float tri[3][3] = {
{300, 500, 400},
{300, 300, 500},
{1, 1, 1} };

float rmat[3][3] = { {0},{0},{0} };


float res[3][3] = { {0}, {0}, {0} };
float xf = 200, yf = 200; // fixed point
float theta, t;

void multiply()
{ // Rotation MATRIX and Object Matrix => resultant Transformed Triangle
int i, j, k;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++) /*baracket as it is for i,j,k loop*/
{
res[i][j] = 0;
for (k = 0; k < 3; k++)
res[i][j] = res[i][j] + rmat[i][k] * tri[k][j];
}
}

void rotate()
{
// Build the rotation matrix about the origin and a fixed point
rmat[0][0] = cos(t);
rmat[0][1] = -sin(t);
rmat[0][2] = xf - xf * cos(t) + yf * sin(t);

rmat[1][0] = sin(t);
rmat[1][1] = cos(t);
rmat[1][2] = yf - xf * sin(t) - yf * cos(t);

rmat[2][0] = 0;
rmat[2][1] = 0;
rmat[2][2] = 1;

//multiply the two matrices: Rotation Matrix * Object Matrix(triangle)


multiply();
}

void triangle()
{
glColor3f(0, 0, 1);
glBegin(GL_TRIANGLES); //GL_LINE_LOOP
glVertex2f(tri[0][0], tri[1][0]);
glVertex2f(tri[0][1], tri[1][1]);
glVertex2f(tri[0][2], tri[1][2]);
glEnd();
}

void rotatedtriangle()
{
glColor3f(1, 0, 1);
glBegin(GL_TRIANGLES); //GL_LINE_LOOP
glVertex2f(res[0][0], res[1][0]);
glVertex2f(res[0][1], res[1][1]);
glVertex2f(res[0][2], res[1][2]);
glEnd();
}

void display()
{
glClear(GL_COLOR_BUFFER_BIT);
triangle();
rotate();
rotatedtriangle();
glFlush();
}

void myinit()
{
glClearColor(1, 1, 1, 1);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 600, 0, 600);
}

void main(int argc, char** argv)


{
printf("Enter the rotation angle : ");
scanf_s("%f", &theta); //convert degree to radians
t = (3.142 / 180) * theta;
printf("Enter the Fixed point about which to Rotate : ");
scanf_s("%f%f", &xf, &yf);

glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(600, 600);
glutInitWindowPosition(0, 0);
glutCreateWindow("Triangle Rotation");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}

You might also like