示例#1
0
 def add_ground(self):
     cm = CardMaker("ground")
     cm.setFrame(-1, 1, -1, 1)
     ground = render.attachNewNode(cm.generate())
     ground.setColor(0.5, 0.7, 0.8)
     ground.lookAt(0, 0, -1)
     groundGeom = OdePlaneGeom(self.space, Vec4(0, 0, 1, 0))
class MatPlotLibDemo(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        base.setFrameRateMeter(True)

        m = loader.loadModel("models/smiley")
        m.reparent_to(render)
        m.set_pos(0, 5, 0)

        x_size, y_size = 640, 480
        xy_ratio = float(y_size) / float(x_size)
        self.plot = Plot(x_size, y_size)

        self.input_img = PNMImage(x_size, y_size)
        self.input_tex = Texture()
        self.input_tex.load(self.input_img)

        self.card = CardMaker('pygame_card')
        self.card.setUvRange(Point2(0, 1),  # ll
                             Point2(1, 1),  # lr
                             Point2(1, 0),  # ur
                             Point2(0, 0))  # ul
        self.screen = render.attach_new_node(self.card.generate())
        self.screen.set_scale(1, 1, xy_ratio)
        self.screen.set_pos(-0.5, 2, -0.5 * xy_ratio)
        self.screen.setTexture(self.input_tex)
        # FIXME: Apparently mpl's print_to_buffer() doesn't write
        # alpha values properly. 
        self.screen.setTransparency(TransparencyAttrib.MAlpha)

        taskMgr.add(self.update, "update plot")

    def update(self, task):
        self.input_tex.set_ram_image_as(self.plot.draw(), "RGBA")
        return task.cont
示例#3
0
    def draw_image(self, image, box, identifier="", parameters=None):
        cm = CardMaker(identifier)
        tex = self.get_loader().loadTexture(image.value)

        if box.mode == "pixels":
            parent2d = self.get_parent_pixel2d()
        elif box.mode == "standard":
            parent2d = self.get_parent_render2d()
        elif box.mode == "aspect":
            parent2d = self.get_parent_aspect2d()

        node = NodePath(cm.generate())
        node.setTexture(tex)

        if parameters is not None:
            if hasattr(parameters, "transparency") and parameters.transparency == True:
                node.setTransparency(TransparencyAttrib.MAlpha)

        node.setPos(box.x, 0, box.y + box.sizey)
        node.setScale(box.sizex, 1, -box.sizey)
        node.setBin("fixed", self.get_next_sortid())
        node.setDepthTest(False)
        node.setDepthWrite(False)
        node.reparentTo(parent2d)
        return (node, image, box, parameters)
示例#4
0
	def constructModel(self):
		self.obstacles = []
		self.blocks = []
		self.liftables = []

		if self.nodePath != None:
			self.nodePath.removeNode()
			self.cards = []

		self.nodePath = NodePath("Map")
		#the ground
		cm = CardMaker('CardMaker')
		cm.setFrame(-2,2,-2,2)
		card = self.nodePath.attachNewNode(cm.generate())
		card.setTexture(tex)

		for y in range(self.height):
			for x in range(self.width):
				# TO DO: MUDAR NOME
				a = {"block": self.blocks,
					 "obstacle": self.obstacles,
					 "tree": self.obstacles,
					 "bush" : self.obstacles,
					 "liftable": self.liftables}
				tType = self.tileType(Map.COLLISION, (x,y))

				if tType != 'free':
					a[tType].append(self.makeObject(tType, x,y))
 def __createAnimationSequence__(self,name,sprite_images,sprites_time,is_left = False):
   """
     Creates the sequence node that plays these images
   """
   
   seq = SpriteSequencePlayer(name)
   
   for i in range(0,len(sprite_images)):
       
     txtr = sprite_images[i]
     
     w = txtr.getXSize() 
     h = txtr.getYSize()       
     
     # creating CardMaker to hold the texture
     cm = CardMaker(name +    str(i))
     cm.setFrame(0,w,-h,0 )  # This configuration places the image's topleft corner at the origin
     card = NodePath(cm.generate())            
     card.setTexture(txtr)
     seq.addChild(card.node(),i)
     seq.addFrame(card.node(),i,sprites_time[i])
     
     # offseting image
     xoffset = float(txtr.axisx + (-w if is_left else 0))
     yoffset = float(txtr.axisy)
     card.setPos(Vec3(xoffset,0,yoffset))
     
     AnimationActor.LOGGER.debug("Animation %s Sprite [%i] image size %s and offset %s."%( name,i, str((w,h)), str((txtr.axisx,txtr.axisy)) ) ) 
    
              
   return seq     
   
   
示例#6
0
    def __initSceneGraph(self):
        
        self.point_path = self.host_planet.point_path.attachNewNode("unit_center_node")
        self.model_path = self.point_path.attachNewNode("unit_node")
        self.model_path.reparentTo(self.point_path)
        self.model_path.setPos(Vec3(0,6,0))
        
        self.model_path.setPythonTag('pyUnit', self)
        
        rad = 1
        cnode = CollisionNode("coll_sphere_node")
        cnode.addSolid(CollisionBox(Point3(-rad,-rad,-rad),Point3(rad,rad,rad)))
        cnode.setIntoCollideMask(BitMask32.bit(1))
        cnode.setTag('unit', str(id(self)))
        self.cnode_path = self.model_path.attachNewNode(cnode)
        #self.cnode_path.show()
        
        tex = loader.loadTexture("models/billboards/flare.png")
        cm = CardMaker('quad')
        cm.setFrameFullscreenQuad()
        self.quad_path = self.model_path.attachNewNode(cm.generate())
        self.quad_path.setTexture(tex)
        self.quad_path.setTransparency(TransparencyAttrib.MAlpha)
        self.quad_path.setBillboardPointEye()

        self.quad_path.setColor(self.player.color)
示例#7
0
    def __init__(self, battleGraphics, matrixContainer):
        self.battleGraphics = battleGraphics
        self.matrixContainer = matrixContainer

        self.curtex = loader.loadTexture(GAME+'/textures/cursor.png')
        self.curtex.setMagfilter(Texture.FTNearest)
        self.curtex.setMinfilter(Texture.FTNearest)

        self.x = False
        self.y = False
        self.z = False

        self.cursor = loader.loadModel(GAME+'/models/slopes/flat')
        self.cursor.reparentTo( self.matrixContainer )
        self.cursor.setScale(3.7)
        self.cursor.setTransparency(TransparencyAttrib.MAlpha)
        self.cursor.setColor( 1, 1, 1, 1 )
        self.cursor.setTexture(self.curtex)

        pointertex = loader.loadTexture(GAME+'/textures/pointer.png')
        pointertex.setMagfilter(Texture.FTNearest)
        pointertex.setMinfilter(Texture.FTNearest)
        cm = CardMaker('card')
        cm.setFrame(-2, 2, -2, 2) 
        self.pointer = render.attachNewNode(cm.generate())
        self.pointer.setTexture(pointertex)
        self.pointer.setTransparency(True)
        self.pointer.setBillboardPointEye()
        self.pointer.reparentTo(render)
        self.pointer.setScale(256.0/240.0)
	def register(self, render, camera, keys):
		State.register(self, render, camera, keys)

		cm = CardMaker('CardMaker-Title')
		tex = loadTexture('titlescreen.png')

		cm.setFrame(-1, 1, -1, 1)

		self.bg = self.node.attachNewNode(cm.generate())
		self.bg.setPos(0, 0, 0)
		self.bg.setTexture(tex)

		menuActions = {'up': (Menu.previousOpt, self.menu),
						'down': (Menu.nextOpt, self.menu),
						'action': (self.selectOption, None)
						}

		self.menu.registerKeys(keys, menuActions)

		self.title = OnscreenText(text="", mayChange = True , style=2,
							 fg=(1,1,1,1), pos=(0, 0.75), scale = 0.2) # is this used??
		self.text = {}

		id=0
		for opt in self.menu.options:
			self.text[opt] = OnscreenText(text=opt, mayChange = True , style=2, fg=(1,1,1,1), pos=(0, -0.3 - 0.15*id), scale = .1)
			id+=1

		self.title.reparentTo(self.node)
		for opt in self.text.keys():
			self.text[opt].reparentTo(self.node)


		State.register(self, render, camera, keys)
示例#9
0
    def __init__(self):
        ShowBase.__init__(self)

        cm = CardMaker('grass')
        cm.setFrame(-1, 1, -1, 1)

        grass1 = render.attachNewNode(cm.generate())
        grass2 = render.attachNewNode(cm.generate())

        grass1.setTexture(loader.loadTexture("data/env/grass1.png"), 1)
        grass2.setTexture(loader.loadTexture("data/env/grass2.png"), 1)

        grass1.setTransparency(True)
        grass2.setTransparency(True)

        grass1.setBillboardPointEye()
        grass2.setBillboardPointEye()

        grass1.setHpr(0, -40, 0)
        grass2.setHpr(0, -40, 0)

        grass1.setPos(0, 1, -0.4)
        grass2.setPos(0, 1, -0.3)

        self.taskMgr.add(self.panCameraTask, "PanCameraTask")
    def renderQuadInto(self, xsize, ysize, colortex=None, cmode = GraphicsOutput.RTMBindOrCopy, auxtex = None):

        buffer = self.createBuffer("filter-stage", xsize, ysize, colortex, cmode, auxtex)

        if (buffer == None):
            return None

        cm = CardMaker("filter-stage-quad")
        cm.setFrameFullscreenQuad()
        quad = NodePath(cm.generate())
        quad.setDepthTest(0)
        quad.setDepthWrite(0)
        quad.setColor(Vec4(1,0.5,0.5,1))

        quadcamnode = Camera("filter-quad-cam")
        lens = OrthographicLens()
        lens.setFilmSize(2, 2)
        lens.setFilmOffset(0, 0)
        lens.setNearFar(-1000, 1000)
        quadcamnode.setLens(lens)
        quadcam = quad.attachNewNode(quadcamnode)
        
        buffer.getDisplayRegion(0).setCamera(quadcam)
        buffer.getDisplayRegion(0).setActive(1)

        return quad, buffer
示例#11
0
	def __init__(self, world, attach, name = '', position = Vec3(0,0,0), orientation = Vec3(0,0,0), size = (32, 32)):
		cm=CardMaker('')
		cm.setFrame(0,1,0,1)
		floor = render.attachNewNode(PandaNode("floor"))
		tex = loader.loadTexture('media/'+'ground.png')
		tex.setMagfilter(Texture.FTNearest)
		tex.setMinfilter(Texture.FTNearest)
		for y in range(size[0]):
			for x in range(size[1]):
				nn = floor.attachNewNode(cm.generate())
				nn.setP(-90)
				nn.setPos((x), (y), 0)
		floor.setTexture(tex)
		floor.flattenStrong()



		myMaterial = Material()
		myMaterial.setShininess(0) #Make this material shiny
		myMaterial.setAmbient(VBase4(0.5,.5,.5,1)) #Make this material blue
		myMaterial.setDiffuse(VBase4(.5,.5,.5,1))
		nn.setMaterial(myMaterial)
		shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

		StaticWorldObject.__init__(self, world, attach, name, position, shape, orientation) ##Mass must be zero.

		self._nodePath.node().setFriction(1)
示例#12
0
文件: MazeMapGui.py 项目: nate97/src
 def _createSimpleMarker(self, size, color = (1, 1, 1)):
     halfSize = size * 0.5
     cm = CardMaker('mazemap_simple_marker')
     cm.setFrame(-halfSize, halfSize, -halfSize, halfSize)
     markerNP = self.maskedLayer.attachNewNode(cm.generate())
     markerNP.setColor(*color)
     return markerNP
 def setupBackgroundImage(self):    
   
   image_file = Filename(TestGameBase.__BACKGROUND_IMAGE_PATH__)
   
   # check if image can be loaded
   img_head = PNMImageHeader()
   if not img_head.readHeader(image_file ):
       raise IOError("PNMImageHeader could not read file %s. Try using absolute filepaths"%(image_file.c_str()))
       sys.exit()
       
   # Load the image with a PNMImage
   w = img_head.getXSize()
   h = img_head.getYSize()
   img = PNMImage(w,h)
   #img.alphaFill(0)
   img.read(image_file) 
   
   texture = Texture()        
   texture.setXSize(w)
   texture.setYSize(h)
   texture.setZSize(1)    
   texture.load(img)
   texture.setWrapU(Texture.WM_border_color) # gets rid of odd black edges around image
   texture.setWrapV(Texture.WM_border_color)
   texture.setBorderColor(LColor(0,0,0,0))
   
   # creating CardMaker to hold the texture
   cm = CardMaker('background')
   cm.setFrame(-0.5*w,0.5*w,-0.5*h,0.5*h)  # This configuration places the image's topleft corner at the origin (left, right, bottom, top)
   background_np = NodePath(cm.generate())            
   background_np.setTexture(texture)
   
   background_np.reparentTo(self.render)
   background_np.setPos(TestGameBase.__BACKGROUND_POSITION__)
   background_np.setScale(TestGameBase.__BACKGROUND_SCALE__)
示例#14
0
    def setup(self):
        self.tex1 = MovieTexture('videos/saturn5_apollo_launch.mp4')
        assert self.tex1.read('videos/saturn5_apollo_launch.mp4')
        self.tex2 = MovieTexture('videos/boards_eye_view.mp4')
        assert self.tex2.read('videos/boards_eye_view.mp4')

        self.cm1 = CardMaker('saturn')
        self.cm1.setFrameFullscreenQuad()
        self.cm1.setUvRange(self.tex1)
        self.card1 = NodePath(self.cm1.generate())
        self.card1.reparentTo(self.path)
        self.card1.setPos(0,0,10)
        self.card1.setP(50)

        self.cm2 = CardMaker('board')
        self.cm2.setFrameFullscreenQuad()
        self.cm2.setUvRange(self.tex2)
        self.card2 = NodePath(self.cm2.generate())
        self.card2.reparentTo(self.path)
        self.card2.setPos(0,0,-10)
        self.card2.setP(-50)

        self.card1.setTexture(self.tex1)
        self.card1.setTexScale(TextureStage.getDefault(), self.tex1.getTexScale())
        self.card2.setTexture(self.tex2)
        self.card2.setTexScale(TextureStage.getDefault(), self.tex2.getTexScale())

        self.card1.setScale(10)
        self.card2.setScale(10)
示例#15
0
 def genArrow(self, pos, hpr, id):
     factory = CardMaker('factory')
     factory.setFrame(-.5, 0.5, -.5, 0.5)
     arrowNode = factory.generate()
     arrowRoot = NodePath('root')
     baseArrow = NodePath(arrowNode)
     baseArrow.setTransparency(1)
     baseArrow.setTexture(self.boostArrowTexture)
     baseArrow.reparentTo(arrowRoot)
     arrow2 = baseArrow.copyTo(baseArrow)
     arrow2.setPos(0, 0, 1)
     arrow3 = arrow2.copyTo(arrow2)
     arrowRoot.setPos(*pos)
     arrowRoot.setHpr(*hpr)
     baseArrow.setHpr(0, -90, 0)
     baseArrow.setScale(24)
     arrowRoot.reparentTo(self.geom)
     trigger = 'boostArrow' + str(id)
     cs = CollisionTube(Point3(0.6, -6, 0), Point3(0.6, 54, 0), 4.8)
     cs.setTangible(0)
     triggerEvent = 'imIn-' + trigger
     cn = CollisionNode(trigger)
     cn.addSolid(cs)
     cn.setIntoCollideMask(BitMask32(32768))
     cn.setFromCollideMask(BitMask32(32768))
     cnp = NodePath(cn)
     cnp.reparentTo(arrowRoot)
     self.accept(triggerEvent, self.hitBoostArrow)
     arrowVec = arrow2.getPos(self.geom) - baseArrow.getPos(self.geom)
     arrowVec.normalize()
     idStr = str(id)
     cnp.setTag('boostId', idStr)
     self.boostDir[idStr] = arrowVec
     base.arrows.append(arrowRoot)
示例#16
0
文件: MazeMapGui.py 项目: nate97/src
    def _createMapTextureCard(self):
        mapImage = PNMImage(MAP_RESOLUTION, MAP_RESOLUTION)
        mapImage.fill(*self._bgColor)
        fgColor = VBase4D(*self._fgColor)
        for x in xrange(self._mazeHeight):
            for y in xrange(self._mazeWidth):
                if self._mazeCollTable[y][x] == 1:
                    ax = float(x) / self._mazeWidth * MAP_RESOLUTION
                    invertedY = self._mazeHeight - 1 - y
                    ay = float(invertedY) / self._mazeHeight * MAP_RESOLUTION
                    self._drawSquare(mapImage, int(ax), int(ay), 10, fgColor)

        mapTexture = Texture('mapTexture')
        mapTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba)
        mapTexture.setMinfilter(Texture.FTLinear)
        mapTexture.load(mapImage)
        mapTexture.setWrapU(Texture.WMClamp)
        mapTexture.setWrapV(Texture.WMClamp)
        mapImage.clear()
        del mapImage
        cm = CardMaker('map_cardMaker')
        cm.setFrame(-1.0, 1.0, -1.0, 1.0)
        map = self.attachNewNode(cm.generate())
        map.setTexture(mapTexture, 1)
        return map
