我正在研究opengl和python并创建了一个基本程序,用两个三角形绘制一个矩形。
def draw(self, shader):
shader.bind()
#glDrawArrays(GL_TRIANGLES, 1, 3)
glDrawElements(GL_TRIANGLES,
len(self.indices),
GL_UNSIGNED_INT,
0)
glBindVertexArray(0)
shader.unbind()
def _setupMesh(self):
# VAO
glGenVertexArrays(1, self._VAO)
glBindVertexArray(self._VAO)
#VBO
glGenBuffers(1, self._VBO)
glBindBuffer(GL_ARRAY_BUFFER, self._VBO)
self.vertices_size = (GLfloat * len(self.vertices))(*self.vertices)
glBufferData(GL_ARRAY_BUFFER,
len(self.vertices)*sizeof(GLfloat),
self.vertices_size,
GL_STATIC_DRAW)
#EBO
glGenBuffers(1, self._EBO)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._EBO)
self.indices_size = (GLfloat * len(self.indices))(*self.indices)
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
len(self.indices)*sizeof(GLfloat),
self.indices_size,
GL_STATIC_DRAW)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), c_void_p(0))
glEnableVertexAttribArray(0)
我发送的数据如下:
vertices: [ 0.5, 0.5, 0.0,
0.5, -0.5, 0.0,
-0.5, -0.5, 0.0,
-0.5, 0.5, 0.0]
indices: [0,1,3,1,2,3]
glDrawElements
调用不执行任何操作,glDrawArrays
在窗口中绘制一个漂亮的三角形。
很明显我怀疑为什么glDrawElements
不起作用?
答案 0 :(得分:2)
索引的数据类型必须为GL_UNSIGNED_BYTE
,GL_UNSIGNED_SHORT
或GL_UNSIGNED_INT
。 (见glDrawElements
)
要创建数据类型为unsigned int
的正确值数组,您可以使用array
:
from array import array
indAr = array("I", self.indices)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indAr.tostring(), GL_STATIC_DRAW)
或者您可以使用numpy.array
:
import numpy
numIndAr = numpy.array(self.indices, dtype='uint')
glBufferData(GL_ELEMENT_ARRAY_BUFFER, numIndAr, GL_STATIC_DRAW)
如果使用顶点数组对象,那么glDrawElements
的第4个参数必须是None
而不是0
:
glDrawElements(GL_TRIANGLES, len(self.indices), GL_UNSIGNED_INT, None)