def __init__(self):      
    self.sphere = loader.loadModel("InvertedSphere.egg")
    # Load a sphere with a radius of 1 unit and the faces directed inward.
    
    self.sphere.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition)
    self.sphere.setTexProjector(TextureStage.getDefault(), render, self.sphere)
    self.sphere.setTexPos(TextureStage.getDefault(), 0, 0, 0)
    self.sphere.setTexScale(TextureStage.getDefault(), .5)
    # Create some 3D texture coordinates on the sphere. For more info on this, check the Panda3D manual.
    
    tex = loader.loadCubeMap("BlueGreenNebula_#.png")
    self.sphere.setTexture(tex)
    # Load the cube map and apply it to the sphere.
    
    self.sphere.setLightOff()
    # Tell the sphere to ignore the lighting.
       
    self.sphere.setScale(1000)
    # Increase the scale of the sphere so it will be larger than the scene.
    
    self.sphere.reparentTo(render)
    # Reparent the sphere to render so you can see it.
    
    result = self.sphere.writeBamFile("SkySphere.bam")
    # Save out the bam file.
    print(result)
    def __init__(self):
        self.sphere = loader.loadModel("InvertedSphere.egg")
        # Load a sphere with a radius of 1 unit and the faces directed inward.

        self.sphere.setTexGen(TextureStage.getDefault(),
                              TexGenAttrib.MWorldPosition)
        self.sphere.setTexProjector(TextureStage.getDefault(), render,
                                    self.sphere)
        self.sphere.setTexPos(TextureStage.getDefault(), 0, 0, 0)
        self.sphere.setTexScale(TextureStage.getDefault(), .5)
        # Create some 3D texture coordinates on the sphere. For more info on this, check the Panda3D manual.

        tex = loader.loadCubeMap("data/skybox/sky_#.png")
        self.sphere.setTexture(tex)
        # Load the cube map and apply it to the sphere.

        self.sphere.setLightOff()
        # Tell the sphere to ignore the lighting.

        self.sphere.setScale(1000)
        # Increase the scale of the sphere so it will be larger than the scene.

        self.sphere.reparentTo(render)
        # Reparent the sphere to render so you can see it.

        result = self.sphere.writeBamFile("skysphere.bam")
        # Save out the bam file.
        print(result)
Exemple #3
0
 def __init__(self, base):
     tex = base.loader.loadCubeMap("./sky/sky_#.png")
     cube = base.loader.loadModel("./sky/icube.egg")
     cube.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition)
     cube.setTexProjector(TextureStage.getDefault(), base.render, cube)
     cube.setTexture(tex)
     cube.setBin("background", 1)
     cube.setLightOff()
     cube.setDepthWrite(False)
     cube.setScale(5, 5, 5)
     cube.reparentTo(base.camera)
     cube.setCompass()
Exemple #4
0
 def flipTexture(self):
     """ Sets the texture coordinates of the texture to the current frame"""
     sU = self.offsetX * self.repeatX
     sV = self.offsetY * self.repeatY
     oU = 0 + self.frames[self.currentFrame].col * self.uSize
     oV = 1 - self.frames[self.currentFrame].row * self.vSize - self.offsetY
     if self.flip['x']:
         sU *= -1
         oU = self.uSize + self.frames[self.currentFrame].col * self.uSize
     if self.flip['y']:
         sV *= -1
         oV = 1 - self.frames[self.currentFrame].row * self.vSize
     self.node.setTexScale(TextureStage.getDefault(), sU, sV)
     self.node.setTexOffset(TextureStage.getDefault(), oU, oV)
Exemple #5
0
 def flipTexture(self):
     """ Sets the texture coordinates of the texture to the current frame"""
     sU = self.offsetX * self.repeatX
     sV = self.offsetY * self.repeatY
     oU = 0 + self.frames[self.currentFrame].col * self.uSize
     oV = 1 - self.frames[self.currentFrame].row * self.vSize - self.offsetY
     if self.flip['x']:
         sU *= -1
         oU = self.uSize + self.frames[self.currentFrame].col * self.uSize
     if self.flip['y']:
         sV *= -1
         oV = 1 - self.frames[self.currentFrame].row * self.vSize
     self.node.setTexScale(TextureStage.getDefault(), sU, sV)
     self.node.setTexOffset(TextureStage.getDefault(), oU, oV)
    def __init__(self, **kwargs):
        """
        See the Element class to find out what attributes are available
        from scratch
        """
        super(VideoPlayer, self).__init__(**kwargs)

        self.videofile = getattr(self.config, 'file_video', None)
        self.loopCount = getattr(self.config, 'loop', 1)
        self.hoffset = getattr(self.config, 'hoffset', 0)
        self.voffset = getattr(self.config, 'voffset', 0)

        #self.videoScale = getattr(self.config, 'scale', (1,1))
        #self.playrate = getattr(self.config, 'speed', 1.0)

        if self.videofile:
            movieTexture = loader.loadTexture(self.videofile)
            cm = CardMaker("video_card")
            # cm.setFrameFullscreenQuad()
            cm.setUvRange(movieTexture)
            card = NodePath(cm.generate())
            card.reparentTo(self.hudNP)
            card.setTexture(movieTexture)
            card.setTexScale(TextureStage.getDefault(),
                             movieTexture.getTexScale())
            card.setPos(-0.5 + self.hoffset, 0.0, -0.5 + self.voffset)
            self.movie = movieTexture
            print card.getScale()
            self.time = 0
            self.movie.stop()

        self.hideElement()
Exemple #7
0
    def renderToGeom(resources, geom, video, audio):

        videoTex = loader.loadTexture(
            resources.getResourceFullPath(PanoConstants.RES_TYPE_VIDEOS,
                                          video))

        if videoTex is None:
            print "Couldn't load video %s" % video
            return None

#        if (base.sfxManagerList[0].getType().getName() != "OpenALAudioManager"):
#            self.log.error("OpenAL support is not enabled, cannot proceed.")
#            return None

        if (videoTex.getType().getName() != "MovieTexture"):
            print "MovieTexture support is not enabled, cannot proceed."
            return None

        geom.setTexture(videoTex)
        videoTex.setWrapU(Texture.WMClamp)
        videoTex.setWrapV(Texture.WMClamp)
        if videoTex.getTexturesPower2():
            geom.setTexScale(TextureStage.getDefault(), videoTex.getTexScale())

        if audio is not None:
            vidSound = loader.loadSfx(
                resources.getResourceFullPath(PanoConstants.RES_TYPE_MUSIC,
                                              audio))
            videoTex.synchronizeTo(vidSound)
            return vidSound
        else:
            return videoTex
    def __setupLevel(self):
        """
        Originally planned to have multiple levels, that never happened.
        """
        level1 = render.attachNewNode("level 1 node path")
        
        execfile("rooms/room.py")

        self.room = loader.loadModel("rooms/room")
        self.room.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        self.room.setScale(10,10,5)
        self.room.setTexScale(TextureStage.getDefault(), 10)
        self.room.reparentTo(render)
        self.room.find("**/Cube;+h").setTag("Room", "1")
        
        gate = loader.loadModel("models/box")
        
        gateTo2 = self.room.attachNewNode("gateTo2")
        gate.instanceTo(gateTo2)
        gateTo2.setPos(8, -10, 0)
        gateTo2.hide()
        
        self.physicsCollisionHandler.addInPattern("%fn-into-%in")
        self.physicsCollisionHandler.addOutPattern("%fn-out-%in")

        #messenger.toggleVerbose()
        self.gate = gate
    def __setupLevel(self):
        """
        Originally planned to have multiple levels, that never happened.
        """
        level1 = render.attachNewNode("level 1 node path")

        execfile("rooms/room.py")

        self.room = loader.loadModel("rooms/room")
        self.room.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        self.room.setScale(10, 10, 5)
        self.room.setTexScale(TextureStage.getDefault(), 10)
        self.room.reparentTo(render)
        self.room.find("**/Cube;+h").setTag("Room", "1")

        gate = loader.loadModel("models/box")

        gateTo2 = self.room.attachNewNode("gateTo2")
        gate.instanceTo(gateTo2)
        gateTo2.setPos(8, -10, 0)
        gateTo2.hide()

        self.physicsCollisionHandler.addInPattern("%fn-into-%in")
        self.physicsCollisionHandler.addOutPattern("%fn-out-%in")

        #messenger.toggleVerbose()
        self.gate = gate
Exemple #10
0
    def __init__(self,
                 world,
                 parent,
                 pos,
                 dir,
                 width,
                 height,
                 color,
                 name,
                 textureFilename=None):
        self.node = parent.attachNewNode("")
        self.node.setPos(*pos)
        self.node.lookAt(self.node, *dir)
        self.name = name

        divisions = 1
        for i in range(divisions):
            for j in range(divisions):
                self.makeCard(color, width, height, i, j, divisions)

        if textureFilename == None:
            self.texture = None
        else:
            self.texture = loader.loadTexture(textureFilename)
            self.texture.setWrapU(Texture.WMRepeat)
            self.texture.setWrapV(Texture.WMRepeat)
            self.node.setTexture(self.texture)
            self.node.setTexScale(TextureStage.getDefault(), 0.5, 0.5)

        self.geom = OdePlaneGeom(world.space,
                                 makeVec4FromPointAndNormal(pos, dir))
        world.space.setSurfaceType(self.geom, world.surfaces["plane"])
Exemple #11
0
    def _createSpritesNodeSetup(self, parent):
        '''
        Setups a new scenegraph that allows using screen coordinates instead of 3D. The conversions are automated
        by the configuration of the scene nodes. 
        '''
        screenWidth = base.win.getXSize()
        screenHeight = base.win.getYSize()

        aspect_ratio = parent.getScale()[0]

        screenOrigin = parent.attachNewNode('screen_origin')
        screenNode = screenOrigin.attachNewNode('screen_node')

        screenOrigin.setPos(-1.0 / aspect_ratio, 0.0, 1.0)
        screenOrigin.setScale(2.0, 1.0, -2.0)

        screenNode.setPos(0, 0, 0)

        screenNode.setScale(1.0 / (aspect_ratio * screenWidth), 1.0,
                            1.0 / screenHeight)
        screenNode.setTexScale(TextureStage.getDefault(), 1.0, -1.0)

        # test some points
        #    points = [(0,0), (screenWidth, 0), (screenWidth, screenHeight), (screenWidth/2.0, screenHeight/2.0), (0, screenHeight)]
        #    for pt in points:
        #        print '%s -> %s' % (pt, str(parent.getRelativePoint(screenNode, Vec3(pt[0], 0, pt[1]))))

        return screenNode
