コード例 #1
0
class Alert(Notifier):
    def __init__(self, reason):
        Notifier.__init__(self, "alert")
        VirtualFileSystem.getGlobalPtr().mount(Filename("mf/alert.mf"), ".",
                                               VirtualFileSystem.MFReadOnly)
        ok = loader.loadModel("alert.egg")

        if reason not in LOCAL_EN:
            reason = GENERAL

        self.reason = reason

        self.bg_frame = DirectFrame(frameColor=(0, 0, 0, 0),
                                    frameSize=(-1, 1, -1, 1),
                                    suppressMouse=1,
                                    state=DGG.NORMAL,
                                    sortOrder=1000)
        self.frame = DirectFrame(frameSize=(1, 1, 1, 1),
                                 image=ok.find('**/alert'),
                                 image_scale=(1, 0, 0.6),
                                 state=DGG.NORMAL,
                                 parent=self.bg_frame)
        self.text = OnscreenText(text=LOCAL_EN[reason],
                                 fg=(1, 1, 1, 1),
                                 pos=(0, 0.15, 0),
                                 align=TextNode.ACenter,
                                 wordwrap=13,
                                 parent=self.frame)
        self.button = DirectButton(geom=(ok.find('**/ok-ready'),
                                         ok.find('**/ok-click'),
                                         ok.find('**/ok-hover'),
                                         ok.find('**/ok-click')),
                                   relief=None,
                                   geom_scale=(0.3, 0, 0.15),
                                   geom_pos=(0, 0, -0.175),
                                   pressEffect=0,
                                   command=self.destroy,
                                   parent=self.frame)

        self.notify.debug(
            f"[__init__] Created Alert with reason {self.reason}")

        loader.unloadModel(ok)

    def __repr__(self):
        return str(self.reason)

    def destroy(self):
        VirtualFileSystem.getGlobalPtr().unmount("mf/alert.mf")
        VirtualFileSystem.getGlobalPtr().unmount("mf/ok_small.mf")
        self.bg_frame.destroy()
        self.frame.destroy()
        self.button.destroy()
        self.text.cleanup()
        self.text.destroy()
        del self.frame
        del self.button
        del self.text
        del self
コード例 #2
0
        def newGame(self):
				self.hideMenu()
				
                # Loading screen
				loadingText=OnscreenText("Loading...",1,fg=(1,1,1,1),pos=(0,0),align=TextNode.ACenter,scale=.07,mayChange=1)
				base.graphicsEngine.renderFrame() 
				base.graphicsEngine.renderFrame() 
				base.graphicsEngine.renderFrame() 
				base.graphicsEngine.renderFrame()
				
				self.world = SMWorld(1, self.textObj, self.audioMgr)
				
				loadingText.cleanup()
コード例 #3
0
    def newGame(self):
        self.hideMenu()

        # Loading screen
        loadingText = OnscreenText("Loading...",
                                   1,
                                   fg=(1, 1, 1, 1),
                                   pos=(0, 0),
                                   align=TextNode.ACenter,
                                   scale=.07,
                                   mayChange=1)
        base.graphicsEngine.renderFrame()
        base.graphicsEngine.renderFrame()
        base.graphicsEngine.renderFrame()
        base.graphicsEngine.renderFrame()

        self.world = SMWorld(1, self.textObj, self.audioMgr)

        loadingText.cleanup()
