Ejemplo n.º 1
0
def boid_vision_poly(vision_area: np.ndarray,
                     position: np.ndarray) -> torch.Tensor:
    '''Cutting boid reaction area from game screen'''
    screen = pg.display.get_surface()

    for point in vision_area:
        if point[0] < 0:
            point[0] = 0
        elif point[0] >= screen_width:
            point[0] = screen_width
        if point[1] < 0:
            point[1] = 0
        elif point[1] >= screen_height:
            point[1] = screen_height
    radius = cfg.fish()['reaction_radius']

    left = int(max(0, round(position.x - radius)))
    up = int(max(0, round(position.y - radius)))
    right = int(min(screen.get_width() - 1, round(position.x + radius)))
    bottom = int(min(screen.get_height() - 1, round(position.y + radius)))
    bounding_box = pg.Rect(left, up, right - left, bottom - up)
    vision_surface = pg.Surface((radius * 2, radius * 2))
    clipped = vision_surface.copy()
    dest = (max(0, radius - position.x), max(0, radius - position.y))
    vision_surface.blit(screen, dest=dest, area=bounding_box)
    textured_polygon(clipped,
                     vision_area - position + pg.Vector2(radius, radius),
                     vision_surface, 0, 0)
    return pg.surfarray.pixels3d(clipped)
