No display from glDrawElements

后端 未结 3 1495
孤独总比滥情好
孤独总比滥情好 2021-02-13 18:27

When I use glDrawArrays I get a triangle in the middle of my screen, as expected. But when I try to use glDrawElements nothing comes up at all.

I have tried all sorts of

相关标签:
3条回答
  • 2021-02-13 18:40

    I would start your index at zero as others have pointed out. But there is one other problem I see...

    glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, &index);
    

    should be...

    glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, index);
    

    ...as index is an array, it is already a pointer, no need for &.

    0 讨论(0)
  • 2021-02-13 18:51

    glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, &index); // this doesn't work

    Of course it doesn't. You are storing your indices in a buffer object. In the same way the last pointer argument to glVertexAttribPointer is interpreted as an offset into the currently bound GL_ARRAY_BUFFER (if one is bound), the last pointer argument to glDrawElements is interpreted as an offset into the buffer currently bound to GL_ELEMENT_ARRAY_BUFFER. You already properly store your indices into that, so you have to tell `glDrawElements that the indices start at offset 0 of this buffer, like you did with glVertexAttribPointer:

    glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, nullptr);
    

    EDIT: And like bwroga points out in his answer, you should start your indices with 0 instead of 1.

    EDIT: And you also pass the wrong sizes into glBufferData. You use sizeof(verts) * sizeof(floats) (and likewise for index), but verts is an array and the sizeof an array already is the size of the whole thing in bytes and not just the number of elements, so it should rather just be sizeof(verts), otherwise the glBufferData will try to read data beyond the actual array size which is undefined behaviour (and in your case unfortunately seems to work).

    EDIT: And of course as Grimmy points out in his comment you shouldn't recreate your VAO and VBO each time you draw, that's initialization stuff. But this is more of a conceptual/optimization error (albeit a severe one) rather than an actual "non-working" error.

    0 讨论(0)
  • 2021-02-13 18:55

    I think this:

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

    should be this:

    unsigned int index[] = {
        0, 1, 2,
    };
    
    0 讨论(0)
提交回复
热议问题