コード例 #4
0
class SMWorld(DirectObject):

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Constructor
    # (Game state, Map name, Height of death plane)
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def __init__(self, mapID, tObj, aObj):

        self.mapID = mapID

        # EX: maps/map-1/map-1.yetimap
        metaFile = open(
            "../maps/map" + str(self.mapID) + "/map" + str(self.mapID) +
            ".yetimap", 'r')
        metaLines = metaFile.readlines()
        lineCount = len(metaLines)
        self.snowflakeCount = lineCount - 2
        self.snowCount = 0

        # First Line: Player's starting position
        # EX: 50,50,50 (NO SPACES)
        playerLine = metaLines[0]
        playerPosList = playerLine.split(",")
        playerInitX = int(playerPosList[0])
        playerInitY = int(playerPosList[1])
        playerInitZ = int(playerPosList[2])
        self.playerStart = Point3(playerInitX, playerInitY, playerInitZ)

        # 2nd Line: Deathzone Height
        # ONE INTEGER
        self.deathHeight = int(metaLines[1])

        # Get dem snowflakes
        self.snowflakePositions = []
        print("Snowflake Count: " + str(self.snowflakeCount))
        for i in xrange(0, self.snowflakeCount):
            sfline = metaLines[i + 2]
            sfList = sfline.split(",")
            sfx = int(sfList[0])
            sfy = int(sfList[1])
            sfz = int(sfList[2])
            self.snowflakePositions.append(Point3(sfx, sfy, sfz))
            print("New snowflake to add: (" + str(sfx) + "," + str(sfy) + "," +
                  str(sfz) + ")")

        #load in controls
        ctrlFl = open("ctrConfig.txt")
        #will skip n lines where [n,]
        #makes a list of controls
        self.keymap = eval(ctrlFl.read())
        #close file
        ctrlFl.close()

        # Create new instances of our various objects
        self.mapName = str(mapID)
        self.audioMgr = aObj
        self.worldObj = self.setupWorld()
        self.heightMap = self.setupHeightmap(self.mapName)
        self.deathZone = self.setupDeathzone(self.deathHeight)
        self.debugNode = self.setupDebug()

        # Player Init
        self.playerObj = SMPlayer(self.worldBullet, self.worldObj, self,
                                  self.playerStart, self.audioMgr)
        self.playerNP = self.playerObj.getNodePath()
        self.playerNP.setH(180)
        self.canUseShift = True
        self.canAirDash = True

        # Snowball Init
        self.ballObj = SMBall(self.worldBullet, self.worldObj, self.playerObj,
                              self.playerNP)
        self.sbCollideFlag = False
        self.ballNP = self.ballObj.getNodePath()

        # Key Handler
        self.kh = SMKeyHandler()
        self.lastMousePos = self.kh.getMouse()

        # Collision Handler
        self.colObj = self.setupCollisionHandler()

        # Lighting
        self.ligObj = SMLighting(Vec4(.4, .4, .4, 1), Vec3(-5, -5, -5),
                                 Vec4(2.0, 2.0, 2.0, 1.0))

        # Camera
        self.camObj = SMCamera(self.playerObj, self.worldBullet, self.worldObj)
        self.cameraControl = False

        # GUI
        self.GUI = SMGUI()
        self.snowflakeCounter = SMGUICounter(
            "snowflake",
            self.snowflakeCount)  # Replace 3 with # of snowflakes in level.
        self.snowMeter = SMGUIMeter(100)
        self.GUI.addElement("snowflake", self.snowflakeCounter)
        self.GUI.addElement("snowMeter", self.snowMeter)

        #Snowy Outside
        # base.enableParticles()
        # self.p = ParticleEffect()
        # self.p.cleanup()
        # self.p = ParticleEffect()
        # self.p.loadConfig('snow.ptf')
        # self.p.start(self.camObj.getNodePath())
        # self.p.setPos(0.00, 0.500, 0.000)

        # AI
        # self.goat1 = SMAI("../res/models/goat.egg", 75.0, self.worldBullet, self.worldObj, -70, -95, 5)
        # self.goat1.setBehavior("flee", self.playerNP)
        # self.goat2 = SMAI("../res/models/goat.egg", 75.0, self.worldBullet, self.worldObj, -80, -83, 5)
        # self.goat2.setBehavior("flee", self.playerNP)
        # print("AI Initialized")

        # Debug Text
        self.textObj = tObj
        self.textObj.addText("yetiPos", "Position: ")
        self.textObj.addText("yetiVel", "Velocity: ")
        self.textObj.addText("yetiFric", "Friction: ")
        self.textObj.addText("onIce", "Ice(%): ")
        self.textObj.addText("onSnow", "Snow(%): ")
        self.textObj.addText("terrHeight", "T Height: ")
        self.textObj.addText("terrSteepness", "Steepness: ")

        # Pause screen transition
        self.transition = Transitions(loader)

        # Method-based keybindings
        # self.accept('b', self.spawnBall)
        self.accept('escape', base.userExit)
        self.accept('enter', self.pauseUnpause)
        self.accept('f1', self.toggleDebug)

        self.accept('lshift-up', self.enableShiftActions)
        self.accept('mouse1', self.enableCameraControl)
        self.accept('mouse1-up', self.disableCameraControl)
        self.accept('wheel_up', self.camObj.zoomIn)
        self.accept('wheel_down', self.camObj.zoomOut)

        self.pauseUnpause()

        # Disable the mouse
        base.disableMouse()
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)

        # Uncomment this to see everything being rendered.
        self.printSceneGraph()

        # Play the BGM
        self.audioMgr.playBGM("snowmanWind")

        # Skybox formed
        skybox = loader.loadModel("../res/models/skybox.egg")
        # skybox.set_two_sided(true)
        skybox.setScale(500)
        skybox.setPos(0, 0, -450)
        skybox.reparentTo(render)

        mountain = loader.loadModel("../res/models/mountain.egg")
        mountain.reparentTo(render)
        mountain.setPos(650, 800, 20)
        mountain.setScale(120)

        self.colObjects = []

        self.caveNew = SMCollide("../res/models/cave_new.egg",
                                 self.worldBullet, self.worldObj,
                                 Point3(-50, 95, -13), 11, Vec3(0, 0, 0))
        self.colObjects.append(self.caveNew)

        self.planeFront = SMCollide("../res/models/plane_front",
                                    self.worldBullet, self.worldObj,
                                    Point3(190, -100,
                                           -15), 8, Vec3(190, 0, 30))
        self.colObjects.append(self.planeFront)

        self.caveModel = SMCollide("../res/models/cave_tunnel.egg",
                                   self.worldBullet, self.worldObj,
                                   Point3(233, 68, 32), 4, Vec3(135, 180, 0))
        self.colObjects.append(self.caveModel)

        self.planeTail = SMCollide("../res/models/plane_tail.egg",
                                   self.worldBullet, self.worldObj,
                                   Point3(-40, -130, -7), 10, Vec3(230, 0, 0))
        self.colObjects.append(self.planeTail)

        self.ropeBridge = SMCollide("../res/models/rope_bridge.egg",
                                    self.worldBullet, self.worldObj,
                                    Point3(180, 115, 30), 6, Vec3(50, 0, 0))
        self.colObjects.append(self.ropeBridge)

        self.colObjectCount = len(self.colObjects)

        print("World initialized.")

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Enables the camera to be rotated by moving the mouse horizontally.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def enableCameraControl(self):
        self.cameraControl = True

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Disables the camera control.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def disableCameraControl(self):
        self.cameraControl = False

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Enables the use of shift actions again.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def enableShiftActions(self):
        self.canUseShift = True

    def disableShiftActions(self):
        self.canUseShift = False

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Respawns the yeti's snowball.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def spawnBall(self):
        if (not (self.playerObj.getAirborneFlag())):
            self.ballObj.respawn()

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Toggles the pause screen
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def pauseUnpause(self):
        if taskMgr.hasTaskNamed('UpdateTask'):
            taskMgr.remove('UpdateTask')
            self.transition.fadeScreen(0.5)
        else:
            taskMgr.add(self.update, 'UpdateTask')
            self.transition.noFade()

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Sets up the world and returns a NodePath of the BulletWorld
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def setupWorld(self):
        self.worldBullet = BulletWorld()
        self.worldBullet.setGravity(Vec3(0, 0, -GRAVITY))
        self.terrSteepness = -1
        wNP = render.attachNewNode('WorldNode')

        self.audioMgr.loadSFX("snowCrunch01")
        self.audioMgr.loadBGM("snowmanWind")

        return wNP

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Prints all nodes that are a child of render.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def printSceneGraph(self):
        print(render.ls())

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Initializes and returns a DebugNode NodePath.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def setupDebug(self):
        debug = BulletDebugNode()
        debug.showWireframe(
            False
        )  # Yeah, don't set this to true unless you want to emulate an 80's computer running Crysis on Ultra settings.
        debug.showConstraints(True)
        debug.showBoundingBoxes(True)  # This is the main use I have for it.
        debug.showNormals(True)
        debugNP = render.attachNewNode(debug)
        self.worldBullet.setDebugNode(debugNP.node())
        debugNP.hide()
        return debugNP

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Initializes and returns a BulletRigidBodyNode of the terrain, which loads the map with the specified name.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def setupHeightmap(self, name):

        # Automatically generate a heightmap mesh from a monochrome image.
        self.hmHeight = 120
        hmPath = "../maps/map" + name + "/map" + name + "-h.png"
        imPath = "../maps/map" + name + "/map" + name + "-i.png"
        smPath = "../maps/map" + name + "/map" + name + "-s.png"
        scmPath = "../maps/map" + name + "/map" + name + "-sc.png"
        print(hmPath)
        print(imPath)
        print(smPath)
        print(scmPath)
        hmImg = PNMImage(Filename(hmPath))
        hmShape = BulletHeightfieldShape(hmImg, self.hmHeight, ZUp)
        hmNode = BulletRigidBodyNode('Terrain')
        hmNode.addShape(hmShape)
        hmNode.setMass(0)
        self.hmNP = render.attachNewNode(hmNode)
        self.worldBullet.attachRigidBody(hmNode)
        self.hmOffset = hmImg.getXSize() / 2.0 - 0.5
        self.hmTerrain = GeoMipTerrain('gmTerrain')
        self.hmTerrain.setHeightfield(hmImg)

        # Optimizations and fixes
        self.hmTerrain.setBruteforce(
            True)  # I don't think this is actually needed.
        self.hmTerrain.setMinLevel(3)  # THIS is what triangulates the terrain.
        self.hmTerrain.setBlockSize(
            128)  # This does a pretty good job of raising FPS.
        # Level-of-detail (not yet working)
        # self.hmTerrain.setNear(40)
        # self.hmTerrain.setFar(200)

        self.hmTerrain.generate()

        self.hmTerrainNP = self.hmTerrain.getRoot()
        self.hmTerrainNP.setSz(self.hmHeight)
        self.hmTerrainNP.setPos(-self.hmOffset, -self.hmOffset,
                                -self.hmHeight / 2.0)
        self.hmTerrainNP.flattenStrong(
        )  # This only reduces the number of nodes; nothing to do with polys.
        self.hmTerrainNP.analyze()

        # Here begins the scenery mapping
        treeModel = loader.loadModel("../res/models/tree_1.egg")
        rockModel = loader.loadModel("../res/models/rock_1.egg")
        rock2Model = loader.loadModel("../res/models/rock_2.egg")
        rock3Model = loader.loadModel("../res/models/rock_3.egg")
        # caveModel = loader.loadModel("../res/models/cave_new.egg")
        # planeFrontModel = loader.loadModel("../res/models/plane_front.egg")
        # planeWingModel = loader.loadModel("../res/models/plane_wing.egg")
        texpk = loader.loadTexture(scmPath).peek()

        # GameObject nodepath for flattening
        self.objNP = render.attachNewNode("gameObjects")
        self.treeNP = self.objNP.attachNewNode("goTrees")
        self.rockNP = self.objNP.attachNewNode("goRocks")
        self.rock2NP = self.objNP.attachNewNode("goRocks2")
        self.rock3NP = self.objNP.attachNewNode("goRocks3")
        # self.caveNP = self.objNP.attachNewNode("goCave")
        # self.planeFrontNP = self.objNP.attachNewNode("goPlaneFront")
        # self.planeWingNP = self.objNP.attachNewNode("goPlaneWing")

        for i in range(0, texpk.getXSize()):
            for j in range(0, texpk.getYSize()):
                color = VBase4(0, 0, 0, 0)
                texpk.lookup(color,
                             float(i) / texpk.getXSize(),
                             float(j) / texpk.getYSize())
                if (int(color.getX() * 255.0) == 255.0):
                    newTree = self.treeNP.attachNewNode("treeNode")
                    treeModel.instanceTo(newTree)
                    newTree.setPos(
                        i - texpk.getXSize() / 2, j - texpk.getYSize() / 2,
                        self.hmTerrain.get_elevation(i, j) * self.hmHeight -
                        self.hmHeight / 2)
                    # newTree.setScale(randint(0,4))
                    newTree.setScale(2)

                if (int(color.getX() * 255.0) == 128):
                    newRock = self.rockNP.attachNewNode("newRock")
                    newRock.setPos(
                        i - texpk.getXSize() / 2, j - texpk.getYSize() / 2,
                        self.hmTerrain.get_elevation(i, j) * self.hmHeight -
                        self.hmHeight / 2)
                    rockModel.instanceTo(newRock)

                if (int(color.getX() * 255.0) == 77):
                    newRock2 = self.rock2NP.attachNewNode("newRock2")
                    newRock2.setPos(
                        i - texpk.getXSize() / 2, j - texpk.getYSize() / 2,
                        self.hmTerrain.get_elevation(i, j) * self.hmHeight -
                        self.hmHeight / 2)
                    rock2Model.instanceTo(newRock2)

                if (int(color.getX() * 255.0) == 102):
                    newRock3 = self.rock3NP.attachNewNode("newRock3")
                    newRock3.setPos(
                        i - texpk.getXSize() / 2, j - texpk.getYSize() / 2,
                        self.hmTerrain.get_elevation(i, j) * self.hmHeight -
                        self.hmHeight / 2)
                    rock3Model.instanceTo(newRock3)

                # if(int(color.getX() * 255.0) == 64):
                # newCave = self.caveNP.attachNewNode("newCave")
                # newCave.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
                # newCave.setScale(5)
                # newCave.setP(180)
                # caveModel.instanceTo(newCave)

                # if(int(color.getX() * 255.0) == 191):
                # newPlaneFront = self.planeFrontNP.attachNewNode("newPlaneFront")
                # newPlaneFront.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
                # newPlaneFront.setScale(6)
                # planeFrontModel.instanceTo(newPlaneFront)

                # if(int(color.getX() * 255.0) == 179):
                # newPlaneWing = self.planeWingNP.attachNewNode("newPlaneWing")
                # newPlaneWing.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
                # newPlaneWing.setScale(6)
                # newPlaneWing.setH(250)
                # newPlaneWing.setR(180)
                # newPlaneWing.setP(135)
                # planeWingModel.instanceTo(newPlaneWing)

        self.snowflakes = []

        for i in xrange(0, self.snowflakeCount):
            print("Call " + str(i))
            sf = SMCollect(self.worldBullet, self.worldObj,
                           self.snowflakePositions[i])
            self.snowflakes.append(sf)

        # render.flattenStrong()
        self.hmTerrainNP.reparentTo(render)

        # Here begins the attribute mapping
        ts = TextureStage("stage-alpha")
        ts.setSort(0)
        ts.setPriority(1)
        ts.setMode(TextureStage.MReplace)
        ts.setSavedResult(True)
        self.hmTerrainNP.setTexture(ts, loader.loadTexture(imPath, smPath))

        ts = TextureStage("stage-stone")
        ts.setSort(1)
        ts.setPriority(1)
        ts.setMode(TextureStage.MReplace)
        self.hmTerrainNP.setTexture(
            ts, loader.loadTexture("../res/textures/stone_tex.png"))
        self.hmTerrainNP.setTexScale(ts, 32, 32)

        ts = TextureStage("stage-ice")
        ts.setSort(2)
        ts.setPriority(1)
        ts.setCombineRgb(TextureStage.CMInterpolate, TextureStage.CSTexture,
                         TextureStage.COSrcColor, TextureStage.CSPrevious,
                         TextureStage.COSrcColor,
                         TextureStage.CSLastSavedResult,
                         TextureStage.COSrcColor)
        self.hmTerrainNP.setTexture(
            ts, loader.loadTexture("../res/textures/ice_tex.png"))
        self.hmTerrainNP.setTexScale(ts, 32, 32)

        ts = TextureStage("stage-snow")
        ts.setSort(3)
        ts.setPriority(0)
        ts.setCombineRgb(TextureStage.CMInterpolate, TextureStage.CSTexture,
                         TextureStage.COSrcColor, TextureStage.CSPrevious,
                         TextureStage.COSrcColor,
                         TextureStage.CSLastSavedResult,
                         TextureStage.COSrcAlpha)
        self.hmTerrainNP.setTexture(
            ts, loader.loadTexture("../res/textures/snow_tex_1.png"))
        self.hmTerrainNP.setTexScale(ts, 32, 32)

        # print(self.snowflakes)

        return hmNode

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Sets up and returns the death zone plane (returns its NodePath) with the specified height.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def setupDeathzone(self, height):
        planeShape = BulletPlaneShape(Vec3(0, 0, 1), 1)
        planeNode = BulletRigidBodyNode('DeathZone')
        planeNode.addShape(planeShape)
        planeNP = render.attachNewNode(planeNode)
        planeNP.setPos(0, 0, height)
        self.worldBullet.attachRigidBody(planeNode)
        return planeNP

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Sets up and returns the collision handler.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def setupCollisionHandler(self):
        colHand = SMCollisionHandler(self.worldBullet)
        return colHand

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Toggles showing bounding boxes.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def toggleDebug(self):
        if self.debugNode.isHidden():
            self.debugNode.show()
        else:
            self.debugNode.hide()

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Returns the terrain height of the nearest vertical descending raycast from the passed Point3.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def getTerrainHeight(self, pos):
        result = 0
        x = pos.getX()
        y = pos.getY()
        z = pos.getZ()
        rayTerrA = Point3(x, y, z)
        rayTerrB = Point3(x, y, z - 256)
        rayTest = self.worldBullet.rayTestClosest(rayTerrA, rayTerrB)

        rayNode = rayTest.getNode()
        if (rayTest.hasHit()):
            rayPos = rayTest.getHitPos()
            result = rayPos.getZ()
        else:
            self.playerObj.respawn()
        return result
        # return self.hmTerrain.get_elevation(x + self.hmOffset, y + self.hmOffset) * self.hmHeight

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Handles player movement
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def playerMove(self):

        # Go through the collision and flag tests, and update them
        self.doPlayerTests()

        # Rotation and camera movement
        if self.kh.poll(self.keymap['Left']):
            self.playerObj.turn(True)
        elif self.kh.poll(self.keymap['Right']):
            self.playerObj.turn(False)
        elif (self.cameraControl):
            newMousePos = self.kh.getMouse()
            mx = newMousePos.getX()
            self.camObj.rotateCamera(mx)

        self.camObj.calculatePosition()

        # Movement
        if self.kh.poll(self.keymap['Forward']):
            self.playerObj.move(True)
            self.camObj.rotateTowards(90)
        elif self.kh.poll(self.keymap['Back']):

            self.playerObj.move(False)
        else:
            self.playerObj.stop()

        # Jump
        if (self.kh.poll(self.keymap['Space']) and self.terrSteepness <
                0.25):  #and not(self.ballObj.isRolling())):
            self.playerObj.jump()
        else:
            self.playerObj.resetJump()

        # Air Dash
        if (
                self.kh.poll(self.keymap['airDash'])
        ):  #and self.playerObj.getAirborneFlag() == True and self.canAirDash == True):
            self.canAirDash = False
            self.playerObj.airDash()

        # Shift-based actions
        if (self.kh.poll("lshift") and not (self.sbCollideFlag)
                and not (self.playerObj.getAirborneFlag())
                and self.canUseShift):

            # If there's another snowball already placed
            if (self.ballObj.exists() and not (self.ballObj.isRolling())):
                self.ballObj.respawn()

            # If we're rolling a snowball
            elif (self.ballObj.isRolling()):

                # Absorb snowball
                if (self.kh.poll("v")):
                    self.canUseShift = False
                    snowAmt = self.ballObj.getSnowAmount()
                    self.playerObj.addSnow(snowAmt)
                    # self.snowMeter.fillBy(snowAmt)
                    self.ballObj.destroy()

                # Go to iceball throwing mode
                elif (self.kh.poll("b")):
                    print("TODO: Ice ball throwing mode.")

                # Grow the snowball
                elif (self.kh.poll("w")):
                    self.ballObj.grow()

            # Spawn a new snowball
            elif (self.ballObj.exists() == False):
                self.ballObj.respawn()

        # If the player is not pressing shift
        else:
            if (self.ballObj.isRolling()):
                self.ballObj.dropBall()

        base.win.movePointer(0, 400, 300)

        # So updating the stats is VERY expensive.
        if (self.debugNode.isHidden() == False):
            self.updateStats()

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Various tests concerning the player flags and collisions.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def doPlayerTests(self):

        # Player's position
        plPos = self.playerObj.getPosition()
        px = plPos.getX()
        py = plPos.getY()
        pz = plPos.getZ()

        # Raycast directly down for terrain steepness
        rayYetiA = Point3(px, py, pz)
        rayYetiB = Point3(px, py, pz - 300)
        self.downRayTest = self.worldBullet.rayTestClosest(
            rayYetiA, rayYetiB).getHitNormal()
        rx = self.downRayTest.getX()
        ry = self.downRayTest.getY()
        rz = self.downRayTest.getZ()
        self.terrSteepness = 1.0 - rz

        # Redo collision flags later
        objCollisionFlag = False

        # Snow/Ice height adjust
        self.playerObj.updateTerrain()

        # Collision: Player x Objects
        for i in xrange(0, self.colObjectCount):
            if (self.colObj.didCollide(self.playerNP.node(),
                                       self.colObjects[i].AINode)):
                objCollisionFlag = True
                self.playerObj.setAirborneFlag(False)
                self.canAirDash = True
                self.playerObj.setFactor(1, 1, 1)

        # Collision: Player x Snowball
        if (self.ballObj.exists() and self.colObj.didCollide(
                self.playerNP.node(), self.ballObj.getRigidbody())):
            self.sbCollideFlag = True
            self.playerObj.setAirborneFlag(False)
            self.playerObj.setFactor(1, 1, 1)
        else:
            self.sbCollideFlag = False

        # Collision: Player x Terrain
        if (self.colObj.didCollide(self.playerNP.node(), self.heightMap)):
            if (self.playerObj.getAirborneFlag()):
                self.audioMgr.playSFX("snowCrunch01")
            self.playerObj.setAirborneFlag(False)
            self.canAirDash = True
            self.playerObj.setFactor(1, 1, 1)
            objCollisionFlag = False

        # Collision: Player x Death Zone
        # if(pz - 7 <= self.deathHeight or (self.colObj.didCollide(self.playerNP.node(), self.deathZone.node()))):
        if (self.colObj.didCollide(self.playerNP.node(),
                                   self.deathZone.node())):
            print("Player confirmed #REKT")
            self.playerObj.respawn()

        # Out of bounds checking
        if (abs(px) > 254 or abs(py) > 254):
            print("Player out of bounds!")
            self.playerObj.respawn()

        # Snap to terrain if... something. I need to restructure this. Don't read it.
        if (not (self.playerObj.getAirborneFlag()) and not (self.sbCollideFlag)
                and not (objCollisionFlag)):
            z = self.getTerrainHeight(Point3(px, py, pz))
            self.playerObj.snapToTerrain(z)
            # self.playerObj.snapToTerrain(th, self.hmHeight)

        # Collision: Player x Snowflakes
        for i in xrange(0, self.snowflakeCount):
            if (self.snowflakes[i].exists() and self.colObj.didCollide(
                    self.playerNP.node(), self.snowflakes[i].getNode())):
                self.snowflakes[i].destroy()
                self.snowflakeCounter.increment()
                self.snowCount += 1

        self.snowMeter.updateSnow(self.playerObj)

        #Check if there is a "next" level. If there is, load it. Otherwise display end game screen.
        if (self.snowCount >= self.snowflakeCount):
            file_path = "../maps/map" + str(self.mapID +
                                            1) + "/map" + str(self.mapID +
                                                              1) + ".yetimap"
            if os.path.lexists(file_path):

                self.snowCount = 0
                self.snowflakeCount = 0
                self.snowflakeCounter.setValue(0)
                self.snowflakeCounter.setState(2)

                #Loading Screen
                self.transition.fadeScreen(0.7)
                self.loadingText = OnscreenText("Loading...",
                                                1,
                                                fg=(1, 1, 1, 0),
                                                pos=(0, 0),
                                                align=TextNode.ACenter,
                                                scale=.07,
                                                mayChange=1)
                base.graphicsEngine.renderFrame()
                base.graphicsEngine.renderFrame()
                base.graphicsEngine.renderFrame()
                base.graphicsEngine.renderFrame()
                self.transition.noFade()

                #destroy objects
                self.worldBullet.removeRigidBody(self.heightMap)
                self.hmTerrainNP.removeNode()
                self.objNP.removeNode()
                self.treeNP.removeNode()
                self.rockNP.removeNode()
                self.rock2NP.removeNode()
                self.rock3NP.removeNode()
                # self.caveNP.removeNode()
                # self.planeFrontNP.removeNode()
                # self.planeWingNP.removeNode()
                self.hmNP.removeNode()
                if (int(self.mapID) == 1):
                    self.ropeBridge.AIChar.setPos(-200, -300, -200)
                    # self.ropeBridge.AIChar.removeNode()
                    self.planeFront.AIChar.removeNode()
                    self.planeTail.AIChar.setPos(-200, -200, -200)
                    # self.planeTail.AIChar.removeNode()
                    self.caveNew.AIChar.setPos(-1000, -1000, -1000)
                    self.caveModel.AIChar.removeNode()
                    #Added More Props here!
                    self.boulder = SMCollide("../res/models/rock_3.egg",
                                             self.worldBullet, self.worldObj,
                                             Point3(117, 123, 17), 15,
                                             Vec3(0, 0, 0))
                elif (int(self.mapID) == 2):
                    self.boulder.AIChar.setPos(-222, -222, -222)
                    self.caveNew.AIChar.setScale(150)
                    self.caveNew.AIChar.setPos(-50, 95, -50)
                    # self.skybox.setScale(600)
                    # self.caveNew.setH(0)
                    # self.boulder.removeNode()

                self.mapID += 1
                print self.mapID
                # EX: maps/map-1/map-1.yetimap
                metaFile = open(
                    "../maps/map" + str(self.mapID) + "/map" +
                    str(self.mapID) + ".yetimap", 'r')
                metaLines = metaFile.readlines()
                lineCount = len(metaLines)
                self.snowflakeCount = lineCount - 2

                # First Line: Player's starting position
                # EX: 50,50,50 (NO SPACES)
                playerLine = metaLines[0]
                playerPosList = playerLine.split(",")
                playerInitX = int(playerPosList[0])
                playerInitY = int(playerPosList[1])
                playerInitZ = int(playerPosList[2])
                self.playerObj.playerNP.setPos(playerInitX, playerInitY,
                                               playerInitZ)
                self.playerObj.startX = playerInitX
                self.playerObj.startY = playerInitY
                self.playerObj.startZ = playerInitZ

                # 2nd Line: Deathzone Height
                # ONE INTEGER
                self.deathHeight = int(metaLines[1])

                self.snowflakePositions = []
                print("Snowflake Count: " + str(self.snowflakeCount))
                for i in xrange(0, self.snowflakeCount):
                    sfline = metaLines[i + 2]
                    sfList = sfline.split(",")
                    sfx = int(sfList[0])
                    sfy = int(sfList[1])
                    sfz = int(sfList[2])
                    self.snowflakePositions.append(Point3(sfx, sfy, sfz))
                    print("New snowflake to add: (" + str(sfx) + "," +
                          str(sfy) + "," + str(sfz) + ")")
                self.snowflakeCounter.setMaxValue(self.snowflakeCount)

                #load new map
                self.mapName = str(self.mapID)
                self.heightMap = self.setupHeightmap(self.mapName)
                self.deathZone = self.setupDeathzone(self.deathHeight)

                self.loadingText.cleanup()
            else:
                taskMgr.remove('UpdateTask')
                self.endImage = OnscreenImage(
                    image="../res/icons/endgame1.png",
                    pos=(0.0, 0.0, 0.0),
                    scale=(1.35, 2, 1))

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Update the debug text.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def updateStats(self):
        pos = self.playerObj.getPosition()
        x = pos.getX()
        y = pos.getY()
        z = pos.getZ()
        vel = self.playerObj.getVelocity()
        vx = str(round(vel.getX(), 1))
        vy = str(round(vel.getY(), 1))
        vz = str(round(vel.getZ(), 1))
        sx = str(round(x, 1))
        sy = str(round(y, 1))
        sz = str(round(z, 1))
        rx = str(round(self.downRayTest.getX(), 2))
        ry = str(round(self.downRayTest.getY(), 2))
        rz = str(round(self.terrSteepness, 2))
        fric = str(round(self.playerObj.getFriction(), 2))
        ip = str(round(self.playerObj.getIceCoefficient(), 2))
        sp = str(round(self.playerObj.getSnowCoefficient(), 2))
        tHeight = str(round(self.getTerrainHeight(Point3(x, y, z)), 1))
        self.textObj.editText("yetiPos",
                              "Position: (" + sx + ", " + sy + ", " + sz + ")")
        self.textObj.editText("yetiVel",
                              "Velocity: (" + vx + ", " + vy + ", " + vz + ")")
        self.textObj.editText("yetiFric", "Friction: " + fric)
        self.textObj.editText("onIce", "Ice(%): " + ip)
        self.textObj.editText("onSnow", "Snow(%): " + sp)
        self.textObj.editText("terrHeight", "T Height: " + tHeight)
        self.textObj.editText("terrSteepness", "Steepness: " + rz)

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # throw Snowball
    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    def throw(self):
        self.throwing = True
        size = self.ballObj.getSize()
        #zoom camera and grab pos you wish to throw
        self.camObj.aimMode()
        taskMgr.add(self.controlCamera, "camera-task")
        rotation = self.camObj.getH()
        pitch = self.camObj.getP()
        self.ballObj.throwBall(size, pitch, rotation)
        #fix camera
        #self.throwing = False

    #------------------------------------------------------------------------------------------------------------------------------------------------------------
    # Update the world. Called every frame.
    #------------------------------------------------------------------------------------------------------------------------------------------------------------

    def update(self, task):
        dt = globalClock.getDt()
        self.worldBullet.doPhysics(dt)
        # self.goat1.AIUpdate()
        # self.goat2.AIUpdate()
        self.playerMove()
        return task.cont