示例#17
0
 def __init__(self):
     self.cm = CardMaker("fadeout")
     self.cm.setFrame(-2,2,-2,2)
     self.cmnode = NodePath(self.cm.generate())
     self.cmnode.setTransparency(TransparencyAttrib.MAlpha)
     self.cmnode.setY(-1)
     self.cmnode.setColorScale(LVecBase4f(0.0,0.0,0.0,0.0))
     self.cmnode.reparentTo(aspect2d)
示例#18
0
 def _addCard(self,texture):
     tex = loader.loadTexture(MAIN_DIR+"/../assets/models/bamboo/"+texture)
     cm = CardMaker('card')
     ratio = float(tex.getXSize())/tex.getYSize()
     cm.setFrame(-0.5*ratio,0.5*ratio,-0.5,0.5)
     card = self.menuNP.attachNewNode(cm.generate())
     card.setTexture(tex)
     return card
示例#19
0
    def __init__(self, charid, sprite, camhandler, callback, cancelcallback):
    
        self.charid = charid
        self.sprite = sprite
        self.camhandler = camhandler
        self.callback = callback
        self.cancelcallback = cancelcallback
        self.initdir  = self.sprite.realdir
        self.hidir = None

        # Textures
        self.readytex = loader.loadTexture(GAME+'/textures/gui/direction.png')
        self.readytex.setMagfilter(Texture.FTNearest)
        self.readytex.setMinfilter(Texture.FTNearest)
        self.hovertex = loader.loadTexture(GAME+'/textures/gui/direction_hover.png')
        self.hovertex.setMagfilter(Texture.FTNearest)
        self.hovertex.setMinfilter(Texture.FTNearest)

        # Sounds
        self.hover_snd   = base.loader.loadSfx(GAME+'/sounds/hover.ogg')
        self.clicked_snd = base.loader.loadSfx(GAME+'/sounds/clicked.ogg')
        self.cancel_snd  = base.loader.loadSfx(GAME+'/sounds/cancel.ogg')

        # Buttons list
        self.directionbuttons = []

        # Buttons container
        self.directionRoot = sprite.node.attachNewNode( "directionRoot" )

        directionsdata = [
            { 'direction': '1', 'pos': ( 1.45, 0.0, 5) },
            { 'direction': '2', 'pos': ( 0.0, 1.45, 5) },
            { 'direction': '3', 'pos': (-1.45, 0.0, 5) },
            { 'direction': '4', 'pos': ( 0.0,-1.45, 5) }
        ]
        for directiondata in directionsdata:
            cm = CardMaker('card')
            cm.setFrame(-.5, .5, -.5, .5) 
            card = render.attachNewNode(cm.generate())
            card.setTexture(self.readytex)
            card.setTransparency(True)
            card.setBillboardPointEye()
            card.reparentTo(self.directionRoot)
            card.setPos(directiondata['pos'])
            card.setScale(256.0/240.0)

            self.directionbuttons.append(card)

            if int(directiondata['direction']) == int(self.initdir):
                self.hidir = directiondata['direction']
                card.setTexture(self.hovertex)

        self.accept("b", self.onCircleClicked)
        self.accept("space", self.onCrossClicked)
        self.accept("arrow_up", lambda: self.onArrowClicked('up'))
        self.accept("arrow_down", lambda: self.onArrowClicked('down'))
        self.accept("arrow_left", lambda: self.onArrowClicked('left'))
        self.accept("arrow_right", lambda: self.onArrowClicked('right'))