Exemple #12
0
	def updateHeightField( self ):
		''' recalculate heightfield
		'''
		if self.mHeightFieldNode != None:
			self.mHeightFieldNode.removeNode()
		posX, posY = self.world2MapPos( ( self.cameraPos.getX(), self.cameraPos.getY() ) )
		self.mHeightFieldTesselator.setFocalPoint( int(posX), int(posY) )
		self.mHeightFieldNode = self.mHeightFieldTesselator.generate()
		self.mHeightFieldNode.setPos( MAPSIZE/2, MAPSIZE/2, 0 )
		self.mHeightFieldNode.setHpr( 270, 0, 0 )
		self.mHeightFieldNode.reparentTo(render) 
		
		self.mHeightFieldNode.setTexGen( TextureStage.getDefault(), TexGenAttrib.MWorldPosition )
		scale = 1.0/8.0
		self.mHeightFieldNode.setTexScale( TextureStage.getDefault(), scale, scale );
		
		self.mHeightFieldNode.setTexture( self.tex0, 1 )
 def ry_floor(self, gso):
     tex = self.loader.loadTexture("wood_floor_tex_0.jpg")
     ts = TextureStage.getDefault()
     gso.setTexGen(ts, TexGenAttrib.MWorldPosition)
     gso.setTexProjector(ts, self.render, gso)
     gso.setTexture(ts, tex)
     gso.setTexScale(ts, Vec2(0.25, 0.25) * 10.)
     gso.setColor((0.99, 0.99, 0.99, 1.))
 def __setupEnvironment(self):
     cm = CardMaker("ground")
     size = 200
     cm.setFrame(-size, size, -size, size)
     environment = render.attachNewNode(cm.generate())
     environment.lookAt(0, 0, -1)
     environment.setPos(100, -100, 0)
     environment.setCollideMask(BitMask32.allOn())
     environment.reparentTo(render)
     
     texture = loader.loadTexture("textures/ground.png")
     
     # This is so the textures can look better from a distance
     texture.setMinfilter(Texture.FTLinearMipmapLinear)
     
     environment.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) 
     environment.setTexScale(TextureStage.getDefault(), 0.02, 0.02)
     environment.setTexture(texture, 1)
Exemple #15
0
	def add_texture(self,tex_path):
		plat_texture = loader.loadTexture(tex_path)
		#plat_texture.setWrapU(Texture.WMRepeat)
		#plat_texture.setWrapV(Texture.WMRepeat)
                self.model.setTexture(plat_texture,1)
        	ts = TextureStage.getDefault()
       	 	texture = self.model.getTexture()
		#self.model.setTexOffset(ts, -0.5, -0.5)
		self.model.setTexScale(ts, 2, 2)
Exemple #16
0
    def __init__(self, cubeMapPath=None):
        yawOff = 198
        self.sphere = loader.loadModel("InvertSphereBlend.egg")
        # self.sphere = loader.loadModel("InvertedSphere.egg")
        # Load a sphere with a radius of 1 unit and the faces directed inward.

        self.sphere.setTexGen(TextureStage.getDefault(),
                              TexGenAttrib.MWorldPosition)
        self.sphere.setTexProjector(TextureStage.getDefault(), render,
                                    self.sphere)
        self.sphere.setTexTransform(
            TextureStage.getDefault(),
            TransformState.makeHpr(VBase3(yawOff, 0, 0)))

        # Create some 3D texture coordinates on the sphere. For more info on this, check the Panda3D manual.
        self.sphere.setPos((0, 0, 0))
        self.sphere.setTexPos(TextureStage.getDefault(), 0, 0, 0)
        self.sphere.setTexScale(TextureStage.getDefault(), 1)

        # tex = loader.loadCubeMap(cubeMapPath)
        if cubeMapPath is None:
            cubeMapPath = renamer()
        tex = loader.loadCubeMap(cubeMapPath)
        self.sphere.setTexture(tex)
        # Load the cube map and apply it to the sphere.

        self.sphere.setLightOff()
        # Tell the sphere to ignore the lighting.

        self.sphere.setScale(10)

        # Increase the scale of the sphere so it will be larger than the scene.
        print self.sphere.getHpr()
        print self.sphere.getPos()
        self.sphere.reparentTo(render)

        # Reparent the sphere to render so you can see it.
        # result = self.sphere.writeBamFile(cubeMapPath.split('_#.tga')[0]+'.bam')
        print '/'.join(cubeMapPath.split('/')[:-1]) + '.bam'
        base.saveCubeMap('streetscene_cube_#.jpg', size=512)
        result = self.sphere.writeBamFile(
            '/'.join(cubeMapPath.split('/')[:-1]) + '.bam')
        # Save out the bam file.
        print(result)
    def __setupEnvironment(self):
        cm = CardMaker("ground")
        size = 100
        cm.setFrame(-size, size, -size, size)
        environment = render.attachNewNode(cm.generate())
        environment.lookAt(0, 0, -1)
        environment.setPos(0, 0, 0)
        environment.setCollideMask(BitMask32.allOn())
        environment.reparentTo(render)

        texture = loader.loadTexture("textures/ground.png")

        # This is so the textures can look better from a distance
        texture.setMinfilter(Texture.FTLinearMipmapLinear)

        environment.setTexGen(TextureStage.getDefault(),
                              TexGenAttrib.MWorldPosition)
        environment.setTexScale(TextureStage.getDefault(), 0.02, 0.02)
        environment.setTexture(texture, 1)
Exemple #18
0
    def __init__(self,cubeMapPath=None):
        yawOff=198
        self.sphere = loader.loadModel("InvertSphereBlend.egg")
        # self.sphere = loader.loadModel("InvertedSphere.egg")
        # Load a sphere with a radius of 1 unit and the faces directed inward.

        self.sphere.setTexGen(TextureStage.getDefault(),
                              TexGenAttrib.MWorldPosition)
        self.sphere.setTexProjector(TextureStage.getDefault(), render,
                                    self.sphere)
        self.sphere.setTexTransform(TextureStage.getDefault(),
                                    TransformState.makeHpr(VBase3(yawOff, 0, 0)))

        # Create some 3D texture coordinates on the sphere. For more info on this, check the Panda3D manual.
        self.sphere.setPos((0,0,0))
        self.sphere.setTexPos(TextureStage.getDefault(), 0, 0, 0)
        self.sphere.setTexScale(TextureStage.getDefault(), 1)

        # tex = loader.loadCubeMap(cubeMapPath)
        if cubeMapPath is None:
            cubeMapPath=renamer()
        tex = loader.loadCubeMap(cubeMapPath)
        self.sphere.setTexture(tex)
        # Load the cube map and apply it to the sphere.

        self.sphere.setLightOff()
        # Tell the sphere to ignore the lighting.

        self.sphere.setScale(10)

        # Increase the scale of the sphere so it will be larger than the scene.
        print self.sphere.getHpr()
        print self.sphere.getPos()
        self.sphere.reparentTo(render)


        # Reparent the sphere to render so you can see it.
        # result = self.sphere.writeBamFile(cubeMapPath.split('_#.tga')[0]+'.bam')
        print '/'.join(cubeMapPath.split('/')[:-1])+'.bam'
        base.saveCubeMap('streetscene_cube_#.jpg', size=512)
        result = self.sphere.writeBamFile('/'.join(cubeMapPath.split('/')[:-1])+'.bam')
        # Save out the bam file.
        print(result)
Exemple #19
0
    def applyTexture(self):
        self.texture = loader.loadTexture("media/gray_stone_tile.png")
        self.texture.setWrapU(Texture.WMRepeat)
        self.texture.setWrapV(Texture.WMRepeat)
        self.model.setTexture(self.texture, 1)

        # Calculate and apply texture scale factors.
        sizes = entrywiseMult(vecInvert(self.tileDir), self.size)
        scales = []
        for i in sizes:
            scales.append(i) if i != 0 else None
        self.model.setTexScale(TextureStage.getDefault(), scales[0], scales[1])
	def applyTexture(self):
		self.texture = loader.loadTexture("media/gray_stone_tile.png")
		self.texture.setWrapU(Texture.WMRepeat)
		self.texture.setWrapV(Texture.WMRepeat)
		self.model.setTexture(self.texture, 1)

		# Calculate and apply texture scale factors.
		sizes = entrywiseMult(vecInvert(self.tileDir), self.size)
		scales = []
		for i in sizes:
			scales.append(i) if i != 0 else None
		self.model.setTexScale(TextureStage.getDefault(), scales[0], scales[1])
Exemple #21
0
    def flipTexture(self):
        """ Sets the texture coordinates of the texture to the current frame"""
        for i in range(len(self.cards)):
            currentRow = self.rowPerFace[i]

            sU = self.offsetX * self.repeatX
            sV = self.offsetY * self.repeatY
            oU = 0 + self.currentFrame * self.uSize
            #oU = 0 + self.frames[self.currentFrame].col * self.uSize
            #oV = 1 - self.frames[self.currentFrame].row * self.vSize - self.offsetY
            oV = 1 - currentRow * self.vSize - self.offsetY
            if self.flip['x'] ^ i == 1:  ##hack to fix side view
                #print "flipping, i = ",i
                sU *= -1
                #oU = self.uSize + self.frames[self.currentFrame].col * self.uSize
                oU = self.uSize + self.currentFrame * self.uSize
            if self.flip['y']:
                sV *= -1
                #oV = 1 - self.frames[self.currentFrame].row * self.vSize
                oV = 1 - currentRow * self.vSize
            self.cards[i].setTexScale(TextureStage.getDefault(), sU, sV)
            self.cards[i].setTexOffset(TextureStage.getDefault(), oU, oV)
Exemple #22
0
	def flipTexture(self):
		""" Sets the texture coordinates of the texture to the current frame"""
		for i in range(len(self.cards)):
			currentRow = self.rowPerFace[i]

			sU = self.offsetX * self.repeatX
			sV = self.offsetY * self.repeatY
			oU = 0 + self.currentFrame * self.uSize
			#oU = 0 + self.frames[self.currentFrame].col * self.uSize
			#oV = 1 - self.frames[self.currentFrame].row * self.vSize - self.offsetY
			oV = 1 - currentRow * self.vSize - self.offsetY
			if self.flip['x'] ^ i==1: ##hack to fix side view
				#print "flipping, i = ",i
				sU *= -1
				#oU = self.uSize + self.frames[self.currentFrame].col * self.uSize
				oU = self.uSize + self.currentFrame * self.uSize
			if self.flip['y']:
				sV *= -1
				#oV = 1 - self.frames[self.currentFrame].row * self.vSize
				oV = 1 - currentRow * self.vSize
			self.cards[i].setTexScale(TextureStage.getDefault(), sU, sV)
			self.cards[i].setTexOffset(TextureStage.getDefault(), oU, oV)
Exemple #23
0
	def renderObject(self,scale,hpr,collisionOn=False):
		(x_scale,y_scale,z_scale) = scale
		(h,p,r) = hpr
		if collisionOn is True:
			if self.name is 'wide_ramp':
				(x_c,y_c,z_c) = (x_scale + .2,y_scale+2.5,z_scale+1.75)
			if self.name is 'tree1':
				(x_c,y_c,z_c) = (x_scale,y_scale,z_scale)
			if self.name is 'tree2':
				(x_c,y_c,z_c) = (x_scale,y_scale,z_scale)
			if self.name is 'rock1':
				(x_c,y_c,z_c) = (x_scale * 2,y_scale * 2,z_scale*2)
			if self.name is 'rock2':
				(x_c,y_c,z_c) = (x_scale*100,y_scale*100,z_scale*100)
			if self.name is 'gate':
				(x_c,y_c,z_c) = (x_scale * 10,y_scale,z_scale*3.5)
			if self.name is 'statue':
				(x_c,y_c,z_c) = (x_scale,y_scale,z_scale)

       			mesh = BulletTriangleMesh()
        		for geomNP in self.model.findAllMatches('**/+GeomNode'):
            			geomNode = geomNP.node()
            			ts = geomNP.getTransform(self.model)
          		for geom in geomNode.getGeoms():
                		mesh.addGeom(geom, ts)

        		shape = BulletTriangleMeshShape(mesh, dynamic=False)

            		node = BulletRigidBodyNode(self.name)
            		node.setMass(0)
            		node.addShape(shape)

			np = self.__game.render.attachNewNode(node)
			np.setPos(self.x,self.y,self.z)
			np.setHpr(h,p,r)
			np.setScale(x_c,y_c,z_c)

			self.__game.world.attachRigidBody(node)
		self.model.setPos(self.x,self.y,self.z)
		self.model.setHpr(h,p,r)
		self.model.setScale(x_scale,y_scale,z_scale)
		self.model.reparentTo(self.__game.render)
		
		if self.name is 'statue':
			plat_texture = loader.loadTexture('models/textures/rocky.jpg')
		        self.model.setTexture(plat_texture,1)
			ts = TextureStage.getDefault()
	       	 	texture = self.model.getTexture()
			self.model.setTexScale(ts, 1, 1)
