Search code examples
c++openglclipping

OpenGL clipping Z>1.0


For some reason i cant draw anything past z>1 in openGL. The Z buffer works fine, I'm stuck on this for a while now. I thought that the problem was the gluPerspective, but its still not working. I can see anything between 0 and 1, the triangle of the code apears clipped. Sorry for my poor english.

#include <iostream>
#include <GL/glut.h>

using namespace std;

void idle() {
    glutPostRedisplay();
}

void changeSize(int w, int h) {

    // Prevent a divide by zero, when window is too short
    // (you cant make a window of zero width).
    if(h == 0)
        h = 1;
    float ratio = 1.0* w / h;

    // Use the Projection Matrix
    glMatrixMode(GL_PROJECTION);

        // Reset Matrix
    glLoadIdentity();

    // Set the viewport to be the entire window
    glViewport(0, 0, w, h);

    // Set the correct perspective.
    gluPerspective(0, ratio, 0.1, 1000.0);

    // Get Back to the Modelview
    glMatrixMode(GL_MODELVIEW);
}

void renderScene(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();

    glBegin(GL_TRIANGLES);
        glVertex3f(-0.5,-0.5,0.0);
        glVertex3f(0.5,0.0,0.0);
        glVertex3f(0.0,0.5,2.0);
    glEnd();

    glutSwapBuffers();
}

int main(int argc, char **argv) {

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowSize(800,600);
    glutCreateWindow("OpenGL");

    glutDisplayFunc(renderScene);
    glutReshapeFunc(changeSize);
    glutIdleFunc(idle);

    glEnable(GL_DEPTH_TEST);

    glutMainLoop();

    return 0;
}

Solution

  • First of all, your gluPerspective has a value of zero for fovy, which is completely nonsensical. Try putting a nominal value for field of view (maybe 60).

    Secondly, with that being fixed, I don't think any of your three vertices should be visible. Provided that you have no view matrix (there's none shown), the first two vertices should be clipped by the near plane. For the third vertex you probably mean for it to be at -2, not 2 (the default eye looks down the negative z axis). So this vertex is also behind the eye.

    Frankly I'm surprised that you were able to see anything at all, but see if correcting these things helps. Try drawing your triangle with z values of -0.2, -0.2, and -2.0.