示例#20
0
    def renderQuadInto(self,
                       mul=1,
                       div=1,
                       align=1,
                       depthtex=None,
                       colortex=None,
                       auxtex0=None,
                       auxtex1=None):
        """ Creates an offscreen buffer for an intermediate
        computation. Installs a quad into the buffer.  Returns
        the fullscreen quad.  The size of the buffer is initially
        equal to the size of the main window.  The parameters 'mul',
        'div', and 'align' can be used to adjust that size. """

        texgroup = (depthtex, colortex, auxtex0, auxtex1)

        winx, winy = self.getScaledSize(mul, div, align)

        depthbits = bool(depthtex != None)

        buffer = self.createBuffer("filter-stage", winx, winy, texgroup,
                                   depthbits)

        if (buffer == None):
            return None

        cm = CardMaker("filter-stage-quad")
        cm.setFrameFullscreenQuad()
        quad = NodePath(cm.generate())
        quad.setDepthTest(0)
        quad.setDepthWrite(0)
        quad.setColor(1, 0.5, 0.5, 1)

        quadcamnode = Camera("filter-quad-cam")
        lens = OrthographicLens()
        lens.setFilmSize(2, 2)
        lens.setFilmOffset(0, 0)
        lens.setNearFar(-1000, 1000)
        quadcamnode.setLens(lens)
        quadcam = quad.attachNewNode(quadcamnode)

        dr = buffer.makeDisplayRegion((0, 1, 0, 1))
        dr.disableClears()
        dr.setCamera(quadcam)
        dr.setActive(True)
        dr.setScissorEnabled(False)

        # This clear stage is important if the buffer is padded, so that
        # any pixels accidentally sampled in the padded region won't
        # be reading from unititialised memory.
        buffer.setClearColor((0, 0, 0, 1))
        buffer.setClearColorActive(True)

        self.buffers.append(buffer)
        self.sizes.append((mul, div, align))

        return quad
示例#21
0
 def makeEnemyFace(self):
     cm = CardMaker("face")
     cardModel = self.scene.attachNewNode(cm.generate())
     path = base.enemyIconPath + "/" + base.enemyCardBack
     tex = loader.loadTexture(path)
     cardModel.setTexture(tex)
     cardModel.setPos(0, 0, 5)
     cardModel.setPythonTag('zone', base.enemy.face)
     base.enemyFaceNode = cardModel
示例#22
0
    def __init__(self,
                 texture_array,
                 scale=0.2,
                 window_size=512,
                 texture_size=512):
        super().__init__()
        self.scale = scale
        self.texture_array = texture_array
        self.texture_dtype = type(self.texture_array.flat[0])
        self.ndims = self.texture_array.ndim

        #Set window title
        self.window_properties = WindowProperties()
        self.window_properties.setSize(window_size, window_size)
        self.window_properties.setTitle("FullFieldDrift")
        ShowBaseGlobal.base.win.requestProperties(self.window_properties)

        #Create texture stage
        self.texture = Texture("Stimulus")

        #Select Texture ComponentType (e.g., uint8 or whatever)
        if self.texture_dtype == np.uint8:
            self.texture_component_type = Texture.T_unsigned_byte
        elif self.texture_dtype == np.uint16:
            self.texture_component_type = Texture.T_unsigned_short

        #Select Texture Format (color or b/w etc)
        if self.ndims == 2:
            self.texture_format = Texture.F_luminance  #grayscale
            self.texture.setup2dTexture(texture_size, texture_size,
                                        self.texture_component_type,
                                        self.texture_format)
            self.texture.setRamImageAs(self.texture_array, "L")
        elif self.ndims == 3:
            self.texture_format = Texture.F_rgb8
            self.texture.setup2dTexture(texture_size, texture_size,
                                        self.texture_component_type,
                                        self.texture_format)
            self.texture.setRamImageAs(self.texture_array, "RGB")
        else:
            raise ValueError("Texture needs to be 2d or 3d")

        self.textureStage = TextureStage("Stimulus")

        #Create scenegraph
        cm = CardMaker('card')
        cm.setFrameFullscreenQuad()
        self.card = self.aspect2d.attachNewNode(cm.generate())
        self.card.setTexture(self.textureStage, self.texture)  #ts, tx

        #Set the scale on the card (note this is different from scaling the texture)
        self.card.setScale(np.sqrt(2))

        if self.scale != 0:
            #Add task to taskmgr to translate texture
            self.taskMgr.add(self.scaleTextureTask, "scaleTextureTask")