Exemple #24
0
    def __init__(self):
        self.sphere = loader.loadModel("models/InvertedSphere.egg")
        # Load a sphere with a radius of 1 unit and the faces directed inward.

        self.sphere.setTexGen(TextureStage.getDefault(),
                              TexGenAttrib.MWorldPosition)
        self.sphere.setTexProjector(TextureStage.getDefault(), render,
                                    self.sphere)
        self.sphere.setTexPos(TextureStage.getDefault(), 0, 0, 0)
        self.sphere.setTexScale(TextureStage.getDefault(), .5)
        # Create some 3D texture coordinates on the sphere. For more info on this, check the Panda3D manual.

        tex = loader.loadCubeMap("models/Daylight Box_#.bmp")
        self.sphere.setTexture(tex)
        # Load the cube map and apply it to the sphere.

        self.sphere.setLightOff()
        # Tell the sphere to ignore the lighting.
        self.sphere.setP(-90)
        self.sphere.setScale(1000)

        # Increase the scale of the sphere so it will be larger than the scene.

        self.sphere.reparentTo(render)
Exemple #25
0
 def createSpritesNodeSetup(self): 
 
     aspect_ratio = self.mainRef.render2d.getScale()[0]    
      
     screenOrigin = self.mainRef.render2d.attachNewNode('screen_origin') 
     screenNode = screenOrigin.attachNewNode('screen_node') 
     
     screenOrigin.setPos(-1.0/aspect_ratio, 0.0, 1.0) 
     screenOrigin.setScale(2.0, 1.0, -2.0) 
     
     screenNode.setPos(0, 0, 0) 
      
     screenNode.setScale(1.0/(aspect_ratio*self.winSizeX), 1.0, 1.0/self.winSizeY) 
     screenNode.setTexScale(TextureStage.getDefault(), 1.0, -1.0)  
      
     return screenNode 
 def loadIcon(self, iconsFile, name):
     retVal = iconsFile.find(name)
     retVal.setBillboardAxis()
     retVal.reparentTo(self)
     dark = retVal.copyTo(NodePath())
     dark.reparentTo(retVal)
     dark.setColor(0.5, 0.5, 0.5, 1)
     retVal.setEffect(DecalEffect.make())
     retVal.setTransparency(TransparencyAttrib.MAlpha, 1)
     ll, ur = dark.getTightBounds()
     center = retVal.attachNewNode('center')
     center.setPos(0, 0, ll[2])
     dark.wrtReparentTo(center)
     dark.setTexProjector(TextureStage.getDefault(), center, retVal)
     retVal.hide()
     return (retVal, center)
 def loadIcon(self, iconsFile, name):
     """Load and returns one icon and the associated meter."""
     retVal = iconsFile.find(name)
     retVal.setBillboardAxis()
     retVal.reparentTo(self)
     # create a dark copy
     dark = retVal.copyTo(NodePath())
     dark.reparentTo(retVal)
     dark.setColor(0.5, 0.5, 0.5, 1)
     # make it look right when they are both on top of each other
     retVal.setEffect(DecalEffect.make())
     retVal.setTransparency(TransparencyAttrib.MAlpha, 1)
     # now for the tricky part, move it down and do the texture projection
     ll, ur = dark.getTightBounds()
     center = retVal.attachNewNode('center')
     center.setPos(0, 0, ll[2])
     dark.wrtReparentTo(center)
     dark.setTexProjector(TextureStage.getDefault(), center, retVal)
     retVal.hide()
     return retVal, center
	def __init__(self, world, parent, pos, dir, width, height, color, name, textureFilename=None):
		self.node = parent.attachNewNode("")
		self.node.setPos(*pos)
		self.node.lookAt(self.node, *dir)
		self.name = name

		divisions = 1
		for i in range(divisions):
			for j in range(divisions):
				self.makeCard(color, width, height, i, j, divisions)

		if textureFilename == None:
			self.texture = None
		else:
			self.texture = loader.loadTexture(textureFilename)
			self.texture.setWrapU(Texture.WMRepeat)
			self.texture.setWrapV(Texture.WMRepeat)
			self.node.setTexture(self.texture)
			self.node.setTexScale(TextureStage.getDefault(), 0.5, 0.5)

		self.geom = OdePlaneGeom(world.space, makeVec4FromPointAndNormal(pos, dir))
		world.space.setSurfaceType(self.geom, world.surfaces["plane"])
 def setTexture(self,texFile,sx,sy):
     self.terrain.getRoot().setTexture(loader.loadTexture(texFile))
     self.terrain.getRoot().setTexScale(TextureStage.getDefault(), sx, sy)
     self.terrain.getRoot().getTexture().setMinfilter(Texture.FTLinearMipmapLinear)
    def getShip(
        self,
        shipClass,
        style=ShipGlobals.Styles.Undefined,
        logo=ShipGlobals.Logos.Undefined,
        hullDesign=None,
        detailLevel=2,
        wantWheel=True,
        hullMaterial=None,
        sailMaterial=None,
        sailPattern=None,
        prowType=None,
    ):
        Ship = Ship
        import pirates.ship

        modelClass = ShipGlobals.getModelClass(shipClass)
        shipConfig = ShipGlobals.getShipConfig(shipClass)
        if style == ShipGlobals.Styles.Undefined:
            style = shipConfig["defaultStyle"]

        complexCustomization = 0
        if sailPattern and sailMaterial and hullMaterial or SailReplace.has_key(shipClass):
            complexCustomization = 1

        if not prowType:
            prowType = shipConfig["prow"]

        if not hullMaterial:
            hullMaterial = style

        if not sailMaterial:
            if SailReplace.has_key(shipClass):
                sailMaterial = SailReplace[shipClass]
            else:
                sailMaterial = style

        if not sailPattern:
            sailPattern = style

        shipHullTexture = ShipBlueprints.getShipTexture(hullMaterial)
        shipTextureSail = ShipBlueprints.getShipTexture(sailMaterial)
        logoTex = None
        if logo:
            logoTex = ShipBlueprints.getLogoTexture(logo)

        sailPatternTex = None
        if sailPattern:
            sailPatternTex = ShipBlueprints.getSailTexture(sailPattern)

        self.notify.debug("%s %s" % (sailPattern, logo))
        if logo == ShipGlobals.Logos.Undefined:
            logo = shipConfig["sailLogo"]

        if logo in ShipGlobals.MAST_LOGO_PLACEMENT_LIST:
            placeLogos = 1
        else:
            placeLogos = 0
        if modelClass <= ShipGlobals.INTERCEPTORL3:
            mastHax = True
        else:
            mastHax = False
        customHull = hullDesign is not None
        if not logo != 0:
            pass
        customMasts = sailPattern != 0
        hull = self.getHull(modelClass, customHull)
        breakAnims = {}
        metaAnims = {}
        hitAnims = {}
        root = NodePath("Ship")
        hull.locators.reparentTo(root)
        charRoot = root.attachNewNode(Character("ShipChar"))
        collisions = root.attachNewNode("collisions")
        lodNode = charRoot.attachNewNode(LODNode("lod"))
        if detailLevel == 0:
            lodNode.node().addSwitch(200, 0)
            lodNode.node().addSwitch(800, 200)
            lodNode.node().addSwitch(100000, 800)
            high = lodNode.attachNewNode("high")
            low = lodNode.attachNewNode("low")
            med = NodePath("med")
            superlow = lodNode.attachNewNode("superlow")
        elif detailLevel == 1:
            lodNode.node().addSwitch(300, 0)
            lodNode.node().addSwitch(1000, 300)
            lodNode.node().addSwitch(2000, 1000)
            lodNode.node().addSwitch(100000, 2000)
            high = lodNode.attachNewNode("high")
            med = lodNode.attachNewNode("med")
            low = lodNode.attachNewNode("low")
            superlow = lodNode.attachNewNode("superlow")
        else:
            lodNode.node().addSwitch(750, 0)
            lodNode.node().addSwitch(3000, 750)
            lodNode.node().addSwitch(8000, 3000)
            lodNode.node().addSwitch(100000, 8000)
            high = lodNode.attachNewNode("high")
            med = lodNode.attachNewNode("med")
            low = lodNode.attachNewNode("low")
            superlow = lodNode.attachNewNode("superlow")
        mastSetup = ShipGlobals.getMastSetup(shipClass)
        for data in [
            (0, "location_mainmast_0"),
            (1, "location_mainmast_1"),
            (2, "location_mainmast_2"),
            (3, "location_aftmast*"),
            (4, "location_foremast*"),
        ]:
            mastData = mastSetup.get(data[0])
            if mastData:
                mast = self.mastSets[mastData[0]].getMastSet(mastData[1] - 1, customMasts)
                mastRoot = hull.locators.find("**/%s" % data[1]).getTransform(hull.locators)
                model = NodePath(mast.charRoot)
                model.setTransform(mastRoot)
                if complexCustomization:
                    model.setTexture(shipTextureSail)

                useLogoTex = logoTex
                if placeLogos:
                    mastNum = data[0]
                    if mastNum not in ShipGlobals.MAST_LOGO_PLACEMENT.get(modelClass):
                        useLogoTex = None

                charBundle = mast.charRoot.getBundle(0)
                if data[0] < 3:
                    for side in ["left", "right"]:
                        ropeNode = hull.locators.find("**/location_ropeLadder_%s_%s" % (side, data[0]))
                        if ropeNode:
                            transform = ropeNode.getTransform(NodePath(mast.charRoot))
                            charBundle.findChild("def_ladder_0_%s" % side).applyFreeze(transform)
                            continue

                if sailPatternTex and useLogoTex:
                    for node in model.findAllMatches("**/sails"):
                        node.setTextureOff(TextureStage.getDefault())
                        node.setTexture(self.colorLayer, sailPatternTex)
                        node.setTexture(self.logoLayer, logoTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                elif sailPatternTex:
                    for node in model.findAllMatches("**/sails"):
                        node.setTextureOff(TextureStage.getDefault())
                        node.setTexture(self.colorLayer, sailPatternTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                elif useLogoTex:
                    for node in model.findAllMatches("**/sails"):
                        node.setTextureOff(TextureStage.getDefault())
                        node.setTexture(self.logoLayerNoColor, logoTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                model.flattenLight()
                if detailLevel == 0:
                    model.find("**/low").copyTo(high)
                    model.find("**/low").copyTo(low)
                    model.find("**/superlow").copyTo(superlow)
                elif detailLevel == 1:
                    model.find("**/med").copyTo(high)
                    model.find("**/med").copyTo(med)
                    low.node().stealChildren(model.find("**/low").node())
                    superlow.node().stealChildren(model.find("**/superlow").node())
                elif detailLevel == 2:
                    high.node().stealChildren(model.find("**/high").node())
                    med.node().stealChildren(model.find("**/med").node())
                    low.node().stealChildren(model.find("**/low").node())
                    superlow.node().stealChildren(model.find("**/superlow").node())

                mastRoot = mast.collisions.find("**/collision_masts")
                if modelClass > ShipGlobals.INTERCEPTORL3 or data[0] != 3:
                    mastCode = str(data[0])
                    mastRoot.setTag("Mast Code", mastCode)
                else:
                    mastRoot.setName("colldision_sub_mast")
                    mastRoot.reparentTo(collisions.find("**/collision_masts"))
                    mastCode = "0"
                for coll in mast.collisions.findAllMatches("**/collision_sail_*"):
                    coll.setName("Sail-%s" % data[0])
                    coll.setTag("Mast Code", mastCode)

                for coll in mast.collisions.findAllMatches("**/sail_*"):
                    coll.setName("Sail-%s" % data[0])
                    coll.setTag("Mast Code", mastCode)

                collisions.node().stealChildren(mast.collisions.node())
                charBundle = mast.charRoot.getBundle(0)
                if mastHax and data[0] == 3:
                    breakAnims[0][0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.breakAnim[0], -1, MastSubset, True), "1"
                    )
                    breakAnims[0][1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.breakAnim[1], -1, MastSubset, True), "1"
                    )
                    tempHit = hitAnims[0]
                    tempHit[0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, HitMastSubset, True), "1"
                    )
                    tempHit[1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, PartSubset(), True), "1"
                    )
                else:
                    breakAnims[data[0]] = (AnimControlCollection(), AnimControlCollection())
                    breakAnims[data[0]][0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.breakAnim[0], -1, MastSubset, True), "0"
                    )
                    breakAnims[data[0]][1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.breakAnim[1], -1, MastSubset, True), "0"
                    )
                    tempHit = [AnimControlCollection(), AnimControlCollection()]
                    tempHit[0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, HitMastSubset, True), "0"
                    )
                    tempHit[1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim, -1, PartSubset(), True), "0"
                    )
                    hitAnims[data[0]] = tempHit
                for (anim, fileName) in mast.metaAnims.iteritems():
                    if anim not in metaAnims:
                        metaAnims[anim] = AnimControlCollection()

                    if anim not in MissingAnims.get(modelClass, []):
                        ac = charBundle.loadBindAnim(loader.loader, fileName, -1, SailSubset, True)
                        if ac:
                            metaAnims[anim].storeAnim(ac, str(metaAnims[anim].getNumAnims()))

                charRoot.node().combineWith(mast.charRoot)
                continue

        if self.wantProws and prowType:
            (highSprit, medSprit, lowSprit) = self.sprits[prowType].getAsset()
            transform = hull.locators.find("**/location_bowsprit").getTransform(hull.locators)
            highSprit.setTransform(transform)
            medSprit.setTransform(transform)
            lowSprit.setTransform(transform)
            highSprit.reparentTo(hull.geoms[0])
            medSprit.reparentTo(hull.geoms[1])
            lowSprit.reparentTo(hull.geoms[2])

        if wantWheel:
            shipWheel = ShipBlueprints.getWheel()
            wheelPoint = hull.locators.find("**/location_wheel;+s").getTransform(hull.locators)
            shipWheel.setTransform(wheelPoint)
            shipWheel.flattenLight()
            shipWheel.find("**/collisions").copyTo(collisions)
            hull.geoms[0].node().stealChildren(shipWheel.find("**/high").node())
            hull.geoms[1].node().stealChildren(shipWheel.find("**/med").node())
            hull.geoms[2].node().stealChildren(shipWheel.find("**/low").node())

        if complexCustomization:
            hull.geoms[0].setTexture(shipHullTexture)
            hull.geoms[0].flattenLight()
            hull.geoms[1].setTexture(shipHullTexture)
            hull.geoms[1].flattenLight()
            hull.geoms[2].setTexture(shipHullTexture)
            hull.geoms[2].flattenLight()
            hull.geoms[3].setTexture(shipHullTexture)
            hull.geoms[3].flattenLight()

        high.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[0].node())
        med.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[1].node())
        low.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[2].node())
        superlow.attachNewNode(ModelNode("non-animated")).node().stealChildren(hull.geoms[3].node())
        collisions.node().stealChildren(hull.collisions.node())
        hull.locators.stash()
        charRoot.flattenStrong()
        ship = Ship.Ship(shipClass, root, breakAnims, hitAnims, metaAnims, collisions, hull.locators)
        if not complexCustomization:
            ship.char.setTexture(shipHullTexture)

        return ship
