Search code examples
pythonpolygonpyglet

Rendering a Polygon in Pyglet using GL_TRIANGLES - KeyError 'v' Error


I am trying to render a polygon using the GL_TRIANGLES mode for pyglet.graphics.draw but have been running into issues.

I have been attempting to render it like I've seen people do in many other places

def draw(self):
    pyglet.graphics.draw(
       size=int(len(self.coords) / 2), 
       mode=pyglet.gl.GL_TRIANGLES,
       position=('v2f', self.coords),
    )

but have been running into the following error:

  File "C:\Python311\Lib\site-packages\pyglet\graphics\__init__.py", line 52, in draw
    gl_type = vertexdomain._gl_types[fmt[0]]
              ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
KeyError: 'v'

Did the usage change? Not sure exactly what I'm doing wrong here.


Solution

  • v2f is the old format specification. In Pyglet Version 2.0, this has changed. See the documentation of draw(size, mode, **data). The first parameter is the number of vertices and each vertex has to have 3 components. The format is just f for float. e.g.:

    self.coords = [x0, y0, z0, x1, y1, z1, ...]
    
    pyglet.graphics.draw(
        size = len(self.coords) // 3,
        mode = pyglet.gl.GL_TRIANGLES,
        position = ('f', self.coords)
    )
    

    Note that this will draw only black triangles. Set the colors attribute to draw a colorful shape.

    Minimal example:

    import pyglet
    
    window = pyglet.window.Window(800, 600)
    
    vertices = [100, 100, 0, 300, 100, 0, 200, 300, 0]
    colors = [255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]
    
    @window.event
    def on_draw():
        window.clear()
        pyglet.graphics.draw(
            size = 3, 
            mode = pyglet.gl.GL_TRIANGLES, 
            position = ('f', vertices),
            colors = ('Bn', colors))
        
    pyglet.app.run()