Example #1
0
 def __init__(self, total_length=1):
     # relative lengths, will be scaled so that the total length is according to
     shaft_length = 0.8
     shaft_width = 0.2
     tip_length = 0.2
     tip_width = 0.5
     depth = 0.1
     self.shaft_length = shaft_length
     self.tip_length = tip_length
     # everything that makes up the arrow will be stored under this dummy root node
     self.root_node_path = render.attachNewNode(PandaNode(''))
     # everything that makes up the shaft will be stored under this node path
     self.shaft_vdata = list()
     self.shaft_node_path = self.root_node_path.attachNewNode(
         PandaNode('arrow_shaft_root'))
     self._create_shaft(shaft_length, shaft_width, depth,
                        self.shaft_node_path)
     # everything that makes up the tip will be stored under this node path
     self.tip_node_path = self.root_node_path.attachNewNode(
         PandaNode('arrow_tip'))
     self._create_tip(tip_length, tip_width, depth, self.tip_node_path)
     self.tip_node_path.setZ(shaft_length)
     # set properties that affect the whole arrow
     self.set_color(0, 1, 0)
     self.set_scale(0.5)
     self.root_node_path.setTwoSided(True)
Example #2
0
 def __init__(self,
              bar_height=1,
              bar_width=0.2,
              thresholds=(0.3, 0.7),
              padding=0.02,
              frame_line_width=2):
     """ Creates a framed bar. The frame borders will have a distance to the actual bar, which is given by
     padding. """
     #from direct.directbase import DirectStart
     self.padding = padding
     # everything that belongs to this ControlSignalBar will be stored under the root node
     self.root_node_path = render.attachNewNode(PandaNode(''))
     # create the geometry node that is the frame
     self.frame_node_path = self.root_node_path.attachNewNode(
         PandaNode('frame_node'))
     self._create_frame(bar_height + 2 * padding, bar_width + 2 * padding,
                        thresholds, self.frame_node_path)
     self.frame_node_path.setY(-0.01)
     self.frame_node_path.setZ(-padding)
     self.set_frame_line_width(frame_line_width)
     # create the geometry node that is the actual bar
     self.bar_node_path = self.root_node_path.attachNewNode(
         PandaNode('bar_node'))
     self._create_bar(bar_height, bar_width, self.bar_node_path)
     self.set_frame_color(0, 0, 1)
     self.set_bar_color(0, 1, 0)
     self.root_node_path.setTwoSided(True)
    def __init__(self,
                 scene=base.render,
                 ambient=0.2,
                 hardness=16,
                 fov=40,
                 near=10,
                 far=100):
        """Create an instance of this class to initiate shadows.
    Also, a shadow casting 'light' is created when this class is called.
    The first parameter is the nodepath in the scene where you
    want to apply your shadows on, by default this is render."""

        # Read and store the function parameters
        self.scene = scene
        self.__ambient = ambient
        self.__hardness = hardness

        # By default, mark every object as textured.
        self.flagTexturedObject(self.scene)

        # Create the buffer plus a texture to store the output in
        buffer = createOffscreenBuffer(-3)
        depthmap = Texture()
        buffer.addRenderTexture(depthmap, GraphicsOutput.RTMBindOrCopy,
                                GraphicsOutput.RTPColor)

        # Set the shadow filter if it is supported
        if (base.win.getGsg().getSupportsShadowFilter()):
            depthmap.setMinfilter(Texture.FTShadow)
            depthmap.setMagfilter(Texture.FTShadow)

        # Make the camera
        self.light = base.makeCamera(buffer)
        self.light.node().setScene(self.scene)
        self.light.node().getLens().setFov(fov)
        self.light.node().getLens().setNearFar(near, far)

        # Put a shader on the Light camera.
        lci = NodePath(PandaNode("lightCameraInitializer"))
        lci.setShader(loader.loadShader("caster.sha"))
        self.light.node().setInitialState(lci.getState())

        # Put a shader on the Main camera.
        mci = NodePath(PandaNode("mainCameraInitializer"))
        mci.setShader(loader.loadShader("softshadow.sha"))
        base.cam.node().setInitialState(mci.getState())

        # Set up the blurring buffers, one that blurs horizontally, the other vertically
        #blurXBuffer = makeFilterBuffer(buffer, "Blur X", -2, loader.loadShader("blurx.sha"))
        #blurYBuffer = makeFilterBuffer(blurXBuffer, "Blur Y", -1, loader.loadShader("blury.sha"))

        # Set the shader inputs
        self.scene.setShaderInput("light", self.light)
        #self.scene.setShaderInput("depthmap", blurYBuffer.getTexture())
        self.scene.setShaderInput("depthmap", buffer.getTexture())
        self.scene.setShaderInput("props", ambient, hardness, 0, 1)