Exemple #31
0
    def getShip(self,
                shipClass,
                style=ShipGlobals.Styles.Undefined,
                logo=ShipGlobals.Logos.Undefined,
                hullDesign=None,
                detailLevel=2,
                wantWheel=True,
                hullMaterial=None,
                sailMaterial=None,
                sailPattern=None,
                prowType=None,
                invertLogo=False):
        Ship = Ship
        import pirates.ship
        modelClass = ShipGlobals.getModelClass(shipClass)
        shipConfig = ShipGlobals.getShipConfig(shipClass)
        if style == ShipGlobals.Styles.Undefined:
            style = shipConfig['defaultStyle']

        complexCustomization = 0
        if sailPattern and sailMaterial and hullMaterial or SailReplace.has_key(
                shipClass):
            complexCustomization = 1

        if not prowType:
            prowType = shipConfig['prow']

        if not hullMaterial:
            hullMaterial = style

        if not sailMaterial:
            if SailReplace.has_key(shipClass):
                sailMaterial = SailReplace[shipClass]
            else:
                sailMaterial = style

        if not sailPattern:
            sailPattern = style

        shipHullTexture = ShipBlueprints.getShipTexture(hullMaterial)
        shipTextureSail = ShipBlueprints.getShipTexture(sailMaterial)
        logoTex = None
        if logo:
            logoTex = ShipBlueprints.getLogoTexture(logo)

        sailPatternTex = None
        if sailPattern:
            sailPatternTex = ShipBlueprints.getSailTexture(sailPattern)

        self.notify.debug('%s %s' % (sailPattern, logo))
        if logo == ShipGlobals.Logos.Undefined:
            logo = shipConfig['sailLogo']

        if logo in ShipGlobals.MAST_LOGO_PLACEMENT_LIST:
            placeLogos = 1
        else:
            placeLogos = 0
        if modelClass <= ShipGlobals.INTERCEPTORL3:
            mastHax = True
        else:
            mastHax = False
        customHull = hullDesign is not None
        if not logo != 0:
            pass
        customMasts = sailPattern != 0
        hull = self.getHull(modelClass, customHull)
        breakAnims = {}
        metaAnims = {}
        hitAnims = {}
        root = NodePath('Ship')
        hull.locators.reparentTo(root)
        charRoot = root.attachNewNode(Character('ShipChar'))
        collisions = root.attachNewNode('collisions')
        lodNode = charRoot.attachNewNode(LODNode('lod'))
        if detailLevel == 0:
            lodNode.node().addSwitch(200, 0)
            lodNode.node().addSwitch(800, 200)
            lodNode.node().addSwitch(100000, 800)
            high = lodNode.attachNewNode('high')
            low = lodNode.attachNewNode('low')
            med = NodePath('med')
            superlow = lodNode.attachNewNode('superlow')
        elif detailLevel == 1:
            lodNode.node().addSwitch(300, 0)
            lodNode.node().addSwitch(1000, 300)
            lodNode.node().addSwitch(2000, 1000)
            lodNode.node().addSwitch(100000, 2000)
            high = lodNode.attachNewNode('high')
            med = lodNode.attachNewNode('med')
            low = lodNode.attachNewNode('low')
            superlow = lodNode.attachNewNode('superlow')
        else:
            lodNode.node().addSwitch(750, 0)
            lodNode.node().addSwitch(3000, 750)
            lodNode.node().addSwitch(8000, 3000)
            lodNode.node().addSwitch(100000, 8000)
            high = lodNode.attachNewNode('high')
            med = lodNode.attachNewNode('med')
            low = lodNode.attachNewNode('low')
            superlow = lodNode.attachNewNode('superlow')
        mastSetup = ShipGlobals.getMastSetup(shipClass)
        for data in [(0, 'location_mainmast_0'), (1, 'location_mainmast_1'),
                     (2, 'location_mainmast_2'), (3, 'location_aftmast*'),
                     (4, 'location_foremast*')]:
            mastData = mastSetup.get(data[0])
            if mastData:
                mast = self.mastSets[mastData[0]].getMastSet(
                    mastData[1] - 1, customMasts)
                mastRoot = hull.locators.find('**/%s' % data[1]).getTransform(
                    hull.locators)
                model = NodePath(mast.charRoot)
                model.setTransform(mastRoot)
                if complexCustomization:
                    model.setTexture(shipTextureSail)

                useLogoTex = logoTex
                if placeLogos:
                    mastNum = data[0]
                    if mastNum not in ShipGlobals.MAST_LOGO_PLACEMENT.get(
                            modelClass):
                        useLogoTex = None

                charBundle = mast.charRoot.getBundle(0)
                if data[0] < 3:
                    for side in ['left', 'right']:
                        ropeNode = hull.locators.find(
                            '**/location_ropeLadder_%s_%s' % (side, data[0]))
                        if ropeNode:
                            transform = ropeNode.getTransform(
                                NodePath(mast.charRoot))
                            charBundle.findChild('def_ladder_0_%s' %
                                                 side).applyFreeze(transform)
                            continue

                if sailPatternTex and useLogoTex:
                    for node in model.findAllMatches('**/sails'):
                        node.setTextureOff(TextureStage.getDefault())
                        node.setTexture(self.colorLayer, sailPatternTex)
                        if invertLogo:
                            node.setTexture(self.logoLayerInv, logoTex)
                        else:
                            node.setTexture(self.logoLayer, logoTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                elif sailPatternTex:
                    for node in model.findAllMatches('**/sails'):
                        node.setTextureOff(TextureStage.getDefault())
                        node.setTexture(self.colorLayer, sailPatternTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                elif useLogoTex:
                    for node in model.findAllMatches('**/sails'):
                        node.setTextureOff(TextureStage.getDefault())
                        if invertLogo:
                            node.setTexture(self.logoLayerNoColorInv, logoTex)
                        else:
                            node.setTexture(self.logoLayerNoColor, logoTex)
                        node.setTexture(self.vertLayer, shipTextureSail)
                        node.setTexture(self.baseLayer, shipTextureSail)

                model.flattenLight()
                if detailLevel == 0:
                    model.find('**/low').copyTo(high)
                    model.find('**/low').copyTo(low)
                    model.find('**/superlow').copyTo(superlow)
                elif detailLevel == 1:
                    model.find('**/med').copyTo(high)
                    model.find('**/med').copyTo(med)
                    low.node().stealChildren(model.find('**/low').node())
                    superlow.node().stealChildren(
                        model.find('**/superlow').node())
                elif detailLevel == 2:
                    high.node().stealChildren(model.find('**/high').node())
                    med.node().stealChildren(model.find('**/med').node())
                    low.node().stealChildren(model.find('**/low').node())
                    superlow.node().stealChildren(
                        model.find('**/superlow').node())

                mastRoot = mast.collisions.find('**/collision_masts')
                if modelClass > ShipGlobals.INTERCEPTORL3 or data[0] != 3:
                    mastCode = str(data[0])
                    mastRoot.setTag('Mast Code', mastCode)
                else:
                    mastRoot.setName('colldision_sub_mast')
                    mastRoot.reparentTo(collisions.find('**/collision_masts'))
                    mastCode = '0'
                for coll in mast.collisions.findAllMatches(
                        '**/collision_sail_*'):
                    coll.setName('Sail-%s' % data[0])
                    coll.setTag('Mast Code', mastCode)

                for coll in mast.collisions.findAllMatches('**/sail_*'):
                    coll.setName('Sail-%s' % data[0])
                    coll.setTag('Mast Code', mastCode)

                collisions.node().stealChildren(mast.collisions.node())
                charBundle = mast.charRoot.getBundle(0)
                if mastHax and data[0] == 3:
                    breakAnims[0][0].storeAnim(
                        charBundle.loadBindAnim(loader.loader,
                                                mast.breakAnim[0], -1,
                                                MastSubset, True), '1')
                    breakAnims[0][1].storeAnim(
                        charBundle.loadBindAnim(loader.loader,
                                                mast.breakAnim[1], -1,
                                                MastSubset, True), '1')
                    tempHit = hitAnims[0]
                    tempHit[0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim,
                                                -1, HitMastSubset, True), '1')
                    tempHit[1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim,
                                                -1, PartSubset(), True), '1')
                else:
                    breakAnims[data[0]] = (AnimControlCollection(),
                                           AnimControlCollection())
                    breakAnims[data[0]][0].storeAnim(
                        charBundle.loadBindAnim(loader.loader,
                                                mast.breakAnim[0], -1,
                                                MastSubset, True), '0')
                    breakAnims[data[0]][1].storeAnim(
                        charBundle.loadBindAnim(loader.loader,
                                                mast.breakAnim[1], -1,
                                                MastSubset, True), '0')
                    tempHit = [
                        AnimControlCollection(),
                        AnimControlCollection()
                    ]
                    tempHit[0].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim,
                                                -1, HitMastSubset, True), '0')
                    tempHit[1].storeAnim(
                        charBundle.loadBindAnim(loader.loader, mast.hitAnim,
                                                -1, PartSubset(), True), '0')
                    hitAnims[data[0]] = tempHit
                for (anim, fileName) in mast.metaAnims.iteritems():
                    if anim not in metaAnims:
                        metaAnims[anim] = AnimControlCollection()

                    if anim not in MissingAnims.get(modelClass, []):
                        ac = charBundle.loadBindAnim(loader.loader, fileName,
                                                     -1, SailSubset, True)
                        if ac:
                            metaAnims[anim].storeAnim(
                                ac, str(metaAnims[anim].getNumAnims()))

                charRoot.node().combineWith(mast.charRoot)
                continue

        if self.wantProws and prowType:
            (highSprit, medSprit, lowSprit) = self.sprits[prowType].getAsset()
            transform = hull.locators.find(
                '**/location_bowsprit').getTransform(hull.locators)
            highSprit.setTransform(transform)
            medSprit.setTransform(transform)
            lowSprit.setTransform(transform)
            highSprit.reparentTo(hull.geoms[0])
            medSprit.reparentTo(hull.geoms[1])
            lowSprit.reparentTo(hull.geoms[2])

        if wantWheel:
            shipWheel = ShipBlueprints.getWheel()
            wheelPoint = hull.locators.find(
                '**/location_wheel;+s').getTransform(hull.locators)
            shipWheel.setTransform(wheelPoint)
            shipWheel.flattenLight()
            shipWheel.find('**/collisions').copyTo(collisions)
            hull.geoms[0].node().stealChildren(
                shipWheel.find('**/high').node())
            hull.geoms[1].node().stealChildren(shipWheel.find('**/med').node())
            hull.geoms[2].node().stealChildren(shipWheel.find('**/low').node())

        if complexCustomization:
            hull.geoms[0].setTexture(shipHullTexture)
            hull.geoms[0].flattenLight()
            hull.geoms[1].setTexture(shipHullTexture)
            hull.geoms[1].flattenLight()
            hull.geoms[2].setTexture(shipHullTexture)
            hull.geoms[2].flattenLight()
            hull.geoms[3].setTexture(shipHullTexture)
            hull.geoms[3].flattenLight()

        high.attachNewNode(ModelNode('non-animated')).node().stealChildren(
            hull.geoms[0].node())
        med.attachNewNode(ModelNode('non-animated')).node().stealChildren(
            hull.geoms[1].node())
        low.attachNewNode(ModelNode('non-animated')).node().stealChildren(
            hull.geoms[2].node())
        superlow.attachNewNode(ModelNode('non-animated')).node().stealChildren(
            hull.geoms[3].node())
        collisions.node().stealChildren(hull.collisions.node())
        hull.locators.stash()
        charRoot.flattenStrong()
        ship = Ship.Ship(shipClass, root, breakAnims, hitAnims, metaAnims,
                         collisions, hull.locators)
        if not complexCustomization:
            ship.char.setTexture(shipHullTexture)

        return ship
