예제 #1
0
    def place_markers(self,nodes):
        for n in range(len(nodes)):
            town_node = NodePath("town")
            town = loader.loadModel("models/infantry_counter.egg")
            x = (nodes[n+1]["x"]-map_center[0])*amplification
            y = (nodes[n+1]["y"]-map_center[1])*amplification
            town.setPos(x,y,0)
            if nodes[n+1]["type"] == "city":
                scale = 12
            elif nodes[n+1]["type"] == "town":
                scale = 7
            elif nodes[n+1]["type"] == "village":
                scale = 4
            town.setScale(scale,scale,scale)
            town.reparentTo(town_node)
            town_node.reparentTo(render)

            text_node = TextNode("town_text_node")
            text_node.setText(nodes[n+1]["name"])
            text_node_path = town.attachNewNode(text_node)
            text_node_path.setPos(1,0,0)
            text_node_path.setHpr(0,-90,0)
            text_node_path.setScale(scale/2)
            text_node_path.setTransparency(TransparencyAttrib.MAlpha)
            text_node.setTextColor(0.8, 0.1, 0.1, 1)
            text_node.setAlign(TextNode.ALeft)
예제 #2
0
 def announceGenerate(self):
     assert(self.notify.debug("announceGenerate()"))
     DistributedObject.DistributedObject.announceGenerate(self)
     self.sendUpdate("avIdEnteredParty", [base.localAvatar.doId])
     # we probably just spent a lot of time loading, so
     # tell globalClock to update the frame timestamp
     globalClock.syncFrameTime()
     self.startPartyClock()
     base.localAvatar.chatMgr.chatInputSpeedChat.addInsidePartiesMenu()
     self.spawnTitleText()
     if config.GetBool('show-debug-party-grid', 0):
         # Debug grid
         self.testGrid = NodePath("test_grid")
         self.testGrid.reparentTo(base.cr.playGame.hood.loader.geom)
         for i in range(len(self.grid)):
             for j in range(len(self.grid[i])):
                 cm = CardMaker("gridsquare")
                 np = NodePath(cm.generate())
                 np.setScale(12)
                 np.setP(-90.0)
                 np.setPos(PartyUtils.convertDistanceFromPartyGrid(j,0)-6.0, PartyUtils.convertDistanceFromPartyGrid(i,1)-6.0, 0.1)
                 np.reparentTo(self.testGrid)
                 if self.grid[i][j]:
                     np.setColorScale(0.0, 1.0, 0.0, 1.0)
                 else:
                     np.setColorScale(1.0, 0.0, 0.0, 1.0)
예제 #3
0
 def announceGenerate(self):
     # TODO - for some reason this is getting called hundreds of times when there are multiple districts
     DistributedObject.DistributedObject.announceGenerate(self)
     self.sendUpdate("enteredParty", [])
     globalClock.syncFrameTime()
     self.startPartyClock()
     base.localAvatar.chatMgr.chatInputSpeedChat.addInsidePartiesMenu()
     self.spawnTitleText()
     messenger.send(self.generatedEvent)
     if config.GetBool("show-debug-party-grid", 0):
         self.testGrid = NodePath("test_grid")
         self.testGrid.reparentTo(base.cr.playGame.hood.loader.geom)
         for i in xrange(len(self.grid)):
             for j in xrange(len(self.grid[i])):
                 cm = CardMaker("gridsquare")
                 np = NodePath(cm.generate())
                 np.setScale(12)
                 np.setP(-90.0)
                 np.setPos(
                     PartyUtils.convertDistanceFromPartyGrid(j, 0) - 6.0,
                     PartyUtils.convertDistanceFromPartyGrid(i, 1) - 6.0,
                     0.1,
                 )
                 np.reparentTo(self.testGrid)
                 if self.grid[i][j]:
                     np.setColorScale(0.0, 1.0, 0.0, 1.0)
                 else:
                     np.setColorScale(1.0, 0.0, 0.0, 1.0)
    def _loadAndBuildMazeModel(self, flatten = False):
        self.getMazeData()
        self._model = NodePath('CogdoMazeModel')
        levelModel = CogdoUtil.loadMazeModel('level')
        self.quadrants = []
        quadrantUnitSize = int(self.quadrantSize * self.cellWidth)
        frameActualSize = self.frameWallThickness * self.cellWidth
        size = quadrantUnitSize + frameActualSize
        halfWidth = int(self.width / 2)
        halfHeight = int(self.height / 2)
        i = 0
        for y in range(self.height):
            for x in range(self.width):
                ax = (x - halfWidth) * size
                ay = (y - halfHeight) * size
                extension = ''
                if hasattr(getBase(), 'air'):
                    extension = '.bam'
                filepath = self.quadrantData[i][0] + extension
                angle = self.quadrantData[i][2]
                m = self._createQuadrant(filepath, i, angle, quadrantUnitSize)
                m.setPos(ax, ay, 0)
                m.reparentTo(self._model)
                self.quadrants.append(m)
                i += 1

        quadrantHalfUnitSize = quadrantUnitSize * 0.5
        barrierModel = CogdoUtil.loadMazeModel('grouping_blockerDivider').find('**/divider')
        y = 3
        for x in range(self.width):
            if x == (self.width - 1) / 2:
                continue
            ax = (x - halfWidth) * size
            ay = (y - halfHeight) * size - quadrantHalfUnitSize - (self.cellWidth - 0.5)
            b = NodePath('barrier')
            barrierModel.instanceTo(b)
            b.setPos(ax, ay, 0)
            b.reparentTo(self._model)

        offset = self.cellWidth - 0.5
        for x in (0, 3):
            for y in range(self.height):
                ax = (x - halfWidth) * size - quadrantHalfUnitSize - frameActualSize + offset
                ay = (y - halfHeight) * size
                b = NodePath('barrier')
                barrierModel.instanceTo(b)
                b.setPos(ax, ay, 0)
                b.setH(90)
                b.reparentTo(self._model)

            offset -= 2.0

        barrierModel.removeNode()
        levelModel.getChildren().reparentTo(self._model)
        for np in self._model.findAllMatches('**/*lightCone*'):
            CogdoUtil.initializeLightCone(np, 'fixed', 3)

        if flatten:
            self._model.flattenStrong()
        return self._model
예제 #5
0
파일: GeomObjects.py 프로젝트: crempp/psg
class AttackCursor(object):
    _EDGES = 40
    _color = Vec4(0.8, 0.3, 0.3, 1)

    def __init__(self, parent, entity, foot=1):
        self.entity = entity
        self.pos = entity.pos
        self.attackRad = entity.attackRad
        self.footRad = foot
        self._footCircle = LineSegs()
        self._footCircleNP = NodePath("Movement Foot Circle Node")
        self._attackRadCircle = LineSegs()
        self._attackRadCircleNP = NodePath("Attack Radius Node")
        self._np = NodePath("Movement Node")
        self.attackables = Entity.EntityManager().getEntitiesWithin(
            self.pos, self.attackRad)

        for e in self.attackables:
            if isinstance(
                    e, Entity.EntityShip
            ) and e != self.entity and e.owner != self.entity.owner:
                e.representation.setAttackable()

    def draw(self):
        # Draw attack radius
        attackRadLine = LineSegs()
        attackRadLine.setThickness(1)
        attackRadLine.setColor(self._color)
        attackRadLine.moveTo(self.attackRad, 0, 0)
        for i in range(self._EDGES + 1):
            newX = (self.attackRad * math.cos((2 * math.pi / self._EDGES) * i))
            newY = (self.attackRad * math.sin((2 * math.pi / self._EDGES) * i))
            attackRadLine.drawTo(newX, newY, 0)
        attackRadGeom = attackRadLine.create()
        self._attackRadCircleNP = NodePath(attackRadGeom)
        self._attackRadCircleNP.reparentTo(self._np)

        # Draw foot circle
        self._footCircle.setThickness(1)
        self._footCircle.setColor(self._color)
        self._footCircle.moveTo(self.footRad, 0, 0)
        for i in range(self._EDGES):
            newX = (self.footRad * math.cos((2 * math.pi / self._EDGES) * i))
            newY = (self.footRad * math.sin((2 * math.pi / self._EDGES) * i))
            self._footCircle.drawTo(newX, newY, 0)
        self._footCircle.drawTo(self.footRad, 0, 0)
        footCircleGeom = self._footCircle.create()
        self._footCircleNP = NodePath(footCircleGeom)
        self._footCircleNP.reparentTo(self._np)

    def removeNode(self):
        for e in self.attackables:
            if isinstance(e, Entity.EntityShip):
                e.representation.unsetAttackable()
        self._footCircleNP.removeNode()
        self._attackRadCircleNP.removeNode()
        self._np.removeNode()

    def __del__(self):
        self.removeNode()
