Home > Software engineering >  openGL 3D Rectangle not overlapping properly in C
openGL 3D Rectangle not overlapping properly in C

Time:02-18

You are given 3 rectangular strips whose vertex coordinates are as given below.

  • Rectangle A (RED COLOR) (-0.5,0.6,-0.8), (-0.2,0.9,-0.8), (0.8,-0.1, 0.8), (0.5, -0.4, 0.8)
  • Rectangle B (GREEN COLOR) (0.0, 0.8, 0.8), (0.3, 0.5, 0.8), (-0.7, -0.5, -0.8), (-1.0, -0.2, -0.8)
  • Rectangle C (BLUE COLOR) (0.6, 0, -0.8), (0.6, -0.3, -0.8), (-0.9, -0.3, 0.8), (-0.9, 0, 0.8)

Plot these strips on screen. Make the background black.

Required Output: Output Image

This is my C program:

#include <iostream>
#include <fstream>
#include <GL/freeglut.h>
#include <GL/gl.h>
#include<bits/stdc  .h>

using namespace std;

void renderFunction(){

    glClearColor(0.0, 0.0, 0.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

    // Red Polygon
    glColor3f(1.0, 0.0, 0.0);
    glBegin(GL_POLYGON);
        glVertex3f(-0.5,0.6,-0.8);
        glVertex3f(-0.2,0.9,-0.8);
        glVertex3f(0.8,-0.1, 0.8);
        glVertex3f(0.5, -0.4, 0.8);
    glEnd();

    // Green Polygon
    glColor3f(0.0, 1.0, 0.0);
    glBegin(GL_POLYGON);
        glVertex3f(0.0, 0.8, 0.8);
        glVertex3f(0.3, 0.5, 0.8);
        glVertex3f(-0.7, -0.5, -0.8);
        glVertex3f(-1.0, -0.2, -0.8);
    glEnd();

    // Blue Polygon
    glColor3f(0.0, 0.0, 1.0);
    glBegin(GL_POLYGON);
        glVertex3f(0.6, 0.0, -0.8);
        glVertex3f(0.6, -0.3, -0.8);
        glVertex3f(-0.9, -0.3, 0.8);
        glVertex3f(-0.9, 0.0, 0.8);
    glEnd();

    glFlush();
}

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

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE);
    glutInitWindowSize(1366, 768);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("Q6 - 3D Polygon");

    glutDisplayFunc(renderFunction);
    glutMainLoop();

    return 0;
}

My Output: output based on above code

Now the problem is that the right end of the blue rectagular part is on top of the red rectangle which is not the required output. The required output is blue's right end is below the red rectangle. I don't know what's the problem. I tried by clearing the GL_DEPTH_BUFFER_BIT. But it creates the same output. Please help me on this.

CodePudding user response:

The reason why this was not working is because

  1. You initialized display mode as GLUT_SINGLE (Not including the GLUT_DEPTH).
  2. You did not enabled glEnable(GL_DEPTH_TEST).

Those two are needed to enable the depth test, so, you have to put glEnable(GL_DEPTH_TEST); right after glClear, and change glutInitDisplayMode(GLUT_SINGLE) to glutInitDisplayMode(GLUT_SINGLE|GLUT_DEPTH).

  • Related