Creating a Square using the OpenGL API
Back to OpenGL Tutorial Index
OpenGL allows us to use a variety of geometrical shapes within it.
These are;
GL_LINES
GL_LINE_STRIP
GL_LINE_LOOP
GL_POINTS
GL_POLYGON
GL_QUADS
GL_QUAD_STRIP
GL_TRIANGLES
GL_TRIANGLE_FAN
GL_TRIANGLE_STRIP
In this tutorial I am only going to work with Quads to create
a simple square.
As you can tell from the name Quads, we are creating a 4 sided
shape.
To start of any shape, you need to set the start of it.
This is achieved with:
glBegin(shape);
So because I am using a quad, I call:
glBegin(GL_QUADS);
Next comes the code to create the vertices of the shape.
A vertex is a point in 3d space.
OpenGL will automatically link together our vertices to create
our shape.
Because this is a 4 sided shape, it has 4 corners (vertices) so it
creates a new shape every 5th vertex.
To set up a vertex, you can either use, 2d or 3d space.
To set up a 2d vertex, call:
glVertex2d
This takes the parameters of:
x
y
In that order.
But we want to use 3d space, so we use:
glVertex3f
Which takes the parameters of:
x
y
z
In that order.
So if we go to our code, we have:
glBegin(GL_QUADS);
Now to set up our vertices I am simply calling:
glBegin(GL_QUADS); //begin the four sided shape
glVertex3f(-0.5, -0.5, 0.0); //first corner at -0.5, -0.5
glVertex3f(-0.5, 0.5, 0.0); //second corner at -0.5, 0.5
glVertex3f(0.5, 0.5, 0.0); //third corner at 0.5, 0.5
glVertex3f(0.5, -0.5, 0.0); //fourth corner at 0.5, -0.5
Then after we are done calling our vertices, we need to specify
the end of our shape. To do this well call:
glEnd();
And there we have it, a nice little cube.
If you have any questions relating to this tutorial, email me at swiftless@gmail.com
#include <GL/gl.h>
#include <GL/glut.h>
void square (void) {
glBegin(GL_QUADS); //begin the four sided shape
glVertex3f(-0.5, -0.5, 0.0); //first corner at -0.5, -0.5
glVertex3f(-0.5, 0.5, 0.0); //second corner at -0.5, 0.5
glVertex3f(0.5, 0.5, 0.0); //third corner at 0.5, 0.5
glVertex3f(0.5, -0.5, 0.0); //fourth corner at 0.5, -0.5
glEnd(); //end the shape we are currently working on
}
void display (void) {
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
square();
glFlush();
}
void reshape (int w, int h) {
glViewport (0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective (60, (GLfloat)w / (GLfloat)h, 1.0, 100.0);
glMatrixMode (GL_MODELVIEW);
}
int main (int argc, char **argv) {
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("A basic OpenGL Window");
glutDisplayFunc (display);
glutReshapeFunc (reshape);
glutMainLoop ();
return 0;
}
Download C++ Source Code for this Tutorial
Download Visual Basic Source Code for this Tutorial |