【问题标题】:Is there a faster way to draw on screen using pyglet and threading?有没有更快的方法使用 pyglet 和线程在屏幕上绘图?
【发布时间】:2020-05-11 12:59:04
【问题描述】:

下面的三个函数展示了我如何使用 pyglet 库在屏幕上绘制正方形。代码工作正常。但我想让它运行得更快。

以我对线程的新手理解,我认为draw_grid() 中的 for 循环可以通过使用线程来更快,因为它等待使用pos 绘制一个正方形,然后绘制一个新正方形。既然已经提供了all_positions,有没有办法同时绘制所有的正方形?

def draw_square(single_location):
    # draws a single square
    pyglet.graphics.draw_indexed(4, pyglet.graphics.gl.GL_TRIANGLES,
                             [0,1,2,1,2,3],
                             ('v2i', single_location))

def position_array():
    # returns an 2D array with each row representing the coordinates of the rectangle to draw
    ...relevant code...
    return all_positions

def draw_grid(all_positions):
    # uses draw_square function and all_positions to draw multiple squares at the specified locations.
    for pos in all_positions:
        draw_square(pos)

在查找了一些关于线程的视频后,我找到了concurrent.futures 库。所以我试图实现它,它给了我错误。所以现在我被卡住了。

这是我在 draw_grid() 中使用 concurrent.futures.ThreadPoolExecutor() 的方法

def draw_grid(all_positions):
    # uses draw_square function and all_positions to draw multiple squares at the specified locations.
    with concurrent.futures.ThreadPoolExecutor as executor:
        for pos in all_positions:
        f1 = executor.submit(draw_square, pos)
        f1.result()

【问题讨论】:

    标签: python multithreading pyglet concurrent.futures


    【解决方案1】:

    作为一般规则,切勿混合使用线程和图形渲染。这是灾难的收据。可以将线程与渲染 (GL) 结合使用。但同样,不推荐

    相反,您可能想看看批处理渲染。
    documentation on Batched rendering 很棒,您可能会发现它很容易理解。

    请记住,如果要在将顶点添加到补丁后修改顶点,则需要将它们存储并修改从批处理返回,不要尝试直接操作批处理。

    vertex_list = batch.add(2, pyglet.gl.GL_POINTS, None,
        ('v2i', (10, 15, 30, 35)),
        ('c3B', (0, 0, 255, 0, 255, 0))
    )
    # vertex_list.vertices <-- Modify here
    

    您不想使用线程的原因是,几乎 99.9% 的保证您最终会因竞争条件而出现分段错误。当你渲染你试图操作的东西时,有东西试图更新屏幕。

    更多信息请点击此处的 cmets:Update and On_Draw Pyglet in Thread

    因此,请将所有方块添加到一批中,然后执行batch.draw(),它会一次模拟地绘制所有方块。而不是浪费 CPU 周期调用函数并每次重新创建正方形,然后一个一个地渲染它们。

    batch = pyglet.graphics.Batch()
    batch.add(2, pyglet.gl.GL_TRIANGLES, None,
        ('v2i', [0,1,2,1,2,3])
    )
    
    def on_draw():
        batch.draw()
    

    类似的东西。但显然你想在不同位置创建正方形等。但作为指导,在渲染逻辑之外创建批处理和正方形,然后在渲染周期中对批处理调用 .draw()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      相关资源
      最近更新 更多