Shadow Casting Python的优化

时间:2016-06-18 11:40:16

标签: python optimization pygame shadow bresenham

我一直在为一个我正在做的小型RPG做暗影施法者。

我遇到的麻烦是,当我在游戏中使用它时,它只是减缓和引发可怕延迟的方法。

请不要因为帖子的长度而吓唬。这是相当简单的,但是你可以运行我包括所有Bresenham算法的代码。

原则如下: - 做一个黑色的表面 - 定义具有位置和半径的光源。 - 使用Bresenham的圆算法得到由该位置和半径定义的圆周上的所有点。 - 对于沿着圆周的每个点,使用Bresenham的线算法从光源的位置绘制一个ligne。 - 然后迭代线的点并检查它们是否与屏幕上显示的每个障碍物发生碰撞。 - 如果没有碰撞,则在该点上居中绘制一个半径为10像素左右的白色圆圈。 - 如果碰撞移动到沿圆周的下一个点。 - 最后用表面上的所有白色圆圈对表面进行blit,黑色的透明度值为100,WHITE颜色的透明度为完全透明度。

到目前为止,我尝试过以下方法: 这确实减少了滞后: - 将障碍物列表限制为屏幕上显示的障碍物列表 - 将屏幕边缘视为障碍物,以减少不可见区域的迭代。 - 仅围绕圆圈每3个点迭代一次,沿着线条迭代12个点。 哪个没改变什么: - 使用从光源到范围边缘或障碍物的椭圆,而不是沿着线的许多圆圈。问题是我必须为每个椭圆重绘表面,然后旋转整个批次。

如果您对如何提高效率有任何建议,我会很高兴在这里。

Bresenham's Line Algo:

def get_line(start, end):
    """Bresenham's Line Algorithm
    Produces a list of tuples from start and end

    >>> points1 = get_line((0, 0), (3, 4))
    >>> points2 = get_line((3, 4), (0, 0))
    >>> assert(set(points1) == set(points2))
    >>> print points1
    [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]
    >>> print points2
    [(3, 4), (2, 3), (1, 2), (1, 1), (0, 0)]
    """
    # Setup initial conditions
    x1, y1 = start
    x2, y2 = end
    dx = x2 - x1
    dy = y2 - y1

    # Determine how steep the line is
    is_steep = abs(dy) > abs(dx)

    # Rotate line
    if is_steep:
        x1, y1 = y1, x1
        x2, y2 = y2, x2

    # Swap start and end points if necessary and store swap state
    swapped = False
    if x1 > x2:
        x1, x2 = x2, x1
        y1, y2 = y2, y1
        swapped = True

    # Recalculate differentials
    dx = x2 - x1
    dy = y2 - y1

    # Calculate error
    error = int(dx / 2.0)
    ystep = 1 if y1 < y2 else -1

    # Iterate over bounding box generating points between start and end
    y = y1
    points = []
    for x in range(x1, x2 + 1):
        coord = (y, x) if is_steep else (x, y)
        points.append(coord)
        error -= abs(dy)
        if error < 0:
            y += ystep
            error += dx

    # Reverse the list if the coordinates were swapped
    if swapped:
        points.reverse()
    return points

Bresenham的Circle Algo:

def get_circle((dx,dy),radius):
    "Bresenham complete circle algorithm in Python"
    # init vars
    switch = 3 - (2 * radius)
    points = set()
    x = 0
    y = radius
    # first quarter/octant starts clockwise at 12 o'clock
    while x <= y:
        # first quarter first octant
        points.add((x,-y))
        # first quarter 2nd octant
        points.add((y,-x))
        # second quarter 3rd octant
        points.add((y,x))
        # second quarter 4.octant
        points.add((x,y))
        # third quarter 5.octant
        points.add((-x,y))        
        # third quarter 6.octant
        points.add((-y,x))
        # fourth quarter 7.octant
        points.add((-y,-x))
        # fourth quarter 8.octant
        points.add((-x,-y))
        if switch < 0:
            switch = switch + (4 * x) + 6
        else:
            switch = switch + (4 * (x - y)) + 10
            y = y - 1
        x = x + 1
    offset_points = set()
    for pt in points:
        offset_points.add((pt[0]+dx,pt[1]+dy))

    return offset_points

