February 11, 2014

OpenGL - Drawing a cube

Started playing around with 3D in preparation for my upcoming lab assignment.  I always like to start small, so I tried making a simple cube.  Instead of hardcoding values in for the square, I noticed that vertices follow a simple pattern, which I'm too lazy to describe here but I realized it was codeable.  So I did.  Here is my "draw a cube" program:

#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glext.h>

void display();
void specialKeys();
double rotate_y=0;
double rotate_x=0;

void display(){

  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
  glLoadIdentity();

  // Rotate when user changes rotate_x and rotate_y
  glRotatef( rotate_x, 1.0, 0.0, 0.0 );
  glRotatef( rotate_y, 0.0, 1.0, 0.0 );

  float c = 0.5;
  glColor3f( 1.0, 0.0, 0.0 );
  glBegin(GL_TRIANGLES);

  int a[3] = {0, 0, 0,};
  int b[12] = { 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1 };
  for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++)
{
int k = 0;
while (k < 12)
{
if (k % 2 == 0) {
glColor3f( b[k], b[k], b[k] );
}

a[i] = j;
a[(i + 1) % 3] = b[k++];
a[(i + 2) % 3] = b[k++];

float x = a[0] == 0 ? -1 : 1;
float y = a[1] == 0 ? -1 : 1;
float z = a[2] == 0 ? -1 : 1;

glVertex3f(c * x, c * y, c * z);
}
}
  }
  glEnd();

  glFlush();
  glutSwapBuffers();

}

// ----------------------------------------------------------
// specialKeys() Callback Function
// ----------------------------------------------------------
void specialKeys( int key, int x, int y ) {

  if (key == GLUT_KEY_RIGHT)
    rotate_y += 5;
  else if (key == GLUT_KEY_LEFT)
    rotate_y -= 5;
  else if (key == GLUT_KEY_UP)
    rotate_x += 5;
  else if (key == GLUT_KEY_DOWN)
    rotate_x -= 5;

  //  Request display update
  glutPostRedisplay();

}

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

  glutInit(&argc,argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
  glutCreateWindow("Awesome Cube");
  glEnable(GL_DEPTH_TEST);
  glutDisplayFunc(display);
  glutSpecialFunc(specialKeys);
  glutMainLoop();
  return 0;

}

Some of the base code I stole somewhere from online but I coded everything in the display() function except for the two glRotatef calls.

Here is my cube:

Unfortunately I'm not sure I can use that algorithm for my lab if I wanna use VBO's for extra credit..

My next goal is to have two cubes (like another smaller cube on top of this cube) and be able to apply transformations to the base cube (moving the smaller cube) and the smaller cube (moving only the smaller cube).  Start small, start small.  Eventually I'm going to code up a T rex made entirely of square and rectangles.