Example #4
0
    def setupGlowFilter(self):
        #create the shader that will determime what parts of the scene will glow
        glowShader=Shader.load(self.pandapath + "/data/glowShader.sha")
        
        # create the glow buffer. This buffer renders like a normal scene,
        # except that only the glowing materials should show up nonblack.
        glowBuffer=base.win.makeTextureBuffer("Glow scene", 512, 512)
        glowBuffer.setSort(-3)
        glowBuffer.setClearColor(Vec4(0,0,0,1))

        # We have to attach a camera to the glow buffer. The glow camera
        # must have the same frustum as the main camera. As long as the aspect
        # ratios match, the rest will take care of itself.
        self.glowCamera=base.makeCamera(glowBuffer, lens=base.cam.node().getLens())

        # Tell the glow camera to use the glow shader
        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(glowShader)
        self.glowCamera.node().setInitialState(tempnode.getState())

        # set up the pipeline: from glow scene to blur x to blur y to main window.
        blurXBuffer=self.makeFilterBuffer(glowBuffer,  "Blur X", -2, self.pandapath+"/data/XBlurShader.sha")
        blurYBuffer=self.makeFilterBuffer(blurXBuffer, "Blur Y", -1, self.pandapath+"/data/YBlurShader.sha")
        self.finalcard = blurYBuffer.getTextureCard()
        self.finalcard.reparentTo(render2d)
        self.finalcard.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))
        
        render.setShaderInput('glow', Vec4(0,0,0,0),0)
        
        render.analyze()
Example #5
0
 def __init__(self,
              text_color=(1, 1, 1),
              max_nr_rows=3,
              nr_char_per_row=20,
              frame_color=(0, 0, 0),
              frame_padding=0.4,
              frame_line_width=2,
              background_color=(1, 1, 0),
              background_padding=0.8):
     #print "TextBoard::init"
     # everything that belongs to this TextBoard will be stored under the root node
     self.root_node_path = render.attachNewNode(PandaNode(''))
     # create the text node that will be the TextBoard
     self.text_node = TextNode('')
     self.text_node_path = self.root_node_path.attachNewNode(self.text_node)
     self.set_max_nr_rows(max_nr_rows)
     r, g, b = text_color
     self.set_text_color(r, g, b)
     self.text_node.setAlign(
         TextNode.ALeft)  # TextNode.ALeft, TextNode.ACenterba
     letter_width, letter_height = self._compute_letter_size()
     self.max_row_length = nr_char_per_row * letter_width
     self.text_node.setWordwrap(self.max_row_length)
     width, height = self._compute_max_text_size()
     self.text_node_path.setPos(0.5 * background_padding, -0.01,
                                -letter_height)
     self.background_node_path = self.root_node_path.attachNewNode(
         PandaNode('background_node'))
     self._create_background(self.background_node_path,
                             width + background_padding,
                             height + background_padding + letter_height)
     self.frame_node_path = self.root_node_path.attachNewNode(
         PandaNode('frame_node'))
     self._create_frame(self.frame_node_path, width + background_padding,
                        height + background_padding + letter_height)
     r, g, b = frame_color
     self.set_frame_color(r, g, b)
     self.set_frame_line_width(frame_line_width)
     r, g, b = background_color
     self.set_background_color(r, g, b)