예제 #6
0
 def makeNew(self, pos, nor, parent=None):
     """Makes a new bullet hole."""
     if parent == None:
         parent = self.container
     else:
         # Add a subnode to the parent, if it's not already there
         child = parent.find('bullet-holes')
         if child.isEmpty():
             parent = parent.attachNewNode('bullet-holes')
         else:
             parent = child
     newhole = NodePath(self.card.generate())
     newhole.reparentTo(parent)
     newhole.lookAt(render, Point3(newhole.getPos(render) - nor))
     newhole.setR(newhole, random() * 360.0)
     newhole.setPos(render, pos)
     # Offset it a little to avoid z-fighting
     # Increase this value if you still see it.
     newhole.setY(newhole, -.001 - random() * 0.01)
     del newhole
     # We don't want one batch per bullet hole, so flatten it.
     # This could be made smarter to preserve culling, but
     # I have yet to see a performance loss.
     # The clearTexture() is a necessary hack.
     parent.clearTexture()
     parent.flattenStrong()
     parent.setTexture(self.texture)
     parent.setTransparency(TransparencyAttrib.MDual)
     parent.setShaderOff(1)
     parent.hide(BitMask32.bit(
         2))  # Invisible to volumetric lighting camera (speedup)
     parent.hide(BitMask32.bit(3))  # Invisible to shadow cameras (speedup)
예제 #7
0
class bigWall(StaticObject):


    
    def __init__(self, game):
        self.game = game
        
        
        self.collGeom = OdeBoxGeom( self.game.physicsSpace, 50, 15, 15)
        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0x000000ff) )#ffffffff) )
        self.collGeom.setCollideBits( BitMask32(0x000000ff) )
        
        #remember to make wall model with "50" length... no idea 50 what, though
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('BigWall.egg')
        model.reparentTo(self.visualNode) 
        
        
   
        
        
    def osuminen(self, ship1):
         if OdeUtil.collide(ship1.collGeom, self.collGeom):
 
            print "sdfgfdhgdfhxfhdhghcfh"
            print "ship1 xdfhgxdgxdgfbcdll!!"
    def _optimize(self):
        lightCones = NodePath('lightCones')
        for np in self._platformsRoot.findAllMatches('**/*lightCone*'):
            np.wrtReparentTo(lightCones)

        lightCones.reparentTo(self._model)
        node = self._model.find('**/ducts')
        if not node.isEmpty():
            node.flattenStrong()
            for np in node.getChildren():
                np.wrtReparentTo(self._model)

        node = self._model.find('**/nests')
        if not node.isEmpty():
            for np in node.getChildren():
                np.flattenStrong()
                np.wrtReparentTo(self._model)

        for np in self._model.findAllMatches('**/*LayerStack*'):
            np.wrtReparentTo(self._model)

        if not self._model.find('**/static').isEmpty():
            for np in self._model.find('**/static').getChildren():
                np.wrtReparentTo(self._model)

        self._model.flattenMedium()
예제 #9
0
class BigWall(StaticObject):

    def __init__(self, game, width=200.0, thickness=4.0, height=10):
        self.game = game
        self.collGeom = OdeBoxGeom( self.game.physicsSpace, width, thickness, height)

        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0x000000ff) )#ffffffff) )
        self.collGeom.setCollideBits( BitMask32(0x000000ff) )
        
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        
        model = loader.loadModel('BigWall.egg')
        model.setScale(width/50.0, thickness/4.0, height)
        model.reparentTo(self.visualNode)
        model.setZ(266)
#        tex = loader.loadTexture('seina.jpg')
#        model.setTexture(tex, 1)
        
        
    def osuminen(self, ship1):
         if OdeUtil.collide(ship1.collGeom, self.collGeom):
 
            print "sdfgfdhgdfhxfhdhghcfh"
            print "ship1 xdfhgxdgxdgfbcdll!!"
예제 #10
0
파일: main.py 프로젝트: JohnBish/NSD
    def title(self):
        #Removes title and loads current room
        def destroyTitle(task):
            card.removeNode()
            startGame()

        def startGame():
            if os.path.isfile('saves/location.json'):
                self.directToRoom()
            else:
                self.homeFirst()

        #Loads title animation
        titleText = self.loader.loadTexture('resources/titleText.avi')
        titleText.setLoopCount(1)
        titleText.play()

        #Displays title
        cm = CardMaker('titleText')
        cm.setFrameFullscreenQuad()
        cm.setUvRange(titleText)
        # noinspection PyArgumentList
        card = NodePath(cm.generate())
        card.reparentTo(self.render2d)
        card.setTexture(titleText)
        self.taskMgr.doMethodLater(5.6, destroyTitle, 'endTitle')
예제 #11
0
class TileGroup(object):
    "group and flatten tiles, for rendering performance"

    def __init__(self, parent, tile_x, tile_y):
        self.parent = parent
        self.name = "{0}:TileGroup({1},{2})".format(parent.name, tile_x, tile_y)
        self.nodepath = NodePath(PandaNode(self.name))
        self.textures = [[None] * TILE_GRP_SIZE for i in range(TILE_GRP_SIZE)]
        self.nodepath.reparentTo(self.parent.nodepath)
        self.dirty = False

    def update(self, x, y, texture):
        if self.textures[x][y] != texture:
            self.textures[x][y] = texture
            self.dirty = True

    def redraw(self):
        if not self.dirty:
            return  # nothing has changed, no need to redraw
        container = NodePath(PandaNode(self.name + "container"))
        for i in range(TILE_GRP_SIZE):
            for j in range(TILE_GRP_SIZE):
                cur = self.textures[i][j]
                if cur:
                    node = container.attachNewNode(CARD_MAKER.generate())
                    node.setTexture(cur)
                    node.setTwoSided(True)
                    node.setPos(i * TILE_SIZE, 0, j * TILE_SIZE)
        container.flattenStrong()
        for child in self.nodepath.getChildren():
            child.removeNode()
        container.reparentTo(self.nodepath)
        self.dirty = False
예제 #12
0
 def makeNew(self, pos, nor, parent = None):
   """Makes a new bullet hole."""
   if parent == None:
     parent = self.container
   else:
     # Add a subnode to the parent, if it's not already there
     child = parent.find('bullet-holes')
     if child.isEmpty():
       parent = parent.attachNewNode('bullet-holes')
     else:
       parent = child
   newhole = NodePath(self.card.generate())
   newhole.reparentTo(parent)
   newhole.lookAt(render, Point3(newhole.getPos(render) - nor))
   newhole.setR(newhole, random() * 360.0)
   newhole.setPos(render, pos)
   # Offset it a little to avoid z-fighting
   # Increase this value if you still see it.
   newhole.setY(newhole, -.001 - random() * 0.01)
   del newhole
   # We don't want one batch per bullet hole, so flatten it.
   # This could be made smarter to preserve culling, but
   # I have yet to see a performance loss.
   # The clearTexture() is a necessary hack.
   parent.clearTexture()
   parent.flattenStrong()
   parent.setTexture(self.texture)
   parent.setTransparency(TransparencyAttrib.MDual)
   parent.setShaderOff(1)
   parent.hide(BitMask32.bit(2)) # Invisible to volumetric lighting camera (speedup)
   parent.hide(BitMask32.bit(3)) # Invisible to shadow cameras (speedup)
예제 #13
0
    def restart(self):
        """Start or restart the plugin."""

        self.draw = Draw() # Utility for drawing 2D lines and shapes in 3-space
        path = Path([Vec2(40,40),Vec2(40,-40),Vec2(-40,40),Vec2(-40,-40)])
        for vehicle in self.vehicles[:3]:
            vehicle._pos = SteerVec((random.random()-0.5)*100,(random.random()-0.5)*100)
            vehicle._velocity = SteerVec((random.random()-0.5)*2,(random.random()-0.5)*2)
            vehicle.followPath(path,loop=True)
        c=(.6,.6,.6,.3)
        t=1
        z=1.5
        self.draw.drawLine(Vec3(path[0].getX(),path[0].getY(),z),Vec3(path[1].getX(),path[1].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[1].getX(),path[1].getY(),z),Vec3(path[2].getX(),path[2].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[2].getX(),path[2].getY(),z),Vec3(path[3].getX(),path[3].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[3].getX(),path[3].getY(),z),Vec3(path[0].getX(),path[0].getY(),z),color=c,thickness=t)
        path = Path([Vec2(-40,-40),Vec2(40,-40),Vec2(-40,40),Vec2(40,40)])
        for vehicle in self.vehicles[3:]:
            vehicle._pos = SteerVec((random.random()-0.5)*100,(random.random()-0.5)*100)
            vehicle._velocity = SteerVec((random.random()-0.5)*2,(random.random()-0.5)*2)
            vehicle.followPath(path,loop=True)
        self.draw.drawLine(Vec3(path[0].getX(),path[0].getY(),z),Vec3(path[1].getX(),path[1].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[1].getX(),path[1].getY(),z),Vec3(path[2].getX(),path[2].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[2].getX(),path[2].getY(),z),Vec3(path[3].getX(),path[3].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[3].getX(),path[3].getY(),z),Vec3(path[0].getX(),path[0].getY(),z),color=c,thickness=t)        
        for vehicle in self.vehicles:
            vehicle.avoidObstacles = True
            vehicle.avoidVehicles = True
            vehicle.maxforce = 0.1
            vehicle.maxspeed = 0.5 + (random.random()/2)            
        node = self.draw.create()
        np = NodePath(node)   
        np.reparentTo(render)
