我正在尝试使用pygame可视化数值流体动力学模型的输出。模型状态是一个(nx,ny)numpy数组,我正在{nx,ny)曲面上使用surfarray.blit_array
,然后将其渗入屏幕。我在下面放了一个工作示例(按ESC停止它)。
当screen_size为(nx,ny)时,在我的计算机上,代码以60FPS运行。当我将screen_size设置为(nx * 5,ny)时,它降至14FPS。
我认为我在做正确的事情来更新显示,仅更新矩形而不是整个屏幕,所以当在屏幕上添加额外的空白时,为什么速度如此之快呢?使用display.update
似乎并不比使用display.flip
快。
import pygame
import numpy as np
from matplotlib.cm import viridis
from matplotlib.colors import Normalize
pygame.init()
pygame.font.init()
font = pygame.font.SysFont("Arial", 18)
nx = 256
ny = 257
# CHANGE THIS TO SEE THE SLOWDOWN
screen_size = (nx, ny)
flags = pygame.DOUBLEBUF #|pygame.HWACCEL|pygame.FULLSCREEN
screen = pygame.display.set_mode(screen_size, flags)
screen.set_alpha(None)
clock = pygame.time.Clock()
def show_array(arr, surf=screen, cmap=viridis):
normed = Normalize()(arr)
cmapped = cmap(normed, bytes=True)[:,:, :3]
pygame.surfarray.blit_array(surf, cmapped)
surf = pygame.Surface((nx, ny))
ocean = np.zeros((nx, ny))
x, y = np.indices(ocean.shape)
ocean[:] = np.cos(x/nx*2*np.pi) # initial condition
for i in range(10000):
active_rects = []
clock.tick(100)
# move the wave left (this is a stand-in for the real physics)
ocean = np.roll(ocean, 1, axis=0)
show_array(ocean, surf)
active_rects.append(screen.blit(surf, (0, 0)))
fps = font.render('FPS: %1.f'%clock.get_fps(), True, (255, 255, 255))
active_rects.append(screen.blit(fps, (5, 5)))
for e in pygame.event.get():
if e.type == pygame.QUIT:
exit()
if e.type == pygame.KEYDOWN:
if e.key == 27: exit()
pygame.display.update(active_rects)
#pygame.display.flip()