我正在尝试使用 OpenGL 中的顶点缓冲区对象绘制两个四边形。他们应该用不同的颜色绘制。如您所见,第一个四边形具有红色、绿色、蓝色和黄色顶点。第二个四边形有不同的颜色,但问题是第二个四边形被完全绘制成黄色。这是我的代码:
GLfloat vertices[24] = {10.0, 10.0, 0.0, 10.0, -10.0, 0.0, -10.0, -10.0, 0.0, -10.0, 10.0, 0.0,
20.0, 20.0, 0.0, 20.0, 10.0, 0.0, 10.0, 10.0, 0.0, 10.0, 20.0, 0.0 };
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 24, vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
GLfloat colors[24] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0,
0.5, 0.5, 0.5, 0.7, 0.2, 1.0, 0.2, 1.0, 0.7, 0.8, 0.0, 0.45 };
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLfloat) * 24, colors, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glEnableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glVertexPointer(3, GL_FLOAT, 0, 0);
glEnableClientState(GL_COLOR_ARRAY);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, colorBuffer);
glColorPointer(3, GL_FLOAT, 0, 0);
glDrawArrays(GL_QUADS, 0, 8);
四边形是这样画的:
第二个四边形是右上角的那个。它应该是多色的,但它是使用颜色缓冲区的第 4 个元素绘制的。我应该怎么做才能修复它?
最佳答案
参见 OpenGL 2.1 Reference Pages; glColorPointer
:
glColorPointer
specifies the location and data format of an array of color components to use when rendering. ...If a non-zero named buffer object is bound to the
GL_ARRAY_BUFFER
target while a color array is specified, pointer is treated as a byte offset into the buffer object's data store.
在你的代码中 buffer
绑定(bind)到目标 GL_ARRAY_BUFFER
;
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
然后 colorBuffer
绑定(bind)到目标 GL_ELEMENT_ARRAY_BUFFER
并定义颜色数组:
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, colorBuffer);
glColorPointer(3, GL_FLOAT, 0, 0);
因为此时 buffer
仍然绑定(bind)到目标 GL_ARRAY_BUFFER
,glColorPointer
使用 buffer
。这导致顶点坐标被视为颜色,这就是您在渲染中可以看到的。
要解决此问题,您必须将 colorBuffer
绑定(bind)到目标 GL_ARRAY_BUFFER
:
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
关于c++ - VBO - 绘制具有不同颜色的多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222257/