예제 #14
0
class Level(object):
    """
	Represents one level of the asteroid.
	Internal to Asteroid mostly.
	"""

    def __init__(self, parent, num):
        self.parent = parent
        self.name = "{0}-Level#{1}".format(parent.name, num)
        # create one root nodepath for the overall level
        self.nodepath = NodePath(PandaNode(self.name))
        self.tile_groups = {}
        self.nodepath.reparentTo(self.parent.nodepath)

    def update(self, x, y, texture):
        tgs = TILE_GRP_SIZE
        tg_pos = tg_x, tg_y = x / tgs, y / tgs
        if tg_pos not in self.tile_groups:
            self.tile_groups[tg_pos] = TileGroup(self, tg_x, tg_y)
            scale = TILE_GRP_SIZE * TILE_SIZE
            self.tile_groups[tg_pos].nodepath.setPos(tg_x * scale, 0, tg_y * scale)
        self.tile_groups[tg_pos].update(x % tgs, y % tgs, texture)

    def redraw(self):
        for tg in self.tile_groups.values():
            tg.redraw()
예제 #15
0
 def generateToonMoveTrack(self, toon):
     node = NodePath('tempNode')
     displacement = Vec3(toon.getPos(render) - self.getPos(render))
     displacement.setZ(0)
     displacement.normalize()
     movieDistance = self.movieNode.getDistance(self.rotateNode)
     displacement *= movieDistance
     node.reparentTo(render)
     node.setPos(displacement + self.getPos(render))
     node.lookAt(self)
     heading = PythonUtil.fitDestAngle2Src(toon.getH(render),
                                           node.getH(render))
     hpr = toon.getHpr(render)
     hpr.setX(heading)
     finalX = node.getX(render)
     finalY = node.getY(render)
     finalZ = node.getZ(render)
     node.removeNode()
     toonTrack = Sequence(
         Parallel(
             ActorInterval(toon, 'walk', loop=True, duration=1),
             Parallel(
                 LerpPosInterval(toon,
                                 1.0,
                                 Point3(finalX, finalY, toon.getZ(render)),
                                 fluid=True,
                                 bakeInStart=False)),
             LerpHprInterval(toon, 1.0, hpr=hpr)),
         Func(toon.loop, 'neutral'))
     return toonTrack
예제 #16
0
 def loadModel(self):
     self.rotateNode = self.plantPath.attachNewNode('rotate')
     self.model = Actor.Actor()
     animPath = self.modelPath + self.anims[1]
     self.model.loadModel(self.modelPath + self.anims[0])
     self.model.loadAnims(dict([
         [
             self.anims[1],
             animPath]]))
     colNode = self.model.find('**/+CollisionNode')
     if self.typeIndex == 234:
         colNode.setScale(0.5)
     
     if not colNode.isEmpty():
         (score, multiplier) = ToontownGlobals.PinballScoring[ToontownGlobals.PinballStatuary]
         if self.pinballScore:
             score = self.pinballScore[0]
             multiplier = self.pinballScore[1]
         
         scoreNodePath = NodePath('statuary-%d-%d' % (score, multiplier))
         colNode.setName('statuaryCol')
         scoreNodePath.reparentTo(colNode.getParent())
         colNode.reparentTo(scoreNodePath)
     
     self.model.setScale(self.worldScale)
     self.model.reparentTo(self.rotateNode)
     self.model.loop(self.anims[1])
    def _loadAndBuildMazeModel(self, flatten = False):
        self.getMazeData()
        self._model = NodePath('CogdoMazeModel')
        levelModel = CogdoUtil.loadMazeModel('level')
        self.quadrants = []
        quadrantUnitSize = int(self.quadrantSize * self.cellWidth)
        frameActualSize = self.frameWallThickness * self.cellWidth
        size = quadrantUnitSize + frameActualSize
        halfWidth = int(self.width / 2)
        halfHeight = int(self.height / 2)
        i = 0
        for y in range(self.height):
            for x in range(self.width):
                ax = (x - halfWidth) * size
                ay = (y - halfHeight) * size
                extension = ''
                if hasattr(getBase(), 'air'):
                    extension = '.bam'
                filepath = self.quadrantData[i][0] + extension
                angle = self.quadrantData[i][2]
                m = self._createQuadrant(filepath, i, angle, quadrantUnitSize)
                m.setPos(ax, ay, 0)
                m.reparentTo(self._model)
                self.quadrants.append(m)
                i += 1

        quadrantHalfUnitSize = quadrantUnitSize * 0.5
        barrierModel = CogdoUtil.loadMazeModel('grouping_blockerDivider').find('**/divider')
        y = 3
        for x in range(self.width):
            if x == (self.width - 1) / 2:
                continue
            ax = (x - halfWidth) * size
            ay = (y - halfHeight) * size - quadrantHalfUnitSize - (self.cellWidth - 0.5)
            b = NodePath('barrier')
            barrierModel.instanceTo(b)
            b.setPos(ax, ay, 0)
            b.reparentTo(self._model)

        offset = self.cellWidth - 0.5
        for x in (0, 3):
            for y in range(self.height):
                ax = (x - halfWidth) * size - quadrantHalfUnitSize - frameActualSize + offset
                ay = (y - halfHeight) * size
                b = NodePath('barrier')
                barrierModel.instanceTo(b)
                b.setPos(ax, ay, 0)
                b.setH(90)
                b.reparentTo(self._model)

            offset -= 2.0

        barrierModel.removeNode()
        levelModel.getChildren().reparentTo(self._model)
        for np in self._model.findAllMatches('**/*lightCone*'):
            CogdoUtil.initializeLightCone(np, 'fixed', 3)

        if flatten:
            self._model.flattenStrong()
        return self._model
 def generateToonMoveTrack(self, toon):
     node = NodePath("tempNode")
     displacement = Vec3(toon.getPos(render) - self.getPos(render))
     displacement.setZ(0)
     displacement.normalize()
     movieDistance = self.movieNode.getDistance(self.rotateNode)
     displacement *= movieDistance
     node.reparentTo(render)
     node.setPos(displacement + self.getPos(render))
     node.lookAt(self)
     heading = PythonUtil.fitDestAngle2Src(toon.getH(render), node.getH(render))
     hpr = toon.getHpr(render)
     hpr.setX(heading)
     finalX = node.getX(render)
     finalY = node.getY(render)
     finalZ = node.getZ(render)
     node.removeNode()
     toonTrack = Sequence(
         Parallel(
             ActorInterval(toon, "walk", loop=True, duration=1),
             Parallel(
                 LerpPosInterval(toon, 1.0, Point3(finalX, finalY, toon.getZ(render)), fluid=True, bakeInStart=False)
             ),
             LerpHprInterval(toon, 1.0, hpr=hpr),
         ),
         Func(toon.loop, "neutral"),
     )
     return toonTrack
예제 #19
0
    def _optimize(self):
        lightCones = NodePath('lightCones')
        for np in self._platformsRoot.findAllMatches('**/*lightCone*'):
            np.wrtReparentTo(lightCones)

        lightCones.reparentTo(self._model)
        node = self._model.find('**/ducts')
        if not node.isEmpty():
            node.flattenStrong()
            for np in node.getChildren():
                np.wrtReparentTo(self._model)

        node = self._model.find('**/nests')
        if not node.isEmpty():
            for np in node.getChildren():
                np.flattenStrong()
                np.wrtReparentTo(self._model)

        for np in self._model.findAllMatches('**/*LayerStack*'):
            np.wrtReparentTo(self._model)

        for np in self._model.find('**/static').getChildren():
            np.wrtReparentTo(self._model)

        self._model.flattenMedium()
