Skip to content

2.2. OpenGL

Ioannis Tsakpinis edited this page Oct 29, 2019 · 4 revisions

Display Creation using GLFW

The first command which should be called is:

GLFWErrorCallback errorCallback;
glfwSetErrorCallback(errorCallback = GLFWErrorCallback.createPrint(System.err));

This line will make all GLFW errors print to the console Then, glfwInit() has to be called to initialize GLFW.

So far, the code would look something like this:

GLFWErrorCallback errorCallback;
glfwSetErrorCallback(errorCallback = GLFWErrorCallback.createPrint(System.err));
if ( glfwInit() != GLFW_TRUE ) {
    throw new IllegalStateException("Unable to initialize GLFW");

The next job to tackle, now that GLFW has been set up, is to create the display:

String title = "MyTitle"; // The title of the window, WARNING, if title is
                          // null, the code will segfault at glfwCreateWindow()
boolean resizable = true; // Whether or not the window is resizable

int m_width = 1024; // width of the window
int m_height = 768; // height of the window

glfwDefaultWindowHints(); // Loads GLFW's default window settings
glfwWindowHint(GLFW_VISIBLE, GLFW_TRUE); // Sets window to be visible
glfwWindowHint(GLFW_RESIZABLE, resizable ? GLFW_TRUE : GLFW_FALSE); // Sets whether the window is resizable

long id = glfwCreateWindow(m_width, m_height, title, NULL, NULL); // Does the actual window creation
if ( id == NULL ) throw new RuntimeException("Failed to create window");

glfwMakeContextCurrent(id); // glfwSwapInterval needs a context on the calling thread, otherwise will cause NO_CURRENT_CONTEXT error
GL.createCapabilities(); // Will let lwjgl know we want to use this context as the context to draw with

glfwSwapInterval(1); // How many draws to swap the buffer
glfwShowWindow(id); // Shows the window

Setting the mouse to grabbed

After the display has been created, this command can be used to set the mouse to grabbed


Hiding the mouse

If you want the mouse to disappear when over the window, but to still be movable, use this command (for example, you might want to draw your own mouse)


Calling OpenGL functions

First, before any functions can be called, an OpenGL context needs to be created using


Then, you are good to go and can call OpenGL functions!

The static classes GL11, GL12, GL13, GL20, GL21, GL22,... can be used the access functions of a certain GL version where GL11 would correspond to OpenGL 1.1, and GL20 would correspond to OpenGL 2.0.

Since LWJGL 3.2.0, the GLnn classes form a hierarchy (GL12 extends GL11, GL13 extends GL12 and so on). Even though this is not a good practice in Java (pseudo-inheritance of static functionality), it considerably simplifies working with the OpenGL bindings. For example, a single import static org.lwjgl.opengl.GL21.* exposes all functionality up to OpenGL 2.1.

You can’t perform that action at this time.