Example #6
0
 def _create_hexagon(self, root_path, radius, width):
     hex_path = root_path.attachNewNode(PandaNode('hexagon'))
     # create the individual components of the hexagon and put them together
     front_side = create_hexagon(radius)[0]
     node_path = hex_path.attachNewNode(front_side)
     node_path.setY(-width / 2.0)
     node_path.setR(30)
     back_side = create_hexagon(radius)[0]
     node_path = hex_path.attachNewNode(back_side)
     node_path.setH(180)
     node_path.setY(width / 2.0)
     node_path.setR(30)
     side_dist = cos(degrees_to_radians(30)) * radius
     for phi in range(0, 360, 60):
         rot_path = hex_path.attachNewNode(PandaNode(''))
         side = create_side((-radius / 2.0, width / 2.0),
                            (radius / 2.0, -width / 2.0))[0]
         side_path = rot_path.attachNewNode(side)
         side_path.setP(-90)
         side_path.setZ(side_dist)
         rot_path.setR(phi)
     return hex_path
Example #7
0
    def __init__(self):
        self.avatar = None
        self.active = True
        self.objectCode = None

        self.chatButton = NametagGlobals.noButton
        self.chatReversed = False

        self.font = None
        self.chatFont = None

        self.shadow = None

        self.marginManager = None
        self.visible3d = True

        self.chatType = NametagGlobals.CHAT
        self.chatBalloonType = NametagGlobals.CHAT_BALLOON

        self.nametagColor = NametagGlobals.NametagColors[
            NametagGlobals.CCNormal]
        self.chatColor = NametagGlobals.ChatColors[NametagGlobals.CCNormal]
        self.speedChatColor = VBase4(1, 1, 1, 1)

        self.wordWrap = 8
        self.chatWordWrap = 12

        self.text = ''

        self.chatPages = []
        self.chatPageIndex = 0
        self.chatTimeoutTask = None
        self.chatTimeoutTaskName = self.getUniqueName() + '-timeout'

        self.stompChatText = ''
        self.stompTask = None
        self.stompTaskName = self.getUniqueName() + '-stomp'

        self.icon = PandaNode('icon')

        self.nametag2d = Nametag2d()
        self.nametag3d = Nametag3d()

        self.nametags = set()
        self.add(self.nametag2d)
        self.add(self.nametag3d)

        # Add the tick task:
        self.tickTaskName = self.getUniqueName() + '-tick'
        self.tickTask = taskMgr.add(self.tick, self.tickTaskName, sort=45)
Example #8
0
    def __init__(self, actor):
        """Initialise the camera, setting it to follow 'actor'. 
        
        Arguments: 
        actor -- The Actor that the camera will initially follow. 
        
        """

        self.actor = actor
        self.prevtime = 0

        # The camera's controls:
        # "left" = move the camera left, 0 = off, 1 = on
        # "right" = move the camera right, 0 = off, 1 = on
        self.controlMap = {"left": 0, "right": 0}

        taskMgr.add(self.move, "cameraMoveTask")

        # Create a "floater" object. It is used to orient the camera above the
        # target actor's head.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Set up the camera.

        base.disableMouse()
        base.camera.setPos(self.actor.getX(), self.actor.getY() + 2, 2)
        # uncomment for topdown
        #base.camera.setPos(self.actor.getX(),self.actor.getY()+10,2)
        #base.camera.setHpr(180, -50, 0)

        # A CollisionRay beginning above the camera and going down toward the
        # ground is used to detect camera collisions and the height of the
        # camera above the ground. A ray may hit the terrain, or it may hit a
        # rock or a tree.  If it hits the terrain, we detect the camera's
        # height.  If it hits anything else, the camera is in an illegal
        # position.

        self.cTrav = CollisionTraverser()
        self.groundRay = CollisionRay()
        self.groundRay.setOrigin(0, 0, 1000)
        self.groundRay.setDirection(0, 0, -1)
        self.groundCol = CollisionNode('camRay')
        self.groundCol.addSolid(self.groundRay)
        self.groundCol.setFromCollideMask(BitMask32.bit(1))
        self.groundCol.setIntoCollideMask(BitMask32.allOff())
        self.groundColNp = base.camera.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)
