Ejemplo n.º 1
0
def loadtexture(name):
    if name not in textures:
        dircon = dict(dircontents('art'))
        try:
            textures[name] = texture.Texture(dircon[name])
        except KeyError:
            textures[name] = texture.Texture(name)
    return textures[name]
Ejemplo n.º 2
0
def create_based_on_char(char):
    if char == '1':
        return Tile(True, False, texture.Texture())
    elif char == '2':
        return Tile(True, False, texture.Texture('res/colorstone.png'))
    elif char == '3':
        return Tile(True, False, texture.Texture('res/wood.png'))
    else:
        return Tile()
Ejemplo n.º 3
0
def loadtexture(name):
    if name not in textures:
        dircon = dict(
            dircontents('terrain') + dircontents('data') +
            dircontents('entities'))
        try:
            textures[name] = texture.Texture(dircon[name])
        except KeyError:
            textures[name] = texture.Texture(name)
    return textures[name]
Ejemplo n.º 4
0
    def __init__(self,
                 Z,
                 format=None,
                 cmap=colormap.IceAndFire,
                 vmin=None,
                 vmax=None,
                 interpolation='nearest',
                 origin='lower',
                 lighted=False,
                 gridsize=(0.0, 0.0, 0.0),
                 elevation=0.0):
        ''' Creates a texture from numpy array.

        Parameters:
        -----------
        Z : numpy array
            Z may be a float32 or uint8 array with following shapes:
                * M
                * MxN
                * MxNx[1,2,3,4]

        format: [None | 'A' | 'LA' | 'RGB' | 'RGBA']
            Specify the texture format to use. Most of times it is possible to
            find it automatically but there are a few cases where it not
            possible to decide. For example an array with shape (M,3) can be
            considered as 2D alpha texture of size (M,3) or a 1D RGB texture of
            size (M,).

        interpolation: 'nearest', 'bilinear' or 'bicubic'
            Interpolation method.

        vmin: scalar
            Minimal representable value.

        vmax: scalar
            Maximal representable value.

        origin: 'lower' or 'upper'
            Place the [0,0] index of the array in the upper left or lower left
            corner.
        '''

        self._lut = None
        self._interpolation = interpolation
        self._lighted = lighted
        self._gridsize = gridsize
        self._elevation = elevation
        self._texture = texture.Texture(Z)
        self._origin = origin
        self._vmin = vmin
        self._vmax = vmax
        self._data = Z
        self.cmap = cmap  # This takes care of actual build
        self._shader = None
        self.build()
Ejemplo n.º 5
0
    def __init__(self, feedback):
        """Constructor for an OpenGL scene"""
        self.feedback = feedback
        self.lightPos = [100.0, 100.0, 100.0, 1.0] # The scene light position
        self.pieces = []
        self.highlights = {}
        self._animationQueue = []
        self.animating = False
        self.piecesMoving = False

        # The viewport dimensions
        self.viewportWidth    = 0
        self.viewportHeight   = 0
        self.viewportAspect   = 1.0
    
        # Loading screen properties
        self.throbberEnabled  = False
        self.throbberAngle    = 0.0
    
        # The board angle in degrees
        self.boardAngle       = 0.0
        self.oldBoardAngle    = 0.0
        self.targetBoardAngle = 0.0
    
        # OpenGL display list for the board and a flag to regenerate it
        self.boardList        = None
        self.regenerateBoard  = False
    
        self.jitters = ((0.0, 0.0),)

        self.showNumbering = False
        self.numberingTexture = None
        
        self.chessSets = {'white': models.WhiteBuiltinSet(), 'black': models.BlackBuiltinSet()}
        
        # Texture objects for the board
        self.whiteTexture = texture.Texture(os.path.join(TEXTURE_DIR, 'board.png'),
                                            ambient = BOARD_AMBIENT, diffuse = BOARD_DIFFUSE,
                                            specular = BOARD_SPECULAR, shininess = BOARD_SHININESS)
        self.blackTexture = texture.Texture(os.path.join(TEXTURE_DIR, 'board.png'),
                                            ambient = BOARD_AMBIENT, diffuse = BOARD_DIFFUSE,
                                            specular = BOARD_SPECULAR, shininess = BOARD_SHININESS)
