To be able to make use of OpenGL in C# at all, we need some sort of wrapper around the C interface of the API. While there are alternatives, the most popular choice is probably OpenTK, the Open Toolkit library.
The library provides a low level wrapper around OpenGL, allowing us to use all its features. It also includes a large amount of useful mathematical types, including vectors and matrices which are a key element in computer graphics.
Further, it includes cross-platform window management, allowing us to run the exact same code on any platform without having to worry much about creating windows and handling associated events.
In fact, the only thing we have to do to create both a window, and an OpenGL context to render with is create an instance of OpenTK’s
GameWindow class, and call its
To allow for our own behaviour, we will subclass the class. We will give some default parameters in our base constructor call to make sure the window and context are initialised correctly, and then call the
Run() method in our programs static
Basic OpenGL calls
To access any kind of OpenGL functionality, we will use OpenTK’s static
GL class. There are several different versions of it, and which one you want to use depends on the platform you are targeting.
If, like us today, you are going for Windows/Mac/Linux then you should use the one in
The most basic things we can do are:
- show the version of the context that we created using
- set the size of our viewport to the same size as our window in
GL.Viewport()(you need to do this to see anything);
- clear the screen before rendering our frame, and swapping the backbuffer afterwards using
Adding these things our class looks as follows.
If you are familiar with OpenGL, you may notice that we are using virtually the same commands that one would use in a C++ or C application.
GL.GetString() instead of
This pattern is true for almost the entire OpenGL API in OpenTK, making it not only easier to use when switching from pure OpenGL, but also allowing us to easily look up the documentation of any GL call online.