C++ OpenGL, drawing shapes is returning an error

0

I am trying to draw shapes onto my application. I have added #include <glad/glad.h> into my code.

I set my vertex array, vertex buffer & index buffer as unsigned ints in my header file.

In my application.h file I added this:

unsigned int m_FCvertexArray; // Textured Phong VAO
unsigned int m_FCvertexBuffer;// Textured Phong VBO
unsigned int m_FCindexBuffer; // Index buffer for texture Phong cube

In my application.cpp in my constructor I added this:

Application::Application()
{
    //------------- OPENGL VALUES -----------//

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    // Enabling backface culling to ensure triangle vertices are correct ordered (CCW)

    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);

    ////--------DRAW VERTICES---------//

    float FCvertices[3 * 3] = {
                -0.5f, -0.5f, 0.0f,
                 0.5f, -0.5f, 0.0f,
                 0.0f,  0.5f, 0.0f
            };

    glGenVertexArrays(1, &m_FCvertexArray);
    glBindVertexArray(m_FCvertexArray);

    glCreateBuffers(1, &m_FCvertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, m_FCvertexBuffer);

    //
    //

    glBufferData(GL_ARRAY_BUFFER, sizeof(FCvertices), FCvertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(sizeof(float) * 3));


    ////--------DRAW INDICES---------//

    glCreateBuffers(1, &m_FCindexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, m_FCindexBuffer);

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

    glBufferData(GL_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
}

in my void Application::run() I added:

glUseProgram(m_FCprogram);
glBindVertexArray(m_FCvertexArray);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, nullptr);

now the problem is when I run the code, it gives me the error mentioned on the title:

Exception thrown at 0x000000005D78F420 (nvoglv64.dll) in Sandbox.exe: 0xC0000005: Access violation reading location 0x0000000000000000.

I've been trying ways to fix this but it seems not to work. and if i comment out glDrawElements, the code runs and works but no shapes are drawn (obvious).

c++
opengl
glad
asked on Stack Overflow Jan 13, 2020 by Mahraf Ahmed

1 Answer

-1

When you create the index buffer, you need to use GL_ELEMENT_ARRAY_BUFFER instead of GL_ARRAY_BUFFER.

answered on Stack Overflow Jan 13, 2020 by noobius • edited Jan 13, 2020 by noobius

User contributions licensed under CC BY-SA 3.0