Exemple #32
0
    def __init__(self, image_path, name=None,\
                  rows=1, cols=1, scale=1.0,\
                  twoSided=True, alpha=TRANS_ALPHA,\
                  repeatX=1, repeatY=1,\
                  anchorX=ALIGN_LEFT, anchorY=ALIGN_BOTTOM):
        """
        Create a card textured with an image. The card is sized so that the ratio between the
        card and image is the same.
        """
       
        scale *= self.PIXEL_SCALE
       
        self.animations = {}
       
        self.scale = scale
        self.repeatX = repeatX
        self.repeatY = repeatY
        self.flip = {'x':False,'y':False}
        self.rows = rows
        self.cols = cols
       
        self.currentFrame = 0
        self.currentAnim = None
        self.loopAnim = False
        self.frameInterrupt = True
       
        # Create the NodePath
        if name:
            self.node = NodePath("Sprite2d:%s" % name)
        else:
            self.node = NodePath("Sprite2d:%s" % image_path)
       
        # Set the attribute for transparency/twosided
        self.node.node().setAttrib(TransparencyAttrib.make(alpha))
        if twoSided:
            self.node.setTwoSided(True)
       
        # Make a filepath
        self.imgFile = Filename(image_path)
        if self.imgFile.empty():
            raise IOError, "File not found"
       
        # Instead of loading it outright, check with the PNMImageHeader if we can open
        # the file.
        imgHead = PNMImageHeader()
        if not imgHead.readHeader(self.imgFile):
            raise IOError, "PNMImageHeader could not read file. Try using absolute filepaths"
       
        # Load the image with a PNMImage
        image = PNMImage()
        image.read(self.imgFile)
       
        self.sizeX = image.getXSize()
        self.sizeY = image.getYSize()
       
        self.frames = []
        for rowIdx in xrange(self.rows):
            for colIdx in xrange(self.cols):
                self.frames.append(Sprite2d.Cell(colIdx, rowIdx))
       
        # We need to find the power of two size for the another PNMImage
        # so that the texture thats loaded on the geometry won't have artifacts
        textureSizeX = self.nextsize(self.sizeX)
        textureSizeY = self.nextsize(self.sizeY)
       
        # The actual size of the texture in memory
        self.realSizeX = textureSizeX
        self.realSizeY = textureSizeY
       
        self.paddedImg = PNMImage(textureSizeX, textureSizeY)
        if image.hasAlpha():
            self.paddedImg.alphaFill(0)
        # Copy the source image to the image we're actually using
        self.paddedImg.blendSubImage(image, 0, 0)
        # We're done with source image, clear it
        image.clear()
       
        # The pixel sizes for each cell
        self.colSize = self.sizeX/self.cols
        self.rowSize = self.sizeY/self.rows
       
        # How much padding the texture has
        self.paddingX = textureSizeX - self.sizeX
        self.paddingY = textureSizeY - self.sizeY
       
        # Set UV padding
        self.uPad = float(self.paddingX)/textureSizeX
        self.vPad = float(self.paddingY)/textureSizeY
       
        # The UV dimensions for each cell
        self.uSize = (1.0 - self.uPad) / self.cols
        self.vSize = (1.0 - self.vPad) / self.rows
       
        card = CardMaker("Sprite2d-Geom")

        # The positions to create the card at
        if anchorX == self.ALIGN_LEFT:
            posLeft = 0
            posRight = (self.colSize/scale)*repeatX
        elif anchorX == self.ALIGN_CENTER:
            posLeft = -(self.colSize/2.0/scale)*repeatX
            posRight = (self.colSize/2.0/scale)*repeatX
        elif anchorX == self.ALIGN_RIGHT:
            posLeft = -(self.colSize/scale)*repeatX
            posRight = 0
       
        if anchorY == self.ALIGN_BOTTOM:
            posTop = 0
            posBottom = (self.rowSize/scale)*repeatY
        elif anchorY == self.ALIGN_CENTER:
            posTop = -(self.rowSize/2.0/scale)*repeatY
            posBottom = (self.rowSize/2.0/scale)*repeatY
        elif anchorY == self.ALIGN_TOP:
            posTop = -(self.rowSize/scale)*repeatY
            posBottom = 0
       
        card.setFrame(posLeft, posRight, posTop, posBottom)
        card.setHasUvs(True)
        self.card = self.node.attachNewNode(card.generate())
       
        # Since the texture is padded, we need to set up offsets and scales to make
        # the texture fit the whole card
        self.offsetX = (float(self.colSize)/textureSizeX)
        self.offsetY = (float(self.rowSize)/textureSizeY)
       
        self.node.setTexScale(TextureStage.getDefault(), self.offsetX * repeatX, self.offsetY * repeatY)
        self.node.setTexOffset(TextureStage.getDefault(), 0, 1-self.offsetY)
       
        self.texture = Texture()
       
        self.texture.setXSize(textureSizeX)
        self.texture.setYSize(textureSizeY)
        self.texture.setZSize(1)
       
        # Load the padded PNMImage to the texture
        self.texture.load(self.paddedImg)

        self.texture.setMagfilter(Texture.FTNearest)
        self.texture.setMinfilter(Texture.FTNearest)
       
        #Set up texture clamps according to repeats
        if repeatX > 1:
            self.texture.setWrapU(Texture.WMRepeat)
        else:
            self.texture.setWrapU(Texture.WMClamp)
        if repeatY > 1:
            self.texture.setWrapV(Texture.WMRepeat)
        else:
            self.texture.setWrapV(Texture.WMClamp)
       
        self.node.setTexture(self.texture)
