Reputation: 467
I'm looking into opengl and python and have created a basic program to draw a rectangle using two triangles.
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)
I send in data as follows:
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]
The glDrawElements
call does nothing, glDrawArrays
paints a nice triangle in the window.
Somthing obvious I suspect why the glDrawElements
doesn't work?
Upvotes: 1
Views: 1043
Reputation: 210877
The data type of the indices has to be GL_UNSIGNED_BYTE
, GL_UNSIGNED_SHORT
, or GL_UNSIGNED_INT
. (see glDrawElements
)
To create a proper array of values with data type unsigned int
you can either use array
:
from array import array
indAr = array("I", self.indices)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indAr.tostring(), GL_STATIC_DRAW)
Or you can use numpy.array
:
import numpy
numIndAr = numpy.array(self.indices, dtype='uint')
glBufferData(GL_ELEMENT_ARRAY_BUFFER, numIndAr, GL_STATIC_DRAW)
If a vertex array object is used, then the 4th parameter of glDrawElements
has to be None
and not 0
:
glDrawElements(GL_TRIANGLES, len(self.indices), GL_UNSIGNED_INT, None)
Upvotes: 2