drawing interleaved VBO with glDrawArrays

只谈情不闲聊 提交于 2019-12-23 17:40:12

问题


I'm currently using glDrawElements to render using multiple VBOs (vertex, color, texture, and index). I've found that very few vertices are shared, so I'd like to switch to glDrawArrays, and a single interleaved VBO.

I've been unable to find a clear example of 1) creating an interleaved VBO and adding a quad or tri to it (vert, color, texture), and 2) doing whatever is needed to draw it using glDrawArrays. What is the code for these two steps?


回答1:


Off the top of my head:

//init
glBindBuffer(GL_ARRAY_BUFFER, new_array);
GLfloat data[] = { 
    0.f, 0.f, 0.f, 0.f, 0.f,
    0.f, 0.f, 100.f, 0.f, 1.f,
    0.f, 100.f, 100.f, 1.f, 1.f,
    0.f, 100.f, 100.f, 1.f, 1.f,
    0.f, 100.f, 0.f, 1.f, 0.f,
    0.f, 0.f, 0.f, 0.f, 0.f,
};
glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW);

// draw
glBindBuffer(GL_ARRAY_BUFFER, new_array);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 5*sizeof(GLfloat), NULL);
glClientActiveTexture(GL_TEXTURE0);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 5*sizeof(GLfloat), ((char*)NULL)+3*sizeof(GLfloat) );
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);

There is nothing particularly magic in this code. Just watch how:

  • The data from the data array gets loaded: as is, all contiguous
  • the stride for the various attributes is set to 5*sizeof(GLfloat), as this is what is in data: 3 floats for position and 2 for texcoord. Side note, you usually want this to be a power of 2, unlike here.
  • the offset is computed from the start of the array. so since we store vertex first, the offset for vertex is 0. texcoord is stored after 3 floats of position data, so its offset is 3*sizeof(GLfloat).

I did not include color in there for a reason: they typically are stored as UNORMs, which makes for a messier initialization code. You need to store both GLfloat and GLubyte in the same memory chunk. At that point, structs can help if you want to do it in code, but it largely depends on where your data is ultimately coming from.



来源:https://stackoverflow.com/questions/5906742/drawing-interleaved-vbo-with-gldrawarrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!