Exemple #33
0
    def loadLevel(self, level):

        #Resets

        self.avatarActor = Actor("models/panda",
                                {"walk": "models/panda-walk"})
        self.avatarActor.setScale(.5, .5, .5)
        self.avatarActor.setHpr(180, 0, 0)
        self.avatarActor.setCollideMask(BitMask32.allOff())

        self.asteroidManager = AsteroidManager()

        #Alternate modes

        if int(self.level) == self.level: self.play_mode = TERRAIN

        else: self.play_mode = SPACE

        #Specifics

        if self.play_mode == SPACE:

            self.avatar = Avatar(self.avatarActor)
            self.avatar.objectNP.reparentTo(render)

            ########## Sky #########

            cubeMap = loader.loadCubeMap(self.loadSpaceTexture(self.level))
            self.spaceSkyBox = loader.loadModel('models/box')

            self.spaceSkyBox.setScale(100)
            self.spaceSkyBox.setBin('background', 0)
            self.spaceSkyBox.setDepthWrite(0)
            self.spaceSkyBox.setTwoSided(True)
            self.spaceSkyBox.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldCubeMap)
            self.spaceSkyBox.setTexture(cubeMap, 1)
            #self.spaceSkyBox.setEffect(CompassEffect.make(render))

            parentNP = render.attachNewNode('parent')

            self.spaceSkyBox.reparentTo(parentNP)
            self.spaceSkyBox.setPos(-self.spaceSkyBox.getSx()/2, -self.spaceSkyBox.getSy()/2, 
                                    -self.spaceSkyBox.getSz()/2)

            self.asteroidManager.initialize(self.level)

        elif self.play_mode == TERRAIN:

            ########## Terrain #########

            #self.environ = loader.loadModel("../mystuff/test.egg")
            self.environ = loader.loadModel("models/environment")
            self.environ.setName("terrain")
            self.environ.reparentTo(render)
            self.environ.setPos(0, 0, 0)
            self.environ.setCollideMask(BitMask32.bit(0))

            ######### Models #########

            ######### Physics #########

            base.enableParticles()

            gravityForce = LinearVectorForce(0, 0, -9.81)
            gravityForce.setMassDependent(False)
            gravityFN = ForceNode("world-forces")
            gravityFN.addForce(gravityForce)
            render.attachNewNode(gravityFN)
            base.physicsMgr.addLinearForce(gravityForce)

            self.avatarPhysicsActorNP = render.attachNewNode(ActorNode("player"))
            self.avatarPhysicsActorNP.node().getPhysicsObject().setMass(50.)
            self.avatarActor.reparentTo(self.avatarPhysicsActorNP)
            base.physicsMgr.attachPhysicalNode(self.avatarPhysicsActorNP.node())

            self.avatarPhysicsActorNP.setPos(15, 10, 5)

            ######### Game objects #########

            self.avatar = Avatar(self.avatarPhysicsActorNP)

            ######### Collisions #########

            self.cTrav = CollisionTraverser()

            #Make player rigid body

            self.pandaBodySphere = CollisionSphere(0, 0, 4, 3)

            self.pandaBodySphereNode = CollisionNode("playerBodyRay")
            self.pandaBodySphereNode.addSolid(self.pandaBodySphere)
            self.pandaBodySphereNode.setFromCollideMask(BitMask32.bit(0))
            self.pandaBodySphereNode.setIntoCollideMask(BitMask32.allOff())

            self.pandaBodySphereNodepath = self.avatar.objectNP.attachNewNode(self.pandaBodySphereNode)
            self.pandaBodySphereNodepath.show()

            self.pandaBodyCollisionHandler = PhysicsCollisionHandler()
            self.pandaBodyCollisionHandler.addCollider(self.pandaBodySphereNodepath, self.avatar.objectNP)

            #Keep player on ground

            self.pandaGroundSphere = CollisionSphere(0, 0, 1, 1)

            self.pandaGroundSphereNode = CollisionNode("playerGroundRay")
            self.pandaGroundSphereNode.addSolid(self.pandaGroundSphere)
            self.pandaGroundSphereNode.setFromCollideMask(BitMask32.bit(0))
            self.pandaGroundSphereNode.setIntoCollideMask(BitMask32.allOff())

            self.pandaGroundSphereNodepath = self.avatar.objectNP.attachNewNode(self.pandaGroundSphereNode)
            self.pandaGroundSphereNodepath.show()

            self.pandaGroundCollisionHandler = PhysicsCollisionHandler()
            self.pandaGroundCollisionHandler.addCollider(self.pandaGroundSphereNodepath, self.avatar.objectNP)

            #Notify when player lands

            self.pandaGroundRayJumping = CollisionSphere(0, 0, 1, 1)

            self.pandaGroundRayNodeJumping = CollisionNode("playerGroundRayJumping")
            self.pandaGroundRayNodeJumping.addSolid(self.pandaGroundRayJumping)
            self.pandaGroundRayNodeJumping.setFromCollideMask(BitMask32.bit(0))
            self.pandaGroundRayNodeJumping.setIntoCollideMask(BitMask32.allOff())

            self.pandaGroundRayNodepathJumping = self.avatar.objectNP.attachNewNode(self.pandaGroundRayNodeJumping)
            self.pandaGroundRayNodepathJumping.show()

            self.collisionNotifier = CollisionHandlerEvent()
            self.collisionNotifier.addInPattern("%fn-in")
            self.collisionNotifier.addOutPattern("%fn-out")

            self.cTrav.addCollider(self.pandaGroundSphereNodepath, self.pandaGroundCollisionHandler)
            self.cTrav.addCollider(self.pandaGroundRayNodepathJumping, self.collisionNotifier)
            self.cTrav.addCollider(self.pandaBodySphereNodepath, self.pandaBodyCollisionHandler)
Exemple #34
0
    def __setupLevel(self):
        """
        Some notes and caveats: Each time you add a room, make sure that you tag it with key "Room" and value "<room number>".
        This is so our A* algorithm can do clear path detection on only the rooms, not anything else.
        """
        level1 = render.attachNewNode("level 1 node path")

        execfile("rooms/room1.py")

        self.room1 = loader.loadModel("rooms/room1")
        self.room1.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        self.room1.setScale(10)
        self.room1.setTexScale(TextureStage.getDefault(), 10)
        self.room1.reparentTo(render)
        self.room1.find("**/Cube*;+h").setTag("Room", "1")

        keyNest = loader.loadModel("models/nest")
        keyNest.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        keyNest.setScale(0.5)
        keyNest.setTexScale(TextureStage.getDefault(), 0.1)

        #place keyNest (Like a birds nest, but for keys!)
        self.keyNest1 = self.room1.attachNewNode("key nest 1")
        keyNest.instanceTo(self.keyNest1)
        self.keyNest1.setPos(0, 0, 0.05)

        self.room1Key = loader.loadModel("models/redKey")
        self.room1Key.findTexture("*").setMinfilter(
            Texture.FTLinearMipmapLinear)
        self.room1Key.reparentTo(self.keyNest1)
        self.room1Key.setScale(render, 10)
        self.room1Key.setTexScale(TextureStage.getDefault(), 0.1)

        #self.setWaypoints("room2")
        self.room2waypoints = None
        execfile("rooms/room2.py")

        self.room2 = loader.loadModel("rooms/room2")
        self.room2.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        self.room2.setScale(10)
        self.room2.setTexScale(TextureStage.getDefault(), 10)
        self.room2.reparentTo(level1)
        self.room2.setY(self.room1, -20)
        self.room2.find("**/Cube*;+h").setTag("Room", "2")

        self.keyNest2 = self.room2.attachNewNode("key nest 2")
        keyNest.instanceTo(self.keyNest2)
        self.keyNest2.setPos(-2.5, -2.5, 0.05)

        self.room2Key = loader.loadModel("models/blueKey")
        self.room2Key.findTexture("*").setMinfilter(
            Texture.FTLinearMipmapLinear)
        self.room2Key.reparentTo(self.keyNest2)
        self.room2Key.setScale(render, 10)
        self.room2Key.setTexScale(TextureStage.getDefault(), 0.1)

        # Jim thinks there should be a comment here
        # he also thinks that the above comment is very useful
        # TODO: fix this hack by re-creating room3 in blender

        execfile("rooms/room3.py")

        room3Model = loader.loadModel("rooms/room3")
        room3Model.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        room3Model.setH(90)
        room3Model.setP(180)
        room3Model.setZ(2)
        self.room3 = level1.attachNewNode("room 3")
        room3Model.reparentTo(self.room3)
        self.room3.setScale(10)
        self.room3.setTexScale(TextureStage.getDefault(), 10)
        self.room3.reparentTo(level1)
        self.room3.setX(self.room1, 20)
        self.room3.find("**/Cube*;+h").setTag("Room", "3")

        self.keyNest3 = self.room3.attachNewNode("room 3 keynest")
        keyNest.instanceTo(self.keyNest3)
        self.keyNest3.setPos(0, 0, 0.05)

        self.room3Key = loader.loadModel("models/greenKey")
        self.room3Key.findTexture("*").setMinfilter(
            Texture.FTLinearMipmapLinear)
        self.room3Key.reparentTo(self.keyNest3)
        self.room3Key.setScale(render, 10)
        self.room3Key.setTexScale(TextureStage.getDefault(), 0.1)

        room3SphereOfDoom = self.room3.attachNewNode(
            CollisionNode("Jim's Hair"))
        room3SphereOfDoom.node().addSolid(CollisionSphere(3, -9, 0.5, 1.0))

        room1Floor = self.room1.attachNewNode(CollisionNode("room1Floor"))
        room1Floor.node().addSolid(
            CollisionPolygon(Point3(9, -9, 0), Point3(9, 9, 0),
                             Point3(-9, 9, 0), Point3(-9, -9, 0)))

        room2Floor = self.room2.attachNewNode(CollisionNode("room2Floor"))
        room2Floor.node().addSolid(
            CollisionPolygon(Point3(9, -9, 0), Point3(9, 9, 0),
                             Point3(-9, 9, 0), Point3(-9, -9, 0)))

        room3Floor = self.room3.attachNewNode(CollisionNode("room3Floor"))
        room3Floor.node().addSolid(
            CollisionPolygon(Point3(9, -9, 0), Point3(9, 9, 0),
                             Point3(-9, 9, 0), Point3(-9, -9, 0)))

        gate = loader.loadModel("models/box")

        gateTo2 = self.room1.attachNewNode("gateTo2")
        gate.instanceTo(gateTo2)
        gateTo2.setPos(8, -10, 0)
        gateTo2.hide()

        gateTo3 = self.room1.attachNewNode("gateTo3")
        gate.instanceTo(gateTo3)
        gateTo3.setPos(10, 8, 0)
        gateTo3.hide()

        self.physicsCollisionHandler.addInPattern("%fn-into-%in")
        self.physicsCollisionHandler.addOutPattern("%fn-out-%in")

        def orderNPC(parameters, entry):

            if (parameters == "ralph has entered room 1"):
                self.__room1NPC.handleTransition("playerEnteredRoom")
                self.reComputeHUD(self.room1)
                if self.__mainAgent.hasKey(self.room1Key):
                    self.__mainAgent.setCurrentKey(self.room1Key)
            elif (parameters == "ralph has left room 1"):
                self.__room1NPC.handleTransition("playerLeftRoom")
                if self.__mainAgent.hasKey(self.room1Key):
                    self.__mainAgent.setCurrentKey(None)
            elif (parameters == "ralph has entered room 2"):
                self.__room2NPC.handleTransition("playerEnteredRoom")
                self.reComputeHUD(self.room2)
                if self.__mainAgent.hasKey(self.room2Key):
                    self.__mainAgent.setCurrentKey(self.room2Key)
            elif (parameters == "ralph has left room 2"):
                self.__room2NPC.handleTransition("playerLeftRoom")
                if self.__mainAgent.hasKey(self.room2Key):
                    self.__mainAgent.setCurrentKey(None)
            elif (parameters == "ralph has entered room 3"):
                self.__room3NPC.handleTransition("playerEnteredRoom")
                if self.__mainAgent.hasKey(self.room3Key):
                    self.__mainAgent.setCurrentKey(self.room3Key)
                self.reComputeHUD(self.room3)
            elif (parameters == "ralph has left room 3"):
                self.__room3NPC.handleTransition("playerLeftRoom")
                if self.__mainAgent.hasKey(self.room3Key):
                    self.__mainAgent.setCurrentKey(None)
            elif (parameters == "NPC1 bumped into wall"):
                self.__room1NPC.handleTransition("bumpedIntoWall")
            elif (parameters == "NPC2 bumped into wall"):
                self.__room2NPC.handleTransition("bumpedIntoWall")
            elif (parameters == "NPC3 bumped into wall"):
                self.__room3NPC.handleTransition("bumpedIntoWall")

        self.accept("ralph collision node-into-room1Floor", orderNPC,
                    ["ralph has entered room 1"])
        self.accept("ralph collision node-out-room1Floor", orderNPC,
                    ["ralph has left room 1"])
        self.accept("ralph collision node-into-room2Floor", orderNPC,
                    ["ralph has entered room 2"])
        self.accept("ralph collision node-out-room2Floor", orderNPC,
                    ["ralph has left room 2"])
        self.accept("ralph collision node-into-room3Floor", orderNPC,
                    ["ralph has entered room 3"])
        self.accept("ralph collision node-out-room3Floor", orderNPC,
                    ["ralph has left room 3"])
        self.accept("Eve 1 collision node-into-Cube1", orderNPC,
                    ["NPC1 bumped into wall"])
        self.accept("Eve 2 collision node-into-Cube2", orderNPC,
                    ["NPC2 bumped into wall"])
        self.accept("Eve 3 collision node-into-Cube3", orderNPC,
                    ["NPC3 bumped into wall"])

        #messenger.toggleVerbose()
        self.gate = gate
    def reComputeHUD(self, room):
       """
       reComputeHUD is called when the player leaves a room and enters another room.
       The HUD shows the images of the keys that the player has in his backpack,
       but not the key to the current room.
       """