Example #9
0
    def do_setup(self, data, type='main'):
        self.type = type
        self.root = base.cam.attachNewNode(PandaNode('menu'))
        self.manager.panda.absolute_mouse()

        #Menu setup
        self.setup_camera()
        self.load_background()
        self.load_sound()
        self.load_buttons()
        self.load_fonts()

        #Load game defaults
        load_game_defaults()

        #Load and show main menu
        self.main_menu = MainMenu(state=self, type=self.type)
        self.main_menu.do_paint()
        self.main_menu.do_connect()
Example #10
0
 def __init__(self, radius=1, width=0.4, color=(1, 1, 0), hex_index=0):
     """ Creates a hexagon, centered around the origin with radius being the distance to the vertices. """
     #print "Hexagon::init"
     self._create_index_and_pos_lists(hex_index)
     self.front_side_symbols = []
     # everything that belongs to this hexagon will be stored under the root node
     self.root_node_path = render.attachNewNode(PandaNode(''))
     # create the geometry node which is the hexagon surface
     self.hex_node_path = self._create_hexagon(self.root_node_path, radius,
                                               width)
     r, g, b = color
     self.set_color(r, g, b)
     # create the text fields
     self.back_side_text = None
     self.front_side_text = list()
     self._create_text_fields(radius, width)
     # clear all text fields
     for text_path in self.front_side_text:
         text_path.node().setText('')
     self.back_side_text.node().setText('')
Example #11
0
    def make_glow(self, data_dir='./src/core/sha'):
        """
        TODO: data_dir = current module directory?
        """

        glow_shader = Shader.load(data_dir + "/glow_shader.sha")

        # create the glow buffer. This buffer renders like a normal
        # scene, except that only the glowing materials should show up
        # nonblack.
        glow_buffer = base.win.makeTextureBuffer("glow_scene", 512, 512)
        glow_buffer.setSort(-3)
        glow_buffer.setClearColor(Vec4(0, 0, 0, 1))

        # We have to attach a camera to the glow buffer. The glow
        # camera must have the same frustum as the main camera. As
        # long as the aspect ratios match, the rest will take care of
        # itself.
        glow_camera = base.makeCamera(glow_buffer,
                                      lens=base.cam.node().getLens())

        # Tell the glow camera to use the glow shader
        temp_node = NodePath(PandaNode("temp_node"))
        temp_node.setShader(glow_shader)
        glow_camera.node().setInitialState(temp_node.getState())

        # set up the pipeline: from glow scene to blur x to blur y to
        # main window.
        blur_xbuffer = make_filter_buffer(glow_buffer, "blur_x", -2,
                                          data_dir + "/x_blur_shader.sha")
        blur_ybuffer = make_filter_buffer(blur_xbuffer, "blur_y", -1,
                                          data_dir + "/y_blur_shader.sha")

        final_card = blur_ybuffer.getTextureCard()
        final_card.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))

        self.glow_camera = glow_camera
        self.glow_buffer = glow_buffer
        self.blur_xbuffer = blur_xbuffer
        self.blur_ybuffer = blur_ybuffer
        self.final_card = final_card
