Search code examples
c++openglglm-mathindicesvertices

Having issues drawing 3D cube's edges with OpenGL 3


I'm trying to draw 3D cube's vertices (edges only) using OpenGL (4.3 core profile), I know the glPolygonMode function but I'd like not to draw the intermediate diagonal lines. I declare my vertices and my indices like so :

struct Vertex {
    glm::vec3 pos;
    glm::vec3 color;
    glm::vec3 normal;
    glm::vec2 uv;
};

Vertex vertices[8];

// Front vertices
vertices[0].pos = glm::vec3(-0.5f, -0.5f, +0.5f);
vertices[1].pos = glm::vec3(+0.5f, -0.5f, +0.5f);
vertices[2].pos = glm::vec3(+0.5f, +0.5f, +0.5f);
vertices[3].pos = glm::vec3(-0.5f, +0.5f, +0.5f);

// Back vertices
vertices[4].pos = glm::vec3(-0.5f, -0.5f, -0.5f);
vertices[5].pos = glm::vec3(+0.5f, -0.5f, -0.5f);
vertices[6].pos = glm::vec3(+0.5f, +0.5f, -0.5f);
vertices[7].pos = glm::vec3(-0.5f, +0.5f, -0.5f);

GLuint indices[36] = {
    0, 1, 2, 2, 3, 0, // Front
    1, 5, 6, 6, 2, 1, // Right
    7, 6, 5, 5, 4, 7, // Back
    4, 0, 3, 3, 7, 4, // Left
    4, 5, 1, 1, 0, 4, // Bottom
    3, 2, 6, 6, 7, 3 // Top
};

My buffer is updated accordingly :

// Bind Vertex Array
glBindVertexArray(_VAO);

// Bind VBO to GL_ARRAY_BUFFER type so that all calls to GL_ARRAY_BUFFER use VBO
glBindBuffer(GL_ARRAY_BUFFER, _VBO);

// Upload vertices to VBO
glBufferData(GL_ARRAY_BUFFER, verticesNb * sizeof(Vertex), vertices, GL_STATIC_DRAW);

// Bind EBO to GL_ARRAY_BUFFER type so that all calls to GL_ARRAY_BUFFER use EBO
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _EBO);

// Updload indices to EBO
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesNb * sizeof(GLuint), indices, GL_STATIC_DRAW);

I'm using glDrawElements(GL_LINES, 36, GL_UNSIGNED_INT, 0); to draw my cube's edges, but for some reason it doesn't draw some edges and I don't understand why.

If I use GL_TRIANGLES, it works pretty well though when I want to render my 3D cube in fill-mode. Does anyone know what I'm missing here ? Is it an issue with the indices ?

(The "cube" below has a custom size of (1.0f, 2.0f, 3.0f))

OpenGL cube


Solution

  • Your indices form GL_TRIANGLES primitives rather than GL_LINES primitives. See GL_LINES:

    Vertices 0 and 1 are considered a line. Vertices 2 and 3 are considered a line. And so on.

    The indices form the primitives. Change the indices:

    GLuint indices[] = {
        0, 1, 1, 2, 2, 3, 3, 0, // Front
        4, 5, 5, 6, 6, 7, 7, 4, // Back
        0, 4, 1, 5, 2, 6, 3, 7
    };
    
    glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0);