예제 #20
0
    def map_populate(self,task):
        self.init_collisions()
        for p in range(len(self.provinces)):
            city = loader.loadModel("models/house2.x")
            city.reparentTo(render)
            city.setName(self.provinces[p+1][0])
            city.setScale(2, 2, 2)
            x = float(self.provinces[p+1][2]*self.map_scale)-(self.map_width/2)
            y = self.map_height-float(self.provinces[p+1][3]*self.map_scale)-(self.map_height/2)
            city.setPos(x, y, 1.0)
            city_col = city.attachNewNode(CollisionNode("CityCNode%d"%p))
            city_col.setScale((3,3,3))
            city_col.node().addSolid(CollisionSphere(0,0,0,1))
            city_col.setTag("prov","city")
            city.setTag("id",str(p+1))
        for p in range(len(self.paths)):
            path_split = string.replace(self.paths[p],"-"," ")
            path_split = string.split(path_split)
            prov_a = int(path_split[0])
            prov_b = int(path_split[1])
            line = LineSegs()
            line.setColor(1, 0, 0, 1)
            line.setThickness(5)
            line.moveTo(self.provinces[prov_a][2]-600, -(self.provinces[prov_a][3])+350, 2)
            line.drawTo(self.provinces[prov_b][2]-600, -(self.provinces[prov_b][3])+350, 2)

            node = line.create()
            node_path = NodePath(node)
            node_path.reparentTo(render)
            print "line drawn",self.provinces[prov_a][2],self.provinces[prov_a][3]
        for a in range(len(self.armies)):
            self.army_create(a+1,self.armies[a+1][2])

        self.load_state = "Done!"
        task.done
    def attach_to(self, render):
        '''creates Panda3D representation that can be attached to render
		this function is mainly used inside Render class and its derivatives and
		user not need to worry to call it'''
        lines = NodePath(self.line_seqs.create())
        lines.reparentTo(render.render)
        return lines
예제 #22
0
 def announceGenerate(self):
     #TODO - for some reason this is getting called hundreds of times when there are multiple districts
     DistributedObject.DistributedObject.announceGenerate(self)
     self.sendUpdate('enteredParty', [])
     globalClock.syncFrameTime()
     self.startPartyClock()
     base.localAvatar.chatMgr.chatInputSpeedChat.addInsidePartiesMenu()
     self.spawnTitleText()
     messenger.send(self.generatedEvent)
     if config.GetBool('show-debug-party-grid', 0):
         self.testGrid = NodePath('test_grid')
         self.testGrid.reparentTo(base.cr.playGame.hood.loader.geom)
         for i in range(len(self.grid)):
             for j in range(len(self.grid[i])):
                 cm = CardMaker('gridsquare')
                 np = NodePath(cm.generate())
                 np.setScale(12)
                 np.setP(-90.0)
                 np.setPos(
                     PartyUtils.convertDistanceFromPartyGrid(j, 0) - 6.0,
                     PartyUtils.convertDistanceFromPartyGrid(i, 1) - 6.0,
                     0.1)
                 np.reparentTo(self.testGrid)
                 if self.grid[i][j]:
                     np.setColorScale(0.0, 1.0, 0.0, 1.0)
                 else:
                     np.setColorScale(1.0, 0.0, 0.0, 1.0)
예제 #23
0
class Block( object ):

	def __init__(self, blockType, position, owner, damage, seed, baseColor ):
		""" """

		from blockType import BlockType
		from player import Player
		from pandac.PandaModules import Vec3

		if not isinstance( blockType, BlockType ): raise TypeError( blockType )
		if not isinstance( owner, Player ): raise TypeError( owner )
		if not isinstance( position, Vec3 ): raise TypeError( position )
		if not isinstance( damage, int ): raise TypeError( damage )
		if not isinstance( seed, int ): raise TypeError( seed )
		if not isinstance( baseColor, tuple ): raise TypeError( baseColor )

		super(Block, self).__init__()

		self.identifier = blockType.identifier
		self.blockType = blockType
		self.position = position
		self.damage = damage
		self.owner = owner
		self.seed = seed
		self.baseColor = baseColor

		return None

	def damage(self, amount):
		""" """
		# Abuse the fact that int rounds down?
		self.damage += int( amount / self.blockType.rate )
		if self.damage > self.blockType.durability: return self.destroy()
		else: return self.damage

	def create(self, environment ): return self.load( environment )

	def load(self, environment):
		"""Add the block to the world. Do the actual construction of the model when
		necessary and add it to the environment (should actually be a chunk)."""

		if self.blockType.name == 'air': return None
		self.cube = NodePath('cube')
		model = self.blockType.getModel()
		model.instanceTo( self.cube )
		self.cube.setPos( self.position )
		self.cube.reparentTo( environment )

		return self

	def unload( self ):
		''' '''
		self.cube.detachNode()
		return None

	def destroy(self):
		"""See what items should be dropped, remove the block from the world, and handle
		everything else that should happens when a block breaks."""
		raise NotImplementedError
예제 #24
0
class CogdoMaze(MazeBase, DirectObject):
    def __init__(self, model, data, cellWidth):
        MazeBase.__init__(self, model, data, cellWidth)
        self._initWaterCoolers()
        self.elevatorPos = self.maze.find('**/elevator_loc').getPos(render)
        self.exitPos = self.maze.find('**/exit_loc').getPos(render)
        self.maze.flattenStrong()
        self._clearColor = VBase4(base.win.getClearColor())
        self._clearColor.setW(1.0)
        base.win.setClearColor(VBase4(0.0, 0.0, 0.0, 1.0))

    def _initWaterCoolers(self):
        self._waterCoolers = []
        self._waterCoolerRoot = NodePath('WaterCoolerRoot')
        self._waterCoolerRoot.reparentTo(render)
        models = []
        for model in self.maze.findAllMatches('**/*waterCooler'):
            model.wrtReparentTo(render)
            models.append(
                (model.getPos(self.maze), model.getHpr(self.maze), model))

        models.sort()
        i = 0
        for pos, hpr, model in models:
            wc = CogdoMazeWaterCooler(i, model)
            wc.wrtReparentTo(self._waterCoolerRoot)
            wc.setPos(pos)
            wc.setHpr(hpr)
            self._waterCoolers.append(wc)
            i += 1

        self._waterCoolerRoot.stash()

    def getWaterCoolers(self):
        return self._waterCoolers

    def isAccessible(self, tX, tY):
        if tX < 0 or tY < 0 or tX >= self.width or tY >= self.height:
            return 0
        return self.collisionTable[tY][tX] != 1

    def destroy(self):
        for waterCooler in self._waterCoolers:
            waterCooler.destroy()

        del self._waterCoolers
        self._waterCoolerRoot.removeNode()
        del self._waterCoolerRoot
        base.win.setClearColor(self._clearColor)
        del self._clearColor
        MazeBase.destroy(self)

    def onstage(self):
        MazeBase.onstage(self)
        self._waterCoolerRoot.unstash()

    def offstage(self):
        self._waterCoolerRoot.stash()
        MazeBase.offstage(self)
class RepairSawingLine:
    def __init__(self, parent, thickness, color, lineSpawnDist=0.01):
        self.points = []
        self.parent = parent
        self.thickness = thickness
        self.color = color
        self.lineNode = None
        self.lineDrawer = LineSegs()
        self.lineDrawer.setThickness(thickness)
        self.lineSpawnDist = lineSpawnDist
        self.currentPoint = None
        self.startPoint = None
        self.redraw()

    def redraw(self):
        self.clearLine()
        self.lineDrawer.reset()
        self.lineDrawer.setThickness(self.thickness)
        self.lineDrawer.setColor(self.color)
        if len(self.points) > 0:
            self.lineDrawer.moveTo(self.points[0])
            for i in range(1, len(self.points)):
                p = self.points[i]
                self.lineDrawer.drawTo(p)
                self.currentPoint = p

        self.lineNode = NodePath(self.lineDrawer.create())
        self.lineNode.reparentTo(self.parent)
        self.lineNode.setBin('fixed', 37)
        self.lineNode.setTransparency(True)

    def update(self, point):
        if self.currentPoint == None or (
                point - self.currentPoint).length() >= self.lineSpawnDist:
            self.addPoint(point)
            self.redraw()

    def addPoint(self, p):
        if len(self.points) == 0:
            self.startPoint = p

        self.points.append(p)

    def clearLine(self):
        if self.lineNode != None:
            self.lineNode.removeNode()

    def reset(self):
        self.clearLine()
        self.points = []
        self.redraw()
        self.currentPoint = None
        self.startPoint = None

    def show(self):
        self.lineNode.unstash()

    def hide(self):
        self.lineNode.stash()