コード例 #5
0
class Hood(StateData):
    def __init__(self, parentFSM, doneEvent, dnaStore, hoodId):
        StateData.__init__(self, doneEvent)
        self.parentFSM = parentFSM
        self.doneEvent = doneEvent
        self.dnaStore = dnaStore
        self.hoodId = hoodId
        self.id = None
        self.titleText = None
        self.suitFog = None
        self.suitLight = None
        self.suitLightColor = (0.4, 0.4, 0.4, 1)
        self.suitFogData = [(0.3, 0.3, 0.3), 0.0025]
        self.titleColor = (1, 1, 1, 1)
        return

    def enter(self, requestStatus):
        StateData.enter(self)
        hoodId = requestStatus['hoodId']
        zoneId = requestStatus['zoneId']
        rootZone = ZoneUtil.getZoneId(hoodId)
        if base.localAvatar.getLastHood(
        ) != rootZone and hoodId != CIGlobals.MinigameArea:
            base.localAvatar.b_setLastHood(rootZone)
        if not base.localAvatar.hasDiscoveredHood(rootZone):
            hoodsDiscovered = list(base.localAvatar.getHoodsDiscovered())
            hoodsDiscovered.append(rootZone)
            base.localAvatar.b_setHoodsDiscovered(hoodsDiscovered)
        text = self.getHoodText(zoneId)
        self.titleText = OnscreenText(text,
                                      fg=self.titleColor,
                                      font=CIGlobals.getMickeyFont(),
                                      scale=0.15,
                                      pos=(0, -0.65))
        self.titleText.hide()

    def enterTheLoader(self, requestStatus):
        self.fsm.request(requestStatus['loader'], [requestStatus])

    def getHoodText(self, zoneId):
        if ZoneUtil.getWhereName(zoneId) == 'street' and zoneId < 61000:
            hoodText = CIGlobals.BranchZone2StreetName[ZoneUtil.getBranchZone(
                zoneId)]
            hoodText += '\n' + self.id
        else:
            hoodText = self.id
            if self.id != CIGlobals.MinigameArea:
                hoodText += '\n' + ZoneUtil.getWhereName(zoneId).upper()
        return hoodText

    def spawnTitleText(self, zoneId):
        hoodText = self.getHoodText(zoneId)
        self.doSpawnTitleText(hoodText)

    def doSpawnTitleText(self, hoodText):
        self.titleText.setText(hoodText)
        self.titleText.show()
        self.titleText.setColor(Vec4(*self.titleColor))
        self.titleText.clearColorScale()
        self.titleText.setFg(self.titleColor)
        seq = Sequence(
            Wait(0.1), Wait(6.0),
            self.titleText.colorScaleInterval(0.5, Vec4(1.0, 1.0, 1.0, 0.0)),
            Func(self.titleText.hide))
        seq.start()

    def hideTitleText(self):
        if self.titleText:
            self.titleText.hide()

    def exit(self):
        if self.titleText:
            self.titleText.cleanup()
            self.titleText = None
        StateData.exit(self)
        return

    def load(self):
        StateData.load(self)
        if self.storageDNAFile:
            loadDNAFile(self.dnaStore, self.storageDNAFile)
        if self.holidayDNAFile:
            loadDNAFile(self.dnaStore, self.holidayDNAFile)
        if not base.cr.holidayManager.getHoliday() == HolidayType.CHRISTMAS:
            self.createNormalSky()
        else:
            self.createSpookySky()

    def unload(self):
        self.notify.info("unload()")
        if hasattr(self, 'loader'):
            self.loader.exit()
            self.loader.unload()
            del self.loader
        del self.parentFSM
        del self.fsm
        self.dnaStore.reset_nodes()
        self.dnaStore.reset_hood_nodes()
        self.dnaStore.reset_place_nodes()
        self.dnaStore.reset_hood()
        self.dnaStore.reset_fonts()
        self.dnaStore.reset_DNA_vis_groups()
        self.dnaStore.reset_textures()
        self.dnaStore.reset_block_numbers()
        self.dnaStore.reset_block_zones()
        self.dnaStore.reset_suit_points()
        del self.dnaStore
        self.deleteCurrentSky()
        self.stopSuitEffect(0)
        self.ignoreAll()
        ModelPool.garbageCollect()
        TexturePool.garbageCollect()
        StateData.unload(self)

    def enterOff(self):
        pass

    def exitOff(self):
        pass

    def isSameHood(self, status):
        return status['hoodId'] == self.hoodId and status['shardId'] == None

    def enterQuietZone(self, requestStatus):
        base.transitions.noTransitions()
        loaderName = requestStatus['loader']
        zoneID = requestStatus['zoneId']
        where = requestStatus['where']
        if where == 'playground' or where == 'toonInterior':
            name = self.id
        elif where == 'minigame':
            name = 'Minigame'
        elif where == 'street':
            name = CIGlobals.BranchZone2StreetName[ZoneUtil.getBranchZone(
                zoneID)]
        if loaderName == 'safeZoneLoader' or loaderName == 'townLoader':
            if not loader.inBulkBlock:
                loader.beginBulkLoad(
                    'hood', name, CIGlobals.safeZoneLSRanges.get(self.id, 6))
            self.loadLoader(requestStatus)
        else:
            base.transitions.fadeScreen(1.0)

        self._quietZoneDoneEvent = uniqueName('quietZoneDone')
        self.acceptOnce(self._quietZoneDoneEvent, self.handleQuietZoneDone)
        self.quietZoneStateData = QuietZoneState(self._quietZoneDoneEvent)
        self.quietZoneStateData.load()
        self.quietZoneStateData.enter(requestStatus)

    def exitQuietZone(self):
        self.ignore(self._quietZoneDoneEvent)
        del self._quietZoneDoneEvent
        self.quietZoneStateData.exit()
        self.quietZoneStateData.unload()
        self.quietZoneStateData = None
        return

    def loadLoader(self, requestStatus):
        pass

    def handleQuietZoneDone(self):
        status = self.quietZoneStateData.getDoneStatus()
        loader.endBulkLoad('hood')
        self.fsm.request(status['loader'], [status])
        if hasattr(self, 'loader'):
            self.loader.enterThePlace(status)

    def enterSafeZoneLoader(self, requestStatus):
        self.accept(self.loaderDoneEvent, self.handleSafeZoneLoaderDone)
        self.loader.enter(requestStatus)
        self.spawnTitleText(requestStatus['zoneId'])

    def exitSafeZoneLoader(self):
        self.ignore(self.loaderDoneEvent)
        self.hideTitleText()
        self.loader.exit()
        self.loader.unload()
        del self.loader

    def handleSafeZoneLoaderDone(self):
        doneStatus = self.loader.getDoneStatus()
        if self.isSameHood(doneStatus) or doneStatus['where'] == 'minigame':
            self.fsm.request('quietZone', [doneStatus])
        else:
            self.doneStatus = doneStatus
            messenger.send(self.doneEvent)

    def createNormalSky(self):
        self.deleteCurrentSky()
        self.sky = loader.loadModel(self.skyFilename)
        if self.__class__.__name__ != 'CTHood':
            self.sky.setScale(1.0)
            self.sky.setFogOff()
        else:
            self.sky.setScale(5.0)

    def createSpookySky(self):
        self.deleteCurrentSky()
        self.sky = loader.loadModel(self.spookySkyFile)
        self.sky.setScale(5.0)
        self.sky.setFogOff()

    def deleteCurrentSky(self):
        if hasattr(self, 'sky'):
            if self.sky:
                self.sky.removeNode()
                del self.sky

    def startSuitEffect(self):
        self.stopSuitEffect()
        light = AmbientLight("suitLight")
        light.setColor(Vec4(*self.suitLightColor))
        self.suitLight = render.attachNewNode(light)
        render.setLight(self.suitLight)
        self.suitFog = Fog("suitFog")
        self.suitFog.setColor(*self.suitFogData[0])
        self.suitFog.setExpDensity(self.suitFogData[1])
        render.setFog(self.suitFog)
        self.createSpookySky()
        Hood.startSky(self)

    def stopSuitEffect(self, newSky=1):
        render.clearFog()
        if self.suitLight:
            render.clearLight(self.suitLight)
            self.suitLight.removeNode()
            self.suitLight = None
        if self.suitFog:
            self.suitFog = None
        if newSky:
            if not base.cr.holidayManager.getHoliday(
            ) == HolidayType.CHRISTMAS:
                self.createNormalSky()
            else:
                self.createSpookySky()
            self.startSky()

    def startSky(self):
        self.sky.reparentTo(camera)
        self.sky.setZ(0.0)
        self.sky.setHpr(0.0, 0.0, 0.0)
        ce = CompassEffect.make(NodePath(),
                                CompassEffect.PRot | CompassEffect.PZ)
        self.sky.node().setEffect(ce)

    def stopSky(self):
        self.sky.reparentTo(hidden)
