使用pyglet中的vertex_list_indexed进行纹理坐标

时间:2014-05-15 16:10:14

标签: opengl textures pyglet

我是新手在pyglet中使用纹理(通常是OpenGL),我对可能是一个愚蠢错误的东西感到难过:我试图将一个从png图像派生的纹理应用到一个组成的正方形两个三角形。我可以成功使用索引顶点列表来定义几何,但是当我为每个三角形的每个顶点指定纹理坐标(u,v)时,我得到:

追踪(最近的呼叫最后):
   在模块
中文件“test_tex.py”,第37行     ('t2f',texture_coords))
   ValueError:只能分配相同大小的序列

建议我的纹理坐标列表不正确。谁有人看到这个问题?一篇相关的帖子对我没有帮助:Triangle texture mapping OpenGL

请查看下面的代码了解详情,谢谢!

import pyglet

config = pyglet.gl.Config(sample_buffers=1, samples=4,
                      depth_size=16, double_buffer=True)
window = pyglet.window.Window(resizable=True, config=config, vsync=True)

# create vertex data
num_verts = 4
side_length = 1.0
half_side = side_length / 2.0

# vertex positions of a square centered at the origin,
# ordered counter-clockwise, starting at lower right corner
vertex_positions = [ half_side,  -half_side,
                     half_side,   half_side,
                    -half_side,   half_side,
                    -half_side,  -half_side]

# six pairs of texture coords, one pair (u,v) for each vertex
# of each triangle
texture_coords = [1.0, 0.0,
                  1.0, 1.0,
                  0.0, 1.0,
                  0.0, 1.0,
                  0.0, 0.0,
                  1.0, 0.0]

# indices of the two triangles that make the square
# counter-clockwise orientation
triangle_indices = [0, 1, 2,
                    2, 3, 0]

# use indexed vertex list
vertex_array = pyglet.graphics.vertex_list_indexed(num_verts,
                                                   triangle_indices,
                                                   ('v2f', vertex_positions),
                                                   ('t2f', texture_coords))

# enable face culling, depth testing
pyglet.gl.glEnable(pyglet.gl.GL_CULL_FACE)
pyglet.gl.glEnable(pyglet.gl.GL_DEPTH_TEST)

# texture set up
pic = pyglet.image.load('test.png')
texture = pic.get_texture()
pyglet.gl.glEnable(texture.target)
pyglet.gl.glBindTexture(texture.target, texture.id)

# set modelview matrix
pyglet.gl.glMatrixMode(pyglet.gl.GL_MODELVIEW)
pyglet.gl.glLoadIdentity()
pyglet.gl.gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0)

@window.event
def on_resize(width, height):
    pyglet.gl.glViewport(0, 0, width, height)
    pyglet.gl.glMatrixMode(pyglet.gl.GL_PROJECTION)
    pyglet.gl.glLoadIdentity()
    pyglet.gl.gluPerspective(45.0, width / float(height), 1.0, 100.0)
    return pyglet.event.EVENT_HANDLED

@window.event
def on_draw():
    window.clear()
    vertex_array.draw(pyglet.gl.GL_TRIANGLES)

pyglet.app.run()

1 个答案:

答案 0 :(得分:1)

它可能很抱怨,因为你有6组纹理坐标,但只有4个顶点。您需要每个顶点的纹理坐标,因此texture_coord数组中应该有4对浮点数:

texture_coords = [1.0, 0.0,
                  1.0, 1.0,
                  0.0, 1.0,
                  0.0, 0.0]