class CogdoMaze(MazeBase, DirectObject):

    def __init__(self, model, data, cellWidth):
        MazeBase.__init__(self, model, data, cellWidth)
        self._initWaterCoolers()
        self.elevatorPos = self.maze.find('**/elevator_loc').getPos(render)
        self.exitPos = self.maze.find('**/exit_loc').getPos(render)
        self.maze.flattenStrong()
        self._clearColor = VBase4(base.win.getClearColor())
        self._clearColor.setW(1.0)
        base.win.setClearColor(VBase4(0.0, 0.0, 0.0, 1.0))

    def _initWaterCoolers(self):
        self._waterCoolers = []
        self._waterCoolerRoot = NodePath('WaterCoolerRoot')
        self._waterCoolerRoot.reparentTo(render)
        models = []
        for model in self.maze.findAllMatches('**/*waterCooler'):
            model.wrtReparentTo(render)
            models.append((model.getPos(self.maze), model.getHpr(self.maze), model))

        models.sort()
        i = 0
        for pos, hpr, model in models:
            wc = CogdoMazeWaterCooler(i, model)
            wc.wrtReparentTo(self._waterCoolerRoot)
            wc.setPos(pos)
            wc.setHpr(hpr)
            self._waterCoolers.append(wc)
            i += 1

        self._waterCoolerRoot.stash()

    def getWaterCoolers(self):
        return self._waterCoolers

    def isAccessible(self, tX, tY):
        if tX < 0 or tY < 0 or tX >= self.width or tY >= self.height:
            return 0
        return self.collisionTable[tY][tX] != 1

    def destroy(self):
        for waterCooler in self._waterCoolers:
            waterCooler.destroy()

        del self._waterCoolers
        self._waterCoolerRoot.removeNode()
        del self._waterCoolerRoot
        base.win.setClearColor(self._clearColor)
        del self._clearColor
        MazeBase.destroy(self)

    def onstage(self):
        MazeBase.onstage(self)
        self._waterCoolerRoot.unstash()

    def offstage(self):
        self._waterCoolerRoot.stash()
        MazeBase.offstage(self)
예제 #27
0
 def cmd_tree(self, params=[]):
     self.game.world.create_trees()
     trees = self.game.world.trees
     x = y = 0
     tree = NodePath("tree")
     trees[0].copyTo(tree)
     tree.setPos(x, y, 0)
     tree.reparentTo(self.game.gui.render)
def printText(name, message, color):
    text = TextNode(name)
    text.setText(message)
    x,y,z = color
    text.setTextColor(x,y,z, 1)
    text3d = NodePath(text)
    text3d.reparentTo(render)
    return text3d
예제 #29
0
def _parseStatic(nodePath, parent):
    notify.debug('creating %s' % nodePath.getName()[len(STATIC_PREFIX) + 1:])
    element = NodePath(nodePath.getName()[len(STATIC_PREFIX) + 1:])
    element.reparentTo(parent)
    nodePath.copyTo(element)
    element.setScale(SCALE_MULTIPLIER)
    element.setPos(0, 0, 0)
    return (nodePath.getName()[len(STATIC_PREFIX) + 1:], element)
예제 #30
0
 def cmd_tree(self, params=[]):
     self.game.world.create_trees()
     trees = self.game.world.trees
     x = y = 0
     tree = NodePath('tree')
     trees[0].copyTo(tree)
     tree.setPos(x, y, 0)
     tree.reparentTo(self.game.gui.render)
예제 #31
0
def printText(name, message, color):
    text = TextNode(name)
    text.setText(message)
    x, y, z = color
    text.setTextColor(x, y, z, 1)
    text3d = NodePath(text)
    text3d.reparentTo(render)
    return text3d
예제 #32
0
def _parseStatic(nodePath, parent):
    notify.debug('creating %s' % nodePath.getName()[len(STATIC_PREFIX) + 1:])
    element = NodePath(nodePath.getName()[len(STATIC_PREFIX) + 1:])
    element.reparentTo(parent)
    nodePath.copyTo(element)
    element.setScale(SCALE_MULTIPLIER)
    element.setPos(0, 0, 0)
    return (nodePath.getName()[len(STATIC_PREFIX) + 1:], element)
예제 #33
0
class DistributedGardenBox(DistributedLawnDecor.DistributedLawnDecor):
    notify = DirectNotifyGlobal.directNotify.newCategory(
        'DistributedGardenPlot')

    def __init__(self, cr):
        DistributedLawnDecor.DistributedLawnDecor.__init__(self, cr)
        #self.defaultModel = "phase_8/models/props/flower_treasure.bam"

        self.plantPath = NodePath('plantPath')
        self.plantPath.reparentTo(self)
        self.plotScale = 1.0

        self.plantingGuiDoneEvent = "plantingGuiDone"
        self.defaultModel = "phase_5.5/models/estate/planterC"

    def announceGenerate(self):
        #print("box announceGenerate!!!!")
        self.notify.debug('announceGenerate')
        DistributedLawnDecor.DistributedLawnDecor.announceGenerate(self)

    def doModelSetup(self):
        if self.typeIndex == GardenGlobals.BOX_THREE:
            self.defaultModel = "phase_5.5/models/estate/planterA"
        elif self.typeIndex == GardenGlobals.BOX_TWO:
            self.defaultModel = "phase_5.5/models/estate/planterC"
        else:
            self.defaultModel = "phase_5.5/models/estate/planterD"
            self.collSphereOffset = 0.0
            self.collSphereRadius = self.collSphereRadius * 1.41
            self.plotScale = Vec3(1.0, 1.0, 1.0)

    def setupShadow(self):
        #we don't want the shadow
        pass

    def loadModel(self):
        self.rotateNode = self.plantPath.attachNewNode('rotate')
        self.model = None

        self.model = loader.loadModel(self.defaultModel)
        self.model.setScale(self.plotScale)
        self.model.reparentTo(self.rotateNode)
        self.stick2Ground()

        #uncomment line below if we want the toons to walk on top of the planter
        #self.model.find("**/collision").stash()

    def handleEnterPlot(self, entry=None):
        #print("Box entered")
        pass

    def handleExitPlot(self, entry=None):
        DistributedLawnDecor.DistributedLawnDecor.handleExitPlot(self, entry)
        pass

    def setTypeIndex(self, typeIndex):
        #print("box setting type index!!!!")
        self.typeIndex = typeIndex
예제 #34
0
class cameraPickingClass( DirectObject ):
  enabled = False
  def __init__( self ):
    self.keybindings  = { "mouse1"     : [self.mousePick, 1] 
                        , "mouse1-up"  : [self.mousePick, 0] }
    self.mouseSetup()
    self.enable()
  
  def enable( self ):
    self.enabled = True
    # set keyboard mappings
    for mapping, [binding, setting] in self.keybindings.items():
      if setting is not None:
        self.accept( mapping, binding, [setting] )
      else:
        self.accept( mapping, binding )
  
  def disable( self ):
    self.enabled = False
    self.ignoreAll()
  
  def mouseSetup( self ):
    # create a node in front of the camera
    self.cameraFrontNode = NodePath( 'cameraFrontNode' )
    self.cameraFrontNode.reparentTo( base.camera )
    self.cameraFrontNode.setPos( Vec3(0,3,0) )
    self.pickedObject = None
    self.pickedObjectDistance = 0
  
  def mousePick( self, keyDown ):
    # pick up item
    if keyDown:
      pickedObject = objectIdPickling.getObjectMousePick()
      if pickedObject:
        self.startDrag( pickedObject )
    # drop item
    else: # key release
      if self.pickedObject:
        self.stopDrag( self.pickedObject )
  
  def startDrag( self, dragNode ):
    # save the object we drag&drop
    self.pickedObject = dragNode
    self.pickedObject.startDrag()
     # start the object move task (required to have the object moving with a free mouse)
    taskMgr.add( self.dragTask, 'mouseDragTask' )
  
  def stopDrag( self, dragNode ):
    self.pickedObject.stopDrag()
    # we dont drag&drop anything now
    self.pickedObject = None
    taskMgr.remove( 'mouseDragTask' )
  
  def dragTask( self, task ):
    # get a ray where the mouse points at
    newMouseRay = objectIdPickling.getPickerRayDirection()
    self.pickedObject.whileDrag( newMouseRay )
    return Task.cont
예제 #35
0
파일: Base.py 프로젝트: i-k/SpaceGrabem
class Base(StaticObject):
    #17.12.2009: collGeomInner -> collGeom, dropBall(x, y ,z, linX, linY), collectible.setPos() ja setVelocity()
    def __init__(self, game):
        self.game = game
        
        #poista se fysiikka-avaruus ja vaan tee se alue... justiinsa
        self.collGeom = OdeBoxGeom( 24,8,2 )

        
        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(1) )
        self.collGeom.setCollideBits( BitMask32(1) )
        