コード例 #6
0
class SMWorld(DirectObject):

	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Constructor
	# (Game state, Map name, Height of death plane)
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def __init__(self, mapID, tObj, aObj):

		self.mapID = mapID
		
		# EX: maps/map-1/map-1.yetimap
		metaFile = open("../maps/map" + str(self.mapID) + "/map" + str(self.mapID) + ".yetimap", 'r')
		metaLines = metaFile.readlines()
		lineCount = len(metaLines)
		self.snowflakeCount = lineCount - 2
		self.snowCount = 0
		
		# First Line: Player's starting position
		# EX: 50,50,50 (NO SPACES)
		playerLine = metaLines[0]
		playerPosList = playerLine.split(",")
		playerInitX = int(playerPosList[0])
		playerInitY = int(playerPosList[1])
		playerInitZ = int(playerPosList[2])
		self.playerStart = Point3(playerInitX, playerInitY, playerInitZ)
		
		# 2nd Line: Deathzone Height
		# ONE INTEGER
		self.deathHeight = int(metaLines[1])
		
		# Get dem snowflakes
		self.snowflakePositions = []
		print("Snowflake Count: " + str(self.snowflakeCount))
		for i in xrange(0, self.snowflakeCount):
			sfline = metaLines[i+2]
			sfList = sfline.split(",")
			sfx = int(sfList[0])
			sfy = int(sfList[1])
			sfz = int(sfList[2])
			self.snowflakePositions.append(Point3(sfx, sfy, sfz))
			print("New snowflake to add: (" + str(sfx) + "," + str(sfy) + "," + str(sfz) + ")")

		#load in controls
		ctrlFl = open("ctrConfig.txt")
		#will skip n lines where [n,]
		#makes a list of controls
		self.keymap = eval(ctrlFl.read())
		#close file
		ctrlFl.close()
		
		# Create new instances of our various objects
		self.mapName = str(mapID)
		self.audioMgr = aObj
		self.worldObj = self.setupWorld()
		self.heightMap = self.setupHeightmap(self.mapName)
		self.deathZone = self.setupDeathzone(self.deathHeight)
		self.debugNode = self.setupDebug()	
		
		# Player Init
		self.playerObj = SMPlayer(self.worldBullet, self.worldObj, self, self.playerStart, self.audioMgr)
		self.playerNP = self.playerObj.getNodePath()
		self.playerNP.setH(180);
		self.canUseShift = True
		self.canAirDash = True
		
		# Snowball Init
		self.ballObj = SMBall(self.worldBullet, self.worldObj, self.playerObj, self.playerNP)
		self.sbCollideFlag = False
		self.ballNP = self.ballObj.getNodePath()
		
		# Key Handler
		self.kh = SMKeyHandler()
		self.lastMousePos = self.kh.getMouse()
		
		# Collision Handler
		self.colObj = self.setupCollisionHandler()
		
		# Lighting
		self.ligObj = SMLighting(Vec4(.4, .4, .4, 1), Vec3(-5, -5, -5), Vec4(2.0, 2.0, 2.0, 1.0))
		
		# Camera
		self.camObj = SMCamera(self.playerObj, self.worldBullet, self.worldObj)
		self.cameraControl = False

		# GUI
		self.GUI = SMGUI()
		self.snowflakeCounter = SMGUICounter("snowflake", self.snowflakeCount) # Replace 3 with # of snowflakes in level.
		self.snowMeter = SMGUIMeter(100)
		self.GUI.addElement("snowflake", self.snowflakeCounter)
		self.GUI.addElement("snowMeter", self.snowMeter)
		
		#Snowy Outside
		# base.enableParticles()
		# self.p = ParticleEffect()
		# self.p.cleanup()
		# self.p = ParticleEffect()
		# self.p.loadConfig('snow.ptf')        
		# self.p.start(self.camObj.getNodePath())
		# self.p.setPos(0.00, 0.500, 0.000)

		# AI
		# self.goat1 = SMAI("../res/models/goat.egg", 75.0, self.worldBullet, self.worldObj, -70, -95, 5)
		# self.goat1.setBehavior("flee", self.playerNP)
		# self.goat2 = SMAI("../res/models/goat.egg", 75.0, self.worldBullet, self.worldObj, -80, -83, 5)
		# self.goat2.setBehavior("flee", self.playerNP)
		# print("AI Initialized")
		
		# Debug Text
		self.textObj = tObj
		self.textObj.addText("yetiPos", "Position: ")
		self.textObj.addText("yetiVel", "Velocity: ")
		self.textObj.addText("yetiFric", "Friction: ")
		self.textObj.addText("onIce", "Ice(%): ")
		self.textObj.addText("onSnow", "Snow(%): ")
		self.textObj.addText("terrHeight", "T Height: ")
		self.textObj.addText("terrSteepness", "Steepness: ")
		
		# Pause screen transition
		self.transition = Transitions(loader)

		# Method-based keybindings
		# self.accept('b', self.spawnBall)
		self.accept('escape', base.userExit)
		self.accept('enter', self.pauseUnpause)
		self.accept('f1', self.toggleDebug)
		
		self.accept('lshift-up', self.enableShiftActions)
		self.accept('mouse1', self.enableCameraControl)
		self.accept('mouse1-up', self.disableCameraControl)
		self.accept('wheel_up', self.camObj.zoomIn)
		self.accept('wheel_down', self.camObj.zoomOut)
		
		self.pauseUnpause()
		
		# Disable the mouse
		base.disableMouse()
		props = WindowProperties()
		props.setCursorHidden(True)
		base.win.requestProperties(props)
		
		# Uncomment this to see everything being rendered.
		self.printSceneGraph()
		
		# Play the BGM
		self.audioMgr.playBGM("snowmanWind")
		
		# Skybox formed
		skybox = loader.loadModel("../res/models/skybox.egg")
		# skybox.set_two_sided(true)
		skybox.setScale(500)
		skybox.setPos(0, 0, -450)
		skybox.reparentTo(render)
		
		mountain = loader.loadModel("../res/models/mountain.egg")
		mountain.reparentTo(render)
		mountain.setPos(650,800,20)
		mountain.setScale(120)
		
		self.colObjects = []
		
		self.caveNew = SMCollide("../res/models/cave_new.egg", self.worldBullet, self.worldObj, Point3(-50, 95, -13), 11, Vec3(0,0,0))
		self.colObjects.append(self.caveNew)
		
		self.planeFront = SMCollide("../res/models/plane_front", self.worldBullet, self.worldObj, Point3(190, -100, -15), 8, Vec3(190,0,30))
		self.colObjects.append(self.planeFront)
		
		self.caveModel = SMCollide("../res/models/cave_tunnel.egg", self.worldBullet, self.worldObj, Point3(233, 68, 32), 4, Vec3(135,180,0))
		self.colObjects.append(self.caveModel)
		
		self.planeTail = SMCollide("../res/models/plane_tail.egg", self.worldBullet, self.worldObj, Point3(-40, -130, -7), 10, Vec3(230,0,0))
		self.colObjects.append(self.planeTail)
		
		self.ropeBridge = SMCollide("../res/models/rope_bridge.egg", self.worldBullet, self.worldObj, Point3(180, 115, 30), 6, Vec3(50,0,0))
		self.colObjects.append(self.ropeBridge)
		
		self.colObjectCount = len(self.colObjects)
		
		print("World initialized.")


	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Enables the camera to be rotated by moving the mouse horizontally.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def enableCameraControl(self):
		self.cameraControl = True
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Disables the camera control.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def disableCameraControl(self):
		self.cameraControl = False
		
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Enables the use of shift actions again.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def enableShiftActions(self):
		self.canUseShift = True
		
	def disableShiftActions(self):
		self.canUseShift = False
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Respawns the yeti's snowball.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
		
	def spawnBall(self):
		if(not(self.playerObj.getAirborneFlag())):
			self.ballObj.respawn()
		
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Toggles the pause screen
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def pauseUnpause(self):
		if taskMgr.hasTaskNamed('UpdateTask'):
			taskMgr.remove('UpdateTask')
			self.transition.fadeScreen(0.5)
		else:
			taskMgr.add(self.update, 'UpdateTask')
			self.transition.noFade()
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Sets up the world and returns a NodePath of the BulletWorld
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def setupWorld(self):
		self.worldBullet = BulletWorld()
		self.worldBullet.setGravity(Vec3(0, 0, -GRAVITY))
		self.terrSteepness = -1
		wNP = render.attachNewNode('WorldNode')
		
		self.audioMgr.loadSFX("snowCrunch01")
		self.audioMgr.loadBGM("snowmanWind")
		
		return wNP
		
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Prints all nodes that are a child of render.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def printSceneGraph(self):
		print(render.ls())
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Initializes and returns a DebugNode NodePath.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def setupDebug(self):
		debug = BulletDebugNode()
		debug.showWireframe(False) # Yeah, don't set this to true unless you want to emulate an 80's computer running Crysis on Ultra settings.
		debug.showConstraints(True)
		debug.showBoundingBoxes(True) # This is the main use I have for it.
		debug.showNormals(True)
		debugNP = render.attachNewNode(debug)
		self.worldBullet.setDebugNode(debugNP.node())
		debugNP.hide()
		return debugNP
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Initializes and returns a BulletRigidBodyNode of the terrain, which loads the map with the specified name.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def setupHeightmap(self, name):
		
		# Automatically generate a heightmap mesh from a monochrome image.
		self.hmHeight = 120
		hmPath = "../maps/map" + name + "/map" + name + "-h.png"
		imPath = "../maps/map" + name + "/map" + name + "-i.png"
		smPath = "../maps/map" + name + "/map" + name + "-s.png"
		scmPath = "../maps/map" + name + "/map" + name + "-sc.png"
		print(hmPath)
		print(imPath)
		print(smPath)
		print(scmPath)
		hmImg = PNMImage(Filename(hmPath))
		hmShape = BulletHeightfieldShape(hmImg, self.hmHeight, ZUp)
		hmNode = BulletRigidBodyNode('Terrain')
		hmNode.addShape(hmShape)
		hmNode.setMass(0)
		self.hmNP = render.attachNewNode(hmNode)
		self.worldBullet.attachRigidBody(hmNode)
		self.hmOffset = hmImg.getXSize() / 2.0 - 0.5
		self.hmTerrain = GeoMipTerrain('gmTerrain')
		self.hmTerrain.setHeightfield(hmImg)
		
		# Optimizations and fixes
		self.hmTerrain.setBruteforce(True) # I don't think this is actually needed. 
		self.hmTerrain.setMinLevel(3) # THIS is what triangulates the terrain.
		self.hmTerrain.setBlockSize(128)  # This does a pretty good job of raising FPS.
		# Level-of-detail (not yet working)
		# self.hmTerrain.setNear(40)
		# self.hmTerrain.setFar(200)
		
		self.hmTerrain.generate()
		
		self.hmTerrainNP = self.hmTerrain.getRoot()
		self.hmTerrainNP.setSz(self.hmHeight)
		self.hmTerrainNP.setPos(-self.hmOffset, -self.hmOffset, -self.hmHeight / 2.0)
		self.hmTerrainNP.flattenStrong() # This only reduces the number of nodes; nothing to do with polys.
		self.hmTerrainNP.analyze()

		# Here begins the scenery mapping
		treeModel = loader.loadModel("../res/models/tree_1.egg")
		rockModel = loader.loadModel("../res/models/rock_1.egg")
		rock2Model = loader.loadModel("../res/models/rock_2.egg")
		rock3Model = loader.loadModel("../res/models/rock_3.egg")
		# caveModel = loader.loadModel("../res/models/cave_new.egg")
		# planeFrontModel = loader.loadModel("../res/models/plane_front.egg")
		# planeWingModel = loader.loadModel("../res/models/plane_wing.egg")
		texpk = loader.loadTexture(scmPath).peek()
		
		# GameObject nodepath for flattening
		self.objNP = render.attachNewNode("gameObjects")
		self.treeNP = self.objNP.attachNewNode("goTrees")
		self.rockNP = self.objNP.attachNewNode("goRocks")
		self.rock2NP = self.objNP.attachNewNode("goRocks2")
		self.rock3NP = self.objNP.attachNewNode("goRocks3")
		# self.caveNP = self.objNP.attachNewNode("goCave")
		# self.planeFrontNP = self.objNP.attachNewNode("goPlaneFront")
		# self.planeWingNP = self.objNP.attachNewNode("goPlaneWing")
		
		for i in range(0, texpk.getXSize()):
			for j in range(0, texpk.getYSize()):
				color = VBase4(0, 0, 0, 0)
				texpk.lookup(color, float(i) / texpk.getXSize(), float(j) / texpk.getYSize())
				if(int(color.getX() * 255.0) == 255.0):
					newTree = self.treeNP.attachNewNode("treeNode")
					treeModel.instanceTo(newTree)
					newTree.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
					# newTree.setScale(randint(0,4))
					newTree.setScale(2)
					
				if(int(color.getX() * 255.0) == 128):
					newRock = self.rockNP.attachNewNode("newRock")
					newRock.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
					rockModel.instanceTo(newRock)
					
				if(int(color.getX() * 255.0) == 77):
					newRock2 = self.rock2NP.attachNewNode("newRock2")
					newRock2.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
					rock2Model.instanceTo(newRock2)
					
				if(int(color.getX() * 255.0) == 102):
					newRock3 = self.rock3NP.attachNewNode("newRock3")
					newRock3.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
					rock3Model.instanceTo(newRock3)
					
				# if(int(color.getX() * 255.0) == 64):
					# newCave = self.caveNP.attachNewNode("newCave")
					# newCave.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
					# newCave.setScale(5)
					# newCave.setP(180)
					# caveModel.instanceTo(newCave)
				
				# if(int(color.getX() * 255.0) == 191):
					# newPlaneFront = self.planeFrontNP.attachNewNode("newPlaneFront")
					# newPlaneFront.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
					# newPlaneFront.setScale(6)
					# planeFrontModel.instanceTo(newPlaneFront)
					
				# if(int(color.getX() * 255.0) == 179):
					# newPlaneWing = self.planeWingNP.attachNewNode("newPlaneWing")
					# newPlaneWing.setPos(i - texpk.getXSize() / 2, j - texpk.getYSize() / 2, self.hmTerrain.get_elevation(i, j) * self.hmHeight - self.hmHeight / 2)
					# newPlaneWing.setScale(6)
					# newPlaneWing.setH(250)
					# newPlaneWing.setR(180)
					# newPlaneWing.setP(135)
					# planeWingModel.instanceTo(newPlaneWing)

		self.snowflakes = []
		
		for i in xrange(0, self.snowflakeCount):
			print("Call " + str(i))
			sf = SMCollect(self.worldBullet, self.worldObj, self.snowflakePositions[i])
			self.snowflakes.append(sf)
					
		# render.flattenStrong()
		self.hmTerrainNP.reparentTo(render)
		
		# Here begins the attribute mapping
		ts = TextureStage("stage-alpha")
		ts.setSort(0)
		ts.setPriority(1)
		ts.setMode(TextureStage.MReplace)
		ts.setSavedResult(True)
		self.hmTerrainNP.setTexture(ts, loader.loadTexture(imPath, smPath))

		ts = TextureStage("stage-stone")
		ts.setSort(1)
		ts.setPriority(1)
		ts.setMode(TextureStage.MReplace)
		self.hmTerrainNP.setTexture(ts, loader.loadTexture("../res/textures/stone_tex.png"))
		self.hmTerrainNP.setTexScale(ts, 32, 32)

		ts = TextureStage("stage-ice")
		ts.setSort(2)
		ts.setPriority(1)
		ts.setCombineRgb(TextureStage.CMInterpolate, TextureStage.CSTexture, TextureStage.COSrcColor,
						 TextureStage.CSPrevious, TextureStage.COSrcColor,
						 TextureStage.CSLastSavedResult, TextureStage.COSrcColor)
		self.hmTerrainNP.setTexture(ts, loader.loadTexture("../res/textures/ice_tex.png"))
		self.hmTerrainNP.setTexScale(ts, 32, 32)

		ts = TextureStage("stage-snow")
		ts.setSort(3)
		ts.setPriority(0)
		ts.setCombineRgb(TextureStage.CMInterpolate, TextureStage.CSTexture, TextureStage.COSrcColor,
						 TextureStage.CSPrevious, TextureStage.COSrcColor,
						 TextureStage.CSLastSavedResult, TextureStage.COSrcAlpha)
		self.hmTerrainNP.setTexture(ts, loader.loadTexture("../res/textures/snow_tex_1.png"))
		self.hmTerrainNP.setTexScale(ts, 32, 32)

		# print(self.snowflakes)
		
		return hmNode
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Sets up and returns the death zone plane (returns its NodePath) with the specified height.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def setupDeathzone(self, height):
		planeShape = BulletPlaneShape(Vec3(0, 0, 1), 1)
		planeNode = BulletRigidBodyNode('DeathZone')
		planeNode.addShape(planeShape)
		planeNP = render.attachNewNode(planeNode)
		planeNP.setPos(0, 0, height)
		self.worldBullet.attachRigidBody(planeNode)
		return planeNP
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Sets up and returns the collision handler.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def setupCollisionHandler(self):
		colHand = SMCollisionHandler(self.worldBullet)
		return colHand
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Toggles showing bounding boxes.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def toggleDebug(self):
		if self.debugNode.isHidden():
			self.debugNode.show()
		else:
			self.debugNode.hide()
	
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Returns the terrain height of the nearest vertical descending raycast from the passed Point3.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def getTerrainHeight(self, pos):
		result = 0
		x = pos.getX()
		y = pos.getY()
		z = pos.getZ()
		rayTerrA = Point3(x, y, z)
		rayTerrB = Point3(x, y, z - 256)
		rayTest = self.worldBullet.rayTestClosest(rayTerrA, rayTerrB)
		
		rayNode = rayTest.getNode()
		if (rayTest.hasHit()):
			rayPos = rayTest.getHitPos()
			result = rayPos.getZ()
		else:
			self.playerObj.respawn()
		return result
		# return self.hmTerrain.get_elevation(x + self.hmOffset, y + self.hmOffset) * self.hmHeight
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Handles player movement
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def playerMove(self):
	
		# Go through the collision and flag tests, and update them
		self.doPlayerTests()
		
		# Rotation and camera movement
		if self.kh.poll(self.keymap['Left']):
			self.playerObj.turn(True)
		elif self.kh.poll(self.keymap['Right']):
			self.playerObj.turn(False)
		elif(self.cameraControl):
			newMousePos = self.kh.getMouse()
			mx = newMousePos.getX()
			self.camObj.rotateCamera(mx)
		
		self.camObj.calculatePosition()
		
		# Movement
		if self.kh.poll(self.keymap['Forward']):
			self.playerObj.move(True)
			self.camObj.rotateTowards(90)
		elif self.kh.poll(self.keymap['Back']):

			self.playerObj.move(False)
		else:
			self.playerObj.stop()

		# Jump
		if(self.kh.poll(self.keymap['Space']) and self.terrSteepness < 0.25): #and not(self.ballObj.isRolling())):
			self.playerObj.jump()
		else:
			self.playerObj.resetJump()
		
		# Air Dash
		if(self.kh.poll(self.keymap['airDash'])): #and self.playerObj.getAirborneFlag() == True and self.canAirDash == True):
			self.canAirDash = False
			self.playerObj.airDash()
		
		# Shift-based actions
		if(self.kh.poll("lshift") and not(self.sbCollideFlag) and not(self.playerObj.getAirborneFlag()) and self.canUseShift):
		
			# If there's another snowball already placed
			if(self.ballObj.exists() and not(self.ballObj.isRolling())):
				self.ballObj.respawn()
				
			# If we're rolling a snowball
			elif(self.ballObj.isRolling()):
			
				# Absorb snowball
				if(self.kh.poll("v")):
					self.canUseShift = False
					snowAmt = self.ballObj.getSnowAmount()
					self.playerObj.addSnow(snowAmt)
					# self.snowMeter.fillBy(snowAmt)
					self.ballObj.destroy()
					
				# Go to iceball throwing mode
				elif(self.kh.poll("b")):
					print("TODO: Ice ball throwing mode.")
					
				# Grow the snowball
				elif(self.kh.poll("w")):
					self.ballObj.grow()
					
			# Spawn a new snowball
			elif(self.ballObj.exists() == False):
				self.ballObj.respawn()
				
		# If the player is not pressing shift
		else:
			if(self.ballObj.isRolling()):
				self.ballObj.dropBall()

		base.win.movePointer(0, 400, 300)
		
		# So updating the stats is VERY expensive.
		if (self.debugNode.isHidden() == False):
			self.updateStats()
	
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Various tests concerning the player flags and collisions.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def doPlayerTests(self):
		
		# Player's position
		plPos = self.playerObj.getPosition()
		px = plPos.getX()
		py = plPos.getY()
		pz = plPos.getZ()
		
		# Raycast directly down for terrain steepness
		rayYetiA = Point3(px, py, pz)
		rayYetiB = Point3(px, py, pz - 300)
		self.downRayTest = self.worldBullet.rayTestClosest(rayYetiA, rayYetiB).getHitNormal()
		rx = self.downRayTest.getX()
		ry = self.downRayTest.getY()
		rz = self.downRayTest.getZ()
		self.terrSteepness = 1.0 - rz

		# Redo collision flags later
		objCollisionFlag = False
		
		# Snow/Ice height adjust
		self.playerObj.updateTerrain()
		
		# Collision: Player x Objects
		for i in xrange(0, self.colObjectCount):
			if(self.colObj.didCollide(self.playerNP.node(), self.colObjects[i].AINode)):
				objCollisionFlag = True
				self.playerObj.setAirborneFlag(False)
				self.canAirDash = True
				self.playerObj.setFactor(1,1,1)
		
		# Collision: Player x Snowball
		if(self.ballObj.exists() and self.colObj.didCollide(self.playerNP.node(), self.ballObj.getRigidbody())):
			self.sbCollideFlag = True
			self.playerObj.setAirborneFlag(False)
			self.playerObj.setFactor(1, 1, 1)
		else:
			self.sbCollideFlag = False
		
		# Collision: Player x Terrain
		if(self.colObj.didCollide(self.playerNP.node(), self.heightMap)):
			if(self.playerObj.getAirborneFlag()):
				self.audioMgr.playSFX("snowCrunch01")
			self.playerObj.setAirborneFlag(False)
			self.canAirDash = True
			self.playerObj.setFactor(1, 1, 1)
			objCollisionFlag = False
			
		# Collision: Player x Death Zone
		# if(pz - 7 <= self.deathHeight or (self.colObj.didCollide(self.playerNP.node(), self.deathZone.node()))):
		if(self.colObj.didCollide(self.playerNP.node(), self.deathZone.node())):
			print("Player confirmed #REKT")
			self.playerObj.respawn()
		
		# Out of bounds checking
		if(abs(px) > 254 or abs(py) > 254):
			print("Player out of bounds!")
			self.playerObj.respawn()
		
		# Snap to terrain if... something. I need to restructure this. Don't read it.
		if(not(self.playerObj.getAirborneFlag()) and not(self.sbCollideFlag) and not(objCollisionFlag)):
			z = self.getTerrainHeight(Point3(px, py, pz))
			self.playerObj.snapToTerrain(z)
			# self.playerObj.snapToTerrain(th, self.hmHeight)
		
		# Collision: Player x Snowflakes
		for i in xrange(0, self.snowflakeCount):
			if(self.snowflakes[i].exists() and self.colObj.didCollide(self.playerNP.node(), self.snowflakes[i].getNode())):
				self.snowflakes[i].destroy()
				self.snowflakeCounter.increment()
				self.snowCount += 1
			
		self.snowMeter.updateSnow(self.playerObj)
		
		#Check if there is a "next" level. If there is, load it. Otherwise display end game screen.
		if(self.snowCount >= self.snowflakeCount):
			file_path="../maps/map" + str(self.mapID+1) + "/map" + str(self.mapID+1) + ".yetimap"
			if  os.path.lexists(file_path):
			
				self.snowCount = 0
				self.snowflakeCount = 0
				self.snowflakeCounter.setValue(0)
				self.snowflakeCounter.setState(2)
				
				#Loading Screen
				self.transition.fadeScreen(0.7)	
				self.loadingText=OnscreenText("Loading...",1,fg=(1,1,1,0),pos=(0,0),align=TextNode.ACenter,scale=.07,mayChange=1)
				base.graphicsEngine.renderFrame() 
				base.graphicsEngine.renderFrame() 
				base.graphicsEngine.renderFrame() 
				base.graphicsEngine.renderFrame()
				self.transition.noFade()
				
				#destroy objects
				self.worldBullet.removeRigidBody(self.heightMap)
				self.hmTerrainNP.removeNode()
				self.objNP.removeNode()
				self.treeNP.removeNode()
				self.rockNP.removeNode()
				self.rock2NP.removeNode()
				self.rock3NP.removeNode()
				# self.caveNP.removeNode()
				# self.planeFrontNP.removeNode()
				# self.planeWingNP.removeNode()
				self.hmNP.removeNode()
				if(int(self.mapID) == 1):
					self.ropeBridge.AIChar.setPos(-200,-300,-200)
					# self.ropeBridge.AIChar.removeNode()
					self.planeFront.AIChar.removeNode()
					self.planeTail.AIChar.setPos(-200,-200,-200)
					# self.planeTail.AIChar.removeNode()
					self.caveNew.AIChar.setPos(-1000,-1000,-1000);
					self.caveModel.AIChar.removeNode()
					#Added More Props here!
					self.boulder = SMCollide("../res/models/rock_3.egg", self.worldBullet, self.worldObj, Point3(117, 123, 17), 15, Vec3(0,0,0))
				elif(int(self.mapID) == 2):
					self.boulder.AIChar.setPos(-222,-222,-222)
					self.caveNew.AIChar.setScale(150)
					self.caveNew.AIChar.setPos(-50, 95, -50)
					# self.skybox.setScale(600)
					# self.caveNew.setH(0)
					# self.boulder.removeNode()
			
				self.mapID += 1
				print self.mapID
				# EX: maps/map-1/map-1.yetimap
				metaFile = open("../maps/map" + str(self.mapID) + "/map" + str(self.mapID) + ".yetimap", 'r')
				metaLines = metaFile.readlines()
				lineCount = len(metaLines)
				self.snowflakeCount = lineCount - 2
			
				# First Line: Player's starting position
				# EX: 50,50,50 (NO SPACES)
				playerLine = metaLines[0]
				playerPosList = playerLine.split(",")
				playerInitX = int(playerPosList[0])
				playerInitY = int(playerPosList[1])
				playerInitZ = int(playerPosList[2])
				self.playerObj.playerNP.setPos(playerInitX, playerInitY, playerInitZ)
				self.playerObj.startX = playerInitX
				self.playerObj.startY = playerInitY
				self.playerObj.startZ = playerInitZ
			
				# 2nd Line: Deathzone Height
				# ONE INTEGER
				self.deathHeight = int(metaLines[1])
			
				
				self.snowflakePositions = []
				print("Snowflake Count: " + str(self.snowflakeCount))
				for i in xrange(0, self.snowflakeCount):
					sfline = metaLines[i+2]
					sfList = sfline.split(",")
					sfx = int(sfList[0])
					sfy = int(sfList[1])
					sfz = int(sfList[2])
					self.snowflakePositions.append(Point3(sfx, sfy, sfz))
					print("New snowflake to add: (" + str(sfx) + "," + str(sfy) + "," + str(sfz) + ")")
				self.snowflakeCounter.setMaxValue(self.snowflakeCount)
				
				#load new map
				self.mapName = str(self.mapID)
				self.heightMap = self.setupHeightmap(self.mapName)
				self.deathZone = self.setupDeathzone(self.deathHeight)
					
				
				self.loadingText.cleanup() 
			else:
				taskMgr.remove('UpdateTask')
				self.endImage=OnscreenImage(image = "../res/icons/endgame1.png", pos = (0.0, 0.0, 0.0), scale = (1.35, 2, 1))
				
		
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Update the debug text.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def updateStats(self):
		pos = self.playerObj.getPosition()
		x = pos.getX()
		y = pos.getY()
		z = pos.getZ()
		vel = self.playerObj.getVelocity()
		vx = str(round(vel.getX(), 1))
		vy = str(round(vel.getY(), 1))
		vz = str(round(vel.getZ(), 1))
		sx = str(round(x, 1))
		sy = str(round(y, 1))
		sz = str(round(z, 1))
		rx = str(round(self.downRayTest.getX(), 2))
		ry = str(round(self.downRayTest.getY(), 2))
		rz = str(round(self.terrSteepness, 2))
		fric = str(round(self.playerObj.getFriction(), 2))
		ip = str(round(self.playerObj.getIceCoefficient(), 2))
		sp = str(round(self.playerObj.getSnowCoefficient(), 2))
		tHeight = str(round(self.getTerrainHeight(Point3(x, y, z)), 1))
		self.textObj.editText("yetiPos", "Position: (" + sx + ", " + sy + ", " + sz + ")")
		self.textObj.editText("yetiVel", "Velocity: (" + vx + ", " + vy + ", " + vz + ")")
		self.textObj.editText("yetiFric", "Friction: " + fric)
		self.textObj.editText("onIce", "Ice(%): " + ip)
		self.textObj.editText("onSnow", "Snow(%): " + sp)
		self.textObj.editText("terrHeight", "T Height: " + tHeight)
		self.textObj.editText("terrSteepness", "Steepness: " + rz)

	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# throw Snowball
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	def throw(self):
		self.throwing = True
		size = self.ballObj.getSize()
		#zoom camera and grab pos you wish to throw
		self.camObj.aimMode()
		taskMgr.add(self.controlCamera, "camera-task")
		rotation = self.camObj.getH()
		pitch =self.camObj.getP()
		self.ballObj.throwBall(size, pitch, rotation)
		#fix camera
		#self.throwing = False
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	# Update the world. Called every frame.
	#------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	def update(self, task):
		dt = globalClock.getDt()
		self.worldBullet.doPhysics(dt)
		# self.goat1.AIUpdate()
		# self.goat2.AIUpdate()
		self.playerMove()
		return task.cont
