Drawing two triangles using index buffer

485 views Asked by At

I am following Cherno's brilliant series on OpenGL, and I have encountered a problem. I have moved on from using a vertex buffer only, to now using a vertex buffer together with an index buffer.

What I want to happen, is for my program to draw two triangles, using the given positions and indices, however when I run my program I only get a black screen. My shaders are working fine when drawing only from a vertex buffer, but introducing the index buffer makes it fail. Here is the relevant parts of code:

float positions[] {
    -0.5, -0.5,
     0.5, -0.5,
     0.5,  0.5,
    -0.5,  0.5
};

unsigned int indices[] {
    0, 1, 2,
    2, 3, 0
};

unsigned int VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, 4*2*sizeof(float), positions, GL_STATIC_DRAW);

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float)*2, 0);

unsigned int IBO;
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6*sizeof(unsigned int), indices, GL_STATIC_DRAW);

ShaderProgramSource source = parseShader("res/shaders/Basic.glsl");

unsigned int shader = createShader(source.vertexSource, source.fragmentSource);
glUseProgram(shader);

/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
    /* Render here */
    glClear(GL_COLOR_BUFFER_BIT);
    
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
    

    /* Swap front and back buffers */
    glfwSwapBuffers(window);

    /* Poll for and process events */
    glfwPollEvents();
}

I am pretty much sure that my code is equal to that of Cherno, but he gets a nice looking square on screen whereas I get nothing. Can you spot an error?

Here's some info on my system:

  • macOS 12.2.1
  • OpenGL Version 4.1
  • GLSL Version 3.3
  • Writing and compiling in Xcode
  • Static linking to GLEW and GLFW
1

There are 1 answers

0
Rabbid76 On BEST ANSWER

Unlike using Linux or Windows, a Compatibility profile OpenGL Context is not supported on a Mac. You must use a Core profile OpenGL Context. If you use a Core profile, you must create a Vertex Array Object because a core profile does not have a default Vertex Array Object.

GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float)*2, 0);