Ejemplo n.º 2
0
    def update_light_surf(self, world):
        """
        This creates the light and bloom surfaces

        Parameters
        ----------
        world : world.World
            The current world

        Returns
        -------
        None.

        """
        self.light_surfs = np.array([])
        self.bloom_surfs = np.array([])

        # to determine the size of each light surface
        lowest_val = None
        highest_val = None

        for chunk in world.loaded_chunks:
            if not lowest_val or int(chunk) < lowest_val:
                lowest_val = int(chunk)
            if not highest_val or int(chunk) > highest_val:
                highest_val = int(chunk)

        for polygon in self.polygons:
            light_surf = pg.Surface(((highest_val + 2) * constants.BLOCK_SIZE *
                                     constants.CHUNK_SIZE, 800)).convert()
            light_surf.set_alpha(50)

            # render the polygon
            # TODO: fix no color with bloom
            if self.shadows:
                light_surf.fill((0, 0, 0))

            if self.antialiasing:
                gfxdraw.aapolygon(light_surf, polygon, self.color)

            gfxdraw.textured_polygon(light_surf, polygon, self.color_surf, 0,
                                     0)

            # set up a bloom surf for each main surface
            if self.bloom:
                bloom_surf = copy.copy(light_surf)

                start_size = bloom_surf.get_size()
                small_size = (start_size[0] // 10, start_size[1] // 10)

                # Shrink the surface then put it back to the normal size, which blurs it
                bloom_surf = pg.transform.smoothscale(bloom_surf, small_size)
                bloom_surf = pg.transform.smoothscale(bloom_surf, start_size)

                light_surf.blit(bloom_surf, (0, 0),
                                special_flags=pg.BLEND_RGBA_MULT)

            self.light_surfs = np.append(self.light_surfs, light_surf)
Ejemplo n.º 3
0
    def render(self):
        """Draw scene into its texture."""
        backgroundColor = (0, 0, 0)
        self.surface.fill(backgroundColor)

        for brick in self.bricks:
            points = [
                brick.topleft, brick.topright, brick.bottomright,
                brick.bottomleft
            ]
            gfxdraw.textured_polygon(self.surface, points, self.bricksImage, 2,
                                     -1)
Ejemplo n.º 4
0
def my_draw_polygon2(polygon, body):
    body.angularVelocity = .5
    vertices = [(body.transform * v) * PPM for v in polygon.vertices]
    vertices = [(v[0], SCREEN_HEIGHT - v[1]) for v in vertices]
    #pygame.draw.polygon(screen, colors[body.type], vertices)
    #i1 = F8sprite.next()
    texture = F8sprite.next()
    #texture.fill((0, 0, 0, 255))
    tx = 0
    ty = 0
    try:
        gfxdraw.textured_polygon(screen, vertices, texture, tx, ty)
    except:
        pass
Ejemplo n.º 5
0
    def render_background(self, size):
        """Render the background

        :param size: (width, height) in pixels
        :return: pygame.surface.Surface
        """

        def render_text(text):
            label.text = text
            return label.draw()

        background = pg.Surface(size)
        points = (0, 0), (size[0], 0), (size[0], size[1]), (0, size[1])
        texture = prepare.GFX['felt']
        textured_polygon(background, points, texture, 1024, 1024)
        # background.fill(prepare.FELT_GREEN)
        if hasattr(self, 'background_filename'):
            im = prepare.GFX[self.background_filename]
            background.blit(im, (0, 0))

        label = TextSprite('', self.font, bg=prepare.FELT_GREEN)
        totals = self.get_bet_totals()
        for name, area in self.betting_areas.items():
            total = totals[name]
            if total:
                image = render_text(area.name)
                image.set_alpha(128)
                label.rect.midbottom = area.rect.center
                background.blit(image, label.rect)

                image = render_text('${}'.format(totals[name]))
                image.set_alpha(192)
                label.rect.midtop = area.rect.center
                background.blit(image, label.rect.move(0, -15))
            else:
                image = render_text(area.name)
                image.set_alpha(128)
                label.rect.center = area.rect.center
                background.blit(image, label.rect)

        return background
Ejemplo n.º 6
0
def my_draw_polygon3(polygon, body):
    body.angularVelocity = .5
    vertices = [(body.transform * v) * PPM for v in polygon.vertices]
    vertices = [(v[0], SCREEN_HEIGHT - v[1]) for v in vertices]

    baseImage = spriteStrips[body.type].next()
    (tx, ty) = body.worldCenter * PPM
    im = baseImage.get_rect()
    sX = boxL_pix
    sY = boxH_pix
    if debug:
        print sX, sY
        print("sprite:" + str(sprX) + " " + str(sprY))
        print("body  :" + str(x) + " " + str(y))
        print("Diff  :" + str(x - sprX) + " " + str(y - sprY))
    image = pygame.transform.scale(baseImage, (sX, sY))
    image = pygame.transform.rotate(image, math.degrees(body.angle))
    rect = image.get_rect()
    tx, ty = (x - (rect.width / 2), -(rect.height / 2) - y + SCREEN_HEIGHT)
    try:
        gfxdraw.textured_polygon(screen, vertices, image, tx, ty)
    except:
        #print"failed"
        pass
Ejemplo n.º 7
0
def render(s,smooth=False):
    
    zBuffer = [] # Z buffer for rendering triangles in correct order
    for mesh in s:
        
        for tris in meshes[mesh["shape"]]:

            pos = mesh["position"] # Gets position of mesh
            scl = mesh["scale"] # Gets scale of mesh
            rot = mesh["rotation"] # Gets rotation of mesh
            point1 = translateVector( rotateVector( scaleVector( tris[0],scl ) ,rot) , pos) # Rotates, scales, and translates each vector according to the position and scale of the mesh
            point2 = translateVector( rotateVector( scaleVector( tris[1],scl ) ,rot) , pos)
            point3 = translateVector( rotateVector( scaleVector( tris[2],scl ) ,rot) , pos)

            
            

            facePos = vectorPos([point1,point2,point3]) # Average of all three vector positions to add to the z buffer

            
            normal = getNormal(point1,point2,point3) # Gets normal for face

            normals = list(normal)
            vertColors = []
            if(smooth):
                for i in range(3):
                    normals[i] /= 300.0*mesh["material"]["metal"]
                
                for i in range(3):
                    color = mesh["material"]["color"] # Gets meshes color
                    shade = float(    max(min(255 - abs(normals[i]),255),1)    )
                    r = color[0] # Gets each channel from color
                    g = color[1]
                    b = color[2]

                    r = r / (255/ shade) # Applies shading to each channel
                    g = g / (255/ shade)
                    b = b / (255/ shade)

                    r = linInterp(r,255,shade/8.0) # add specular
                    g = linInterp(g,255,shade/8.0)
                    b = linInterp(b,255,shade/8.0)

                    r = max(min(255,int(r)),0) # makes valid color argument
                    g = max(min(255,int(g)),0)
                    b = max(min(255,int(b)),0)
                    vertColors.append((r,g,b))

                

            normal = float((normal[0] + normal[1] + normal[2])/3.0)/(300.0*mesh["material"]["metal"]) # Gets average normal
            

            shade = float(    max(min(255 - abs(normal),255),1)    ) # Calculates shading from normal

            color = mesh["material"]["color"] # Gets meshes color


            r = color[0] # Gets each channel from color
            g = color[1]
            b = color[2]

            r = r / (255/ shade) # Applies shading to each channel
            g = g / (255/ shade)
            b = b / (255/ shade)

            r = linInterp(r,255,shade/8.0) # add specular
            g = linInterp(g,255,shade/8.0)
            b = linInterp(b,255,shade/8.0)

            r = max(min(255,int(r)),0) # makes valid color argument
            g = max(min(255,int(g)),0)
            b = max(min(255,int(b)),0)


            color = (r,g,b) # Applies shaded rgb back to color
            alpha = mesh["material"]["alpha"] # Gets alpha from material

            zBuffer.append([point1,point2,point3,facePos,color + (alpha,) ,mesh["material"]["wire"],mesh["material"]["map"] , vertColors ] ) #Adds the triangle data to the z buffer
            
            
    
    zs = [] 
    for i in zBuffer:
        zs.append(i[3][2]) # Get all face z positions(for sorting)
    
    
    # Sorts the indices of the z buffer based on the z positions of the z buffer
    inds = [x for _,x in sorted(zip(zs,range(len(zBuffer))))]

    

   #Renders the triangles from the z buffer in the correct order
    for i in range(0,len(zBuffer)):
        tri = zBuffer[inds[i]] # Gets correct face based on sorted indices

        

        if(not(tri[5])): # Checks to see if the triangle is wireframe
            if(tri[6] == "none"):
                if smooth:
                    smoothTri( project(tri[0]) , project(tri[1]) , project(tri[2]) , tri[7][0] , tri[7][1] , tri[7][2]   )
                else:
                    gfxdraw.filled_polygon(d, (project(tri[0]) , project(tri[1]) , project(tri[2])) , tri[4]) # Draws solid color triangle if there is no texture
                
            else:
                if tri[6] in cachedTextures:
                    imgMap = cachedTextures[tri[6]]
                else:
                    imgMap = pg.image.load(tri[6]) # loads texture
                    cachedTextures[tri[6]] = pg.image.load(tri[6])
                offs = project(tri[0]) # Calculates image offset
                sz = imgMap.get_size() # Gets the size of the image


                if( min(project(tri[0])[0] , project(tri[1])[0] , project(tri[2])[0]  ) >= 0     ): # Checks to see if the triangle is within the bounds of the screen(pygame crashes otherwise)
                    if( max(project(tri[0])[0] , project(tri[1])[0] , project(tri[2])[0]  ) <= w     ):
                        if( min(project(tri[0])[1] , project(tri[1])[1] , project(tri[2])[1]  ) >= 0     ):
                            if( max(project(tri[0])[1] , project(tri[1])[1] , project(tri[2])[1]  ) <= h     ):

                                # Draw textured polygon with offset we calculated before
                                gfxdraw.textured_polygon(d, (project(tri[0]) , project(tri[1]) , project(tri[2])),imgMap, int(offs[0]) % sz[0] , int(h-offs[1])  % sz[1] )
        else:
            gfxdraw.aapolygon(d, (project(tri[0]) , project(tri[1]) , project(tri[2])) , tri[4]) # Draws anti-aliased outline around the triangle
Ejemplo n.º 8
0
    def _draw(self, deco: List[Tuple[int, str, Any]], surface: 'pygame.Surface') -> None:
        """
        Draw.

        :param deco: Decoration list
        :param surface: Pygame surface
        :return: None
        """
        if len(deco) == 0:
            return
        rect = self._obj.get_rect()

        for d in deco:
            dtype, decoid, data = d
            if not self._decor_enabled[decoid]:
                continue

            if dtype == DECORATION_POLYGON:
                points, color, filled, width, gfx, kwargs = data
                points = self._update_pos_list(rect, decoid, points, **kwargs)
                if gfx:
                    if filled:
                        gfxdraw.filled_polygon(surface, points, color)
                    else:
                        gfxdraw.polygon(surface, points, color)
                else:
                    pydraw.polygon(surface, color, points, width)

            elif dtype == DECORATION_CIRCLE:
                points, r, color, filled, width, gfx, kwargs = data
                points = self._update_pos_list(rect, decoid, points, **kwargs)
                x, y = points[0]
                if filled:
                    if gfx:
                        gfxdraw.filled_circle(surface, x, y, r, color)
                    else:
                        pydraw.circle(surface, color, (x, y), r)
                else:
                    pydraw.circle(surface, color, (x, y), r, width)

            elif dtype == DECORATION_SURFACE or dtype == DECORATION_BASEIMAGE or dtype == DECORATION_TEXT:
                pos, surf, centered, kwargs = data
                if isinstance(surf, pygame_menu.BaseImage):
                    surf = surf.get_surface(new=False)
                pos = self._update_pos_list(rect, decoid, pos, **kwargs)[0]
                surfrect = surf.get_rect()
                surfrect.x += pos[0]
                surfrect.y += pos[1]
                if centered:
                    surfrect.x -= surfrect.width / 2
                    surfrect.y -= surfrect.height / 2
                surface.blit(surf, surfrect)

            elif dtype == DECORATION_ELLIPSE:
                pos, rx, ry, color, filled, kwargs = data
                pos = self._update_pos_list(rect, decoid, pos, **kwargs)[0]
                if filled:
                    gfxdraw.filled_ellipse(surface, pos[0], pos[1], rx, ry, color)
                else:
                    gfxdraw.ellipse(surface, pos[0], pos[1], rx, ry, color)

            elif dtype == DECORATION_CALLABLE:
                data(surface, self._obj)

            elif dtype == DECORATION_CALLABLE_NO_ARGS:
                data()

            elif dtype == DECORATION_TEXTURE_POLYGON:
                pos, texture, tx, ty, kwargs = data
                pos = self._update_pos_list(rect, decoid, pos, **kwargs)
                if isinstance(texture, pygame_menu.BaseImage):
                    texture = texture.get_surface()
                gfxdraw.textured_polygon(surface, pos, texture, tx, ty)

            elif dtype == DECORATION_ARC:
                points, r, ia, fa, color, width, gfx, kwargs = data
                points = self._update_pos_list(rect, decoid, points, **kwargs)
                x, y = points[0]
                rectarc = pygame.Rect(x - r, y - r, x + 2 * r, y + 2 * r)
                if gfx:
                    gfxdraw.arc(surface, x, y, r, ia, fa, color)
                else:
                    pydraw.arc(surface, color, rectarc, ia / (2 * pi), fa / (2 * pi), width)

            elif dtype == DECORATION_PIE:
                points, r, ia, fa, color, kwargs = data
                points = self._update_pos_list(rect, decoid, points, **kwargs)
                x, y = points[0]
                gfxdraw.pie(surface, x, y, r, ia, fa, color)

            elif dtype == DECORATION_BEZIER:
                points, color, steps, kwargs = data
                points = self._update_pos_list(rect, decoid, points, **kwargs)
                gfxdraw.bezier(surface, points, steps, color)

            elif dtype == DECORATION_RECT:
                drect: 'pygame.Rect'
                pos, drect, color, width, kwargs = data
                pos = self._update_pos_list(rect, decoid, pos, **kwargs)[0]
                drect = drect.copy()
                drect.x += pos[0]
                drect.y += pos[1]
                pygame.draw.rect(surface, color, drect, width)

            elif dtype == DECORATION_PIXEL:
                pos, color, kwargs = data
                pos = self._update_pos_list(rect, decoid, pos, **kwargs)[0]
                gfxdraw.pixel(surface, pos[0], pos[1], color)

            elif dtype == DECORATION_LINE:
                pos, color, width, kwargs = data
                pos = self._update_pos_list(rect, decoid, pos, **kwargs)
                pydraw.line(surface, color, pos[0], pos[1], width)

            else:
                raise ValueError('unknown decoration type')
Ejemplo n.º 9
0
def render(s):
    zBuffer = []
    for mesh in s:

        for tris in meshes[mesh["shape"]]:
            pos = mesh["position"]
            scl = mesh["scale"]
            point1 = translateVector(scaleVector(tris[0], scl), pos)
            point2 = translateVector(scaleVector(tris[1], scl), pos)
            point3 = translateVector(scaleVector(tris[2], scl), pos)

            facePos = vectorPos([point1, point2, point3])
            rnd = True

            normal = getNormal(point1, point2, point3)
            normal = float((normal[0] + normal[1] + normal[2]) / 3.0) / 300.0

            shade = float(max(min(255 - abs(normal), 255), 1))

            color = mesh["material"]["color"]

            r = color[0]
            g = color[1]
            b = color[2]

            r = int(r / (255 / shade))
            g = int(g / (255 / shade))
            b = int(b / (255 / shade))

            color = (r, g, b)

            zBuffer.append([
                point1, point2, point3, facePos, color,
                mesh["material"]["wire"], mesh["material"]["map"]
            ])
            '''
            point1 = project(point1)
            point2 = project(point2)
            point3 = project(point3)
            '''
            '''
            pg.draw.polygon(d,color,(point1,point2,point3))
            if(mesh["material"]["wire"]):
                pg.draw.line(d,(0,0,0), point1,point2 )
                pg.draw.line(d,(0,0,0), point2,point3 )
                pg.draw.line(d,(0,0,0), point3,point1 )
            '''
    for j in range(0, len(zBuffer)):
        for i in range(0, len(zBuffer) - 1):
            zPos1 = [zBuffer[i][0], zBuffer[i][1], zBuffer[i][2]]
            zPos2 = [zBuffer[i + 1][0], zBuffer[i + 1][1], zBuffer[i + 1][2]]
            zPos1 = vectorPos(zPos1)[2]
            zPos2 = vectorPos(zPos2)[2]
            if zPos1 > zPos2:
                store = zBuffer[i]
                zBuffer[i] = zBuffer[i + 1]
                zBuffer[i + 1] = store

    for i in range(0, len(zBuffer)):
        tri = zBuffer[i]
        gfxdraw.aapolygon(d,
                          (project(tri[0]), project(tri[1]), project(tri[2])),
                          tri[4])
        if (not (tri[5])):
            if (tri[6] == "none"):
                gfxdraw.filled_polygon(
                    d, (project(tri[0]), project(tri[1]), project(tri[2])),
                    tri[4])
            else:
                imgMap = pg.image.load(tri[6])
                offs = project(tri[0])
                sz = imgMap.get_size()
                if (min(
                        project(tri[0])[0],
                        project(tri[1])[0],
                        project(tri[2])[0]) >= 0):
                    if (max(
                            project(tri[0])[0],
                            project(tri[1])[0],
                            project(tri[2])[0]) <= w):
                        if (min(
                                project(tri[0])[1],
                                project(tri[1])[1],
                                project(tri[2])[1]) >= 0):
                            if (max(
                                    project(tri[0])[1],
                                    project(tri[1])[1],
                                    project(tri[2])[1]) <= h):
                                gfxdraw.textured_polygon(
                                    d, (project(tri[0]), project(
                                        tri[1]), project(tri[2])), imgMap,
                                    int(offs[0]) % sz[0],
                                    int(h - offs[1]) % sz[1])
Ejemplo n.º 10
0
def render(s):

    zBuffer = []  # Z buffer for rendering triangles in correct order
    for mesh in s:

        for tris in meshes[mesh["shape"]]:

            pos = mesh["position"]  # Gets position of mesh
            scl = mesh["scale"]  # Gets scale of mesh
            rot = mesh["rotation"]  # Gets rotation of mesh
            point1 = translateVector(
                rotateVector(scaleVector(tris[0], scl), rot), pos
            )  # Rotates, scales, and translates each vector according to the position and scale of the mesh
            point2 = translateVector(
                rotateVector(scaleVector(tris[1], scl), rot), pos)
            point3 = translateVector(
                rotateVector(scaleVector(tris[2], scl), rot), pos)

            facePos = vectorPos([
                point1, point2, point3
            ])  # Average of all three vector positions to add to the z buffer

            normal = getNormal(point1, point2, point3)  # Gets normal for face
            normal = float((normal[0] + normal[1] + normal[2]) / 3.0) / (
                300.0 * mesh["material"]["metal"])  # Gets average normal

            shade = float(max(min(255 - abs(normal), 255),
                              1))  # Calculates shading from normal

            color = mesh["material"]["color"]  # Gets meshes color

            r = color[0]  # Gets each channel from color
            g = color[1]
            b = color[2]

            r = r / (255 / shade)  # Applies shading to each channel
            g = g / (255 / shade)
            b = b / (255 / shade)

            r = linInterp(r, 255, shade / 8.0)  # add specular
            g = linInterp(g, 255, shade / 8.0)
            b = linInterp(b, 255, shade / 8.0)

            r = max(min(255, int(r)), 0)  # makes valid color argument
            g = max(min(255, int(g)), 0)
            b = max(min(255, int(b)), 0)

            color = (r, g, b)  # Applies shaded rgb back to color
            alpha = mesh["material"]["alpha"]  # Gets alpha from material

            zBuffer.append([
                point1, point2, point3, facePos, color + (alpha, ),
                mesh["material"]["wire"], mesh["material"]["map"]
            ])  #Adds the triangle data to the z buffer

    #Sorts the z buffer (bubble sort is not the best solution, but I don't really care it's easy to implement)
    for j in range(0, len(zBuffer)):
        for i in range(0, len(zBuffer) - 1):
            zPos1 = [zBuffer[i][0], zBuffer[i][1], zBuffer[i][2]]
            zPos2 = [zBuffer[i + 1][0], zBuffer[i + 1][1], zBuffer[i + 1][2]]
            zPos1 = vectorPos(zPos1)[2]
            zPos2 = vectorPos(zPos2)[2]
            if zPos1 > zPos2:
                store = zBuffer[i]
                zBuffer[i] = zBuffer[i + 1]
                zBuffer[i + 1] = store

#Renders the triangles from the z buffer in the correct order
    for i in range(0, len(zBuffer)):
        tri = zBuffer[i]

        if (not (tri[5])):  # Checks to see if the triangle is wireframe
            if (tri[6] == "none"):
                gfxdraw.filled_polygon(
                    d, (project(tri[0]), project(tri[1]), project(tri[2])),
                    tri[4]
                )  # Draws solid color triangle if there is no texture
            else:
                imgMap = pg.image.load(tri[6])  # loads texture
                offs = project(tri[0])  # Calculates image offset
                sz = imgMap.get_size()  # Gets the size of the image

                if (
                        min(
                            project(tri[0])[0],
                            project(tri[1])[0],
                            project(tri[2])[0]) >= 0
                ):  # Checks to see if the triangle is within the bounds of the screen(pygame crashes otherwise)
                    if (max(
                            project(tri[0])[0],
                            project(tri[1])[0],
                            project(tri[2])[0]) <= w):
                        if (min(
                                project(tri[0])[1],
                                project(tri[1])[1],
                                project(tri[2])[1]) >= 0):
                            if (max(
                                    project(tri[0])[1],
                                    project(tri[1])[1],
                                    project(tri[2])[1]) <= h):

                                # Draw textured polygon with offset we calculated before
                                gfxdraw.textured_polygon(
                                    d, (project(tri[0]), project(
                                        tri[1]), project(tri[2])), imgMap,
                                    int(offs[0]) % sz[0],
                                    int(h - offs[1]) % sz[1])
        else:
            gfxdraw.aapolygon(
                d, (project(tri[0]), project(tri[1]), project(tri[2])),
                tri[4])  # Draws anti-aliased outline around the triangle
Ejemplo n.º 11
0
    def textured_polygon(self, points, texture, tx, ty):
        """テクスチャ処理のなされた複数の頂点からなる多角形を描画します.

        """
        return gfx.textured_polygon(self.pg.screen, points, texture, tx, ty)