Ejemplo n.º 6
0
    def __init__(self, previous=None):
        vertshader = createshader('color_vertex.shader', GL_VERTEX_SHADER)
        fragshader = createshader('color_fragment.shader', GL_FRAGMENT_SHADER)
        self.shaderprogram = createprogram(vertshader, fragshader)

        self.camera_center_uniform = glGetUniformLocation(
            self.shaderprogram, 'CameraCenter')
        self.camera_to_clip_uniform = glGetUniformLocation(
            self.shaderprogram, 'CameraToClipTransform')
        self.texture_uniform = glGetUniformLocation(self.shaderprogram, 'tex')
        self.scale_uniform = glGetUniformLocation(self.shaderprogram, 'scale')

        self.tex = texture.Texture('terrain.png')

        self.map = initworldmap((50, 50))

        self.hexes = Primitives(GL_TRIANGLES, 0, 1)
        for x, row in enumerate(self.map):
            for y, tile in enumerate(row):
                corners = hexcorners((x - 7, y - 7), 0.5)
                texcorners = hexcorners((0.65, 0.5), 0.5)
                terrainpos = terrainlookup(tile['terrain'])
                texcorners = [[
                    s / 4.0 + (terrainpos[0] / 4.0),
                    t / 3.0 + (terrainpos[1] / 3.0)
                ] for (s, t) in texcorners]
                for i in xrange(len(corners) - 2):
                    self.hexes.addvertex(corners[0], texcorners[0])
                    self.hexes.addvertex(corners[i + 1], texcorners[i + 1])
                    self.hexes.addvertex(corners[i + 2], texcorners[i + 2])
        self.hexes.finalize_buffer()

        texsamplers = ctypes.c_uint(0)
        glGenSamplers(1, texsamplers)
        self.texsampler = texsamplers.value
        glSamplerParameteri(self.texsampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glSamplerParameteri(self.texsampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glSamplerParameteri(self.texsampler, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glSamplerParameteri(self.texsampler, GL_TEXTURE_WRAP_T, GL_REPEAT)

        self.camerapos = [0, 0]
        self.scale = 1.0

        self.time = 0

        self.camcontrols = {
            'left': False,
            'right': False,
            'up': False,
            'down': False,
            'zoomin': False,
            'zoomout': False
        }
Ejemplo n.º 7
0
def sketch():
    pygame.init()

    pywindow = pygame.display.set_mode((int(width), int(height)))
    WHITE = (255, 255, 255)
    BLUE = (0, 0, 255)
    pywindow.fill(WHITE)

    radius = 1
    color = (0, 0, 255)

    new_texture = texture.Texture()

    while True:  #main game loop

        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:  #This checks for the mouse press event
                center = pygame.mouse.get_pos()  #Gets the mouse position

                new_rock = rock.Rock(center, radius, color)

                if new_texture.add(new_rock):
                    pygame.draw.circle(
                        pywindow, color, new_rock.center,
                        radius)  #Draws a circle at the mouse position

            if event.type == pygame.KEYDOWN:
                if int(event.key) == ord('b'):
                    color = (0, 0, 255)

                if int(event.key) == ord('r'):
                    color = (255, 0, 0)

                if int(event.key) == ord('g'):
                    color = (0, 255, 0)

                if 48 < int(event.key) <= 57:
                    radius = (int(event.key) - 48) * 5

            if event.type == QUIT:
                pygame.quit()
                return new_texture
        pygame.display.update()
Ejemplo n.º 8
0
    def __init__(self, previous=None):
        vertshader = createshader('color_vertex.shader', GL_VERTEX_SHADER)
        fragshader = createshader('color_fragment.shader', GL_FRAGMENT_SHADER)
        self.shaderprogram = createprogram(vertshader, fragshader)

        self.camera_center_uniform = glGetUniformLocation(
            self.shaderprogram, 'CameraCenter')
        self.camera_to_clip_uniform = glGetUniformLocation(
            self.shaderprogram, 'CameraToClipTransform')
        self.texture_uniform = glGetUniformLocation(self.shaderprogram, 'tex')
        self.scale_uniform = glGetUniformLocation(self.shaderprogram, 'scale')

        self.tex = texture.Texture('terrain.png')

        texsamplers = ctypes.c_uint(0)
        glGenSamplers(1, texsamplers)
        self.texsampler = texsamplers.value
        glSamplerParameteri(self.texsampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glSamplerParameteri(self.texsampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glSamplerParameteri(self.texsampler, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glSamplerParameteri(self.texsampler, GL_TEXTURE_WRAP_T, GL_REPEAT)

        glClearColor(0.3, 0.3, 0.8, 0.0)

        self.camerapos = [40, 25]
        self.scale = 0.15

        self.time = 0

        self.terrain = Terrain()
        self.playercontrols = {'left': False, 'right': False, 'jump': False}
        self.player = Player((40.0, 25.0))
        self.gravity = -10
        self.terminalspeed = 15
        self.playermoveaccel = 10
        self.playermovespeed = 5

        self.projectiles = []
Ejemplo n.º 9
0
    def __init__(self,
                 Z,
                 format=None,
                 cmap=colormap.IceAndFire,
                 vmin=None,
                 vmax=None,
                 interpolation='nearest',
                 origin='lower'):
        ''' Creates an image from a numpy array.

        Parameters:
        -----------
        Z : numpy array
            Z may be a float32 or uint8 array with following shapes:
                * M
                * MxN
                * MxNx[1,2,3,4]

        format: [None | 'A' | 'LA' | 'RGB' | 'RGBA']
            Specify the texture format to use. Most of times it is possible to
            find it automatically but there are a few cases where it not
            possible to decide. For example an array with shape (M,3) can be
            considered as 2D alpha texture of size (M,3) or a 1D RGB texture of
            size (M,).

        interpolation: 'nearest', 'bilinear' or 'bicubic'
            Interpolation method.

        vmin: scalar
            Minimal representable value.

        vmax: scalar
            Maximal representable value.

        origin: 'lower' or 'upper'
            Place the [0,0] index of the array in the upper left or lower left
            corner.
        '''

        self._lut = None
        self._interpolation = interpolation
        self.texture = texture.Texture(Z)
        self.cmap = cmap
        self.origin = origin
        self.vmin = vmin
        self.vmax = vmax
        self.Z = Z

        # Source format is RGB or RGBA, no need of a colormap
        if self.texture.src_format in [gl.GL_RGB, gl.GL_RGBA]:
            if interpolation == 'bicubic':
                self.shader = shader.Bicubic(False)
            elif interpolation == 'bilinear':
                self.shader = shader.Bilinear(False)
            else:
                self.shader = None
        # Source format is not RGB or RGBA
        else:
            if cmap:
                if interpolation == 'bicubic':
                    self.shader = shader.Bicubic(True)
                elif interpolation == 'bilinear':
                    self.shader = shader.Bilinear(True)
                else:
                    self.shader = shader.Nearest(True)
            else:
                if interpolation == 'bicubic':
                    self.shader = shader.Bicubic(False)
                elif interpolation == 'bilinear':
                    self.shader = shader.Bilinear(False)
                else:
                    self.shader = None
        self.update()
Ejemplo n.º 10
0
 def cmap(self, cmap):
     ''' Colormap to be used to represent the array. '''
     self._cmap = cmap
     colors = self.cmap.LUT['rgb'][1:].flatten().view((np.float32, 3))
     self._lut = texture.Texture(colors)
     self.interpolation = self.interpolation  # This is not a no-op line
Ejemplo n.º 11
0
 def _set_cmap(self, cmap):
     self._cmap = cmap
     colors = self.cmap.LUT['rgb'][1:].flatten().view((np.float32, 3))
     self._lut = texture.Texture(colors)
Ejemplo n.º 12
0
 def set_alpha_map(self, path):
     self.alphamap = texture.Texture(path)
Ejemplo n.º 13
0
 def set_texture(self, path):
     self.texture = texture.Texture(path)
Ejemplo n.º 14
0
def main():
    InitGraphics()

    fps = 0
    fpsdisplay = 0
    starttime = pygame.time.get_ticks()
    fpsstring = 'none'
    clock = pygame.time.Clock()

    background = texture.Texture('data/background.png')

    camptexture = texture.Texture('data/basecamp.png')

    fuelstationtexture = texture.Texture('data/fuelstation.png')

    font = text.BMFont("data/font.fnt")
    foodtexture = texture.Texture('data/foodcrate.png')
    supplytexture = texture.Texture('data/supplycrate.png')
    fueltexture = texture.Texture('data/fuelcrate.png')

    rightgeartexture = texture.Texture('data/right_gear.png')
    leftgeartexture = texture.Texture('data/left_gear.png')
    shiptexture = texture.Texture('data/ship.png')

    world, space, contactgroup = physics.InitPhysics()

    basecampHunger = 0
    basecampEnergy = 100
    basecampSupply = 100
    basecampPopulation = 4000

    ship = physics.Enterprise(world, space, (200, 200, 0),
                              (rightgeartexture, leftgeartexture, shiptexture))
    fuelstation = physics.FuelStation(world, space, (1200, 50, 0),
                                      fuelstationtexture)
    basecamp = physics.BaseCamp(world, space, (2200, 50, 0), camptexture)

    supplycrates = []

    # add 10 of each crate to the world
    for index in range(0, 10):
        xrand = random.randrange(0, 200)
        yrand = random.randrange(0, 25)
        yrand += 400
        xrand += index * 10
        yrand += index * 10
        fuelcrate = physics.SupplyCrate(world, space, (500 + xrand, yrand, 0),
                                        fueltexture, 0)

        xrand = random.randrange(0, 200)
        yrand = random.randrange(0, 25)
        yrand += 400
        xrand += 25
        yrand -= index * 10
        foodcrate = physics.SupplyCrate(world, space, (500 + xrand, yrand, 0),
                                        foodtexture, 1)

        xrand = random.randrange(0, 200)
        yrand = random.randrange(0, 25)
        yrand += 400
        xrand += 25
        yrand -= index * 20
        supplycrate = physics.SupplyCrate(world, space,
                                          (500 + xrand, yrand, 0),
                                          supplytexture, 2)

        supplycrates.append(fuelcrate)
        supplycrates.append(foodcrate)
        supplycrates.append(supplycrate)

    verts = [[0.0, 600.0, 0.0], [200.0, 500.0, 0.0], [400.0, 600.0, 0.0],
             [800.0, 500.0, 0.0], [1000.0, 600.0, 0.0], [1500.0, 550.0, 0.0],
             [2000.0, 600.0, 0.0], [2500.0, 400.0, 0.0], [3000.0, 600.0, 0.0]]
    faces = [[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7, 8]]
    tris = ode.TriMeshData()
    tris.build(verts, faces)
    worldmesh = ode.GeomTriMesh(tris, space)

    gamestate = 0

    basecampstarttime = 0
    basecampendtime = 0
    while 1:
        input(pygame.event.get())
        keystate = pygame.key.get_pressed()
        if keystate[K_UP]:
            ship.thrustUp(1.0)
        if keystate[K_LEFT]:
            ship.rotate(-1.0)
        if keystate[K_RIGHT]:
            ship.rotate(1.0)
        if keystate[K_SPACE]:
            # find the nearest crate to pickup
            if ship.carryingitem == 0:
                index = 0
                for curcrate in supplycrates:
                    x, y, z = curcrate.mainbody.body.getPosition()
                    x1, y1, z1 = ship.mainbody.body.getPosition()
                    dx = x - x1
                    dy = y - y1
                    distance = math.sqrt(dx * dx + dy * dy)
                    if distance < 100:
                        ship.joinBody(world, space, curcrate.mainbody.body,
                                      curcrate.type, index)
                    index += 1
            else:
                ship.dropBody()

        if gamestate == 2:
            background.Bind()
            gl.DrawQuad((0, 0, 4024, 4024))
            font.draw((300, 300),
                      "OMG EVERYONE DIED\nGame Over\nYour score %d" %
                      basecampendtime)

        if gamestate == 0:
            background.Bind()
            gl.DrawQuad((0, 0, 4024, 4024))

            font.draw((
                20, 20
            ), "INSTRUCTIONS:\n\nLEFTARROW:      rotate ship left\nRIGHTARROW:     rotate ship right\nUPARROW:           thrust up\nSPACE:                grapple supply crate\n\nThe point to the game is to keep the base camp\npopulation alive as long as possible.  \nEach resource has a chain reaction on other resources\nwhich can in turn exponential kill off the population.\n\nGrap resource crates and fly them near the basecamp\nRefuel by landing on the fuel platform."
                      )

            glColor4f(1.0, 0.5, 0.5, 0.40)
            gl.DrawColorQuad((110, 520, 550, 32))
            glColor4f(1.0, 1.0, 1.0, 1.0)
            font.draw((200, 520), "CLICK ANYWHERE TO START GAME")
            global mousedown
            if mousedown:
                basecampstarttime = pygame.time.get_ticks()
                gamestate = 1
        if gamestate == 1:
            if basecamp.population < 1:
                gamestate = 2
                basecampendtime = pygame.time.get_ticks() - basecampstarttime

            # basecamp takes resource off of your ship if within proximity
            x, y, z = ship.mainbody.body.getPosition()
            x1, y1, z1 = basecamp.mainbody.body.getPosition()
            dx = x1 - x
            dy = y1 - y
            distance = math.sqrt(dx * dx + dy * dy)
            if distance < 300 and ship.carryingitem == 1 and ship.carryindex > 0:
                if ship.carrytype == 0:
                    basecamp.AddFuel()
                if ship.carrytype == 1:
                    basecamp.AddFood()
                if ship.carrytype == 2:
                    basecamp.AddSupply()

                ship.dropBody()
                del supplycrates[ship.carryindex]
                ship.carryingitem = 0
                ship.carryindex = -1

            # add fuel to ship only if really close to fuel station & landing gear not moving
            x, y, z = ship.mainbody.body.getPosition()
            x1, y1, z1 = fuelstation.mainbody.body.getPosition()
            dx = x1 - x
            dy = y1 - y
            distance = math.sqrt(dx * dx + dy * dy)
            leftgear = abs(ship.leftjoint.getPositionRate())
            rightgear = abs(ship.rightjoint.getPositionRate())
            gearforce = leftgear + rightgear

            if distance < 140 and gearforce < 0.5:
                ship.fuellevel += 0.01
                if ship.fuellevel > 1.0:
                    ship.fuellevel = 1.0

            physics.RunSimulation(world, space, contactgroup, 1.0 / 60.0)

            # translate to the ship
            x, y, z = ship.mainbody.body.getPosition()
            glTranslatef(-x - 200, -y + 300, 0)

            background.Bind()
            gl.DrawQuad((0, 0, 4024, 4024))

            #draw world
            for index in range(0, len(verts) - 1):
                glPushMatrix()
                x1 = verts[index][0]
                y1 = verts[index][1]

                x2 = verts[index + 1][0]
                y2 = verts[index + 1][1]

                gl.DrawLine((x1, y1), (x2, y2))

                glPopMatrix()

            ship.draw()

            # draw basecamp
            basecamp.draw()
            fuelstation.draw()

            #draw supply crates
            for crate in supplycrates:
                crate.draw()

            # draw hud
            glPushMatrix()
            x, y, z = ship.mainbody.body.getPosition()
            glColor4f(1.0, 0.5, 0.5, 0.75)
            gl.DrawColorQuad((x - 375, y - 250, 300 * ship.fuellevel, 32))
            glPopMatrix()

            fuel = basecamp.fuel
            food = basecamp.food
            supply = basecamp.supply
            pop = basecamp.population

            glPushMatrix()
            glColor4f(0.5, 1.0, 0.5, 0.75)
            gl.DrawColorQuad((x - 375, y + 150, fuel, 16))
            glPopMatrix()
            glPushMatrix()
            gl.DrawColorQuad((x - 375, y + 190, food, 16))
            glPopMatrix()
            glPushMatrix()
            gl.DrawColorQuad((x - 375, y + 230, supply, 16))
            glPopMatrix()
            glPushMatrix()
            gl.DrawColorQuad((x - 375, y + 270, pop / 50, 16))
            glPopMatrix()

            glColor4f(1.0, 1.0, 1.0, 1.0)

            font.draw((32, 435), "fuel %d" % fuel)
            font.draw((32, 435 + 38), "food %d" % food)
            font.draw((32, 435 + 38 * 2), "supply %d" % supply)
            font.draw((32, 435 + 38 * 3), "population %d" % pop)

            fuelleveltext = 'fuel level: %.0f' % (ship.fuellevel * 100)
            font.draw((32, 32), fuelleveltext)

            if ship.fuellevel < 0.3:
                fuelleveltext = 'LOW FUEL'
                font.draw((400, 300), fuelleveltext)

        font.draw((screenwidth - 200, 0), fpsstring)
        pygame.display.flip()
        fps += 1

        clock.tick(60)
        if (pygame.time.get_ticks() - starttime > 1000):
            fpsdisplay = fps
            fpsstring = 'fps: %d' % fpsdisplay
            fps = 0
            starttime = pygame.time.get_ticks()