Search code examples
pythonperformancefor-loopopenglpyopengl

How to improve the performance of the following code?


glBegin(GL_TRIANGLES)
for face in faces:
   for vertex_i in face:
      glVertex3f(*vertices[vertex_i])
glEnd()

Is there any way to replace the double for loops with a more efficient function/method?


Solution

  • Yes, you can use the fixed function attributes and define an array of vertex data glVertexPointer / glEnableClientState. In this case you can draw the triangles by glDrawElements. indices has to be an array of the triangle indices and vertexarray and array of the coordinate components. For Instance:

    Once at initilization:

    vertexarray = [c for v in vertices for c in v]
    indices = [i for f in faces for i in f]
    

    Per frame:

    glVertexPointer(3, GL_FLOAT, 0, vertexarray)
    glEnableClientState(GL_VERTEX_ARRAY)
    glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, indices)
    glDisableClientState(GL_VERTEX_ARRAY)
    

    Alternatively you can use numpy.array

    import numpy
    
    vertexarray = numpy.array(vertices, dtype=numpy.float)
    indices = numpy.array(faces, dtype=numpy.uint32)
    
    glVertexPointer(3, GL_FLOAT, 0, vertexarray)
    glEnableClientState(GL_VERTEX_ARRAY)
    glDrawElements(GL_TRIANGLES, indices.size, GL_UNSIGNED_INT, indices)
    glDisableClientState(GL_VERTEX_ARRAY)