def shadow_gen(shadow_surf,source,cir_pt,obstacles):
    line_points = get_line(source.pos,cir_pt)
    for line_pt in line_points[0::12]:
        for obs in obstacles:
            pygame.draw.circle(shadow_surf, WHITE, line_pt, 20, 0) #radius to 5px and 0 to fill the circle
            if obs.rect.collidepoint(line_pt) or pygame.Rect(0,0,500,500).collidepoint(line_pt) == False:
                return

我的光源,障碍物和阴影面具的类:

class Obstacle(object):
    def __init__(self,x,y):
        self.surf = pygame.Surface((150,150))
        self.rect = pygame.Rect((x,y),(150,150))
        self.surf.fill(pygame.color.Color('blue'))

class Light_Source(object):
    def __init__(self,x,y,range_):
        self.range = range_
        self.pos = (x,y)


class Night_Mask(object):
    def __init__(self):
        self.surf = pygame.Surface((500,500)) #Screenwidth and height
        self.alpha = 100
        self.light_sources = []

        '''setting initial alpha and colorkey'''
        self.surf.set_colorkey(WHITE)
        self.surf.set_alpha(self.alpha)


    def apply_shadows(self, obstacles):
        shadow_surf = pygame.Surface((500,500))
        for source in self.light_sources:
            circle_pts = list(get_circle(source.pos,source.range))
            for cir_pt in circle_pts[0::3]:
                shadow_gen(shadow_surf,source,cir_pt,obstacles)
        self.surf.blit(shadow_surf, (0, 0))

阴影生成功能允许我在不使用Night_Mask类的apply_shadows方法中的异常的情况下突破线和障碍循环:

def shadow_gen(shadow_surf,source,cir_pt,obstacles):
    line_points = get_line(source.pos,cir_pt)
    for line_pt in line_points[0::12]:
        for obs in obstacles:
            pygame.draw.circle(shadow_surf, WHITE, line_pt, 20, 0) #radius to 5px and 0 to fill the circle
            if obs.rect.collidepoint(line_pt) or pygame.Rect(0,0,500,500).collidepoint(line_pt) == False:
                return

最后,主要的pygame示例循环运行以上所有内容:

pygame.init()
screen = pygame.display.set_mode((500, 500))

bg = pygame.Surface((500,500))
bg.fill(pygame.color.Color('yellow'))

ob_a = Obstacle(75,80)
ls = Light_Source(75,75,300)
night_m = Night_Mask()
night_m.light_sources.extend([ls])

while True:  
    screen.fill(pygame.color.Color('black'))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    ls.pos = pygame.mouse.get_pos()

    night_m.apply_shadows([ob_a])

    screen.blit(bg, (0,  0))
    screen.blit(ob_a.surf,ob_a.rect)
    screen.blit(night_m.surf, (0, 0))

    pygame.display.flip()

以下是从头到尾的完整代码,以便轻松复制粘贴:

import pygame
import sys

WHITE = (255,255,255)
'''FUNCTIONS'''
def get_line(start, end):
    """Bresenham's Line Algorithm
    Produces a list of tuples from start and end

    >>> points1 = get_line((0, 0), (3, 4))
    >>> points2 = get_line((3, 4), (0, 0))
    >>> assert(set(points1) == set(points2))
    >>> print points1
    [(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]
    >>> print points2
    [(3, 4), (2, 3), (1, 2), (1, 1), (0, 0)]
    """
    # Setup initial conditions
    x1, y1 = start
    x2, y2 = end
    dx = x2 - x1
    dy = y2 - y1

    # Determine how steep the line is
    is_steep = abs(dy) > abs(dx)

    # Rotate line
    if is_steep:
        x1, y1 = y1, x1
        x2, y2 = y2, x2

    # Swap start and end points if necessary and store swap state
    swapped = False
    if x1 > x2:
        x1, x2 = x2, x1
        y1, y2 = y2, y1
        swapped = True

    # Recalculate differentials
    dx = x2 - x1
    dy = y2 - y1

    # Calculate error
    error = int(dx / 2.0)
    ystep = 1 if y1 < y2 else -1

    # Iterate over bounding box generating points between start and end
    y = y1
    points = []
    for x in range(x1, x2 + 1):
        coord = (y, x) if is_steep else (x, y)
        points.append(coord)
        error -= abs(dy)
        if error < 0:
            y += ystep
            error += dx

    # Reverse the list if the coordinates were swapped
    if swapped:
        points.reverse()
    return points