#        self.collGeomOuter = OdeBoxGeom( self.game.physicsSpace, 28,6,2)
#        #self.collGeom.setBody(self.body)
#        self.collGeomOuter.setCategoryBits( BitMask32(1) )
#        self.collGeomOuter.setCollideBits( BitMask32(1) )
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('Base.egg')
        model.reparentTo(self.visualNode)
        
        plight = PointLight('baselight')
        plight.setPoint( Point3(0, 0, 12) )
        plight.setColor( Vec4(1,1,1,1) )
        plight.setAttenuation( Vec3(0.1, 0.1, 0.005) )
        self.visualNode.setLight(model.attachNewNode(plight))
 
    def checkCollision( self, ship, collectiblelist ):
        if OdeUtil.collide(ship.collGeom, self.collGeom) and ship.hasBall():
            #if ship.hasBall():
            ship.addPoints( (ship.Ball.getValue()*2) )
            pos = self.getPos()
            ship.dropBall( x = pos[0], y = pos[1], z = 50, linX = random.randrange(-10,10), linY = (0-pos[1]) / 4 )
            print ship.SHIP_TYPE + " " +  str(ship.getPoints()) + " Points! "
            
            if (self.game.goalSfx.status() == 1):
                self.game.goalSfx.play()
            self.game.updateHUD()
            #print " Base One! "
        for collectible in collectiblelist:
            if OdeUtil.collide(collectible.collGeom, self.collGeom):
                pos = self.getPos()
                ship.addPoints(collectible.getValue())
                collectible.setPos( Vec3(pos[0], pos[1], 50))
                collectible.setVelocity(x = random.randrange(-10,10), y = (0-pos[1]) / 4)
                self.game.goalSfx.play()
                self.game.updateHUD()
                print ship.SHIP_TYPE + " " + str(ship.getPoints()) + " Points! by throwing the ball"

    def addToBaseList(self, baseList):
        baseList.append(self)
        
    def setPos(self, pos, pos2):
        self.visualNode.setPos( pos )
        self.collGeom.setPosition( pos2 )
예제 #36
0
파일: main.py 프로젝트: crempp/Fire-Water
 def printText(self, name, message, color, parent=render): 
     text = TextNode(name) # create a TextNode. Note that 'name' is not the text, rather it is a name that identifies the object.
     text.setText(message) # Here we set the text of the TextNode
     x,y,z = color # break apart the color tuple
     text.setTextColor(x,y,z, 1) # Set the text color from the color tuple
 
     text3d = NodePath(text) # Here we create a NodePath from the TextNode, so that we can manipulate it 'in world'
     text3d.reparentTo(parent)
     return text3d # return the NodePath for further use
예제 #37
0
 def draw_line(self,p,col):
     line = LineSegs()
     line.setColor(col[0],col[1],col[2], 1)
     line.setThickness(2)
     line.moveTo(p[0],p[1],0)
     line.drawTo(p[2],p[3],0)
     line_node = line.create()
     node_path = NodePath(line_node)
     node_path.reparentTo(render)
예제 #38
0
파일: GeomObjects.py 프로젝트: crempp/psg
class AttackCursor(object):
	_EDGES = 40
	_color = Vec4(0.8, 0.3, 0.3, 1)
	
	def __init__(self, parent, entity, foot=1):
		self.entity = entity
		self.pos = entity.pos
		self.attackRad         = entity.attackRad
		self.footRad           = foot
		self._footCircle       = LineSegs()
		self._footCircleNP     = NodePath("Movement Foot Circle Node")
		self._attackRadCircle  = LineSegs()
		self._attackRadCircleNP= NodePath("Attack Radius Node")
		self._np               = NodePath("Movement Node")
		self.attackables       = Entity.EntityManager().getEntitiesWithin(self.pos, self.attackRad)
		
		for e in self.attackables:
			if isinstance(e, Entity.EntityShip) and e != self.entity and e.owner != self.entity.owner: 
				e.representation.setAttackable()
			
	def draw(self):
		# Draw attack radius
		attackRadLine = LineSegs()
		attackRadLine.setThickness(1)
		attackRadLine.setColor(self._color)
		attackRadLine.moveTo(self.attackRad, 0, 0)
		for i in range(self._EDGES + 1):
			newX = (self.attackRad * math.cos((2*math.pi/self._EDGES)*i))
			newY = (self.attackRad * math.sin((2*math.pi/self._EDGES)*i))
			attackRadLine.drawTo(newX, newY, 0)
		attackRadGeom = attackRadLine.create()
		self._attackRadCircleNP = NodePath(attackRadGeom)
		self._attackRadCircleNP.reparentTo(self._np)
		
		# Draw foot circle
		self._footCircle.setThickness(1)
		self._footCircle.setColor(self._color)
		self._footCircle.moveTo(self.footRad, 0, 0)
		for i in range(self._EDGES):
			newX = (self.footRad * math.cos((2*math.pi/self._EDGES)*i))
			newY = (self.footRad * math.sin((2*math.pi/self._EDGES)*i))
			self._footCircle.drawTo(newX, newY, 0)
		self._footCircle.drawTo(self.footRad, 0, 0)
		footCircleGeom = self._footCircle.create()
		self._footCircleNP = NodePath(footCircleGeom)
		self._footCircleNP.reparentTo(self._np)
		
	def removeNode(self):
		for e in self.attackables:
			if isinstance(e, Entity.EntityShip):
				e.representation.unsetAttackable()
		self._footCircleNP.removeNode()
		self._attackRadCircleNP.removeNode()
		self._np.removeNode()

	def __del__(self):
		self.removeNode()
예제 #39
0
class CogdoMazeHud():
    __module__ = __name__

    def __init__(self):
        self._update = None
        self._initQuestArrow()
        return

    def _initQuestArrow(self):
        matchingGameGui = loader.loadModel(
            'phase_3.5/models/gui/matching_game_gui')
        arrow = matchingGameGui.find('**/minnieArrow')
        arrow.setScale(Globals.QuestArrowScale)
        arrow.setColor(*Globals.QuestArrowColor)
        arrow.setHpr(90, -90, 0)
        self._questArrow = NodePath('Arrow')
        arrow.reparentTo(self._questArrow)
        self._questArrow.reparentTo(render)
        self.hideQuestArrow()
        matchingGameGui.removeNode()

    def destroy(self):
        self.__stopUpdateTask()
        self._questArrow.removeNode()
        self._questArrow = None
        return

    def showQuestArrow(self, parent, nodeToPoint, offset=Point3(0, 0, 0)):
        self._questArrowNodeToPoint = nodeToPoint
        self._questArrowParent = parent
        self._questArrowOffset = offset
        self._questArrow.unstash()
        self._questArrowVisible = True
        self.__startUpdateTask()

    def hideQuestArrow(self):
        self._questArrow.stash()
        self.__stopUpdateTask()
        self._questArrowVisible = False
        self._questArrowNodeToPoint = None
        return

    def __startUpdateTask(self):
        self.__stopUpdateTask()
        self._update = taskMgr.add(self._updateTask, 'CogdoMazeHud_Update', 45)

    def __stopUpdateTask(self):
        if self._update is not None:
            taskMgr.remove(self._update)
        return

    def _updateTask(self, task):
        if self._questArrowVisible:
            self._questArrow.setPos(self._questArrowParent,
                                    self._questArrowOffset)
            self._questArrow.lookAt(self._questArrowNodeToPoint)
        return Task.cont
예제 #40
0
class LocalView(View):
    """The pseudo-2D main display where the player is likely to spend
       most of their time."""

    def update_ship(self, view):
        ship = view.obj
        pos3 = Point3(ship.pos.x, ship.pos.y, ship.pos.z)
        view.node.setPos(pos3)
        view.node.setHpr(ship.hpr)

    def view_for(self, obj):
        if isinstance(obj, Star):
            if not self.views.has_key('star'):
                self.views.star = StarView(self, obj)
            return self.views.star
        elif isinstance(obj, Planet):
            if not self.views.planets.has_key(obj):
                self.views.planets[obj] = PlanetView(self, obj)
            return self.views.planets[obj]
        elif isinstance(obj, Ship):
            try: return self.views.ships[obj]
            except KeyError:
                shipview = ShipView(self, obj)
                self.delegate(obj, 'reposition', lambda: self.update_ship(shipview))
                self.views.ships[obj] = shipview
                return shipview
        else:
            raise NotImplementedError

    def render(self):
        starview = self.view_for(self.locality.star)
        starview.node.setScale(100)

        for planet in self.locality.planets:
            pview = self.view_for(planet)
            pview.set_light(starview.light)
            planet.recalc_pos()
            pos = Point3(planet.pos.x, planet.pos.y, planet.pos.z) * self.distance_scale
            pview.node.setPos(pos)
            pview.node.setScale(100)

        for ship in self.locality.ships:
            view = self.view_for(ship)
            self.update_ship(view)

    def __init__(self, parent, locality, **kwargs):
        super(LocalView, self).__init__(parent, locality, **kwargs)
        self.locality = locality
        self.distance_scale = 0.01

        self.views = propdict()
        self.views.planets = {}
        self.views.ships = {}
        self.node = NodePath('local')
        self.node.reparentTo(self.parent.node)

        self.render()
 def drawBestPath(self):
     if self.bestPath != None:
         ls = LineSegs()
         ls.setThickness(10.0)
         for i in range(len(self.bestPath) - 1):
             ls.setColor(0, 0, 1, 1)
             ls.moveTo(self.bestPath[i].getPos())
             ls.drawTo(self.bestPath[i + 1].getPos())
             np = NodePath(ls.create("aoeu"))
             np.reparentTo(render)
