Search code examples
copenglglut

OpenGL glBegin and glPushMatrix


I try to design a scene with 3 spheres and one line horizontal as equator. I got to draw the 3 spheres but I don't know why the line is not draw.

This is my code, for if you can see where I'm wrong:

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

void render(void);

void reshape(int w, int h);

int angle = 90;

int main(int argc, char **argv) {
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
  glutInitWindowPosition(50, 50);
  glutInitWindowSize(800, 600);
  glutCreateWindow("Planets");

  glutDisplayFunc(render);
  glutReshapeFunc(reshape);

  glutMainLoop();
  return 0;
}


void render(void) {
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glClearColor(0, 0, 0, 1);

  // Equator
  glBegin(GL_LINES);
  glColor3f(1,1,1);
  glLineWidth(1);
  glTranslated(0, 0, 0);
  glVertex2f(0, 2);
  glVertex2f(2,2);
  glEnd();

  // Sun
  glPushMatrix();
  glLoadIdentity();
  glColor3f(1.0, 1.0, 0.0);
  glTranslated(0, 0, -2);
  glRotated(angle, 1, 0, 0);
  glutWireSphere(.3, 20, 20);
  glPopMatrix();

  //Earth
  glPushMatrix();
  glLoadIdentity();
  glColor3f(0.0, 0.0, 1.0);
  glTranslated(0.7, 0, -2);
  glRotated(angle, 1, 0, 0);
  glutWireSphere(.15, 20, 20);
  glPopMatrix();

  // Moon
  glPushMatrix();
  glLoadIdentity();
  glColor3f(1.0, 0.0, 1.0);
  glTranslated(1, 0, -2);
  glRotated(angle, 1, 0, 0);
  glutWireSphere(.05, 10, 10);
  glPopMatrix();

  glutSwapBuffers();
}

void reshape(int w, int h) {
  const double ar = (double) w / (double) h;
  glViewport(0, 0, (GLsizei) w, (GLsizei) h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
}

Solution

  • You specify a frustum that has the near clip plane at z=-2. Your intended line would be drawn at z=0, thus outside the projection volume, thereby clipped into non-rendering.

    glTranslate(0,0,0) is a no-op BTW.