Example #12
0
def getBackgroundSet(menuItem, frame, arrowhead):
    item = menuItem.item
    kind = item['kind']
    txt = item['txt']
    grphcs = []
    slctrs = ['menu ' + kind]
    if 'class' in item:  # class after kind: class has higher priority
        slctrs.append('.' + item['class'])
    if 'id' in item:  # id after class: id has higher priority
        slctrs.append('#' + item['id'])
    style = getStyle(slctrs, menuItem.cssFName)
    if 'enter-sound' in style:
        loadSound(menuItem, menuItem.getEnterEvent(), style, 'enter-sound')
    if 'exit-sound' in style:
        loadSound(menuItem, menuItem.getExitEvent(), style, 'exit-sound')
    if 'press-sound' in style:
        loadSound(menuItem, menuItem.getPressEvent(MouseButton.one()), style,
                  'press-sound')
    if 'release-sound' in style:
        loadSound(menuItem, menuItem.getReleaseEvent(MouseButton.one()), style,
                  'release-sound')
    if 'drag-sound' in style: loadSound(menuItem, None, style, 'drag-sound')
    for state in STATES:
        slctrs = ['menu ' + kind + ' :' + stateName[state].lower()]
        if 'class' in item:  # class after kind: class has higher priority
            slctrs.append('.' + item['class'] + ' :' +
                          stateName[state].lower())
        if 'id' in item:  # id after class: id has higher priority
            slctrs.append('#' + item['id'] + ' :' + stateName[state].lower())
        style = getStyle(slctrs, menuItem.cssFName)
        # Want to add more style properties?
        # Do it here:
        # Match style keys here to property names in .ccss
        fontSize = style['font-size']
        bevel = style['bevel'] * fontSize
        font = style['font']
        color = style['color']
        tn = TextNode(txt)
        tn.setText(txt)
        tn.setFont(loader.loadFont(font))
        tn.setSlant(style['slant'])
        tn.setTextColor(color)
        tn.setShadow(*style['shadow-offset'])
        tn.setShadowColor(*style['shadow-color'])
        NodePath(tn).setScale(fontSize)
        sHolder = NodePath(PandaNode('sHolder'))
        sHolder.attachNewNode(tn)
        grphcs.append(sHolder)
        sHolder.attachNewNode(tn)
        borderColor = style['border-Color']
        thk = style['border-thickness']
        if 'background-Color' in style and\
         style['background-Color'] != 'transparent':
            bgColor = style['background-Color']
        else:
            bgColor = None
        if kind == 'parent':
            if state == HOVER: ar = arrowhead * 2
            else: ar = arrowhead
            grphcs[state].attachNewNode(
                bevelArrow(frame, bevel, ar, thk, color, borderColor, bgColor))
        elif kind in ('horizontal', 'titleBar', 'close'):
            grphcs[state].attachNewNode(
                rectangle(frame, thk, color, borderColor, bgColor))
        elif kind == 'checkBox':
            grphcs[state].attachNewNode(
                checkBox(frame, bevel, thk, color, borderColor, bgColor))
            cb = grphcs[state].attachNewNode(
                checkedBox(frame, bevel, thk, color, borderColor, bgColor))
            cb.hide()
        elif kind == 'radioBTN':
            grphcs[state].attachNewNode(
                radioBTN(frame, bevel, thk, color, borderColor, bgColor))
            cb = grphcs[state].attachNewNode(
                checkedRadioBTN(frame, bevel, thk, color, borderColor,
                                bgColor))
            cb.hide()
        else:
            grphcs[state].attachNewNode(
                bevelBG(frame, bevel, thk, borderColor, bgColor))
    return grphcs