예제 #42
0
 def createSafeZone(self, dnaFile):
     SafeZoneLoader.SafeZoneLoader.createSafeZone(self, dnaFile)
     parent = self.geom.getParent()
     geom = self.geom
     n = NodePath('PartyGroundRoot')
     n.reparentTo(parent)
     geom.reparentTo(n)
     geom.setPos(-10.0, 0.0, 0.0)
     self.geom = n
     self.loadSunMoon()
 def createSafeZone(self, dnaFile):
     SafeZoneLoader.SafeZoneLoader.createSafeZone(self, dnaFile)
     parent = self.geom.getParent()
     geom = self.geom
     n = NodePath('PartyGroundRoot')
     n.reparentTo(parent)
     geom.reparentTo(n)
     geom.setPos(-10.0, 0.0, 0.0)
     self.geom = n
     self.loadSunMoon()
예제 #44
0
 def drawBestPath(self):
     if self.bestPath != None:
         ls = LineSegs()
         ls.setThickness(10.0)
         for i in range(len(self.bestPath) - 1):
             ls.setColor(0, 0, 1, 1)
             ls.moveTo(self.bestPath[i].getPos())
             ls.drawTo(self.bestPath[i + 1].getPos())
             np = NodePath(ls.create("aoeu"))
             np.reparentTo(render)
예제 #45
0
    def createCamNodes(self):
        """Creates a few empty nodes around a plane which the camera might be
        parented to. It looks if there are cameras inside the model file and
        uses those if possible. Where everything named "camera CamType" is
        considered a camera. At least ThirdPerson, FirstPerson and Cockpit
        should be defined inside the egg file, otherwise some guessed defaults
        are taken.
        """

        # Look for cameras inside the model (loaded egg file)
        self.cameras = NodePath("cameras")
        found_cams = self.parent.node.findAllMatches("**/camera ?*")
        found_cams.removeDuplicatePaths()
        found_cams.reparentTo(self.cameras)

        if not found_cams.isEmpty():
            self.notifier.info("Cameras found under model:\n%s"
                               % found_cams)
        else:
            self.notifier.info("No cameras found under model.")

        # FirstPerson camera is a must-have. Set up a guessed one if none
        # defined yet.
        if self.cameras.find("camera FirstPerson").isEmpty():
            assert self.notifier.debug("No first person camera found in %s. "
                                  "Guessing best position." % self.parent.name)
            first_person = NodePath("camera FirstPerson")
            # TODO: Guess best position based on bounding box.
            first_person.setY(5)
            first_person.reparentTo(cameras)

        # ThirdPerson camera is a must-have. Set up a guessed one if none
        # defined yet.
        if self.cameras.find("camera ThirdPerson").isEmpty():
            assert self.notifier.debug("No third person camera found in %s. "
                                  "Guessing best position." % self.parent.name)
            third_person = NodePath("camera ThirdPerson")
            # TODO: Guess best position based on bounding box.
            third_person.setPos(0, -30, 5)
            #third_person.setP(-80)
            third_person.reparentTo(cameras)

        # Cockpit needs to be accurate. Don't try to guess it.
        if self.cameras.find("camera Cockpit").isEmpty():
            assert self.notifier.debug("No cockpit camera found in "
                                       "%s. Cockpit camera disabled."
                                       % self.parent.name)
        self.sideview_cam = NodePath("camera Sideview")
        self.sideview_cam.reparentTo(render)

        # Store the cams at parent node..
        # You can edit the camera nodes from outside as well.
        # If you attach new camera nodes, though, you'll have to call this
        # function again.
        self.cameras.reparentTo(self.parent.node)
예제 #46
0
    def createCamNodes(self):
        """Creates a few empty nodes around a plane which the camera might be
        parented to. It looks if there are cameras inside the model file and
        uses those if possible. Where everything named "camera CamType" is
        considered a camera. At least ThirdPerson, FirstPerson and Cockpit
        should be defined inside the egg file, otherwise some guessed defaults
        are taken.
        """

        # Look for cameras inside the model (loaded egg file)
        self.cameras = NodePath("cameras")
        found_cams = self.parent.node.findAllMatches("**/camera ?*")
        found_cams.removeDuplicatePaths()
        found_cams.reparentTo(self.cameras)

        if not found_cams.isEmpty():
            self.notifier.info("Cameras found under model:\n%s"
                               % found_cams)
        else:
            self.notifier.info("No cameras found under model.")

        # FirstPerson camera is a must-have. Set up a guessed one if none
        # defined yet.
        if self.cameras.find("camera FirstPerson").isEmpty():
            assert self.notifier.debug("No first person camera found in %s. "
                                  "Guessing best position." % self.parent.name)
            first_person = NodePath("camera FirstPerson")
            # TODO: Guess best position based on bounding box.
            first_person.setY(5)
            first_person.reparentTo(cameras)

        # ThirdPerson camera is a must-have. Set up a guessed one if none
        # defined yet.
        if self.cameras.find("camera ThirdPerson").isEmpty():
            assert self.notifier.debug("No third person camera found in %s. "
                                  "Guessing best position." % self.parent.name)
            third_person = NodePath("camera ThirdPerson")
            # TODO: Guess best position based on bounding box.
            third_person.setPos(0, -30, 5)
            #third_person.setP(-80)
            third_person.reparentTo(cameras)

        # Cockpit needs to be accurate. Don't try to guess it.
        if self.cameras.find("camera Cockpit").isEmpty():
            assert self.notifier.debug("No cockpit camera found in "
                                       "%s. Cockpit camera disabled."
                                       % self.parent.name)
        self.sideview_cam = NodePath("camera Sideview")
        self.sideview_cam.reparentTo(render)

        # Store the cams at parent node..
        # You can edit the camera nodes from outside as well.
        # If you attach new camera nodes, though, you'll have to call this
        # function again.
        self.cameras.reparentTo(self.parent.node)
예제 #47
0
class CogdoMazeHud():
    __module__ = __name__

    def __init__(self):
        self._update = None
        self._initQuestArrow()
        return

    def _initQuestArrow(self):
        matchingGameGui = loader.loadModel('phase_3.5/models/gui/matching_game_gui')
        arrow = matchingGameGui.find('**/minnieArrow')
        arrow.setScale(Globals.QuestArrowScale)
        arrow.setColor(*Globals.QuestArrowColor)
        arrow.setHpr(90, -90, 0)
        self._questArrow = NodePath('Arrow')
        arrow.reparentTo(self._questArrow)
        self._questArrow.reparentTo(render)
        self.hideQuestArrow()
        matchingGameGui.removeNode()

    def destroy(self):
        self.__stopUpdateTask()
        self._questArrow.removeNode()
        self._questArrow = None
        return

    def showQuestArrow(self, parent, nodeToPoint, offset = Point3(0, 0, 0)):
        self._questArrowNodeToPoint = nodeToPoint
        self._questArrowParent = parent
        self._questArrowOffset = offset
        self._questArrow.unstash()
        self._questArrowVisible = True
        self.__startUpdateTask()

    def hideQuestArrow(self):
        self._questArrow.stash()
        self.__stopUpdateTask()
        self._questArrowVisible = False
        self._questArrowNodeToPoint = None
        return

    def __startUpdateTask(self):
        self.__stopUpdateTask()
        self._update = taskMgr.add(self._updateTask, 'CogdoMazeHud_Update', 45)

    def __stopUpdateTask(self):
        if self._update is not None:
            taskMgr.remove(self._update)
        return

    def _updateTask(self, task):
        if self._questArrowVisible:
            self._questArrow.setPos(self._questArrowParent, self._questArrowOffset)
            self._questArrow.lookAt(self._questArrowNodeToPoint)
        return Task.cont
