OpenGL with C: first steps

As I said in my previous post I will try to make my humble game engine in C with Opengl. I want to keep this as simple as possible (asap), also hope that my C programming skills will increase after this journey. Ok, stop this chit chat and start programming!

Code

First thing you will need is two header files:

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

GLUT initialization

That’s all what we will need for now. Let’s initialize our window!

1
2
3
4
5
6
7
void init_glut(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize(640, 480);
    glutCreateWindow("game");
    glutDisplayFunc(display_frame);
}

glutInit() initialize GLUT library, we pass there arguments from our program.

glutInitDisplayMode() sets the initial display mode. I or’ed there 3 values:

glutInitWindowSize() and glutCreateWindow() I think that these are self-explanatory :D

glutDisplayFunc() here we pass pointer to our display callback function

Display function

How our display function will looks like?

1
2
3
4
5
void display_frame() {
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glutSwapBuffers();
}

glClearColor() will set color to which we will clear our color buffer.

glClear() with to passed bit flags: GL_COLOR_BUFFER_BIT and GL_DEPTH_BUFFER_BIT will clear color and depth buffers.

glutSwapBuffers() swaps current displayed buffer with current edited buffer.

main() function

1
2
3
4
int main(int argc, char **argv) {
    init_glut(argc, argv);
    glutMainLoop();
}

Yeah, it’s pretty short. Now, let’s write simple Makefile:

1
2
build: main.c
	gcc main.c -lGL -lglut

and launch it!

1
2
make
./a.out
opengl_1_1.png
at least more fps than Witcher 3

Display triangle

Without operating on model, view and projection matrices (I will talk about it in the next post, I promise!) let’s assume that our world is cube with edge length of 2 and it’s vertices in points: (1,1,1), (1,1,-1), (1,-1,1)…

Now we will use some mad programming skills to display a triangle. (We will use some old OpenGL functions for simplicity, but next episode will cover openGL 3.+ functions). Let’s edit our display_frame() function:

1
2
3
4
5
6
7
8
9
10
11
void display_frame() {
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glBegin(GL_TRIANGLES);
    glColor3f(1.0, 0.0, 0.0);
    glVertex3f(0.0, 0.5, 0.0);
    glVertex3f(-0.575, -0.5, 0.0);
    glVertex3f(0.575, -0.5, 0.0);
    glEnd();
    glutSwapBuffers();
}

and we should get something like this:

opengl_1_2.png
Yeah, Triforce!

Whoa! That’s all for now. All code is available here.

In next episode we will talk about model, view and projection matrices and make some 3D figures! Have a nice day and feel free to left a comment!