コード例 #7
0
ファイル: main.py プロジェクト: brianjimenez/dockit
from pandac.PandaModules import loadPrcFileData
from dockit.dockit import Dockit

width = 900
height = 600

# Change window properties
loadPrcFileData("", "window-title Dock it!")
loadPrcFileData("", "fullscreen 0")
loadPrcFileData("", "win-size %s %s" % (width, height))

import direct.directbase.DirectStart

# Set up a loading screen
from direct.gui.OnscreenText import OnscreenText,TextNode
loadingText=OnscreenText("Loading molecules...",1,fg=(1,1,1,1),
                         pos=(0,0),align=TextNode.ACenter,
                         scale=.07,mayChange=1)
# Render three frames to avoid black screen
base.graphicsEngine.renderFrame() 
base.graphicsEngine.renderFrame()
base.graphicsEngine.renderFrame()

# Load the game
dockit = Dockit(width, height, pdb_file1, pdb_file2)

# Hide loading
loadingText.cleanup() 

run()
コード例 #8
0
class Hood(StateData):
    def __init__(self, parentFSM, doneEvent, dnaStore, hoodId):
        StateData.__init__(self, doneEvent)
        self.parentFSM = parentFSM
        self.doneEvent = doneEvent
        self.dnaStore = dnaStore
        self.hoodId = hoodId
        self.abbr = ""
        self.id = None
        self.titleText = None
        self.suitFog = None
        self.suitLight = None
        self.suitLightColor = (0.4, 0.4, 0.4, 1)
        self.suitFogData = [(0.3, 0.3, 0.3), 0.0025]
        self.titleColor = (1, 1, 1, 1)

        self.wantLighting = True

        self.olc = ZoneUtil.getOutdoorLightingConfig(self.hoodId)

        return

    def makeLampLight(self, lamp):
        col = (255, 255, 255, 350)
        lightNP = CIGlobals.makePointLight(
            'DLlamp', CIGlobals.colorFromRGBScalar255(col),
            lamp.getPos(render) + (0, 0, 9.5), 0.1)
        lamp.setLightOff(1)
        return lightNP

    def enter(self, requestStatus):
        StateData.enter(self)

        hoodId = requestStatus['hoodId']
        zoneId = requestStatus['zoneId']
        rootZone = ZoneUtil.getZoneId(hoodId)
        if base.localAvatar.getLastHood(
        ) != rootZone and hoodId != ZoneUtil.MinigameArea:
            base.localAvatar.b_setLastHood(rootZone)
        if not base.localAvatar.hasDiscoveredHood(rootZone):
            hoodsDiscovered = list(base.localAvatar.getHoodsDiscovered())
            hoodsDiscovered.append(rootZone)
            base.localAvatar.b_setHoodsDiscovered(hoodsDiscovered)
        text = self.getHoodText(zoneId)
        self.titleText = OnscreenText(text,
                                      fg=self.titleColor,
                                      font=CIGlobals.getMickeyFont(),
                                      scale=0.15,
                                      pos=(0, -0.65))
        self.titleText.hide()

    def enterTheLoader(self, requestStatus):
        self.fsm.request(requestStatus['loader'], [requestStatus])

    def getHoodText(self, zoneId):
        if ZoneUtil.getWhereName(zoneId) == 'street' and zoneId < 61000:
            hoodText = ZoneUtil.BranchZone2StreetName[ZoneUtil.getBranchZone(
                zoneId)]
            hoodText += '\n' + self.id
        else:
            hoodText = self.id
            if self.id != ZoneUtil.MinigameArea:
                whereName = ZoneUtil.getWhereName(zoneId)

                if whereName == 'toonInterior':
                    whereName = 'Unknown'
                    try:
                        whereName = ZoneUtil.zone2TitleDict.get(zoneId)[0]
                        return whereName.upper() + '\n' + self.id
                    except:
                        pass

                hoodText += '\n' + whereName.upper()
        return hoodText

    def spawnTitleText(self, zoneId):
        hoodText = self.getHoodText(zoneId)
        self.doSpawnTitleText(hoodText)

    def doSpawnTitleText(self, hoodText):
        self.titleText.setText(hoodText)
        self.titleText.show()
        self.titleText.setColor(Vec4(*self.titleColor))
        self.titleText.clearColorScale()
        self.titleText.setFg(self.titleColor)
        seq = Sequence(
            Wait(0.1), Wait(6.0),
            self.titleText.colorScaleInterval(0.5, Vec4(1.0, 1.0, 1.0, 0.0)),
            Func(self.hideTitleText))
        seq.start()

    def hideTitleText(self):
        if self.titleText:
            self.titleText.hide()

    def exit(self):
        if self.titleText:
            self.titleText.cleanup()
            self.titleText = None
        StateData.exit(self)
        return

    def setupOutdoorLighting(self):
        self.olc.setup()

    def enableOutdoorLighting(self):
        self.olc.apply()

    def disableOutdoorLighting(self):
        self.olc.unapply()

    def cleanupOutdoorLighting(self):
        self.olc.cleanup()

    def load(self):
        StateData.load(self)
        if self.storageDNAFile:
            loadDNAFile(self.dnaStore, self.storageDNAFile)
        if self.holidayDNAFile:
            loadDNAFile(self.dnaStore, self.holidayDNAFile)

        self.setupOutdoorLighting()

    def unload(self):
        self.cleanupOutdoorLighting()

        if hasattr(self, 'loader'):
            self.loader.exit()
            self.loader.unload()
            del self.loader
        del self.parentFSM
        del self.fsm
        self.dnaStore.reset_nodes()
        self.dnaStore.reset_hood_nodes()
        self.dnaStore.reset_place_nodes()
        self.dnaStore.reset_hood()
        self.dnaStore.reset_fonts()
        self.dnaStore.reset_DNA_vis_groups()
        self.dnaStore.reset_materials()
        self.dnaStore.reset_block_numbers()
        self.dnaStore.reset_block_zones()
        self.dnaStore.reset_suit_points()
        del self.dnaStore
        self.ignoreAll()

        #CIGlobals.doSceneCleanup()

        StateData.unload(self)

    def enterOff(self):
        pass

    def exitOff(self):
        pass

    def isSameHood(self, status):
        return status['hoodId'] == self.hoodId and status['shardId'] is None

    def enterQuietZone(self, requestStatus):
        base.transitions.noTransitions()
        loaderName = requestStatus['loader']
        zoneID = requestStatus['zoneId']
        where = requestStatus['where']
        if where == 'playground' or where == 'toonInterior':
            name = self.id
        elif where == 'minigame':
            name = 'Minigame'
        elif where == 'street':
            name = ZoneUtil.BranchZone2StreetName[ZoneUtil.getBranchZone(
                zoneID)]
        if loaderName == 'safeZoneLoader' or loaderName == 'townLoader':
            if not loader.inBulkBlock:
                loader.beginBulkLoad('hood', name,
                                     ZoneUtil.safeZoneLSRanges.get(self.id, 6))
            self.loadLoader(requestStatus)
        else:
            base.transitions.fadeScreen(1.0)

        self._quietZoneDoneEvent = uniqueName('quietZoneDone')
        self.acceptOnce(self._quietZoneDoneEvent, self.handleQuietZoneDone)
        self.quietZoneStateData = QuietZoneState(self._quietZoneDoneEvent)
        self.quietZoneStateData.load()
        self.quietZoneStateData.enter(requestStatus)

    def exitQuietZone(self):
        self.ignore(self._quietZoneDoneEvent)
        del self._quietZoneDoneEvent
        self.quietZoneStateData.exit()
        self.quietZoneStateData.unload()
        self.quietZoneStateData = None
        return

    def loadLoader(self, requestStatus):
        pass

    def handleQuietZoneDone(self):
        status = self.quietZoneStateData.getDoneStatus()
        loader.endBulkLoad('hood')
        self.fsm.request(status['loader'], [status])
        if hasattr(self, 'loader'):
            self.loader.enterThePlace(status)

    def enterSafeZoneLoader(self, requestStatus):
        self.accept(self.loaderDoneEvent, self.handleSafeZoneLoaderDone)
        self.loader.enter(requestStatus)
        self.spawnTitleText(requestStatus['zoneId'])

    def exitSafeZoneLoader(self):
        self.ignore(self.loaderDoneEvent)
        self.hideTitleText()
        self.loader.exit()
        self.loader.unload()
        del self.loader

    def handleSafeZoneLoaderDone(self):
        doneStatus = self.loader.getDoneStatus()
        if self.isSameHood(doneStatus) or doneStatus['where'] == 'minigame':
            self.fsm.request('quietZone', [doneStatus])
        else:
            self.doneStatus = doneStatus
            messenger.send(self.doneEvent)
