G
G
German2019-07-09 20:25:53
OpenGL
German, 2019-07-09 20:25:53

How to bring polygon to front in OpenGL?

The code below creates 2 square polygons, red and green.
I'm trying to place a red square on top of a green one, but I can't.
The depth buffer is declared, cleared when necessary, the orthogonal system is configured correctly.
If I specify a value outside the range (2;-2), then the polygon disappears, as it should.

#include <...>

constexpr auto FPS_RATE = 120;
int windowHeight = 600, windowWidth = 600, windowDepth = 600;

void init();
void idleFunction();
void displayFunction();
double getTime();

double getTime()
{
  using Duration = std::chrono::duration<double>;
  return std::chrono::duration_cast<Duration>(
    std::chrono::high_resolution_clock::now().time_since_epoch()
    ).count();
}

const double frame_delay = 1.0 / FPS_RATE;
double last_render = 0;

void init()
{
  glutDisplayFunc(displayFunction);
  glutIdleFunc(idleFunction);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(-windowWidth / 2, windowWidth / 2, -windowHeight / 2, windowHeight / 2, 2, -2);
  glClearColor(0.0, 0.0, 0.0, 0.0);
}

void idleFunction()
{
  const double current_time = getTime();
  if ((current_time - last_render) > frame_delay)
  {
    last_render = current_time;
    glutPostRedisplay();
  }
}

void displayFunction()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glPushMatrix();
  //перемещаем красный квадрат на передний план
  glTranslatef(-32.5, -32.5, 2);
  glColor3f(1, 0, 0);
  glBegin(GL_POLYGON);
  glVertex3i(-150, 150, 0);
  glVertex3i(150, 150, 0);
  glVertex3i(150, -150, 0);
  glVertex3i(-150, -150, 0);
  glEnd();
  glPopMatrix();
  glPushMatrix();
  //перемещаем зелёный квадрат на задний план
  glTranslatef(32.5, 32.5, -2);
  glColor3f(0, 1, 0);
  glBegin(GL_POLYGON);
  glVertex3i(-150, 150, 0);
  glVertex3i(150, 150, 0);
  glVertex3i(150, -150, 0);
  glVertex3i(-150, -150, 0);
  glEnd();
  glPopMatrix();
  glutSwapBuffers();
}

int main(int argc, char* argv[])
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
  glutInitWindowSize(windowWidth, windowHeight);
  glutInitWindowPosition((GetSystemMetrics(SM_CXSCREEN) - windowWidth) / 2, (GetSystemMetrics(SM_CYSCREEN) - windowHeight) / 2);
  glutCreateWindow("Window");
  init();
  glutMainLoop();
  return 0;
}

What to do?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question