##       assert False, "add the hack to make sure she doesn't fall through the ground"
       if self.__mainAgent.hasKey(self.room1Key) and room is not self.room1:
          #self.redKeyImage.show()
          self.room1Key.reparentTo(base.cam)
          self.room1Key.setScale(render, 1.25)
          self.room1Key.setP(base.cam, 0)
          self.room1Key.setPos(base.cam.getX(base.cam) + 2.1, base.cam.getY(base.cam) + 10, base.cam.getZ(base.cam) + 2.1)
          self.room1KeyInHUD = True
       elif self.__mainAgent.hasKey(self.room1Key) and room is self.room1:
          rightHand = self.__mainAgent.actor.exposeJoint(None, 'modelRoot', 'RightHand')
          self.room1Key.reparentTo(rightHand)
          self.room1Key.setPosHpr(.11,-1.99,.06, 0,-90,0)
          self.room1Key.setScale(render, 10)
          self.room1Key.setTexScale(TextureStage.getDefault(), 1)
          self.room1KeyInHUD = False
          self.redKeyImage.hide()
       else:
          self.redKeyImage.hide()
          self.room1KeyInHUD = False

       if self.__mainAgent.hasKey(self.room2Key) and room is not self.room2:
          #self.blueKeyImage.show()
          self.room2Key.reparentTo(base.cam)
          self.room2Key.setScale(render, 1.25)
          self.room2Key.setP(base.cam, 0)
          self.room2Key.setPos(base.cam.getX(base.cam) + 2.5, base.cam.getY(base.cam) + 10, base.cam.getZ(base.cam) + 2.1)
          self.room2KeyInHUD = True
       elif self.__mainAgent.hasKey(self.room2Key) and room is self.room2:
          rightHand = self.__mainAgent.actor.exposeJoint(None, 'modelRoot', 'RightHand')
          self.room2Key.reparentTo(rightHand)
          self.room2Key.setPosHpr(.11,-1.99,.06, 0,-90,0)
          self.room2Key.setScale(render, 10)
          self.room2Key.setTexScale(TextureStage.getDefault(), 1)
          self.room2KeyInHUD = False
          self.blueKeyImage.hide()
       elif (self.blueKeyImage != None):
          self.blueKeyImage.hide()
          self.room2KeyInHUD = False

       if self.__mainAgent.hasKey(self.room3Key) and room is not self.room3:
          #self.greenKeyImage.show()
          self.room3Key.reparentTo(base.cam)
          self.room3Key.setScale(render, 1.25)
          self.room3Key.setP(base.cam, 0)
          self.room3Key.setPos(base.cam.getX(base.cam) + 3.0, base.cam.getY(base.cam) + 10, base.cam.getZ(base.cam) + 2.1)
          self.room3KeyInHUD = True
       elif self.__mainAgent.hasKey(self.room3Key) and room is self.room3:
          rightHand = self.__mainAgent.actor.exposeJoint(None, 'modelRoot', 'RightHand')
          self.room3Key.reparentTo(rightHand)
          self.room3Key.setPosHpr(.11,-1.99,.06, 0,-90,0)
          self.room3Key.setScale(render, 10)
          self.room3Key.setTexScale(TextureStage.getDefault(), 1)
          self.room3KeyInHUD = False
          self.greenKeyImage.hide()
       elif (self.greenKeyImage != None):
          self.greenKeyImage.hide()
    def __setupLevel(self):
        """
        Some notes and caveats: Each time you add a room, make sure that you tag it with key "Room" and value "<room number>".
        This is so our A* algorithm can do clear path detection on only the rooms, not anything else.
        """
        level1 = render.attachNewNode("level 1 node path")
        
        execfile("rooms/room1.py")

        self.room1 = loader.loadModel("rooms/room1")
        self.room1.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        self.room1.setScale(10)
        self.room1.setTexScale(TextureStage.getDefault(), 10)
        self.room1.reparentTo(render)
        self.room1.find("**/Cube*;+h").setTag("Room", "1")

        keyNest = loader.loadModel("models/nest")
        keyNest.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        keyNest.setScale(0.5)
        keyNest.setTexScale(TextureStage.getDefault(), 0.1)

        #place keyNest (Like a birds nest, but for keys!)
        self.keyNest1 = self.room1.attachNewNode("key nest 1")
        keyNest.instanceTo(self.keyNest1)
        self.keyNest1.setPos(0, 0, 0.05)

        self.room1Key = loader.loadModel("models/redKey")
        self.room1Key.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        self.room1Key.reparentTo(self.keyNest1)
        self.room1Key.setScale(render, 10)
        self.room1Key.setTexScale(TextureStage.getDefault(), 0.1)
        
        #self.setWaypoints("room2")
        self.room2waypoints = None
        execfile("rooms/room2.py")

        self.room2 = loader.loadModel("rooms/room2")
        self.room2.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        self.room2.setScale(10)
        self.room2.setTexScale(TextureStage.getDefault(), 10)
        self.room2.reparentTo(level1)
        self.room2.setY(self.room1, -20)
        self.room2.find("**/Cube*;+h").setTag("Room", "2")
        
        self.keyNest2 = self.room2.attachNewNode("key nest 2")
        keyNest.instanceTo(self.keyNest2)
        self.keyNest2.setPos(-2.5, -2.5, 0.05)
        
        self.room2Key = loader.loadModel("models/blueKey")
        self.room2Key.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        self.room2Key.reparentTo(self.keyNest2)
        self.room2Key.setScale(render, 10)
        self.room2Key.setTexScale(TextureStage.getDefault(), 0.1)
        
        # Jim thinks there should be a comment here
        # he also thinks that the above comment is very useful
        # TODO: fix this hack by re-creating room3 in blender
        
        execfile("rooms/room3.py")
        
        room3Model = loader.loadModel("rooms/room3")
        room3Model.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        room3Model.setH(90)
        room3Model.setP(180)
        room3Model.setZ(2)
        self.room3 = level1.attachNewNode("room 3")
        room3Model.reparentTo(self.room3)
        self.room3.setScale(10)
        self.room3.setTexScale(TextureStage.getDefault(), 10)
        self.room3.reparentTo(level1)
        self.room3.setX(self.room1, 20)
        self.room3.find("**/Cube*;+h").setTag("Room", "3")
        
        
        self.keyNest3 = self.room3.attachNewNode("room 3 keynest") 
        keyNest.instanceTo(self.keyNest3)
        self.keyNest3.setPos(0, 0, 0.05)
        
        
        self.room3Key = loader.loadModel("models/greenKey")
        self.room3Key.findTexture("*").setMinfilter(Texture.FTLinearMipmapLinear)
        self.room3Key.reparentTo(self.keyNest3)
        self.room3Key.setScale(render, 10)
        self.room3Key.setTexScale(TextureStage.getDefault(), 0.1)
        
        
        room3SphereOfDoom = self.room3.attachNewNode(CollisionNode("Jim's Hair"))
        room3SphereOfDoom.node().addSolid(CollisionSphere(3, -9, 0.5, 1.0))
        
        room1Floor = self.room1.attachNewNode(CollisionNode("room1Floor"))
        room1Floor.node().addSolid(CollisionPolygon(Point3(9,-9,0), Point3(9,9,0),
                                                Point3(-9,9,0), Point3(-9,-9,0)))
                                                
        room2Floor = self.room2.attachNewNode(CollisionNode("room2Floor"))
        room2Floor.node().addSolid(CollisionPolygon(Point3(9,-9,0), Point3(9,9,0),
                                                Point3(-9,9,0), Point3(-9,-9,0)))

        room3Floor = self.room3.attachNewNode(CollisionNode("room3Floor"))
        room3Floor.node().addSolid(CollisionPolygon(Point3(9,-9,0), Point3(9,9,0),
                                                Point3(-9,9,0), Point3(-9,-9,0)))
                                                

        
        gate = loader.loadModel("models/box")
        
        gateTo2 = self.room1.attachNewNode("gateTo2")
        gate.instanceTo(gateTo2)
        gateTo2.setPos(8, -10, 0)
        gateTo2.hide()
        
        gateTo3 = self.room1.attachNewNode("gateTo3")
        gate.instanceTo(gateTo3)
        gateTo3.setPos(10, 8, 0)
        gateTo3.hide()
        
        self.physicsCollisionHandler.addInPattern("%fn-into-%in")
        self.physicsCollisionHandler.addOutPattern("%fn-out-%in")
        
    
        
        def orderNPC(parameters, entry):
            
            if(parameters == "ralph has entered room 1"):
                self.__room1NPC.handleTransition("playerEnteredRoom")
                self.reComputeHUD(self.room1)
                if self.__mainAgent.hasKey(self.room1Key):
                    self.__mainAgent.setCurrentKey(self.room1Key)
            elif(parameters == "ralph has left room 1"):
                self.__room1NPC.handleTransition("playerLeftRoom")
                if self.__mainAgent.hasKey(self.room1Key):
                    self.__mainAgent.setCurrentKey(None)
            elif(parameters == "ralph has entered room 2"):
                self.__room2NPC.handleTransition("playerEnteredRoom")
                self.reComputeHUD(self.room2)
                if self.__mainAgent.hasKey(self.room2Key):
                    self.__mainAgent.setCurrentKey(self.room2Key)
            elif(parameters == "ralph has left room 2"):
                self.__room2NPC.handleTransition("playerLeftRoom")
                if self.__mainAgent.hasKey(self.room2Key):
                    self.__mainAgent.setCurrentKey(None)
            elif(parameters == "ralph has entered room 3"):
                self.__room3NPC.handleTransition("playerEnteredRoom")
                if self.__mainAgent.hasKey(self.room3Key):
                    self.__mainAgent.setCurrentKey(self.room3Key)
                self.reComputeHUD(self.room3)
            elif(parameters == "ralph has left room 3"):
                self.__room3NPC.handleTransition("playerLeftRoom")
                if self.__mainAgent.hasKey(self.room3Key):
                    self.__mainAgent.setCurrentKey(None)
            elif(parameters == "NPC1 bumped into wall"):
                self.__room1NPC.handleTransition("bumpedIntoWall")
            elif(parameters == "NPC2 bumped into wall"):
                self.__room2NPC.handleTransition("bumpedIntoWall")
            elif(parameters == "NPC3 bumped into wall"):
                self.__room3NPC.handleTransition("bumpedIntoWall")
                
        
        self.accept("ralph collision node-into-room1Floor", orderNPC, ["ralph has entered room 1"])
        self.accept("ralph collision node-out-room1Floor", orderNPC, ["ralph has left room 1"])
        self.accept("ralph collision node-into-room2Floor", orderNPC, ["ralph has entered room 2"])
        self.accept("ralph collision node-out-room2Floor", orderNPC, ["ralph has left room 2"])
        self.accept("ralph collision node-into-room3Floor", orderNPC, ["ralph has entered room 3"])
        self.accept("ralph collision node-out-room3Floor", orderNPC, ["ralph has left room 3"])
        self.accept("Eve 1 collision node-into-Cube1", orderNPC, ["NPC1 bumped into wall"])
        self.accept("Eve 2 collision node-into-Cube2", orderNPC, ["NPC2 bumped into wall"])
        self.accept("Eve 3 collision node-into-Cube3", orderNPC, ["NPC3 bumped into wall"])
        

        #messenger.toggleVerbose()
        self.gate = gate