コード例 #9
0
ファイル: main.py プロジェクト: AspirinCode/dockit
height = 600

# Change window properties
loadPrcFileData("", "window-title Dock it!")
loadPrcFileData("", "fullscreen 0")
loadPrcFileData("", "win-size %s %s" % (width, height))

import direct.directbase.DirectStart

# Set up a loading screen
from direct.gui.OnscreenText import OnscreenText, TextNode
loadingText = OnscreenText("Loading molecules...",
                           1,
                           fg=(1, 1, 1, 1),
                           pos=(0, 0),
                           align=TextNode.ACenter,
                           scale=.07,
                           mayChange=1)
# Render three frames to avoid black screen
base.graphicsEngine.renderFrame()
base.graphicsEngine.renderFrame()
base.graphicsEngine.renderFrame()

# Load the game
dockit = Dockit(width, height, pdb_file1, pdb_file2)

# Hide loading
loadingText.cleanup()

run()
コード例 #10
0
ファイル: test.py プロジェクト: ENJ1/PandaFPSController
class MyApp(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        # enable physics engine
        self.enableParticles()

        # take care of cursor shit
        self.resetCursor()

        # set up loading screen
        self.loadingText = OnscreenText("Loading...",
                                        1,
                                        fg=(1, 1, 1, 1),
                                        pos=(0, 0),
                                        align=TextNode.ACenter,
                                        scale=.07,
                                        mayChange=1)
        self.graphicsEngine.renderFrame(
        )  #render a frame otherwise the screen will remain black
        self.graphicsEngine.renderFrame()  #idem dito
        self.graphicsEngine.renderFrame(
        )  #you need to do this because you didn't yet call run()
        self.graphicsEngine.renderFrame(
        )  #run() automatically renders the frames for you

        # get menu background music playing
        self.loadingText.setText('Loading models/audio/sfx/menu_music.ogg')
        self.graphicsEngine.renderFrame(
        )  #render a frame otherwise the screen will remain black
        self.graphicsEngine.renderFrame()  #idem dito
        self.graphicsEngine.renderFrame(
        )  #you need to do this because you didn't yet call run()
        self.graphicsEngine.renderFrame(
        )  #run() automatically renders the frames for you
        menuMusic = self.loader.loadSfx("models/audio/sfx/menu_music.ogg")
        menuMusic.setLoop(True)
        menuMusic.play()

        # set title window
        props = WindowProperties()
        props.setTitle('Tokoyo Ghoul')
        self.win.requestProperties(props)

        # Load the environment model.
        self.loadingText.setText('Loading models/environment.egg.pz')
        self.setBackgroundColor((0, 1, 1, .5))
        self.graphicsEngine.renderFrame(
        )  #render a frame otherwise the screen will remain black
        self.graphicsEngine.renderFrame()  #idem dito
        self.graphicsEngine.renderFrame(
        )  #you need to do this because you didn't yet call run()
        self.graphicsEngine.renderFrame(
        )  #run() automatically renders the frames for you
        self.scene = self.loader.loadModel("models/output.bam")
        # Reparent the model to render.
        self.scene.reparentTo(self.render)
        # Apply scale and position transforms on the model.
        self.scene.setScale(0.15, 0.15, 0.15)
        self.scene.setPos(0, 0, 0)
        # Add the spinCameraTask procedure to the task manager.
        self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")

        # add fog and such
        #myFog = Fog("titlefog")
        #myFog.setColor((1,0,0,0.1))
        #myFog.setExpDensity(0.3)
        #self.render.setFog(myFog)

        # Load and transform the didicus actor.
        #self.pandaActor = Actor("models/camera",
        #{"walk": "models/panda-walk4"})
        self.loadingText.setText('Loading models/african.x')
        self.graphicsEngine.renderFrame(
        )  #render a frame otherwise the screen will remain black
        self.graphicsEngine.renderFrame()  #idem dito
        self.graphicsEngine.renderFrame(
        )  #you need to do this because you didn't yet call run()
        self.graphicsEngine.renderFrame(
        )  #run() automatically renders the frames for you
        self.pandaActor = Actor("models/camera")
        self.pandaActor.setPos(10, -10, 5)
        self.pandaActor.setScale(0.5, 0.5, 0.5)
        self.pandaActor.reparentTo(self.render)
        # Loop its animation.
        #self.pandaActor.loop("walk")
        # Create the four lerp intervals needed for the panda to
        # walk back and forth.
        pandaPosInterval1 = self.pandaActor.posInterval(13,
                                                        Point3(-10, -10, 5),
                                                        startPos=Point3(
                                                            0, 0, 5))
        pandaPosInterval2 = self.pandaActor.posInterval(13,
                                                        Point3(0, 0, 5),
                                                        startPos=Point3(
                                                            -10, -10, 5))
        pandaHprInterval1 = self.pandaActor.hprInterval(3,
                                                        Point3(180, 0, 0),
                                                        startHpr=Point3(
                                                            0, 0, 0))
        pandaHprInterval2 = self.pandaActor.hprInterval(3,
                                                        Point3(0, 0, 0),
                                                        startHpr=Point3(
                                                            180, 0, 0))

        # Create and play the sequence that coordinates the intervals.
        self.pandaPace = Sequence(pandaPosInterval1,
                                  pandaHprInterval1,
                                  pandaPosInterval2,
                                  pandaHprInterval2,
                                  name="pandaPace")
        self.pandaPace.loop()

        # Make the menu options
        # Create a frame
        self.startgamebutton = DirectButton(pos=(1, 0, -0.6),
                                            text=("Play"),
                                            scale=.1,
                                            command=self.startGame)
        self.exitbutton = DirectButton(pos=(1, 0, -0.74),
                                       text=("Exit"),
                                       scale=.1,
                                       command=self.close)

        # load the title image
        self.loadingText.setText('Loading images/title.png')
        self.graphicsEngine.renderFrame(
        )  #render a frame otherwise the screen will remain black
        self.graphicsEngine.renderFrame()  #idem dito
        self.graphicsEngine.renderFrame(
        )  #you need to do this because you didn't yet call run()
        self.graphicsEngine.renderFrame(
        )  #run() automatically renders the frames for you

        # clean up loading screen
        self.loadingText.cleanup()

    # Define a procedure to move the camera.
    def spinCameraTask(self, task):
        angleDegrees = task.time * 6.0
        angleRadians = angleDegrees * (pi / 180.0)
        self.camera.setPos(75 * sin(angleRadians), -75 * cos(angleRadians), 20)
        #self.camera.setPos(0, 0, 20)
        self.camera.setHpr(angleDegrees, -10, 0)
        return Task.cont

    # Callback function to set text
    def startGame(self):
        print("starting game")
        # clear everything on the menu
        self.scene.removeNode()
        self.startgamebutton.removeNode()
        self.exitbutton.removeNode()

        # set cursor for first person shit
        self.disableMouse()
        #self.cursorShit()

        # load the new place
        # Load the environment model.
        self.loadingText = OnscreenText("Loading...",
                                        1,
                                        fg=(1, 1, 1, 1),
                                        pos=(0, 0),
                                        align=TextNode.ACenter,
                                        scale=.07,
                                        mayChange=1)
        self.loadingText.setText('Loading models/environment.egg.pz')
        self.setBackgroundColor((0, 0, 0))
        self.graphicsEngine.renderFrame(
        )  #render a frame otherwise the screen will remain black
        self.graphicsEngine.renderFrame()  #idem dito
        self.graphicsEngine.renderFrame(
        )  #you need to do this because you didn't yet call run()
        self.graphicsEngine.renderFrame(
        )  #run() automatically renders the frames for you
        self.scene = self.loader.loadModel("models/output.bam")
        # Reparent the model to render.
        self.scene.reparentTo(self.render)
        # Apply scale and position transforms on the model.
        self.scene.setScale(1, 1, 1)
        self.scene.setPos(0, 0, 0)
        # clean up loading screen
        self.loadingText.cleanup()

        # remove camera rotation and enable other shit
        self.taskMgr.remove("SpinCameraTask")

        # load the model for first person camera
        node = NodePath("PhysicsNode")
        node.reparentTo(self.render)
        an = ActorNode("girl")
        anp = node.attachNewNode(an)
        self.physicsMgr.attachPhysicalNode(an)
        self.cameraModel = loader.loadModel("models/camera")
        self.cameraModel.reparentTo(self.render)  # inherit transforms
        self.cameraModel.setEffect(
            CompassEffect.make(render))  # NOT inherit rotation
        self.cameraModel.reparentTo(anp)
        self.cameraModel.setPos(10, -10, 30)
        self.cameraModel.setScale(5, 5, 5)
        self.camera.reparentTo(self.cameraModel)
        self.camera.lookAt(self.cameraModel)
        self.camera.setY(0)  # camera distance from model

        # start doing some gravity stuff
        an.getPhysicsObject().setMass(136.077)

        gravityFN = ForceNode('world-forces')
        gravityFNP = self.render.attachNewNode(gravityFN)
        gravityForce = LinearVectorForce(0, 0, -.81)  #gravity acceleration
        gravityFN.addForce(gravityForce)

        base.physicsMgr.addLinearForce(gravityForce)

        # collisions
        fromObject2 = self.scene.attachNewNode(CollisionNode('colNode'))
        fromObject2.node().addSolid(
            CollisionBox(Point3(-100, -100, 0), Point3(100, 100, 20)))
        fromObject2.show()

        fromObject = self.cameraModel.attachNewNode(CollisionNode('colNode'))
        fromObject.node().addSolid(CollisionRay(0, 0, 0, 0, 0, -1))

        lifter = CollisionHandlerFloor()
        lifter.addCollider(fromObject, self.cameraModel)

        self.keyMap = {
            "w": False,
            "s": False,
            "a": False,
            "d": False,
            "spacebar": False
        }

        self.accept("w", self.setKey, ["w", True])
        self.accept("s", self.setKey, ["s", True])
        self.accept("a", self.setKey, ["a", True])
        self.accept("d", self.setKey, ["d", True])
        self.accept("space", self.setKey, ["spacebar", True])

        self.accept("w-up", self.setKey, ["w", False])
        self.accept("s-up", self.setKey, ["s", False])
        self.accept("a-up", self.setKey, ["a", False])
        self.accept("d-up", self.setKey, ["d", False])
        self.accept("space-up", self.setKey, ["spacebar", False])

        self.cursorShit()

        self.taskMgr.add(self.cameraControl, "Camera Control")

    def close(self):
        sys.exit()

    def setKey(self, key, value):
        self.keyMap[key] = value

    def cameraControl(self, task):
        dt = globalClock.getDt()
        if (dt > .20):
            return task.cont

        if (self.mouseWatcherNode.hasMouse() == True):
            mpos = self.mouseWatcherNode.getMouse()
            self.camera.setP(mpos.getY() * 30)
            self.camera.setH(mpos.getX() * -50)
            if (mpos.getX() < 1.0 and mpos.getX() > -1.0):
                self.cameraModel.setH(self.cameraModel.getH())
            else:
                self.cameraModel.setH(self.cameraModel.getH() +
                                      mpos.getX() * -1)
            """ this task updates the mouse 
            md = self.win.getPointer(0)
            x = md.getX()
            y = md.getY()
            if self.win.movePointer(0, self.win.getXSize()/2, self.win.getYSize()/2):
                self.cameraModel.setH(self.cameraModel.getH() -  (x - self.win.getXSize()/2)*0.01)
                self.camera.setP(self.camera.getP() - (y - self.win.getYSize()/2)*0.01)"""

        if (self.keyMap["w"] == True):
            self.cameraModel.setY(self.cameraModel, 15 * dt)
            print("camera moving forward")
            return task.cont
        elif (self.keyMap["s"] == True):
            self.cameraModel.setY(self.cameraModel, -15 * dt)
            print("camera moving backwards")
            return task.cont
        elif (self.keyMap["a"] == True):
            self.cameraModel.setX(self.cameraModel, -10 * dt)
            print("camera moving left")
            return task.cont
        elif (self.keyMap["d"] == True):
            self.cameraModel.setX(self.cameraModel, 10 * dt)
            print("camera moving right")
            return task.cont
        elif (self.keyMap["spacebar"] == True):
            self.cameraModel.setZ(self.cameraModel, 10 * dt)
            print("camera moving up")
            return task.cont
        else:
            return task.cont

    def cursorShit(self):
        # To set relative mode and hide the cursor:
        props = WindowProperties()
        props.setCursorHidden(True)
        props.setMouseMode(WindowProperties.M_confined)
        self.win.requestProperties(props)

    def resetCursor(self):
        # To revert to normal mode:
        props = WindowProperties()
        props.setCursorHidden(False)
        props.setMouseMode(WindowProperties.M_absolute)
        self.win.requestProperties(props)