Gabriel Ortega
Gabriel Ortega

Reputation: 481

OpenGL Perspective

I'm trying to depict a cube using a perspective projection, but all I get is the corner of a square. The face of the square is set at the origin and expands in the positive direction. Using glOrtho I can set the coordinate system, but I'm having trouble doing the same thing using glPerspective.

#include <gl/glut.h>

void mesh(void) {
float v[8][3] = { /* Vertices for 8 corners of a cube. */
{0.0, 0.0, 0.0}, {100.0, 0.0, 0.0}, {100.0, 100.0, 0.0}, {0.0, 100.0, 0.0},
{0.0, 0.0, -100.0}, {100.0, 0.0, -100.0}, {100.0, 100.0, -100.0}, {0.0, 100.0, -100.0} };
float n[6][3] = { /* Normals for the 6 faces of a cube. */
{0.0, 0.0, 1.0}, {1.0, 0.0, 0.0}, {0.0, 1.0, 0.0},
{-1.0, 0.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, -1.0} };
int f[6][4] = { /* Indexes of the vertices in v that make the 6 faces of a cube. */
{0, 1, 2, 3}, {1, 5, 6, 2}, {3, 2, 6, 7}, 
{0, 4, 7, 3}, {0, 1, 5, 4}, {4, 5, 6, 7} };



for (int j = 0; j < 6; j++) {
    glBegin(GL_QUADS);
    glNormal3fv(&n[j][0]);
    glVertex3fv(&v[f[j][0]][0]);
    glVertex3fv(&v[f[j][1]][0]);
    glVertex3fv(&v[f[j][2]][0]);
    glVertex3fv(&v[f[j][3]][0]);
    glEnd();
    glFlush();
}
}

void display(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
mesh();
}

void main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB |GLUT_DEPTH |GLUT_SINGLE);
glutInitWindowSize(400, 300);
glutInitWindowPosition(200, 200);
glutCreateWindow("Mesh");
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//glRotatef(15, 0.0, 0.0, 1.0);
//glOrtho(-400.0, 400.0, -300.0, 300.0, 200.0, -200.0);
gluPerspective(120,1,0,600);
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
glutDisplayFunc(display);
glutMainLoop();
}

Upvotes: 3

Views: 4324

Answers (1)

iKlsR
iKlsR

Reputation: 2672

You say you only see corners of the cube? Then your Field of view is too wide.. you are using gluPerspective() and providing your calculations are correct.. the values are a bit off imo, the function parameters are:

void gluPerspective(GLdouble fovy,
                    GLdouble aspect_ratio,
                    GLdouble zNear,
                    GLdouble zFar);

i propose changing that to something like

gluPerspective(45.0f,
               width_of_window / height_of_window,    //aspect ratio
               0.1f, 
               500.0f);

Upvotes: 4

Related Questions