Exemple #37
0
    def reComputeHUD(self, room):
        """
       reComputeHUD is called when the player leaves a room and enters another room.
       The HUD shows the images of the keys that the player has in his backpack,
       but not the key to the current room.
       """
        ##       assert False, "add the hack to make sure she doesn't fall through the ground"
        if self.__mainAgent.hasKey(self.room1Key) and room is not self.room1:
            #self.redKeyImage.show()
            self.room1Key.reparentTo(base.cam)
            self.room1Key.setScale(render, 1.25)
            self.room1Key.setP(base.cam, 0)
            self.room1Key.setPos(
                base.cam.getX(base.cam) + 2.1,
                base.cam.getY(base.cam) + 10,
                base.cam.getZ(base.cam) + 2.1)
            self.room1KeyInHUD = True
        elif self.__mainAgent.hasKey(self.room1Key) and room is self.room1:
            rightHand = self.__mainAgent.actor.exposeJoint(
                None, 'modelRoot', 'RightHand')
            self.room1Key.reparentTo(rightHand)
            self.room1Key.setPosHpr(.11, -1.99, .06, 0, -90, 0)
            self.room1Key.setScale(render, 10)
            self.room1Key.setTexScale(TextureStage.getDefault(), 1)
            self.room1KeyInHUD = False
            self.redKeyImage.hide()
        else:
            self.redKeyImage.hide()
            self.room1KeyInHUD = False

        if self.__mainAgent.hasKey(self.room2Key) and room is not self.room2:
            #self.blueKeyImage.show()
            self.room2Key.reparentTo(base.cam)
            self.room2Key.setScale(render, 1.25)
            self.room2Key.setP(base.cam, 0)
            self.room2Key.setPos(
                base.cam.getX(base.cam) + 2.5,
                base.cam.getY(base.cam) + 10,
                base.cam.getZ(base.cam) + 2.1)
            self.room2KeyInHUD = True
        elif self.__mainAgent.hasKey(self.room2Key) and room is self.room2:
            rightHand = self.__mainAgent.actor.exposeJoint(
                None, 'modelRoot', 'RightHand')
            self.room2Key.reparentTo(rightHand)
            self.room2Key.setPosHpr(.11, -1.99, .06, 0, -90, 0)
            self.room2Key.setScale(render, 10)
            self.room2Key.setTexScale(TextureStage.getDefault(), 1)
            self.room2KeyInHUD = False
            self.blueKeyImage.hide()
        elif (self.blueKeyImage != None):
            self.blueKeyImage.hide()
            self.room2KeyInHUD = False

        if self.__mainAgent.hasKey(self.room3Key) and room is not self.room3:
            #self.greenKeyImage.show()
            self.room3Key.reparentTo(base.cam)
            self.room3Key.setScale(render, 1.25)
            self.room3Key.setP(base.cam, 0)
            self.room3Key.setPos(
                base.cam.getX(base.cam) + 3.0,
                base.cam.getY(base.cam) + 10,
                base.cam.getZ(base.cam) + 2.1)
            self.room3KeyInHUD = True
        elif self.__mainAgent.hasKey(self.room3Key) and room is self.room3:
            rightHand = self.__mainAgent.actor.exposeJoint(
                None, 'modelRoot', 'RightHand')
            self.room3Key.reparentTo(rightHand)
            self.room3Key.setPosHpr(.11, -1.99, .06, 0, -90, 0)
            self.room3Key.setScale(render, 10)
            self.room3Key.setTexScale(TextureStage.getDefault(), 1)
            self.room3KeyInHUD = False
            self.greenKeyImage.hide()
        elif (self.greenKeyImage != None):
            self.greenKeyImage.hide()
Exemple #38
0
	def applyTexture(self):
		self.texture = loader.loadTexture("media/brick_wall.tga")
		self.texture.setWrapU(Texture.WMRepeat)
		self.texture.setWrapV(Texture.WMRepeat)
		self.model.setTexture(self.texture, 1)
		self.model.setTexScale(TextureStage.getDefault(), max(self.size[0], self.size[1]), self.size[2])
Exemple #39
0
    def __init__(self, image_path, name=None,\
                  rows=1, cols=1, scale=1.0,\
                  twoSided=True, alpha=TRANS_ALPHA,\
                  repeatX=1, repeatY=1,\
                  anchorX=ALIGN_LEFT, anchorY=ALIGN_BOTTOM):
        """
        Create a card textured with an image. The card is sized so that the ratio between the
        card and image is the same.
        """

        scale *= self.PIXEL_SCALE

        self.animations = {}

        self.scale = scale
        self.repeatX = repeatX
        self.repeatY = repeatY
        self.flip = {'x': False, 'y': False}
        self.rows = rows
        self.cols = cols

        self.currentFrame = 0
        self.currentAnim = None
        self.loopAnim = False
        self.frameInterrupt = True

        # Create the NodePath
        if name:
            self.node = NodePath("Sprite2d:%s" % name)
        else:
            self.node = NodePath("Sprite2d:%s" % image_path)

        # Set the attribute for transparency/twosided
        self.node.node().setAttrib(TransparencyAttrib.make(alpha))
        if twoSided:
            self.node.setTwoSided(True)

        # Make a filepath
        self.imgFile = Filename(image_path)
        if self.imgFile.empty():
            raise IOError, "File not found"

        # Instead of loading it outright, check with the PNMImageHeader if we can open
        # the file.
        imgHead = PNMImageHeader()
        if not imgHead.readHeader(self.imgFile):
            raise IOError, "PNMImageHeader could not read file. Try using absolute filepaths"

        # Load the image with a PNMImage
        image = PNMImage()
        image.read(self.imgFile)

        self.sizeX = image.getXSize()
        self.sizeY = image.getYSize()

        self.frames = []
        for rowIdx in xrange(self.rows):
            for colIdx in xrange(self.cols):
                self.frames.append(Sprite2d.Cell(colIdx, rowIdx))

        # We need to find the power of two size for the another PNMImage
        # so that the texture thats loaded on the geometry won't have artifacts
        textureSizeX = self.nextsize(self.sizeX)
        textureSizeY = self.nextsize(self.sizeY)

        # The actual size of the texture in memory
        self.realSizeX = textureSizeX
        self.realSizeY = textureSizeY

        self.paddedImg = PNMImage(textureSizeX, textureSizeY)
        if image.hasAlpha():
            self.paddedImg.alphaFill(0)
        # Copy the source image to the image we're actually using
        self.paddedImg.blendSubImage(image, 0, 0)
        # We're done with source image, clear it
        image.clear()

        # The pixel sizes for each cell
        self.colSize = self.sizeX / self.cols
        self.rowSize = self.sizeY / self.rows

        # How much padding the texture has
        self.paddingX = textureSizeX - self.sizeX
        self.paddingY = textureSizeY - self.sizeY

        # Set UV padding
        self.uPad = float(self.paddingX) / textureSizeX
        self.vPad = float(self.paddingY) / textureSizeY

        # The UV dimensions for each cell
        self.uSize = (1.0 - self.uPad) / self.cols
        self.vSize = (1.0 - self.vPad) / self.rows

        card = CardMaker("Sprite2d-Geom")

        # The positions to create the card at
        if anchorX == self.ALIGN_LEFT:
            posLeft = 0
            posRight = (self.colSize / scale) * repeatX
        elif anchorX == self.ALIGN_CENTER:
            posLeft = -(self.colSize / 2.0 / scale) * repeatX
            posRight = (self.colSize / 2.0 / scale) * repeatX
        elif anchorX == self.ALIGN_RIGHT:
            posLeft = -(self.colSize / scale) * repeatX
            posRight = 0

        if anchorY == self.ALIGN_BOTTOM:
            posTop = 0
            posBottom = (self.rowSize / scale) * repeatY
        elif anchorY == self.ALIGN_CENTER:
            posTop = -(self.rowSize / 2.0 / scale) * repeatY
            posBottom = (self.rowSize / 2.0 / scale) * repeatY
        elif anchorY == self.ALIGN_TOP:
            posTop = -(self.rowSize / scale) * repeatY
            posBottom = 0

        card.setFrame(posLeft, posRight, posTop, posBottom)
        card.setHasUvs(True)
        self.card = self.node.attachNewNode(card.generate())

        # Since the texture is padded, we need to set up offsets and scales to make
        # the texture fit the whole card
        self.offsetX = (float(self.colSize) / textureSizeX)
        self.offsetY = (float(self.rowSize) / textureSizeY)

        self.node.setTexScale(TextureStage.getDefault(),
                              self.offsetX * repeatX, self.offsetY * repeatY)
        self.node.setTexOffset(TextureStage.getDefault(), 0, 1 - self.offsetY)

        self.texture = Texture()

        self.texture.setXSize(textureSizeX)
        self.texture.setYSize(textureSizeY)
        self.texture.setZSize(1)

        # Load the padded PNMImage to the texture
        self.texture.load(self.paddedImg)

        self.texture.setMagfilter(Texture.FTNearest)
        self.texture.setMinfilter(Texture.FTNearest)

        #Set up texture clamps according to repeats
        if repeatX > 1:
            self.texture.setWrapU(Texture.WMRepeat)
        else:
            self.texture.setWrapU(Texture.WMClamp)
        if repeatY > 1:
            self.texture.setWrapV(Texture.WMRepeat)
        else:
            self.texture.setWrapV(Texture.WMClamp)

        self.node.setTexture(self.texture)