This post is the first in a series of OpenGL “tutorials” explaining how to get a triangle on your screen using as few lines of code, in as many languages, and on as many platforms as possible.

I thought I’d inaugurate this series with the classic approach.  A little C.  A little GLUT.  Voila, you’ve got a triangle.

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

// on mac use the following includes instead
//#include <OpenGL/gl.h>
//#include <GLUT/glut.h>

void draw();

int main(int argc, char** argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowSize(500,500);
    glutInitWindowPosition(0,0);
    glutCreateWindow("Hello, GL!");

    glutDisplayFunc(draw);

    glutMainLoop();
    return 0;
}

void draw()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glColor3f(1.0,1.0,1.0);
    glBegin(GL_TRIANGLES);
        glVertex3f(-0.5,-0.5,1.0);
        glVertex3f(0.5,-0.5,1.0);
        glVertex3f(-0.5,0.5,1.0);
    glEnd();

    glutSwapBuffers();
}

Ok, if you’ve done a little bit of OpenGL and GUI programming before that should be pretty straight forward.  In fact, even if you haven’t I bet most of that made sense anyway.

What I like about working in C with GLUT:  OpenGL was designed as a procedural API for languages like C.  So working in C feels very natural and straightforward.  I particularly like GLUT, because I got everything set up with 5 procedural calls.  I don’t have to worry about any complicated object model that my GUI system is asking me to grok.  I don’t have to waste time setting up defaults for any part of the GUI I’m not going to use.  Certainly, for more complicated programs, an elaborate object model with tons of knobs to turn can save you a lot of time, but other GUIs often take more code and conceptual effort to get setup with.

Advertisements