示例#23
0
    def __init__(self):
        ShowBase.__init__(self)

        self.win.setClearColor(Vec4(0, 0, 0, 1))

        self.disableMouse()

        properties = WindowProperties()
        properties.setSize(1280, 750)
        self.win.requestProperties(properties)

        self.exitFunc = self.cleanup

        self.accept("space", self.explode)

        self.accept("f", self.toggleFrameRateMeter)
        self.showFrameRateMeter = False

        self.updateTask = taskMgr.add(self.update, "update")

        cardMaker = CardMaker("explosion maker")
        cardMaker.setFrame(-1, 1, -1, 1)

        self.explosionCard = render.attachNewNode(cardMaker.generate())
        self.explosionCard.setY(5)
        self.explosionCard.setScale(0.4)

        self.duration = 0.4

        shader = Shader.load(Shader.SL_GLSL, "blasterImpactVertex.glsl",
                             "blasterImpactFragment.glsl")
        self.explosionCard.setShader(shader)
        self.explosionCard.setShaderInput("startTime", -1000)
        self.explosionCard.setShaderInput(
            "sourceTex1", loader.loadTexture("noiseRadial1.png"))
        self.explosionCard.setShaderInput(
            "sourceTex2", loader.loadTexture("noiseRadial2.png"))
        self.explosionCard.setShaderInput("duration", self.duration)
        self.explosionCard.setShaderInput("expansionFactor", 1)
        self.explosionCard.setShaderInput("randomisation1", 0)
        self.explosionCard.setShaderInput("randomisation2", 0)

        self.timer = 0
        '''shader = Shader.load(Shader.SL_GLSL, "explosionVertex.glsl", "explosionFragment.glsl")
        self.explosionCard.setShader(shader)
        self.explosionCard.setShaderInput("startTime", -1000)
        self.explosionCard.setShaderInput("sourceTex1", loader.loadTexture("noise1.png"))
        self.explosionCard.setShaderInput("sourceTex2", loader.loadTexture("noise2.png"))
        self.explosionCard.setShaderInput("duration", 1.25)
        self.explosionCard.setShaderInput("starDuration", 1)
        self.explosionCard.setShaderInput("expansionFactor", 7)
        self.explosionCard.setShaderInput("rotationRate", 0.2)
        self.explosionCard.setShaderInput("fireballBittiness", 1.5)
        self.explosionCard.setShaderInput("randomisation1", Vec2(0, 0))
        self.explosionCard.setShaderInput("randomisation2", Vec2(0, 0))'''
        '''self.explosionCard = render.attachNewNode(cardMaker.generate())
示例#24
0
 def makePlayerFace(self):
     cm = CardMaker("face")
     cardModel = self.playerFace.attachNewNode(cm.generate())
     path = base.playerIconPath + "/" + base.playerCardBack
     tex = loader.loadTexture(path)
     cardModel.setTexture(tex)
     self.playerFace.setPythonTag('zone', base.player.face)
     cardModel.setPos(-0.5, 0, -0.5)
     base.playerFaceNode = cardModel
     base.playerFaceNode.setCollideMask(cardBuilder.cardCollisionMask)
示例#25
0
 def _makeSquare(self):
     c = CardMaker("square")
     c.setFrame(-0.5, 0.5, -0.5, 0.5)
     self.square = NodePath(c.generate())
     self.square.setShaderInput("font", self.fontTex)
     self.square.setShader(self.fontShader, 1000)
     self.square.setAttrib(
         TransparencyAttrib.make(TransparencyAttrib.MAlpha), 1000)
     self.square.reparentTo(self.parent)
     return self.square
示例#26
0
 def _makeSquare(self):
     c = CardMaker("square")
     c.setFrame(-0.5, 0.5, -0.5, 0.5)
     self.square = NodePath(c.generate())
     self.square.setShaderInput("font", self.fontTex)
     self.square.setShader(self.fontShader)
     self.square.setAttrib(
         TransparencyAttrib.make(TransparencyAttrib.MAlpha), 100)
     self.square.reparentTo(Globals.base.aspect2d)
     return self.square
示例#27
0
 def __init__(self, startSize, endSize, roll, color, duration):
     NodePath.__init__(self, 'muzzleParticle')
     
     cm = CardMaker("muzzleSpriteCard")
     cm.setFrame(-1, 1, -1, 1)
     cm.setHasUvs(True)
     cm.setUvRange((0, 0), (1, 1))
     cmnp = self.attachNewNode(cm.generate())
     cmnp.setBillboardAxis()
     
     self.setTexture(loader.loadTexture(self.muzzleroot.format(random.randint(*self.muzzles))), 1)
     #self.setShaderOff(1)
     self.setLightOff(1)
     self.setMaterialOff(1)
     self.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOne), 1)
     self.setDepthWrite(False, 1)
     #self.setTransparency(1)
     
     self.startAlpha = 0.5
     self.endAlpha = 0.0
     self.duration = duration
     self.startSize = startSize
     self.endSize = endSize
     self.color = color
     self.startTime = globalClock.getFrameTime()
     self.roll = roll
     taskMgr.add(self.particleUpdate, "muzzleParticleUpdate-" + str(id(self)))
示例#28
0
 def generateAnalysis(self):
     if self.analyzeMode:
         self.cleanupAnalysis()
     
     self.analyzeMode = True
     cm = CardMaker('cm')
     self.analysisBar.show()
     loadingTime = self.loadingEnd - self.loadingStart
     for stepName in self.stepInfo:
         (startTime, duration, color, ticks, startPercent, percent, expectedTicks) = self.stepInfo[stepName]
         cm.setName(stepName)
         cm.setColor(color)
         cm.setFrame((startTime / loadingTime) * 1.8 - 0.90000000000000002, ((startTime + duration) / loadingTime) * 1.8 - 0.90000000000000002, -0.5, -0.10000000000000001)
         self.analysisBarRoot.attachNewNode(cm.generate())
         button = DirectFrame(parent = self.analysisBarRoot, geom = NodePath('empty'), image = NodePath('empty'), state = DGG.NORMAL, relief = None, frameSize = ((startTime / loadingTime) * 1.8 - 0.90000000000000002, ((startTime + duration) / loadingTime) * 1.8 - 0.90000000000000002, -0.5, -0.10000000000000001))
         button.bind(DGG.ENTER, self.showInfo, extraArgs = [
             stepName])
         self.analysisButtons.append(button)
         button = DirectFrame(parent = self.analysisBarRoot, geom = NodePath('empty'), image = NodePath('empty'), state = DGG.NORMAL, relief = None, frameSize = ((startPercent / self.loadScale / 100.0) * 1.8 - 0.90000000000000002, ((startPercent + percent) / self.loadScale / 100.0) * 1.8 - 0.90000000000000002, 0.10000000000000001, 0.5))
         button.bind(DGG.ENTER, self.showInfo, extraArgs = [
             stepName])
         self.analysisButtons.append(button)
         for tick in ticks:
             self.line.moveTo(VBase3((tick / loadingTime) * 1.8 - 0.90000000000000002, 0, -0.5))
             self.line.drawTo(VBase3((tick / loadingTime) * 1.8 - 0.90000000000000002, 0, -0.55000000000000004))
         
     
     for tick in self.unmappedTicks:
         self.line.moveTo(VBase3((tick / loadingTime) * 1.8 - 0.90000000000000002, 0, -0.5))
         self.line.drawTo(VBase3((tick / loadingTime) * 1.8 - 0.90000000000000002, 0, -0.55000000000000004))
     
     self.analysisSegs = self.analysisBarRoot.attachNewNode(self.line.create())
示例#29
0
def makeCube(geom, x, y, z, scale=1.0, texpos=None, colors=False):
    """
    Function that adds six cards to a GeomNode to form a cube
    
    geom: GeomNode to add cards to
    x, y, z: Position offset
    scale: Optional, Scale factor, cube is 1x1x1 by default
    texpos: Optional, Dictionary of tuples with texture co-ordinates
            Tuple has Point2 for top-left and Point2 for bottom-right
            Faces are "front", "back", "left", "right", "top", "bottom"
    colors: Optional, if True set different color for each face for debugging
            (see cardcolors)
    """
    cardmaker = CardMaker("cardmaker")

    mycards = deepcopy(CARDS)
    for k, i in mycards.iteritems():
        points = i
        for j in points:
            j += Point3(x, y, z)
            j *= scale
        cardmaker.setFrame(*points)

        if texpos:
            cardmaker.setUvRange(*texpos[k])
        if colors:
            cardmaker.setColor(*CARDCOLORS[k])
        geom.addGeomsFrom(cardmaker.generate())
 def loadFlatQuad(self, fullFilename):
     cm = CardMaker('cm-%s' % fullFilename)
     cm.setColor(1.0, 1.0, 1.0, 1.0)
     aspect = base.camLens.getAspectRatio()
     htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)
     htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT)
     cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0,
                 htmlHeight / 2.0)
     bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1)
     bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1)
     cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1))
     card = cm.generate()
     quad = NodePath(card)
     jpgFile = PNMImage(WEB_WIDTH, WEB_HEIGHT)
     smallerJpgFile = PNMImage()
     readFile = smallerJpgFile.read(Filename(fullFilename))
     if readFile:
         jpgFile.copySubImage(smallerJpgFile, 0, 0)
         guiTex = Texture('guiTex')
         guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1,
                             Texture.TUnsignedByte, Texture.FRgba)
         guiTex.setMinfilter(Texture.FTLinear)
         guiTex.load(jpgFile)
         guiTex.setWrapU(Texture.WMClamp)
         guiTex.setWrapV(Texture.WMClamp)
         ts = TextureStage('webTS')
         quad.setTexture(ts, guiTex)
         quad.setTransparency(0)
         quad.setTwoSided(True)
         quad.setColor(1.0, 1.0, 1.0, 1.0)
         result = quad
     else:
         result = None
     Texture.setTexturesPower2(1)
     return result
示例#31
0
 def setupTexture(self):
     cm = CardMaker('quadMaker')
     cm.setColor(1.0, 1.0, 1.0, 1.0)
     aspect = base.camLens.getAspectRatio()
     htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)
     htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT)
     cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0)
     bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1)
     bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1)
     cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1))
     card = cm.generate()
     self.quad = NodePath(card)
     self.quad.reparentTo(self.parent_)
     self.guiTex = Texture('guiTex')
     self.guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba)
     self.guiTex.setMinfilter(Texture.FTLinear)
     self.guiTex.setKeepRamImage(True)
     self.guiTex.makeRamImage()
     self.guiTex.setWrapU(Texture.WMRepeat)
     self.guiTex.setWrapV(Texture.WMRepeat)
     ts = TextureStage('webTS')
     self.quad.setTexture(ts, self.guiTex)
     self.quad.setTexScale(ts, 1.0, -1.0)
     self.quad.setTransparency(0)
     self.quad.setTwoSided(True)
     self.quad.setColor(1.0, 1.0, 1.0, 1.0)
     self.calcMouseLimits()
示例#32
0
 def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None):
     if textures:
         colortex = textures.get('color', None)
         depthtex = textures.get('depth', None)
         auxtex = textures.get('aux', None)
         auxtex0 = textures.get('aux0', auxtex)
         auxtex1 = textures.get('aux1', None)
     else:
         auxtex0 = auxtex
         auxtex1 = None
     if colortex == None:
         colortex = Texture('filter-base-color')
         colortex.setWrapU(Texture.WMClamp)
         colortex.setWrapV(Texture.WMClamp)
     texgroup = (depthtex, colortex, auxtex0, auxtex1)
     winx, winy = self.getScaledSize(1, 1, 1)
     buffer = self.createBuffer('filter-base', winx, winy, texgroup)
     if buffer == None:
         return
     cm = CardMaker('filter-base-quad')
     cm.setFrameFullscreenQuad()
     quad = NodePath(cm.generate())
     quad.setDepthTest(0)
     quad.setDepthWrite(0)
     quad.setTexture(colortex)
     quad.setColor(1, 0.5, 0.5, 1)
     cs = NodePath('dummy')
     cs.setState(self.camstate)
     if auxbits:
         cs.setAttrib(AuxBitplaneAttrib.make(auxbits))
     self.camera.node().setInitialState(cs.getState())
     quadcamnode = Camera('filter-quad-cam')
     lens = OrthographicLens()
     lens.setFilmSize(2, 2)
     lens.setFilmOffset(0, 0)
     lens.setNearFar(-1000, 1000)
     quadcamnode.setLens(lens)
     quadcam = quad.attachNewNode(quadcamnode)
     self.region.setCamera(quadcam)
     self.setStackedClears(buffer, self.rclears, self.wclears)
     if auxtex0:
         buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1)
         buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0))
     if auxtex1:
         buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1)
     self.region.disableClears()
     if self.isFullscreen():
         self.win.disableClears()
     dr = buffer.makeDisplayRegion()
     dr.disableClears()
     dr.setCamera(self.camera)
     dr.setActive(1)
     self.buffers.append(buffer)
     self.sizes.append((1, 1, 1))
     return quad
示例#33
0
 def __init__(self, distRace):
     self.race = distRace
     self.timerEnabled = False
     self.maxLapHit = 0
     self.photoFinish = False
     toonInteriorTextures = loader.loadModel(
         'phase_3.5/models/modules/toon_interior_textures')
     invTextures = loader.loadModel('phase_3.5/models/gui/inventory_icons')
     racingTextures = loader.loadModel(
         'phase_6/models/karting/racing_textures')
     self.gagTextures = [
         toonInteriorTextures.find('**/couch'),
         invTextures.find('**/inventory_bannana_peel'),
         racingTextures.find('**/boost_arrow'),
         invTextures.find('**/inventory_anvil'),
         invTextures.find('**/inventory_creampie')
     ]
     self.gagTextures[1].setScale(7.5)
     self.gagTextures[3].setScale(7.5)
     self.gagTextures[4].setScale(7.5)
     self.cardMaker = CardMaker('card')
     self.racerDict = {}
     self.render2dRoot = render2d.attachNewNode('RaceGuiRender2dRoot')
     self.render2dRoot.setDepthWrite(1)
     self.directObjList = []
     self.aspect2dRoot = aspect2d.attachNewNode('RaceGuiAspect2dRoot')
     self.aspect2dRoot.setDepthWrite(1)
     self.raceModeRoot = self.aspect2dRoot.attachNewNode('RaceModeRoot')
     gui = loader.loadModel('phase_3.5/models/gui/avatar_panel_gui')
     self.closeButton = DirectButton(image=(gui.find('**/CloseBtn_UP'),
                                            gui.find('**/CloseBtn_DN'),
                                            gui.find('**/CloseBtn_Rllvr'),
                                            gui.find('**/CloseBtn_UP')),
                                     relief=None,
                                     scale=1.05,
                                     text=TTLocalizer.KartRace_Leave,
                                     text_scale=0.04,
                                     text_pos=(0, -0.07),
                                     text_fg=VBase4(1, 1, 1, 1),
                                     pos=(-0.99, 0, 0.925),
                                     command=self.race.leaveRace)
     self.closeButton.reparentTo(self.aspect2dRoot)
     self.directObjList.append(self.closeButton)
     self.raceTimeDelta = 0
     self.raceModeReady = False
     self.resultModeReady = False
     self.gagCycleSound = base.loader.loadSfx(
         'phase_3.5/audio/sfx/tick_counter.ogg')
     if hasattr(self.gagCycleSound, 'setPlayRate'):
         self.gagCycleSound.setPlayRate(0.2)
     self.gagCycleSound.setLoop(1)
     self.gagAcquireSound = base.loader.loadSfx(
         'phase_6/audio/sfx/SZ_MM_gliss.ogg')
     self.disable()
     return
 def __init__(self, startSize, endSize, roll, color, duration):
     NodePath.__init__(self, 'muzzleParticle')
     
     muzzles = [1, 4]
     muzzleroot = "phase_14/hl2/muzzleflash{0}.png"
     
     cm = CardMaker("muzzleSpriteCard")
     cm.setFrame(-1, 1, -1, 1)
     cm.setHasUvs(True)
     cm.setUvRange((0, 0), (1, 1))
     cmnp = self.attachNewNode(cm.generate())
     cmnp.setBillboardAxis()
     
     self.setTexture(loader.loadTexture(muzzleroot.format(random.randint(*muzzles))), 1)
     #self.setShaderOff(1)
     self.setLightOff(1)
     self.setMaterialOff(1)
     self.setTransparency(1)
     
     self.startAlpha = 0.5
     self.endAlpha = 0.0
     self.duration = duration
     self.startSize = startSize
     self.endSize = endSize
     self.color = color
     self.startTime = globalClock.getFrameTime()
     self.roll = roll
     taskMgr.add(self.particleUpdate, "muzzleParticleUpdate-" + str(id(self)))
示例#35
0
    def __init__(self, name, filename=None, **options):
        DirectObject.__init__(self)
        TextFileNode.__init__(self, name, None, **options)

        self.cardmaker = CardMaker('selection cards')
        self.selection_cards = []
        self.selecting = False
        self.rect_w, self.rect_h = 1, 1

        self.accept('shift', self.toggle_select, extraArgs=[True])
        self.accept('shift-up', self.toggle_select, extraArgs=[False])
    def _create_components(self):
        """ Internal method to init the widgets components """
        card_maker = CardMaker("PixelInspector")
        card_maker.set_frame(-200, 200, -150, 150)
        self._zoomer = self._node.attach_new_node(card_maker.generate())

        # Defer the further loading
        Globals.base.taskMgr.doMethodLater(
            1.0, self._late_init, "PixelInspectorLateInit")
        Globals.base.accept("q", self.show)
        Globals.base.accept("q-up", self.hide)
示例#37
0
 def create_instance(self):
     self.instance = NodePath("card")
     card_maker = CardMaker("card")
     card_maker.set_frame(-1, 1, -1, 1)
     node = card_maker.generate()
     self.card_instance = self.instance.attach_new_node(node)
     self.card_instance.setBillboardPointWorld()
     TransparencyBlend.apply(self.blend, self.instance)
     self.instance.node().setBounds(OmniBoundingVolume())
     self.instance.node().setFinal(True)
     return self.instance
示例#38
0
 def makeEnemyFace(self):
     cm = CardMaker("face")
     cardModel = self.enemyFace.attachNewNode(cm.generate())
     path = base.enemyIconPath + "/" + base.enemyCardBack
     tex = loader.loadTexture(path)
     cardModel.setTexture(tex)
     self.enemyFace.setPythonTag('zone', base.enemy.face)
     cardModel.setPos(-0.5, 0, -0.5)
     base.enemyFaceNode = cardModel
     # Want it to be possible to click on enemy face
     base.enemyFaceNode.setCollideMask(cardBuilder.cardCollisionMask)
示例#39
0
    def _create_components(self):
        """ Internal method to init the widgets components """
        card_maker = CardMaker("PixelInspector")
        card_maker.set_frame(-200, 200, -150, 150)
        self._zoomer = self._node.attach_new_node(card_maker.generate())

        # Defer the further loading
        Globals.base.taskMgr.doMethodLater(1.0, self._late_init,
                                           "PixelInspectorLateInit")
        Globals.base.accept("q", self.show)
        Globals.base.accept("q-up", self.hide)
示例#40
0
def loadPlane(name, widthX = 30.0, widthY = 30.0):
    """load plane stuff"""
    
    cm = CardMaker("plane")
    cm.set_frame(-widthX / 2.0, widthX / 2.0, -widthY / 2.0, widthY / 2.0)
    plane = NodePath(cm.generate())
    plane.set_p(-90.0)
    plane.set_z(0.0)
    plane.set_color(0.15, 0.35, 0.35)
    plane.set_collide_mask(mask)
    plane.set_name(name)
    return plane
示例#41
0
    def prepare(self, curr_cond, stim_period=''):
        self.curr_cond = curr_cond if stim_period == '' else curr_cond[
            stim_period]
        self.period = stim_period

        if not self.curr_cond:
            self.isrunning = False
        self.background_color = self.curr_cond['background_color']

        # set background color
        self.set_background_color(*self.curr_cond['background_color'])

        # Set Ambient Light
        self.ambientLight.setColor(self.curr_cond['ambient_color'])

        # Set Directional Light
        self.lights = dict()
        self.lightsNP = dict()
        for idx, light_idx in enumerate(iterable(self.curr_cond['light_idx'])):
            self.lights[idx] = core.DirectionalLight('directionalLight_%d' %
                                                     idx)
            self.lightsNP[idx] = self.render.attachNewNode(self.lights[idx])
            self.render.setLight(self.lightsNP[idx])
            self.lights[idx].setColor(tuple(
                self.curr_cond['light_color'][idx]))
            self.lightsNP[idx].setHpr(*self.curr_cond['light_dir'][idx])

        # Set Object tasks
        self.objects = dict()
        for idx, obj in enumerate(iterable(self.curr_cond['obj_id'])):
            self.objects[idx] = Agent(self, self.get_cond('obj_', idx))

        if 'movie_name' in self.curr_cond:
            self.movie = True
            loader = Loader(self)
            file_name = self.get_clip_info(self.curr_cond, 'file_name')
            self.mov_texture = loader.loadTexture(self.movie_path +
                                                  file_name[0])
            cm = CardMaker("card")
            tx_scale = self.mov_texture.getTexScale()
            cm.setFrame(-1, 1, -tx_scale[1] / tx_scale[0],
                        tx_scale[1] / tx_scale[0])
            self.movie_node = NodePath(cm.generate())
            self.movie_node.setTexture(self.mov_texture, 1)
            self.movie_node.setPos(0, 100, 0)
            self.movie_node.setTexScale(TextureStage.getDefault(),
                                        self.mov_texture.getTexScale())
            self.movie_node.setScale(48)
            self.movie_node.reparentTo(self.render)

        if not self.isrunning:
            self.timer.start()
            self.isrunning = True
示例#42
0
 def makeHandle(self):
     cm = CardMaker('handle')
     cm.setFrame(-1, 1, -1, 1)
     np = NodePath(cm.generate())
     np.setLightOff(1)
     np.setFogOff(1)
     np.setBin("fixed", LEGlobals.WidgetSort)
     np.setDepthWrite(False)
     np.setDepthTest(False)
     np.setHpr(self.vp.getViewHpr())
     np.hide(~self.vp.getViewportMask())
     return np
示例#43
0
    def __init__(self):
        ShowBase.__init__(self)
        add_device_listener(
            config_file='keybindings.toml',
            assigner=SinglePlayerAssigner(),
        )
        base.disableMouse()
        self.sound = SoundManager()
        self.linefx = LineEffects()
        self.cardmaker = CardMaker("card")
        self.cardmaker.set_frame(-1,1,-1,1)
        self.turn_speed = 0.3 #length of turn animation in seconds
        self.sequence_player = SequencePlayer()
        self.transition = Transitions(loader)
        self.interface = Interface()
        self.bg_color = VBase4(0, 0, 0, 1)
        self.innitialize_fov()

        card, scene, camera, self.buffer = self.make_render_card()
        card.set_x(-0.25)
        self.camera = camera
        self.load_icons()

        self.texts = Texts(camera)
        self.pause = True
        self.instruct = True
        self.gameover = False
        self.won = False

        self.player = Player((0,0,0))
        self.map = Map()
        self.map.new_game()

        camera.reparent_to(self.player.root)
        camera.set_pos(4,-4,8)
        camera.look_at(self.player.root)
        camera.set_compass()
        base.task_mgr.add(self.update)

        card, scene, camera, buffer = self.make_render_card([3,7],[64,256],(0,100))
        self.hudgun = Actor("assets/models/hand.bam")
        self.hudgun.reparent_to(scene)
        self.hudgun.find("**/hand_healthy").show()
        self.hudgun.find("**/hand_hurt").hide()
        self.hudgun.setLODAnimation(1, 0.1, 0.005)
        self.player.weapon.set_hud_bullets()
        camera.look_at(self.hudgun)
        camera.set_pos(0.5,-1.5,10)
        camera.set_p(-90)
        card.set_scale(1/4,1,1)
        card.set_x(1-(1/4))
        self.quad = None
        self.setup_post_effect()
示例#44
0
 def loadImageAsPlane(self, filepath, yresolution = 600):
     tex = loader.loadTexture(filepath) # @UndefinedVariable
     tex.setBorderColor(Vec4(0,0,0,0))
     tex.setWrapU(Texture.WMBorderColor)
     tex.setWrapV(Texture.WMBorderColor)
     cm = CardMaker(filepath + ' card')
     cm.setFrame(-tex.getOrigFileXSize(), tex.getOrigFileXSize(), -tex.getOrigFileYSize(), tex.getOrigFileYSize())
     card = NodePath(cm.generate())
     card.setTexture(tex)
     card.setScale(card.getScale()/ yresolution)
     card.flattenLight() # apply scale
     return card
示例#45
0
    def create_wall(self, render, wall_texture, x_angle, y_angle, angle):
        wall_card_maker = CardMaker("wall")
        wall_card_maker.setUvRange((0, 0), (self.size / 50, self.size / 50))
        wall_gfx = render.attachNewNode(CardMaker.generate(wall_card_maker))
        wall_gfx.setPos(
            copysign(1, x_angle) * self.size / 2,
            copysign(1, y_angle) * self.size / 2, 0)
        wall_gfx.setScale(self.size)
        wall_gfx.setHpr(angle, 0, 0)

        wall_gfx.setTransparency(True)
        wall_gfx.setTexture(wall_texture)
示例#46
0
    def __init__(self):
        #Muestra un texto en pantalla, utilizando la interfaz 2D de Panda3D.
        #Posteriormente se actualizara con otros datos, por eso se mantiene la referencia
        self.title = OnscreenText(text="prueba 1", style=1, fg=(0,0,0,1), pos=(0.8,-0.95), scale = .07)

        #Lee los datos de configuracion de los clasificadores HAAR. En este caso, para deteccion de rostros en posicion frontal
        self.cascade = cv.Load("haarcascades\\haarcascade_frontalface_alt.xml")
        
        #Utiliza por defecto la camara para obtener las imagenes, y no guarda un archivo
        self.cameraHelper = CameraHelper(True, False, "d:\\face-detection.avi")
	
        #Crea una textura para utilizar como fondo, donde se mostraran las imagenes de video
	#CardMaker en realidad es un poligono rectangular, que es util para asociarlo al renderer2D, ya que
	#podremos hacer que ocupe toda la pantalla y mostrar nuestras imagenes como fondo.
        self.cardMaker = CardMaker("My Fullscreen Card");
        self.cardMaker.setFrameFullscreenQuad()

	#Agrega el rectangulo al renderer render2dp. Asi como existe render2d, existe uno adicional que es utilizado
	#en general para casos donde necesita mostrarse un fondo, sea estatico o de video. El render2d estandar,
	#por el contrario, se usa para mostrar informacion al usuario que siempre debe ser visible
        self.card = NodePath(self.cardMaker.generate())
        self.card.reparentTo(render2dp)
	
        #Le da baja prioridad para que los objetos dibujados posteriormente siempre se vean sobre ella
        base.cam2dp.node().getDisplayRegion(0).setSort(-20)
        
        #Crea un rectangulo que se utilizara para mostrar la imagen superpuesta sobre la cara
        self.faceMaker = CardMaker("Face Texture");
        self.faceImage = NodePath(self.faceMaker.generate())
        self.faceImage.setTexture(loader.loadTexture("margarita-glass3.png"))
        self.faceImage.reparentTo(aspect2d)
        #self.faceImage.reparentTo(render2d)
        self.faceImage.setTransparency(TransparencyAttrib.MAlpha)
        
        self.setup_handlers()
        self.setup_lights()

        self.count = 0
        
        #Establece un fondo negro
        #base.setBackgroundColor(0, 0, 0)

        #Carga el objeto tetera (incluido con Panda3D), y lo ubica en el mundo
        #self.teapot = loader.loadModel('models/teapot')
        #self.teapot.reparentTo(base.render)
        #self.teapot.setPos(-10, -10, -10)

        #Coloca la camara en el origen de coordenadas, y hace que apunte hacia la tetera
        #camera.setPos(0, 0, 0)
        #camera.lookAt(-10, -10, -10)

        taskMgr.add(self.onFrameChanged, "frameChange")
示例#47
0
def createSprite(_filename, _x, _z, _transparent=1):
    tex = loader.loadTexture(_filename)
    cm = CardMaker('spritesMaker')
    sprite = NodePath(cm.generate())
    sprite.setTexture(tex)

    #Scale and position
    sx = float(tex.getXSize()) / base.win.getXSize()
    sz = float(tex.getYSize()) / base.win.getYSize()
    sprite.setScale(sx, 1.0, sz)
    #sprite.setPos(_x/2, 0.0, _z/2)
    sprite.setTransparency(_transparent)
    return sprite, (sx, sz)
示例#48
0
 def _draw(self, image, identifier, parentnode, parameters):
     if self.node is not None: self.node.removeNode()
     if image != self.image:
         self.tex = self.canvasdrone.get_loader().loadTexture(image)
         self.image = image
     cm = CardMaker(identifier)
     node = NodePath(cm.generate())
     node.setTexture(self.tex)
     if parameters is not None:
         if hasattr(parameters, "transparency") and parameters.transparency == True:
             node.setTransparency(TransparencyAttrib.MAlpha)
     node.setScale(1, 1, -1)
     node.reparentTo(parentnode)
示例#49
0
    def loadBlank(self, path, card):
        cardBase = self.scene.attachNewNode('mysterious card')

        cm = CardMaker('mysterious card')

        cardFrame = cardBase.attachNewNode(cm.generate())
        tex = loader.loadTexture('ul_frame_alt.png')
        cardFrame.setTexture(tex)
        cardFrame.setScale(1, 1, 509 / 364)
        cardFrame.setTransparency(True)
        cardFrame.setName('frame')
        cardBase.setPythonTag('card', card)
        return cardBase
示例#50
0
 def _activateSunflare(self):
     self.deactivateHighlight()
     flare_tex = base.loader.loadTexture("models/billboards/sunflare.png")
     cm = CardMaker('flare')
     cm.setFrameFullscreenQuad() # so that the center acts as the origin (from -1 to 1)
     self.flare_path = self.point_path.attachNewNode(cm.generate())        
     self.flare_path.setTransparency(TransparencyAttrib.MAlpha)
     self.flare_path.setTexture(self.flare_ts,flare_tex)
     self.flare_path.setColor(Vec4(1.0, 1.0, 1.0, 1))
     self.flare_path.setScale(50)
     self.flare_path.setPos(Vec3(0,0,0))
     self.flare_path.setBillboardPointEye()
     self.flare_path.setLightOff()
示例#51
0
    def __init__(self,
                 tex,
                 angle=0,
                 velocity=0.1,
                 fps=30,
                 window_name="ShowTexMoving",
                 window_size=None,
                 profile_on=False):
        super().__init__()
        self.tex = tex
        if window_size is None:
            self.window_size = self.tex.texture_size
        else:
            self.window_size = window_size
        self.angle = angle
        self.velocity = velocity
        self.texture_stage = TextureStage("texture_stage")
        self.window_name = window_name

        # Set frame rate (fps)
        ShowBaseGlobal.globalClock.setMode(ClockObject.MLimited)
        ShowBaseGlobal.globalClock.setFrameRate(fps)

        #Set up profiling if desired
        if profile_on:
            PStatClient.connect(
            )  # this will only work if pstats is running: see readme
            ShowBaseGlobal.base.setFrameRateMeter(True)  #Show frame rate
            self.center_indicator = None

        #Window properties set up
        self.window_properties = WindowProperties()
        self.window_properties.setSize(self.window_size, self.window_size)
        self.window_properties.setTitle(window_name)
        ShowBaseGlobal.base.win.requestProperties(self.window_properties)

        #Create scenegraph, attach stimulus to card.
        cm = CardMaker('card')
        cm.setFrameFullscreenQuad()
        self.card = self.aspect2d.attachNewNode(cm.generate())
        # Scale is so it can handle arbitrary rotations and shifts in binocular case
        self.card.setScale(np.sqrt(8))
        self.card.setColor(
            (1, 1, 1, 1)
        )  # makes it bright when bright (default combination with card is add)
        self.card.setTexture(self.texture_stage, self.tex.texture)
        self.card.setTexRotate(self.texture_stage, self.angle)

        if self.velocity != 0:
            #Add task to taskmgr to translate texture
            self.taskMgr.add(self.moveTextureTask, "moveTextureTask")
示例#52
0
class CardQuad(visual):
    def setup(self):
        self.path.removeNode()
        self.path = self.render.attachNewNode("Card Quad")

        self.plane = CardMaker("plane")

        self.plane.setFrame(-10,10,-10,10)
        self.left = self.path.attachNewNode(self.plane.generate())
        self.right = self.path.attachNewNode(self.plane.generate())
        self.up = self.path.attachNewNode(self.plane.generate())
        self.down = self.path.attachNewNode(self.plane.generate())
        self.front = self.path.attachNewNode(self.plane.generate())
        self.back = self.path.attachNewNode(self.plane.generate())
        self.left.setX(-10)
        self.right.setX(10)
        self.up.setZ(10)
        self.down.setZ(-10)
        self.left.setH(270)
        self.right.setH(90)
        self.up.setP(270)
        self.down.setP(90)
        self.front.setY(-10)
        self.back.setY(10)
        self.back.setH(180)

        self.tex = self.loader.loadTexture("indian_ornament_texture.png")

        self.path.setTexture(self.tex)
        self.path.setTransparency(TransparencyAttrib.MAlpha, 1)
        self.path.setTwoSided(1)
示例#53
0
 def loadFlatQuad(self, fullFilename):
     cm = CardMaker('cm-%s' % fullFilename)
     cm.setColor(1.0, 1.0, 1.0, 1.0)
     aspect = base.camLens.getAspectRatio()
     htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH)
     htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT)
     cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0)
     bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1)
     bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1)
     cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1))
     card = cm.generate()
     quad = NodePath(card)
     jpgFile = PNMImage(WEB_WIDTH, WEB_HEIGHT)
     smallerJpgFile = PNMImage()
     readFile = smallerJpgFile.read(Filename(fullFilename))
     if readFile:
         jpgFile.copySubImage(smallerJpgFile, 0, 0)
         guiTex = Texture('guiTex')
         guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba)
         guiTex.setMinfilter(Texture.FTLinear)
         guiTex.load(jpgFile)
         guiTex.setWrapU(Texture.WMClamp)
         guiTex.setWrapV(Texture.WMClamp)
         ts = TextureStage('webTS')
         quad.setTexture(ts, guiTex)
         quad.setTransparency(0)
         quad.setTwoSided(True)
         quad.setColor(1.0, 1.0, 1.0, 1.0)
         result = quad
     else:
         result = None
     Texture.setTexturesPower2(1)
     return result
    def renderQuadInto(self, mul=1, div=1, align=1, depthtex=None, colortex=None, auxtex0=None, auxtex1=None):

        """ Creates an offscreen buffer for an intermediate
        computation. Installs a quad into the buffer.  Returns
        the fullscreen quad.  The size of the buffer is initially
        equal to the size of the main window.  The parameters 'mul',
        'div', and 'align' can be used to adjust that size. """

        texgroup = (depthtex, colortex, auxtex0, auxtex1)

        winx, winy = self.getScaledSize(mul, div, align)
        
        depthbits = bool(depthtex != None)

        buffer = self.createBuffer("filter-stage", winx, winy, texgroup, depthbits)

        if (buffer == None):
            return None

        cm = CardMaker("filter-stage-quad")
        cm.setFrameFullscreenQuad()
        quad = NodePath(cm.generate())
        quad.setDepthTest(0)
        quad.setDepthWrite(0)
        quad.setColor(1, 0.5, 0.5, 1)

        quadcamnode = Camera("filter-quad-cam")
        lens = OrthographicLens()
        lens.setFilmSize(2, 2)
        lens.setFilmOffset(0, 0)
        lens.setNearFar(-1000, 1000)
        quadcamnode.setLens(lens)
        quadcam = quad.attachNewNode(quadcamnode)

        dr = buffer.makeDisplayRegion((0, 1, 0, 1))
        dr.disableClears()
        dr.setCamera(quadcam)
        dr.setActive(True)
        dr.setScissorEnabled(False)

        # This clear stage is important if the buffer is padded, so that
        # any pixels accidentally sampled in the padded region won't
        # be reading from unititialised memory.
        buffer.setClearColor((0, 0, 0, 1))
        buffer.setClearColorActive(True)

        self.buffers.append(buffer)
        self.sizes.append((mul, div, align))
        
        return quad
示例#55
0
    def replicate(self, texture):
        cm = CardMaker("replicate-quad")
        cm.set_frame_fullscreen_quad()
        self.quad = NodePath(cm.generate())
        self.quad.set_depth_test(0)
        self.quad.set_depth_write(0)
        self.quad.set_texture(texture)

        lens = OrthographicLens()
        lens.set_film_size(2, 2)
        lens.set_film_offset(0, 0)
        lens.set_near_far(-1000, 1000)
        base.cam.node().set_lens(lens)
        base.cam.reparent_to(self.quad)
示例#56
0
def makeCube(geom, x, y, z, scale=1.0, texpos=None, colors=False):
    """
    Function that adds six cards to a GeomNode to form a cube
    
    geom: GeomNode to add cards to
    x, y, z: Position offset
    scale: Optional, Scale factor, cube is 1x1x1 by default
    texpos: Optional, Dictionary of tuples with texture co-ordinates
            Tuple has Point2 for top-left and Point2 for bottom-right
            Faces are "front", "back", "left", "right", "top", "bottom"
    colors: Optional, if True set different color for each face for debugging
            (see cardcolors)
    """
    cardmaker = CardMaker("cardmaker")
    
    mycards = deepcopy(CARDS)
    for k, i in mycards.iteritems():
        points = i
        for j in points:
            j += Point3(x, y, z)
            j *= scale
        cardmaker.setFrame(*points)
        
        if texpos:
            cardmaker.setUvRange(*texpos[k])
        if colors:
            cardmaker.setColor(*CARDCOLORS[k])
        geom.addGeomsFrom(cardmaker.generate())
示例#57
0
文件: main.py 项目: grimfang/pyweek21
 def create16To9LogoCard(logoPath, tsName):
     cm = CardMaker("fade")
     scale = abs(base.a2dLeft) / 1.7776
     cm.setFrame(-1, 1, -1 * scale, 1 * scale)
     logo = NodePath(cm.generate())
     logo.setTransparency(TransparencyAttrib.MAlpha)
     logoTex = loader.loadTexture(logoPath)
     logoTs = TextureStage(tsName)
     logoTs.setMode(TextureStage.MReplace)
     logo.setTexture(logoTs, logoTex)
     logo.setBin("fixed", 5000)
     logo.reparentTo(render2d)
     logo.hide()
     return logo
示例#58
0
        def __init__(self, scale=1, value=0, r=10, g=0, b=0): 
                NodePath.__init__(self, 'healthbar') 
                self.value = value
                self.scale = scale 
                self.range = 1.0
                self.buff = 0
                
                
                
                cmbg = CardMaker('bg') 
                cmbg.setFrame(- scale, scale, -0.1 * scale, 0.1 * scale) 
                self.bg = self.attachNewNode(cmbg.generate())
 
                self.bg.setColor(0.2, 0.2, 0.2, 1) 
                self.bg.setPos(0,0,5.8)
                
                
                cmfg = CardMaker('fg') 
                cmfg.setFrame(- scale,  scale, -0.1 * scale, 0.1 * scale)
                self.fg = self.bg.attachNewNode(cmfg.generate()) 
               
                self.fg.setColor(r, g, b, 1)             
                self.fg.setPos(0,-0.1,0)
                self.fg.setBillboardPointWorld()
                self.bg.setBillboardPointWorld()
                
                self.fg.clearShader()
                self.bg.clearShader()
       

                self.setValue(0)
示例#59
0
    def __init__(self,
                 tex_classes,
                 stim_params,
                 window_size=512,
                 profile_on=False,
                 fps=30,
                 save_path=None):
        super().__init__()

        self.tex_classes = tex_classes
        self.current_tex_num = 0
        self.stim_params = stim_params
        self.window_size = window_size
        self.stimulus_initialized = False  #to handle case from -1 (uninitalize) to 0 (first stim)
        self.fps = fps
        self.save_path = save_path
        if self.save_path:
            self.filestream = utils.save_initialize(save_path, tex_classes,
                                                    stim_params)
        else:
            self.filestream = None

        #Window properties
        self.windowProps = WindowProperties()
        self.windowProps.setSize(self.window_size, self.window_size)
        self.set_title("Initializing")

        #Create scenegraph
        cm = CardMaker('card')
        cm.setFrameFullscreenQuad()
        self.card = self.aspect2d.attachNewNode(cm.generate())
        self.card.setScale(np.sqrt(8))
        self.texture_stage = TextureStage("texture_stage")

        # Set frame rate
        ShowBaseGlobal.globalClock.setMode(ClockObject.MLimited)
        ShowBaseGlobal.globalClock.setFrameRate(
            self.fps)  #can lock this at whatever

        if profile_on:
            PStatClient.connect()
            ShowBaseGlobal.base.setFrameRateMeter(True)

        #Set initial texture
        self.set_stimulus(str(self.current_tex_num))

        # Set up event handlers and tasks
        self.accept('0', self.set_stimulus, ['0'])  #event handler
        self.accept('1', self.set_stimulus, ['1'])
        self.taskMgr.add(self.move_texture_task, "move_texture")  #task