Example #13
0
    def __init__(self, parserClass, mainClass, mapLoaderClass,
                 modelLoaderClass):
        self.switchState = False

        #self.t = Timer()

        self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0}
        self.ralph = Actor(
            "data/models/units/ralph/ralph", {
                "run": "data/models/units/ralph/ralph-run",
                "walk": "data/models/units/ralph/ralph-walk"
            })
        self.ralph.reparentTo(render)
        #		self.ralph.setPos(42, 30, 0)
        self.ralph.setPos(6, 10, 0)
        self.ralph.setScale(0.1)

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("arrow_down", self.setKey, ["backward", 1])
        self.accept("arrow_down-up", self.setKey, ["backward", 0])

        self.isMoving = False

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 1000)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)
        #self.ralphGroundCol.show()

        base.cam.reparentTo(self.ralph)
        base.cam.setPos(0, 9, 7)
        self.floater2 = NodePath(PandaNode("floater2"))
        self.floater2.reparentTo(self.ralph)
        self.floater2.setZ(self.floater2.getZ() + 6)
        base.cam.lookAt(self.floater2)

        # Uncomment this line to see the collision rays
        #		self.ralphGroundColNp.show()
        #		self.camGroundColNp.show()

        #Uncomment this line to show a visual representation of the
        #collisions occuring
        #		self.cTrav.showCollisions(render)

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        taskMgr.add(self.move,
                    "movingTask",
                    extraArgs=[
                        mainClass, parserClass, mapLoaderClass,
                        modelLoaderClass
                    ])
Example #14
0
    def __init__(self):
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        # enable physics (and particle) engine

        self.throwMode = False
        self.freelook = False

        self.score = OnscreenText('0',
                                  pos=(-1.32, 0.9),
                                  fg=(1, 1, 1, 1),
                                  bg=(0, 0, 0, 0.5),
                                  scale=0.1,
                                  align=TextNode.ALeft)

        # Load the environment in which Eve will walk. Set its parent
        # to the render variable so that it is a top-lplayerl node.
        self.env = loader.loadModel('models/world/world.egg.pz')
        self.env.reparentTo(render)
        self.env.setPos(0, 0, 0)

        self.createCollisionHandlers()

        # Create an Actor instance for Eve. We also specify the animation
        # models that we want to use as a dictionary, where we can use to
        # keys to refer to the animations later on. The start point of Eve
        # is hardcoded in the world model somewhere, so we look that up.
        self.player = Eve('Eve', self,
                          self.env.find('**/start_point').getPos())
        #self.player.nodePath.setZ(self.player.nodePath.getZ() + 10)
        self.player.nodePath.reparentTo(render)

        # Create a floater object that always floats 2 units above Eve.
        # We make sure that it is attached to Eve by reparenting it to
        # Eve's object instance.
        self.floater = NodePath(PandaNode('floater'))
        self.floater.reparentTo(self.player.nodePath)
        self.floater.setZ(self.floater.getZ() + 2)

        # load baseball
        self.baseball = Baseball('baseball', self,
                                 self.player.nodePath.getPos())
        self.baseball.nodePath.reparentTo(render)
        self.player.pickUpItem(self.baseball)

        # Load the panda bear
        self.panda = Panda('panda', self, self.player.nodePath.getPos())
        self.panda.nodePath.reparentTo(render)

        # Disable controlling the camera using the mouse. Note that this does
        # not disable the mouse completely, it merely disables the camera
        # movement by mouse.
        base.disableMouse()

        self.hideMouseCursor()

        # Set the initial position for the camera as X, Y and Z values.
        base.camera.setPos(self.player.nodePath.getX(),
                           self.player.nodePath.getY() + 10, 2)

        # Disable modifier button compound events.
        base.mouseWatcherNode.setModifierButtons(ModifierButtons())
        base.buttonThrowers[0].node().setModifierButtons(ModifierButtons())

        # Register any control callbacks.
        self.accept('escape', sys.exit)
        self.accept('d', self.dropItem)
        self.accept('f', self.toggleFullscreen)

        self.accept('space', self.enterThrowMode)
        self.accept('space-up', self.leaveThrowMode)

        # Also make sure that we can, at any time, request the state (pressed
        # or not) for these keys.
        self.keys = keys.KeyStateManager()
        self.keys.registerKeys({
            'arrow_left': 'left',
            'arrow_right': 'right',
            'arrow_up': 'forward',
            'arrow_down': 'backward',
            'shift': 'shift',
            'r': 'reset'
        })

        self.mouse = mouse.MousePointerManager(0)

        # Schedule the move method to be executed in the game's main loop.
        taskMgr.add(self.update, 'update')