def get_circle((dx,dy),radius):
    "Bresenham complete circle algorithm in Python"
    # init vars
    switch = 3 - (2 * radius)
    points = set()
    x = 0
    y = radius
    # first quarter/octant starts clockwise at 12 o'clock
    while x <= y:
        # first quarter first octant
        points.add((x,-y))
        # first quarter 2nd octant
        points.add((y,-x))
        # second quarter 3rd octant
        points.add((y,x))
        # second quarter 4.octant
        points.add((x,y))
        # third quarter 5.octant
        points.add((-x,y))        
        # third quarter 6.octant
        points.add((-y,x))
        # fourth quarter 7.octant
        points.add((-y,-x))
        # fourth quarter 8.octant
        points.add((-x,-y))
        if switch < 0:
            switch = switch + (4 * x) + 6
        else:
            switch = switch + (4 * (x - y)) + 10
            y = y - 1
        x = x + 1
    offset_points = set()
    for pt in points:
        offset_points.add((pt[0]+dx,pt[1]+dy))

    return offset_points

def shadow_gen(shadow_surf,source,cir_pt,obstacles):
    line_points = get_line(source.pos,cir_pt)
    for line_pt in line_points[0::12]:
        for obs in obstacles:
            pygame.draw.circle(shadow_surf, WHITE, line_pt, 20, 0) #radius to 5px and 0 to fill the circle
            if obs.rect.collidepoint(line_pt) or pygame.Rect(0,0,500,500).collidepoint(line_pt) == False:
                return

'''CLASSES'''                
class Obstacle(object):
    def __init__(self,x,y):
        self.surf = pygame.Surface((150,150))
        self.rect = pygame.Rect((x,y),(150,150))
        self.surf.fill(pygame.color.Color('blue'))

class Light_Source(object):
    def __init__(self,x,y,range_):
        self.range = range_
        self.pos = (x,y)


class Night_Mask(object):
    def __init__(self):
        self.surf = pygame.Surface((500,500)) #Screenwidth and height
        self.alpha = 100
        self.light_sources = []


        '''setting initial alpha and colorkey'''
        self.surf.set_colorkey(WHITE)
        self.surf.set_alpha(self.alpha)


    def apply_shadows(self, obstacles):
        shadow_surf = pygame.Surface((500,500))
        for source in self.light_sources:
            circle_pts = list(get_circle(source.pos,source.range))
            for cir_pt in circle_pts[0::3]:
                shadow_gen(shadow_surf,source,cir_pt,obstacles)
        self.surf.blit(shadow_surf, (0, 0))


'''MAIN GAME'''
pygame.init()
screen = pygame.display.set_mode((500, 500))

bg = pygame.Surface((500,500))
bg.fill(pygame.color.Color('yellow'))

ob_a = Obstacle(75,80)
ls = Light_Source(75,75,300)
night_m = Night_Mask()
night_m.light_sources.extend([ls])

while True:  
    screen.fill(pygame.color.Color('black'))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    ls.pos = pygame.mouse.get_pos()

    night_m.apply_shadows([ob_a])

    screen.blit(bg, (0,  0))
    screen.blit(ob_a.surf,ob_a.rect)
    screen.blit(night_m.surf, (0, 0))

    pygame.display.flip()

1 个答案:

答案 0 :(得分:1)

您的延迟问题似乎来自方法Night_Mask.apply_shadows(self, obstacles)。这似乎是由于嵌套for循环需要经过的纯迭代量。

range_的构造函数中减少Light_Source(x, y, range_)的值可以通过减少上述方法迭代来减少滞后,但视觉效果更差。我发现在将变量设置为~65-70之后,fps开始真正下降。

有一个Pygame图形库,可以很好地处理阴影。

链接到该页面:http://pygame.org/project-Pygame+Advanced+Graphics+Library-660-4586.html 从网站link

直接下载8.1.1版

这是来自网站的图书馆的描述:

  

这是一个通用的图形库,可以快速轻松地创建复杂的效果,并且代码最少。运行非常好的注释示例,每个示例少于一页(不包括注释),并学习如何制作阴影和抗锯齿等复杂效果。

以下是显示阴影示例的页面中的图像。 enter image description here

我下载并测试了该库,它运行良好。我在Pygame1.9.2a0上测试了python 3.4

我相信这是解决您问题的最简单方法,也可以帮助您完成未来的项目。我希望这会有所帮助。