예제 #48
0
파일: main.py 프로젝트: crempp/Fire-Water
    def printText(self, name, message, color, parent=render):
        text = TextNode(
            name
        )  # create a TextNode. Note that 'name' is not the text, rather it is a name that identifies the object.
        text.setText(message)  # Here we set the text of the TextNode
        x, y, z = color  # break apart the color tuple
        text.setTextColor(x, y, z, 1)  # Set the text color from the color tuple

        text3d = NodePath(text)  # Here we create a NodePath from the TextNode, so that we can manipulate it 'in world'
        text3d.reparentTo(parent)
        return text3d  # return the NodePath for further use
예제 #49
0
파일: MazeMapGui.py 프로젝트: z010155/c0d3
 def addToon(self, toon, tX, tY):
     marker = NodePath('toon_marker-%i' % toon.doId)
     marker.reparentTo(self)
     self._getToonMarker(toon).copyTo(marker)
     marker.setColor(toon.style.getHeadColor())
     if toon.isLocal():
         marker.setScale(0.07)
     else:
         marker.setScale(0.05)
     marker.flattenStrong()
     marker.setPos(*self.gui2pos(*self.tile2gui(tX, tY)))
     self._toon2marker[toon] = marker
예제 #50
0
	def regenTree(self):
		forest=	render.findAllMatches("Tree Holder")
		forest.detach()


		bodydata=GeomVertexData("body vertices", self.format, Geom.UHStatic)
		
		treeNodePath=NodePath("Tree Holder")
		makeFractalTree(bodydata, treeNodePath,Vec3(4,4,7), Vec3(0,0,0),self.numIterations, self.numCopies)

		treeNodePath.setTexture(self.barkTexture,1)
		treeNodePath.reparentTo(render)
예제 #51
0
 def addToon(self, toon, tX, tY):
     marker = NodePath('toon_marker-%i' % toon.doId)
     marker.reparentTo(self)
     self._getToonMarker(toon).copyTo(marker)
     marker.setColor(toon.style.getHeadColor())
     if toon.isLocal():
         marker.setScale(0.07)
     else:
         marker.setScale(0.05)
     marker.flattenStrong()
     marker.setPos(*self.gui2pos(*self.tile2gui(tX, tY)))
     self._toon2marker[toon] = marker
예제 #52
0
    def load(self):
        self.root = NodePath('root')
        self.root.reparentTo(render)
        self.root.stash()

        self.world = loadMockup("cogdominium/mockup.egg")
        self.world.reparentTo(self.root)
        self.world.stash()

        # Setup and placement of starting platform
        self.startPlatform = loadMockup("cogdominium/start_platform.egg")
        startPlatformLoc = self.world.find("**/start_platform_loc")
        self.startPlatform.reparentTo(startPlatformLoc)
        colModel = self.startPlatform.find("**/col_floor")
        colModel.setTag('start_platform', '%s' % base.localAvatar.doId)

        # Here we set the current platform for the local player
        self.localPlayer.setCheckpointPlatform(self.startPlatform)

        # Setup and placement of the end platform
        self.endPlatform = loadMockup("cogdominium/end_platform.egg")
        endPlatformLoc = self.world.find("**/end_platform_loc")
        self.endPlatform.reparentTo(endPlatformLoc)
        colModel = self.endPlatform.find("**/col_floor")
        colModel.setTag('end_platform', '%s' % base.localAvatar.doId)

        # Setup and placement for all the fuel platforms
        fuelPlatformModel = loadMockup("cogdominium/fuel_platform.egg")
        fuelIndex = 1
        fuelLoc = self.world.find('**/fuel_platform_loc_%d' % fuelIndex)
        while not fuelLoc.isEmpty():
            fuelModel = NodePath("fuel_platform_%d" % fuelIndex)
            fuelPlatformModel.copyTo(fuelModel)
            fuelModel.reparentTo(fuelLoc)
            colModel = fuelModel.find("**/col_floor")
            colModel.setTag('fuel_platform', '%s' % base.localAvatar.doId)
            colModel.setTag('isUsed', '%s' % 0)
            self.fuelPlatforms[fuelModel.getName()] = fuelModel
            fuelIndex += 1
            fuelLoc = self.world.find('**/fuel_platform_loc_%d' % fuelIndex)

        self.accept("entercol_floor", self.handleCollision)

        self.skybox = self.world.find("**/skybox")
        self.upLimit = self.world.find("**/limit_up").getPos(render).getZ()
        self.downLimit = self.world.find("**/limit_down").getPos(render).getZ()
        self.leftLimit = self.world.find("**/limit_left").getPos(render).getX()
        self.rightLimit = self.world.find("**/limit_right").getPos(
            render).getX()

        del fuelPlatformModel

        self._initFog()
예제 #53
0
 def splitShip(self):
     if not self.isSplit:
         self.isSplit = True
         self.modelGeom.instanceTo(self.clipParent2)
         planeNode1 = NodePath(PlaneNode('planeNode1', Plane(Vec4(0, 1, 0, 0))))
         planeNode1.reparentTo(self.clipParent1)
         planeNode1.setY(ShipGlobals.getShipSplitOffset(self.shipClass))
         self.clipParent1.setClipPlane(planeNode1)
         planeNode2 = NodePath(PlaneNode('planeNode2', Plane(Vec4(0, -1, 0, 0))))
         planeNode2.reparentTo(self.clipParent2)
         planeNode2.setY(ShipGlobals.getShipSplitOffset(self.shipClass))
         self.clipParent2.setClipPlane(planeNode2)
예제 #54
0
    def createSafeZone(self, dnaFile):
        assert (self.notify.debug("createParty()"))
        SafeZoneLoader.SafeZoneLoader.createSafeZone(self, dnaFile)
        parent = self.geom.getParent()
        geom = self.geom
        n = NodePath("PartyGroundRoot")
        n.reparentTo(parent)
        geom.reparentTo(n)
        geom.setPos(-10.0, 0.0, 0.0)
        self.geom = n

        # load the sun and moon
        self.loadSunMoon()
 def addToon(self, toon):
     marker = NodePath('toon_marker-%i' % toon.doId)
     marker.reparentTo(self)
     self._getToonMarker(toon).copyTo(marker)
     marker.setColor(toon.style.getHeadColor())
     if toon.isLocal():
         marker.setScale(Globals.Gui.LocalMarkerScale)
         marker.setBin('fixed', 10)
     else:
         marker.setScale(Globals.Gui.MarkerScale)
         marker.setBin('fixed', 5)
     marker.flattenStrong()
     self._toonMarkers[toon] = marker
예제 #56
0
class SimViewer(LightBase):
    """ Visualizes simulation."""
    def __init__(self):
        super(SimViewer, self).__init__()
        # Make a window.
        size = (700, 520)
        self.create_output(size, "SimViewer")
        self.output.setClearColor((0.0, 0.0, 0.0, 1.0))
        # Lights node
        self.lights = NodePath('lights')
        # Create a spotlight
        slight = Spotlight('slight')
        slight.setScene(self.root)
        slight.setShadowCaster(True, 2**11, 2**11)
        # Set shadow mask, so we can exclude objects from casting shadows
        self.shadow_mask = BitMask32.bit(2)
        slight.setCameraMask(self.shadow_mask)
        c = 1.4
        slight.setColor((c, c, c, 1.0))
        slight.getLens().setNearFar(4, 100)
        slight.getLens().setFov(45)
        slnp = self.lights.attachNewNode(slight)
        slnp.setPos((7, 10, 40))
        slnp.lookAt(2, 0, 1.5)
        self.root.setLight(slnp)
        # Create an ambient light.
        alight = AmbientLight('alight')
        c = 0.6
        alight.setColor((c, c, c, 1.0))
        alnp = self.lights.attachNewNode(alight)
        self.root.setLight(alnp)
        self.lights.reparentTo(self.root)
        # Set auto shading for shadows.
        self.root.setShaderAuto()
        # Set antialiasing on.
        self.root.setAntialias(AntialiasAttrib.MAuto)
        # Camera.
        lens = PerspectiveLens()
        self.lens = lens
        self.lens.setNearFar(0.1, 1000.)
        self.lens.setFov((40, 30))
        self.cameras = self.root.attachNewNode('cameras')
        self.camera = self.make_camera(self.output, lens=self.lens)
        self.camera.setPos(15, 44, 3.)
        self.camera.setPos(15, 35, 15.)
        self.camera.lookAt(0, 0, 1.)

    def create_output(self, size, name):
        self.output = self.make_window(size=size, name=name)
        self.render_frame()
        self.render_frame()