Search code examples
javaopengllwjglglfw

LWJGL 3: OpenGL Quad is not rendered properly


Whenever I run this, the window pops up and I see this. (When I run the game, I see this)

This can be recreated if you simply make a new Java Project, import OpenGL, GLFW, and LWJGL, along with natives, and then copy the code (Remove package)

import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import org.lwjgl.opengl.GL;

public class Game {

    public static void main (String[] args) {

        if(glfwInit() != true) {
            System.err.println("GLFW Failed to initialize!");
            System.exit(1);
        }

        long window = glfwCreateWindow(640,480,"Game", 0, 0);

        glfwShowWindow(window);

        glfwMakeContextCurrent(window);
        GL.createCapabilities();

        while(!glfwWindowShouldClose(window)) {

            glfwPollEvents();

            glClear(GL_COLOR_BUFFER_BIT);

            glBegin(GL_QUADS);

            glVertex2d(-0.5,0.5);
            glVertex2d(0.5,0.5);
            glVertex2d(-0.5,-0.5);
            glVertex2d(0.5,-0.5);

            glEnd();

            glfwSwapBuffers(window);

        }

        glfwTerminate();

    }

}

Solution

  • You're drawing the vertices of the quad in the wrong order. Try

    glVertex2d(0.5,0.5);
    glVertex2d(-0.5,0.5);
    glVertex2d(-0.5,-0.5);
    glVertex2d(0.5,-0.5);
    

    You usually draw them in counterclockwise order for a quad (or triangle) that is facing you (this is called "winding") and clockwise for one that is facing away from you. In your case, you have drawn them as if they were a letter "Z" which is invalid.