C and C++ Computer Graphics

Program for 3D Rotation

Program for 3D Rotation
/* 3D Rotation of a Cube using graphics.h (BGI/WinBGI) */
#include <graphics.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>

#define PI 3.14159265

// Projection function (simple perspective projection)
void project(int x, int y, int z, int *px, int *py) {
int d = 500; // distance from viewer
*px = (x * d) / (z + d) + 320; // 320 = centerX
*py = (y * d) / (z + d) + 240; // 240 = centerY
}

int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");

// Cube vertices (8 points)
float cube[8][3] = {
{-100, -100, -100},
{ 100, -100, -100},
{ 100, 100, -100},
{-100, 100, -100},
{-100, -100, 100},
{ 100, -100, 100},
{ 100, 100, 100},
{-100, 100, 100}
};

int edges[12][2] = {
{0,1},{1,2},{2,3},{3,0}, // back face
{4,5},{5,6},{6,7},{7,4}, // front face
{0,4},{1,5},{2,6},{3,7} // connections
};

float angleX = 0, angleY = 0, angleZ = 0;

while (!kbhit()) {
cleardevice();

// Rotation matrices applied
float rotCube[8][3];
for (int i = 0; i < 8; i++) {
float x = cube[i][0];
float y = cube[i][1];
float z = cube[i][2];

// Rotate around X
float y1 = y * cos(angleX) - z * sin(angleX);
float z1 = y * sin(angleX) + z * cos(angleX);

y = y1;
z = z1;

// Rotate around Y
float x1 = x * cos(angleY) + z * sin(angleY);
z1 = -x * sin(angleY) + z * cos(angleY);

x = x1;
z = z1;

// Rotate around Z
float x2 = x * cos(angleZ) - y * sin(angleZ);
float y2 = x * sin(angleZ) + y * cos(angleZ);

rotCube[i][0] = x2;
rotCube[i][1] = y2;
rotCube[i][2] = z;
}

// Project and draw cube
int px[8], py[8];
for (int i = 0; i < 8; i++) {
project(rotCube[i][0], rotCube[i][1], rotCube[i][2], &px[i], &py[i]);
}

// Draw edges
setcolor(WHITE);
for (int e = 0; e < 12; e++) {
line(px[edges[e][0]], py[edges[e][0]],
px[edges[e][1]], py[edges[e][1]]);
}

// Increment rotation
angleX += 0.02;
angleY += 0.03;
angleZ += 0.01;

delay(50);
}

closegraph();
return 0;
}

Leave a comment

Your email address will not be published. Required fields are marked *