Example #1
0
    def __init__(self):
        ShowBase.__init__(self)
        self.InitRenderPipeline()

        self.recenterMouse()

        self.taskMgr.add(self.updateCamera, "Update Camera")
 def __init__(self):
     # The basics
     ShowBase.__init__(self)
     base.disableMouse()
     # Camera / Audio listener node
     self.cam_node = self.render.attachNewNode("Camera node")
     self.camera.reparentTo(self.cam_node)
     self.audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], self.camera)
     self.cam_node.set_pos(0, -10, 0)
     # Add the model
     self.m = self.loader.loadModel("models/smiley")
     self.m.reparentTo(self.render)
     self.m.setPos(0, 0, 0)
     s = self.audio3d.loadSfx('knocking.ogg')
     s.setLoop(True)
     s.play()
     self.audio3d.attachSoundToObject(s, self.m)
     # Bookkeeping for the rotation around the model
     self.angle = 0.0
     self.adjust_angle = 0
     # Initial camera setup
     self.camera.look_at(self.m)
     # Key events and camera movement task
     self.accept("arrow_left", self.adjust_turning, [-1.0])
     self.accept("arrow_left-up", self.adjust_turning, [1.0])
     self.accept("arrow_right", self.adjust_turning, [1.0])
     self.accept("arrow_right-up", self.adjust_turning, [-1.0])
     self.accept("escape", sys.exit)
     self.taskMgr.add(self.update_camera, 'adjust camera', sort = 10)
Example #3
0
 def __init__(self):
     ## Init panda
     ShowBase.__init__(self)
     ## Init client sql connection
     self.clientConn = clientConnection.clientConnection()
     ## Init world
     self.world = world.world()
    def create(self):
        """ This creates the pipeline, and setups all buffers. It also
        constructs the showbase. The settings should have been loaded before
        calling this, and also the base and write path should have been
        initialized properly (see MountManager). """

        start_time = time.time()

        if not self._mount_mgr.is_mounted:
            self.debug("Mount manager was not mounted, mounting now ...")
            self._mount_mgr.mount()

        if not self._settings.is_file_loaded():
            self.debug("No settings loaded, loading from default location")
            self._settings.load_from_file("$$Config/pipeline.yaml")

        # Check if the pipeline was properly installed, before including anything else
        if not isfile("Data/install.flag"):
            DebugObject.global_error("CORE", "You didn't setup the pipeline yet! Please run setup.py.")
            sys.exit(1)

        # Load the default prc config
        load_prc_file("$$Config/configuration.prc")

        # Construct the showbase and init global variables
        ShowBase.__init__(self._showbase)
        self._init_globals()

        # Create the loading screen
        self._loading_screen.create()
        self._adjust_camera_settings()
        self._create_managers()

        # Init the onscreen debugger
        self._init_debugger()

        # Load plugins and daytime settings
        self._plugin_mgr.load_plugins()
        self._daytime_mgr.load_settings()
        self._com_resources.write_config()

        # Setup common defines
        self._create_common_defines()

        # Let the plugins setup their stages
        self._plugin_mgr.trigger_hook("on_stage_setup")
        self._setup_managers()
        self._plugin_mgr.trigger_hook("on_pipeline_created")

        # Set the default effect on render
        self.set_effect(Globals.render, "Effects/Default.yaml", {}, -10)

        # Hide the loading screen
        self._loading_screen.remove()

        self._start_listener()

        # Measure how long it took to initialize everything
        init_duration = int((time.time() - start_time) * 1000.0)
        self.debug("Finished initialization in {} ms".format(init_duration))
 def __init__(self, windowType = None):
     self.wantEnviroDR = False
     ShowBase.__init__(self, windowType = windowType)
     if config.GetBool('want-phase-checker', 0):
         Loader = Loader
         import direct.showbase
         Loader.phaseChecker = self.loaderPhaseChecker
         self.errorAccumulatorBuffer = ''
         taskMgr.add(self.delayedErrorCheck, 'delayedErrorCheck', priority = 10000)
     
     self.idTags = config.GetBool('want-id-tags', 0)
     if not self.idTags:
         del self.idTags
     
     self.wantNametags = self.config.GetBool('want-nametags', 1)
     self.slowCloseShard = self.config.GetBool('slow-close-shard', 0)
     self.slowCloseShardDelay = self.config.GetFloat('slow-close-shard-delay', 10.0)
     self.fillShardsToIdealPop = self.config.GetBool('fill-shards-to-ideal-pop', 1)
     self.logPrivateInfo = self.config.GetBool('log-private-info', __dev__)
     self.wantDynamicShadows = 1
     self.stereoEnabled = False
     self.enviroDR = None
     self.enviroCam = None
     self.pixelZoomSetup = False
     self.gameOptionsCode = ''
     self.locationCode = ''
     self.locationCodeChanged = time.time()
     if base.cam:
         if self.wantEnviroDR:
             base.cam.node().setCameraMask(OTPRender.MainCameraBitmask)
         else:
             base.cam.node().setCameraMask(OTPRender.MainCameraBitmask | OTPRender.EnviroCameraBitmask)
     
     taskMgr.setupTaskChain('net')
    def __init__(self, width, height, model_path, animation_path):
        ShowBase.__init__(self)

        globalClock.setMode(ClockObject.MNonRealTime)
        globalClock.setDt(0.02)  # 20ms per frame

        self.cam.setPos(0, -200, 100)
        self.cam.lookAt(0, 0, 100)
        self.cam.node().setLens(self.createLens(width / height))

        self.animated_rig = ExposedJointRig(model_path,
                                            {'animation': animation_path})
        self.animated_rig.reparentTo(self.render)
        self.animated_rig.createLines(VBase4(0.5, 0.75, 1.0, 1.0))

        self.control_rig = ControlJointRig(model_path)
        self.control_rig.reparentTo(self.render)
        self.control_rig.createLines(VBase4(1.0, 0.75, 0.5, 1.0))

        self.fbx_manager = FBXManager()
        self.fbx_manager.setupJoints(self.control_rig.control_joints)

        self.num_frames = self.animated_rig.getNumFrames('animation')
        self.setAnimationFrame(0)

        self.accept('escape', sys.exit)
        self.taskMgr.add(self.update, 'update')
Example #7
0
	def __init__(self):
		ShowBase.__init__(self)

		#Load the enviroment model
		self.environ = self.loader.loadModel("models/environment")
		#Reparent the model to render
		self.environ.reparentTo(self.render)
		#Apply scale and position transforms on the model
		self.environ.setScale(0.25, 0.25, 0.25)
		self.environ.setPos(-8, 42, 0)

		#Add the spinCameraTask procedure to the task manager.

		self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")

		#Load and transform panda actor
		self.pandaActor = Actor("models/panda-model", {"walk": "models/panda-walk4"})

		self.pandaActor.setScale(0.005, 0.005, 0.005)
		self.pandaActor.reparentTo(self.render)
		#Loop its animation
		self.pandaActor.loop("walk")

		# Create the four lerp intervals needed for the panda to
		# walk back and forth

		pandaPosInterval1 = self.pandaActor.posInterval(13, Point3(0,-10,0), startPos=Point3(0,10,0))
		pandaPosInterval2 = self.pandaActor.posInterval(13, Point3(0,10,0), startPos=Point3(0,-10,0))
		pandaHprInterval1 = self.pandaActor.hprInterval(3, Point3(180, 0, 0), startHpr = Point3(0,0,0))
		pandaHprInterval2 = self.pandaActor.hprInterval(3, Point3(0,0,0), startHpr=Point3(180,0,0))

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

		self.pandaPace.loop()
    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")
Example #9
0
def main():
    # Handles CLI arguments
    p = OptionParser()
    p.add_option('-m', '--nomusic', action="store_false", dest="music", default = True, help = u"Disable music")
    p.add_option('-e', '--editor-mode', action="store_true", dest="editor", default = False, help = u"Editor mode")
    options, args = p.parse_args()
    levelname = 'level1'
    if args:
        levelname = args[0]

    # Instantiate the ShowBase
    base = ShowBase()

    # Toggle events verbosity :
    #base.messenger.toggleVerbose()

    # Set window properties:
    # - Hide mouse cursor
    # - move the window (because of the pekwm bug)
    curProps = base.win.getProperties()
    props = WindowProperties()
    props.setOrigin(curProps.getXOrigin() + 1, curProps.getYOrigin() + 1)
    props.setCursorHidden(True)
    base.win.requestProperties(props)

    # Now instantiate Gate's own stuff
    fps = FPS(base, levelname, options)
    osd = OSD(base, fps)
    mplayer = MusicPlayer(base, osd)
    if options.music:
        mplayer.play_random_track()
    player = Player(base, fps, osd)

    # And run the ShowBase
    base.run()
Example #10
0
    def __init__(self):

        ShowBase.__init__(self)

        ########## Window configuration #########

        wp = WindowProperties()
        wp.setSize(1024, 860)

        self.win.requestProperties(wp)

        ########## Gameplay settings #########

        self.GAME_MODE = PLAY
        self.play_mode = SPACE

        self.level = 1.5

        self.mode_initialized = False

        ######### Camera #########

        self.disableMouse()

        self.mainCamera = Camera(self.camera)

        self.mainCamera.camObject.setHpr(0, 0, 0)

        #Trigger game chain

        self.loadLevel(LEVEL)

        ######### Events #########

        self.taskMgr.add(self.gameLoop, "gameLoop", priority = 35)

        self.keys = {"w" : 0, "s" : 0, "a" : 0, "d" : 0, "space" : 0}

        self.accept("w", self.setKey, ["w", 1])
        self.accept("w-up", self.setKey, ["w", 0])
        self.accept("s", self.setKey, ["s", 1])
        self.accept("s-up", self.setKey, ["s", 0])
        self.accept("a", self.setKey, ["a", 1])
        self.accept("a-up", self.setKey, ["a", 0])
        self.accept("d", self.setKey, ["d", 1])
        self.accept("d-up", self.setKey, ["d", 0])
        self.accept("space", self.setKey, ["space", 1])
        self.accept("space-up", self.setKey, ["space", 0])
        self.accept("wheel_up", self.zoomCamera, [-1])
        self.accept("wheel_down", self.zoomCamera, [1])
        self.accept("escape", self.switchGameMode, [IN_GAME_MENU])

        self.accept("window-event", self.handleWindowEvent)

        self.accept("playerGroundRayJumping-in", self.avatar.handleCollisionEvent, ["in"])
        self.accept("playerGroundRayJumping-out", self.avatar.handleCollisionEvent, ["out"])

        ######### GUI #########

        self.gui_elements = []
 def __init__(self):
     # The basics
     ShowBase.__init__(self)
     base.disableMouse()
     base.setBackgroundColor(0.1, 0.1, 0.1)
     base.setFrameRateMeter(True)
     self.accept("escape", sys.exit)
     # Camera
     self.camera_orbit = base.render.attach_new_node("Camera orbit")
     self.camera_pitch = self.camera_orbit.attach_new_node("Camera pitch")
     base.camera.reparent_to(self.camera_pitch)
     base.camera.set_pos(0, -5, 0)
     # Camera control
     self.camera_movement = (0, 0)
     self.accept("arrow_up",       self.change_camera_movement, [ 0, -1])
     self.accept("arrow_up-up",    self.change_camera_movement, [ 0,  1])
     self.accept("arrow_down",     self.change_camera_movement, [ 0,  1])
     self.accept("arrow_down-up",  self.change_camera_movement, [ 0, -1])
     self.accept("arrow_left",     self.change_camera_movement, [-1,  0])
     self.accept("arrow_left-up",  self.change_camera_movement, [ 1,  0])
     self.accept("arrow_right",    self.change_camera_movement, [ 1,  0])
     self.accept("arrow_right-up", self.change_camera_movement, [-1,  0])
     base.taskMgr.add(self.move_camera, "Move camera")
     # Object
     self.model = loader.loadModel("models/smiley")
     self.model.reparent_to(base.render)
     shader = Shader.make(
         Shader.SL_GLSL,
         vertex = vertex_shader,
         fragment = fragment_shader,
     )
     self.model.set_shader(shader)
Example #12
0
    def __init__(self):
        ShowBase.__init__(self)
        base.disableMouse()

        with open("models.txt") as f:
            self.model_names = f.readlines()

        print("Loading models...")
        self.loadModels("/misc/lmbraid17/tatarchm/datasets/ShapeNet/3d_models/egg_cars")
        print("Done.")

        self.scene = NodePath("Scene")
        self.scene.reparentTo(self.render)

        self.scene.setScale(1, 1, 1)
        self.scene.setTwoSided(True)
        self.scene.setPos(0, 0, 0)
        self.scene.setHpr(0, 0, 0)
        self.setUpLight()

        #create depth texture
        base.depth_tex = Texture()
        self.depth_tex.setFormat(Texture.FDepthComponent)
        self.depth_buffer=base.win.makeTextureBuffer('depthmap', 128, 128, self.depth_tex, to_ram=True)
        self.depth_cam = self.makeCamera(self.depth_buffer)
        self.depth_cam.reparentTo(base.render)

        self.generateData()
 def __init__(self):
     ShowBase.__init__(self)
     base.disableMouse()#mouse disabled
     #rocky terrain load
     self.environ=loader.loadModel("models/environment")
     self.environ.reparentTo(render)
     self.environ.setScale(0.15,0.15,0.15)
     self.environ.setPos(0,-10,0)
     #loading the sky background
     self.sky=loader.loadModel("models/farmsky")
     self.sky.reparentTo(render)
     self.sky.setScale(0.3,0.3,0.3)
     self.sky.setPos(0,350,0)
     #baby dinosaur model
     self.babyd = Actor("babyd", {"sit": "babydani"})
     self.babyd.reparentTo(render)
     self.babyd.setPos(Vec3(25,-150, 3))
     self.babyd.loop("sit")
     #big dinosaur model
     self.bigd = Actor("bigd", {"roar": "bigdani"})
     self.bigd.reparentTo(render)
     self.bigd.setPos(Vec3(30, -110, 0))
     self.bigd.loop("roar")
     #trex model
     self.trex = Actor("trex", {"run": "trex-eat"})
     self.trex.reparentTo(render)
     self.trex.loop("run")
     self.trex.setHpr(270,0,0)
     self.cam.setPos(-20, -200, 22)
      #trex animation
     trexPosInterval1 = self.trex.posInterval(3,
                                                     Point3(-60,-120, 0),
                                                     startPos = Point3( -10,-120, 0))
     trexPosInterval2 = self.trex.posInterval(3,
                                                     Point3(-60,0, 0),
                                                     startPos = Point3( -60,-120, 0))
     trexPosInterval3 = self.trex.posInterval(3,
                                                     Point3(-10,0, 0),
                                                     startPos = Point3( -60,0, 0))
     trexPosInterval4 = self.trex.posInterval(3,
                                                     Point3(-10,-120, 0),
                                                     startPos = Point3( -10,0, 0))
     trexHprInterval1 = self.trex.hprInterval(0.5,
                                                     Point3(180, 0, 0),
                                                     startHpr = Point3(270, 0, 0))
     trexHprInterval2 = self.trex.hprInterval(0.5,
                                                     Point3(90, 0, 0),
                                                     startHpr = Point3(180, 0, 0))
     trexHprInterval3 = self.trex.hprInterval(0.5,
                                                     Point3(0, 0, 0),
                                                     startHpr = Point3(90, 0, 0))
     trexHprInterval4 = self.trex.hprInterval(0.5,
                                                     Point3(-90, 0, 0),
                                                     startHpr = Point3(0, 0, 0))
     
     # Create and play the sequence that coordinates the intervals.
     self.pandaPace = Sequence(trexPosInterval1, trexHprInterval1,
                               trexPosInterval2, trexHprInterval2,trexPosInterval3,trexHprInterval3,trexPosInterval4,trexHprInterval4,
                               name="pandaPace")
     self.pandaPace.loop()
    def __init__(self, width, height, model_path, animation_path):
        ShowBase.__init__(self)

        globalClock.setMode(ClockObject.MNonRealTime)
        globalClock.setDt(0.02) # 20ms per frame

        self.cam.setPos(0, -300, 100)
        self.cam.lookAt(0, 0, 100)
        self.cam.node().setLens(self.createLens(width / height))

        if animation_path:
            self.animation = ExposedJointRig(model_path, { 'animation': animation_path })
            self.animation.play('animation')
        else:
            self.animation = ExposedJointRig(model_path, {})
        self.animation.createLines(VBase4(1.0, 0.75, 0.5, 1.0))
        self.animation.reparentTo(self.render)

        self.canonical = ExposedJointRig(model_path, { 'animation': 'models/walking-animation.egg' })
        self.canonical.play('animation')
        self.canonical.reparentTo(self.render)
        self.canonical.createLines(VBase4(0.5, 0.75, 1.0, 1.0))

        self.num_frames = self.canonical.getNumFrames('animation')
        self.setAnimationFrame(0)

        self.accept('escape', sys.exit)
        self.taskMgr.add(self.update, 'update')
 def __init__(self):
     
     ShowBase.__init__(self)
     self.setupInput()
     self.setupStates()
     
     taskMgr.add(self.update,"update")
Example #16
0
    def __init__(self):
        ShowBase.__init__(self)

        ambLight = AmbientLight("ambient")
        ambLight.setColor(Vec4(0.1,0.11,0.12,1.0))
        ambNode = render.attachNewNode(ambLight)
        render.setLight(ambNode)

        dirLight = DirectionalLight("directional")
        dirLight.setColor(Vec4(0.7,0.7,0.68,1.0))
        dirNode = render.attachNewNode(dirLight)
        dirNode.setHpr(60,-40,90)
        render.setLight(dirNode)

        sptLight = Spotlight("spot")
        sptLens = PerspectiveLens()
        sptLight.setLens(sptLens)
        sptLight.setColor(Vec4(0.6,0.6,0.6,1.0))
        sptLight.setShadowCaster(True)
        sptNode = render.attachNewNode(sptLight)
        sptNode.setPos(0,0,20)
        sptNode.lookAt(0,0,0)
        render.setLight(sptNode)

        render.setShaderAuto()

        base.camLens.setFov(70)
        base.camLens.setNear(0.1)
        base.camLens.setFar(50)

        self.cam.setPos(-1,-4,4)
        self.cam.lookAt(0,-1,1)
Example #17
0
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)

        base.disableMouse()  # Allow manual positioning of the camera
        camera.setPos(0, -10, 1)  # Set the cameras' position 
        camera.setHpr(0, 0, 0)                         # and orientation

        self.keyMap = {
            "left": 0, "right": 0, "up": 0, "down": 0}

        taskMgr.add(self.startCarousel, "moveTask")

        imageObject = OnscreenImage(image = 'env_sky.jpg', pos = (-10,0,-10))
        imageObject.setImage('env_sky.jpg')
        imageObject.setTransparency(TransparencyAttrib.MAlpha)

        self.loadModels()  # Load and position our models
        self.setupLights()  # Add some basic lighting

        
        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", True])
        self.accept("arrow_right", self.setKey, ["right", True])
        self.accept("arrow_up", self.setKey, ["up", True])
        self.accept("arrow_down", self.setKey, ["down", True])
        self.accept("arrow_left-up", self.setKey, ["left", False])
        self.accept("arrow_right-up", self.setKey, ["right", False])
        self.accept("arrow_up-up", self.setKey, ["up", False])
        self.accept("arrow_down-up", self.setKey, ["down", False])
Example #18
0
    def __init__(self):
        ShowBase.__init__(self)
        
       
        # Load the environment model.
        self.environ = self.loader.loadModel("models/environment")
        self.environ.reparentTo(self.render)
        self.environ.setScale(0.25, 0.25, 0.25)
        self.environ.setPos(-8, 42, 0)

        # Disable default mouse/camera task
        self.disableMouse()
        self.accept("w", self.startMoveForward)
        self.accept("w-up", self.stopMoveForward)
        self.accept("a", self.startMoveLeft)
        self.accept("a-up", self.stopMoveLeft)
        self.accept("d", self.startMoveRight)
        self.accept("d-up", self.stopMoveRight)
        self.accept("s", self.startMoveBack)
        self.accept("s-up", self.stopMoveBack)
        
        self.accept("escape", sys.exit)
        self.taskMgr.add(self.playerControlTask, "playerControlTask")

        # self.User is a dummy node to attach camera to
        self.Player = render.attachNewNode('Player')
        self.camera.reparentTo(self.Player)
        
        #default movement setting
        self.movingForward = False
        self.movingLeft = False
        self.movingRight = False
        self.movingBack = False
Example #19
0
    def __init__(self):
        ShowBase.__init__(self)
        self.Clock = ClockObject.getGlobalClock()
        self._alive = True
        self._connected = False
        self._display_region = self.cam.getNode(0).getDisplayRegion(0)
    
        # Main menu and environment.
        self.LOBBY = Lobby(self)  # <-
        self.ENV = Environment(self)  # <-
        self.PRE_VIEW = Pre_View(self)  # <-
        self.DISPLAY = self.LOBBY
        self.SYS = None
        self.SIM = Simulator(_sim.MAX_LOCAL_BODIES)
        self.servers = []
        self.sys_recipes = self.__refresh_Sys_Recipes()
        
        # Player and main objects.
        ## self.PLAYER = Player()  # <-
        self.UEH = Default_UEH()  # <-
        
        self.setBackgroundColor(0,0,0)
        self.disableMouse()
        
        # Network.
        '''self.host = socket.gethostbyname(socket.gethostname())
        self.tcp_addr = (self.host, CLIENT_TCP_PORT)
        self.udp_addr = (self.host, CLIENT_UDP_PORT)
        ## self.tcp_req_addr = (self.host, CLIENT_REQUEST_PORT)
        self.proxy_tcp_addr = None   ## self.client_proxy_tcp_addr'''

        # Main loop.
        taskMgr.add(self._main_loop_, "main_loop", appendTask=True, sort=0)  # <-
        taskMgr.doMethodLater(1/_net.BROADCAST_HZ, self._state_, "state_loop")
Example #20
0
    def __init__(self):
        load_prc_file_data("", """
            textures-power-2 none
            window-type offscreen
            win-size 100 100
            gl-coordinate-system default
            notify-level-display error
            print-pipe-types #f
        """)

        ShowBase.__init__(self)

        dest_tex = Texture()
        dest_tex.setup_2d_texture(2048, 2048, Texture.T_unsigned_byte, Texture.F_rgba8)
        cshader = Shader.load_compute(Shader.SL_GLSL, "grain.compute.glsl")
        node = NodePath("")
        node.set_shader(cshader)
        node.set_shader_input("DestTex", dest_tex)
        attr = node.get_attrib(ShaderAttrib)
        self.graphicsEngine.dispatch_compute(
            (2048 // 16, 2048 // 16, 1), attr, self.win.get_gsg())

        base.graphicsEngine.extract_texture_data(dest_tex, base.win.get_gsg())

        # Convert to single channel
        img = PNMImage(2048, 2048, 1, 255)
        dest_tex.store(img)
        img.set_num_channels(1)

        tex = Texture()
        tex.load(img)
        tex.write("grain.txo.pz")
 def __init__(self):
     # Basics
     ShowBase.__init__(self)
     base.disableMouse()
     base.setFrameRateMeter(True)
     self.accept("escape", sys.exit)
     self.camera.set_pos(-10, -10, 10)
     self.camera.look_at(0, 0, 0)
     # A light
     plight = PointLight('plight')
     plight.setColor(VBase4(0.5, 0.5, 0.5, 1))
     plnp = render.attachNewNode(plight)
     plnp.setPos(10, 10, 10)
     render.setLight(plnp)
     # Create the geometry
     self.sidelength = 30
     self.map_a = self.create_map(self.sidelength)
     self.map_b = self.map_a
     geom = self.create_geom(self.sidelength)
     np = NodePath(geom)
     np.reparent_to(self.render)
     # Start the task to interpolate the geometry each frame
     self.last_time = 0.0
     self.need_to_swap_maps = True
     self.taskMgr.add(self.swap_maps, 'swap_geometry', sort = 5)
     self.taskMgr.add(self.interpolate_maps, 'interpolate_geometry', sort = 10)
    def __init__(self):
        ShowBase.__init__(self)

        self.camera_control()



        self.REGION_MAP = "maps/italy_provs.png"
        self.TEXTURE_MAP = "maps/italy_terrain2.png"
        self.WORLD_MAP = "maps/italy_map.xml"
        self.SCENARIO_MAP = "scenarios/italy_scen.xml"

        self.terrainScale = 1 # Currently Broken

        self.keyboard_setup()

        self.drawTerrain()



        self.xml_load_map(self.WORLD_MAP,"WorldMap")
        self.xml_load_map(self.SCENARIO_MAP,"Scenario")
        self.init_collisions()
        self.pickingEnabledObject = None

        self.taskMgr.add(self.camera_update, "UpdateCameraTask")

        self.generate_models()
        self.txtBox = OnscreenText("<No province>")
        self.setup_collision_calcs()
        taskMgr.add(self.rayUpdate, "updatePicker")
        taskMgr.doMethodLater(0.2,self.task_calendar, "calendar")
        self.init_variables()
        self.interface()
Example #23
0
    def __init__(self):

        ShowBase.__init__(self)

        #load background image
        self.__image = OnscreenImage(image='../../resources/images/main_menu.jpg', pos=(0, 0, 0), scale=1)
        self.__image.setSx(self.getAspectRatio())
        self.__image.setTransparency(TransparencyAttrib.MAlpha)

        #Three main opertaions
        self.__newGameButton = DirectButton(pos=(-0.9, 0, 0.5,), text=("新的游戏"), scale=0.1,
                                            command=self.new_game,frameColor=(0,0,0,0),
                                            image=("../../resources/images/main_menu.jpg","../../resources/images/main_menu.jpg",
                                                   "../../resources/images/main_menu.jpg"))
        self.__selectArchiveButton = DirectButton(pos=(-0.9, 0, 0.3,), text="选择存档", scale=0.1,text_fg=(1,1,1,1),
                                            command=self.select_archives, frameColor=(0, 0, 0, 0),
                                            image=("../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg",
                                                   "../../resources/images/main_menu.jpg"))
        self.__exitGameButton = DirectButton(pos=(-0.9, 0, 0.1,), text="退出游戏", scale=0.1,text_fg=(1,1,1,1),
                                            command=self.exit_game, frameColor=(0, 0, 0, 0),
                                            image=("../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg",
                                                   "../../resources/images/main_menu.jpg"))

        #add task to update background-image scale
        self.taskMgr.add(self.example_task, 'exampleTask')

        self.__rm=ResourcesManager()
Example #24
0
  def __init__(self):
    ShowBase.__init__(self)
    #This code puts the standard title and instruction text on screen
    self.title = OnscreenText(text="Precipice",
                              style=1, fg=(1,1,0,1),
                              pos=(0.8,-0.95), scale = .07)
    #OnscreenText(parent=base.a2dBottomLeft, font=loader.loadFont('cmss12'), text='press\nSPACE\nto cycle', fg=(0,0,0,1),shadow=(1,1,1,1), scale=.045) 
    #NodePath(ost).setPos(card.getBounds().getCenter()-ost.getBounds().getCenter()) 
    
    
    
    dummyParent=NodePath('') 
    textParent=dummyParent.attachNewNode('') 
    textParent.setDepthTest(0) 
    textParent.setDepthWrite(0) 
    textParent.reparentTo(render)
    textParent.posInterval(50,Point3(0,12,0),Point3(0,-1.05,0)).start()
    self.gameTitleText = OnscreenText(text = 'StarCruiser', pos = (-1.3, .75), fg=(1,1,0,1), align = TextNode.ALeft, scale = .15)
    self.gameTitleText.flattenLight()
    self.gameTitleText.setP(-40)
    
    self.leftkeyText =  onScreenTextCreate("[Left Arrow]: Turn Left (CCW)", 1)
    self.rightkeyText = onScreenTextCreate("[Right Arrow]: Turn Right (CW)", 2)
    self.upkeyText =    onScreenTextCreate("[Up Arrow]: Accelerate", 3)
    self.spacekeyText = onScreenTextCreate("[Space Bar]: Fire", 4)

    #self.stars = loadObject("stars", scale = 146, depth = 200,
    #                     transparency = False) #Load the background starfield
    self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
Example #25
0
 def __init__(self):
     ShowBase.__init__(self)
     
     self.camera.setPosHpr(0, -12, 8, 0, -35, 0)
     self.disableMouse()
     self.tableau = [[0 for i in range(3)]for i in range(3)]
     for i in range(9):
         self.environ = self.loader.loadModel("bois")
         self.environ.reparentTo(self.render)
         self.environ.setScale(0.25, 0.25, 0.25) #Echelle
         self.environ.setColor(MARRON)
         self.environ.setPos(position(i))
     self.environ = [None for i in range(9)]
     self.tourBlanc = True
     self.accept('1',self.addCercle0)
     self.accept('2',self.addCercle1)
     self.accept('3',self.addCercle2)
     self.accept('4',self.addCercle3)
     self.accept('5',self.addCercle4)
     self.accept('6',self.addCercle5)
     self.accept('7',self.addCercle6)
     self.accept('8',self.addCercle7)
     self.accept('9',self.addCercle8)
     self.accept('r',self.reset)
     self.accept('t',self.test)
Example #26
0
	def __init__(self):
		ShowBase.__init__(self)
		
		self.decisions = []
		self.isReady = False
		self.red = 0
		self.messageNode = TextNode("Message")
		self.choiceOneNode = TextNode("ChoiceOne")
		self.choiceTwoNode = TextNode("ChoiceTwo")
		self.instructionsNode = TextNode("Instructions")
		
		self.messageNode.setText('"Antigone, stop screaming!"')
		self.choiceOneNode.setText("[stop]")
		self.choiceTwoNode.setText("[scream louder]")
		self.instructionsNode.setText("Use the arrow keys to make a choice.")
		
		base.setBackgroundColor(self.red, 0, 0)
		base.disableMouse()
		props = WindowProperties()
		props.setTitle("Antigo Me")
		base.win.requestProperties(props)
		
		self.textDisplay()
		self.showText()
		
		self.isReady = True
		
		self.accept("arrow_left", self.decision, [0])
		self.accept("arrow_right", self.decision, [1])
Example #27
0
    def __init__(self):
        ShowBase.__init__(self)

        self.seeNode = self.render.attachNewNode("see")

        self.cam.reparentTo(self.seeNode)
        self.cam.setPos(0, 0, 5)

        self.fpscamera = fpscontroller.FpsController(self, self.seeNode)
        self.fpscamera.setFlyMode(True)

        self.prevPos = self.fpscamera.getPos()
        self.prevInto = None
        self.info = self.genLabelText("Position: <unknown>", 4)

        self.makeInstructions()
        self.initCollisions()

        self.leftColor = LVecBase4i(224, 224, 64, 255)
        self.rightColor = LVecBase4i(64, 224, 224, 255)

        self.isDrawing = False
        self.toggleDrawing()

        self.accept("escape", sys.exit)  # Escape quits
        self.accept("enter", self.toggleDrawing)
Example #28
0
    def __init__(self):
        FixedTimeStepManager.__init__(self)
        ShowBase.__init__(self)

        self.register_signals()

        # Todo: Copy Panda data
        WorldInfo.tick_rate = 60
        self.use_tick_rate = True
        self.animation_rate = 24
        self.use_animation_rate = True

        # Create sub systems
        self.network_system = self.create_network()
        self.input_manager = PandaInputManager()
        self.physics_system = PandaPhysicsSystem()

        # Timing information
        self.last_sent_time = 0
        self.current_time = 0

        self.network_tick_rate = 25
        self.metric_interval = 0.10

        # Load world
        self.pending_exit = False

        print("Network initialised")
Example #29
0
	def __init__(self):
		ShowBase.__init__(self)
		
		#Disable standard mouse camera movement
		#base.disableMouse()
		#Exit app on escape key
		base.accept("escape", sys.exit)
		
		#Get the location of MainGame.py
		projectdir = os.path.abspath(sys.path[0])
		#convert it to Panda's unix-style notation.
		projectdir = Filename.fromOsSpecific(projectdir).getFullpath()
		
		#TODO - Load the level model here
		#base.wireframeOn()
		#self.environ = self.loader.loadModel(projectdir + "/models/levels/ThePlayground")
		#Load the default environment model from the panda Tutorial
		self.environ = self.loader.loadModel(projectdir + "/models/levels/environment")
		
		#Reparent the model to the root of the Scenegraph, aka the "render" node
		#this allows for the object to actually appear on screen
		self.environ.reparentTo(self.render)
		
		#Scale and position the level/environment model
		self.environ.setScale(0.25, 0.25, 0.25)
		self.environ.setPos(-8, 42, 0)
		
		#TODO add camera controls to a function that can be added to the taskMgr
		#Handle camera controls here
		controls = BasicControls()
		#controls.startMovement()
		self.taskMgr.add(controls.movement, 'movement')
		self.taskMgr.add(controls.walk, 'walk')
Example #30
0
	def __init__(self, port, backlog = 1000, compress = False):
		ShowBase.__init__(self)

		self.compress = compress

		self.cManager = QueuedConnectionManager()
		self.cListener = QueuedConnectionListener(self.cManager, 0)
		self.cReader = QueuedConnectionReader(self.cManager, 0)
		self.cWriter = ConnectionWriter(self.cManager,0)
		
		self.clientdb = ClientDataBase()
		if not self.clientdb.connected:
			self.clientdb = None
			print 'Login Server failed to start...'
		else:
			# This is for pre-login
			self.tempConnections = []
			
			# This is for authed clients
			self.activeClients = []
			# This is for authed servers
			self.activeServers = []
			# This is for authed chat servers
			self.activeChats = []
			
			self.connect(port, backlog)
			self.startPolling()
			
			self.taskMgr.doMethodLater(0.5, self.lobbyLoop, 'Lobby Loop')
			
			print 'Login Server operating...'
Example #31
0
#version 3: added:
# controllable camera # Julianos and Stendar with proper orbiting
# edited some orbits speeds

from direct.showbase.ShowBase import ShowBase

base = ShowBase()

from direct.gui.DirectGui import *
from panda3d.core import TextNode
import sys

soundtrack = base.loader.loadSfx("sound\secunda.mp3")
soundtrack.setLoopCount(9999999999999999)  # loop (virually) forever
soundtrack.play()


class World(object):
    def __init__(self):

        #initialization
        self.title = OnscreenText(  # display title
            text="Mundus",
            parent=base.a2dBottomRight,
            align=TextNode.A_right,
            style=1,
            fg=(1, 1, 1, 1),
            pos=(-0.1, 0.1),
            scale=.07)

        base.setBackgroundColor(0, 0, 0)  # Set the background to black
Example #32
0
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)
        self.setBackgroundColor((0, 0, 0, 0))

        # Preliminary capabilities check.

        if not self.win.getGsg().getSupportsBasicShaders():
            self.t = addTitle("Firefly Demo: Video driver reports that Cg "
                              "shaders are not supported.")
            return
        if not self.win.getGsg().getSupportsDepthTexture():
            self.t = addTitle("Firefly Demo: Video driver reports that depth "
                              "textures are not supported.")
            return

        # This algorithm uses two offscreen buffers, one of which has
        # an auxiliary bitplane, and the offscreen buffers share a single
        # depth buffer.  This is a heck of a complicated buffer setup.

        self.modelbuffer = self.makeFBO("model buffer", 1)
        self.lightbuffer = self.makeFBO("light buffer", 0)

        # Creation of a high-powered buffer can fail, if the graphics card
        # doesn't support the necessary OpenGL extensions.

        if self.modelbuffer is None or self.lightbuffer is None:
            self.t = addTitle("Firefly Demo: Video driver does not support "
                              "multiple render targets")
            return

        # Create four render textures: depth, normal, albedo, and final.
        # attach them to the various bitplanes of the offscreen buffers.

        self.texDepth = Texture()
        self.texDepth.setFormat(Texture.FDepthStencil)
        self.texAlbedo = Texture()
        self.texNormal = Texture()
        self.texFinal = Texture()

        self.modelbuffer.addRenderTexture(self.texDepth,
                                          GraphicsOutput.RTMBindOrCopy,
                                          GraphicsOutput.RTPDepthStencil)
        self.modelbuffer.addRenderTexture(self.texAlbedo,
                                          GraphicsOutput.RTMBindOrCopy,
                                          GraphicsOutput.RTPColor)
        self.modelbuffer.addRenderTexture(self.texNormal,
                                          GraphicsOutput.RTMBindOrCopy,
                                          GraphicsOutput.RTPAuxRgba0)

        self.lightbuffer.addRenderTexture(self.texFinal,
                                          GraphicsOutput.RTMBindOrCopy,
                                          GraphicsOutput.RTPColor)

        # Set the near and far clipping planes.

        self.cam.node().getLens().setNear(50.0)
        self.cam.node().getLens().setFar(500.0)
        lens = self.cam.node().getLens()

        # This algorithm uses three cameras: one to render the models into the
        # model buffer, one to render the lights into the light buffer, and
        # one to render "plain" stuff (non-deferred shaded) stuff into the
        # light buffer.  Each camera has a bitmask to identify it.

        self.modelMask = 1
        self.lightMask = 2
        self.plainMask = 4

        self.modelcam = self.makeCamera(self.modelbuffer,
                                        lens=lens,
                                        scene=render,
                                        mask=self.modelMask)
        self.lightcam = self.makeCamera(self.lightbuffer,
                                        lens=lens,
                                        scene=render,
                                        mask=self.lightMask)
        self.plaincam = self.makeCamera(self.lightbuffer,
                                        lens=lens,
                                        scene=render,
                                        mask=self.plainMask)

        # Panda's main camera is not used.

        self.cam.node().setActive(0)

        # Take explicit control over the order in which the three
        # buffers are rendered.

        self.modelbuffer.setSort(1)
        self.lightbuffer.setSort(2)
        self.win.setSort(3)

        # Within the light buffer, control the order of the two cams.

        self.lightcam.node().getDisplayRegion(0).setSort(1)
        self.plaincam.node().getDisplayRegion(0).setSort(2)

        # By default, panda usually clears the screen before every
        # camera and before every window.  Tell it not to do that.
        # Then, tell it specifically when to clear and what to clear.

        self.modelcam.node().getDisplayRegion(0).disableClears()
        self.lightcam.node().getDisplayRegion(0).disableClears()
        self.plaincam.node().getDisplayRegion(0).disableClears()
        self.cam.node().getDisplayRegion(0).disableClears()
        self.cam2d.node().getDisplayRegion(0).disableClears()
        self.modelbuffer.disableClears()
        self.win.disableClears()

        self.modelbuffer.setClearColorActive(1)
        self.modelbuffer.setClearDepthActive(1)
        self.lightbuffer.setClearColorActive(1)
        self.lightbuffer.setClearColor((0, 0, 0, 1))

        # Miscellaneous stuff.

        self.disableMouse()
        self.camera.setPos(-9.112, -211.077, 46.951)
        self.camera.setHpr(0, -7.5, 2.4)
        random.seed()

        # Calculate the projection parameters for the final shader.
        # The math here is too complex to explain in an inline comment,
        # I've put in a full explanation into the HTML intro.

        proj = self.cam.node().getLens().getProjectionMat()
        proj_x = 0.5 * proj.getCell(3, 2) / proj.getCell(0, 0)
        proj_y = 0.5 * proj.getCell(3, 2)
        proj_z = 0.5 * proj.getCell(3, 2) / proj.getCell(2, 1)
        proj_w = -0.5 - 0.5 * proj.getCell(1, 2)

        # Configure the render state of the model camera.

        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setAttrib(
            AlphaTestAttrib.make(RenderAttrib.MGreaterEqual, 0.5))
        tempnode.setShader(loader.loadShader("model.sha"))
        tempnode.setAttrib(DepthTestAttrib.make(RenderAttrib.MLessEqual))
        self.modelcam.node().setInitialState(tempnode.getState())

        # Configure the render state of the light camera.

        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(loader.loadShader("light.sha"))
        tempnode.setShaderInput("texnormal", self.texNormal)
        tempnode.setShaderInput("texalbedo", self.texAlbedo)
        tempnode.setShaderInput("texdepth", self.texDepth)
        tempnode.setShaderInput("proj", (proj_x, proj_y, proj_z, proj_w))
        tempnode.setAttrib(
            ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne,
                                  ColorBlendAttrib.OOne))
        tempnode.setAttrib(
            CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
        # The next line causes problems on Linux.
        # tempnode.setAttrib(DepthTestAttrib.make(RenderAttrib.MGreaterEqual))
        tempnode.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff))
        self.lightcam.node().setInitialState(tempnode.getState())

        # Configure the render state of the plain camera.

        rs = RenderState.makeEmpty()
        self.plaincam.node().setInitialState(rs)

        # Clear any render attribs on the root node. This is necessary
        # because by default, panda assigns some attribs to the root
        # node.  These default attribs will override the
        # carefully-configured render attribs that we just attached
        # to the cameras.  The simplest solution is to just clear
        # them all out.

        render.setState(RenderState.makeEmpty())

        # My artist created a model in which some of the polygons
        # don't have textures.  This confuses the shader I wrote.
        # This little hack guarantees that everything has a texture.

        white = loader.loadTexture("models/white.jpg")
        render.setTexture(white, 0)

        # Create two subroots, to help speed cull traversal.

        self.lightroot = NodePath(PandaNode("lightroot"))
        self.lightroot.reparentTo(render)
        self.modelroot = NodePath(PandaNode("modelroot"))
        self.modelroot.reparentTo(render)
        self.lightroot.hide(BitMask32(self.modelMask))
        self.modelroot.hide(BitMask32(self.lightMask))
        self.modelroot.hide(BitMask32(self.plainMask))

        # Load the model of a forest.  Make it visible to the model camera.
        # This is a big model, so we load it asynchronously while showing a
        # load text.  We do this by passing in a callback function.
        self.loading = addTitle("Loading models...")

        self.forest = NodePath(PandaNode("Forest Root"))
        self.forest.reparentTo(render)
        self.forest.hide(BitMask32(self.lightMask | self.plainMask))
        loader.loadModel([
            "models/background", "models/foliage01", "models/foliage02",
            "models/foliage03", "models/foliage04", "models/foliage05",
            "models/foliage06", "models/foliage07", "models/foliage08",
            "models/foliage09"
        ],
                         callback=self.finishLoading)

        # Cause the final results to be rendered into the main window on a
        # card.

        self.card = self.lightbuffer.getTextureCard()
        self.card.setTexture(self.texFinal)
        self.card.reparentTo(render2d)

        # Panda contains a built-in viewer that lets you view the results of
        # your render-to-texture operations.  This code configures the viewer.

        self.bufferViewer.setPosition("llcorner")
        self.bufferViewer.setCardSize(0, 0.40)
        self.bufferViewer.setLayout("vline")
        self.toggleCards()
        self.toggleCards()

        # Firefly parameters

        self.fireflies = []
        self.sequences = []
        self.scaleseqs = []
        self.glowspheres = []
        self.fireflysize = 1.0
        self.spheremodel = loader.loadModel("misc/sphere")

        # Create the firefly model, a fuzzy dot
        dotSize = 1.0
        cm = CardMaker("firefly")
        cm.setFrame(-dotSize, dotSize, -dotSize, dotSize)
        self.firefly = NodePath(cm.generate())
        self.firefly.setTexture(loader.loadTexture("models/firefly.png"))
        self.firefly.setAttrib(
            ColorBlendAttrib.make(ColorBlendAttrib.M_add,
                                  ColorBlendAttrib.O_incoming_alpha,
                                  ColorBlendAttrib.O_one))

        # these allow you to change parameters in realtime

        self.accept("escape", sys.exit, [0])
        self.accept("arrow_up", self.incFireflyCount, [1.1111111])
        self.accept("arrow_down", self.decFireflyCount, [0.9000000])
        self.accept("arrow_right", self.setFireflySize, [1.1111111])
        self.accept("arrow_left", self.setFireflySize, [0.9000000])
        self.accept("v", self.toggleCards)
        self.accept("V", self.toggleCards)
Example #33
0
            'frames': 0
        },
        'hpr': {
            'inuse': 0,
            'start': [],
            'end': [],
            'current': [],
            'delta': [],
            'frames': 0
        },
        'act': {
            'inuse': 1,
            'start': 0,
            'end': animlen,
            'current': 0,
            'delta': 1,
            'frames': animlen
        }
    }
    gframe = gframe + animlen
    tstat.append(animdat)

ShowBase()
scene = loader.loadModel("openmodels/BeachTerrain")
scene.reparentTo(render)
base.disableMouse()
camera.setPos(0, -60, 12)
camera.setHpr(0, 0, 0)
textObject = OnscreenText(text=" ", pos=(-1.2, 0.9), scale=0.07, align=0)
taskMgr.add(defaultTask, "defaultTask")
base.run()
Example #34
0
# all imports needed by the engine itself
from direct.showbase.ShowBase import ShowBase

# all imports needed by the server
from direct.distributed.ServerRepository import ServerRepository
from panda3d.core import ConfigVariableInt

# initialize the engine
base = ShowBase(windowType='none')


# the main server class
class GameServerRepository(ServerRepository):
    """The server repository class"""
    def __init__(self):
        """initialise the server class"""

        # get the port number from the configuration file
        # if it doesn't exist, we use 4400 as the default
        tcpPort = ConfigVariableInt('server-port', 4400).getValue()

        # list of all needed .dc files
        dcFileNames = ['../direct.dc']

        # initialise a threaded server on this machine with
        # the port number and the dc filenames
        ServerRepository.__init__(self,
                                  tcpPort,
                                  dcFileNames=dcFileNames,
                                  threadedNet=True)
Example #35
0
    def __init__(self, p3d_proto=None, obs_pixel=0, act_disc=0):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)
        
        self.p3d_proto = p3d_proto
        self.obs_pixel = obs_pixel
        self.act_disc = act_disc
        
        globalClock.setFrameRate(30)
        # MNormal:0 MNoneRealTime:1 MForced:2 MLimited:5
        #~ globalClock.setMode(0)
        globalClock.setMode(1)
        
        self.exitFunc=on_exit
        
        # Internal Game State
        self.bullets_fired = 0
        self.bullets_hit = 0
        self.bullets_num = BULLET_LIMIT
        self.ship_firing = 0
        #
        self.ship_arrow = P3DCreateAxes(length=GUN_RANGE/SCREEN_X)
        self.ship_arrow1 = P3DCreateAxes(length=AVOID_DIST/SCREEN_X)
        
        #~ self.ast_arrow = P3DCreateAxes(length=GUN_RANGE/SCREEN_X)
        #~ self.ast_arrow1 = P3DCreateAxes(length=AVOID_DIST/SCREEN_X)
        
        self.bullets_text = OnscreenText(text="bullets %d"%self.bullets_num,
                                  parent=base.a2dBottomRight, scale=.1,
                                  align=TextNode.ALeft, pos=(-1.99, 1.9),
                                  fg=(0, 1, 0, 1), shadow=(0, 0, 0, 0.5))
        
        # This code puts the standard title and instruction text on screen
        #~ self.title = OnscreenText(text="Panda3D: Tutorial - Tasks",
                                  #~ parent=base.a2dBottomRight, scale=.07,
                                  #~ align=TextNode.ARight, pos=(-0.1, 0.1),
                                  #~ fg=(1, 1, 1, 1), shadow=(0, 0, 0, 0.5))
        #~ self.escapeText = genLabelText("ESC: Quit", 0)
        #~ self.leftkeyText = genLabelText("[Left Arrow]: Turn Left (CCW)", 1)
        #~ self.rightkeyText = genLabelText("[Right Arrow]: Turn Right (CW)", 2)
        #~ self.upkeyText = genLabelText("[Up Arrow]: Accelerate", 3)
        #~ self.spacekeyText = genLabelText("[Space Bar]: Fire", 4)

        # Disable default mouse-based camera control.  This is a method on the
        # ShowBase class from which we inherit.
        self.disableMouse()

        # Load the background starfield.
        self.setBackgroundColor((0, 0, 0, 1))
        self.bg = loadObject("stars.jpg", scale=146, depth=200,
                             transparency=False)

        # Load the ship and set its initial velocity.
        self.ship = loadObject("ship.png", scale=2)
        self.setVelocity(self.ship, LVector3.zero())

        # A dictionary of what keys are currently being pressed
        # The key events update this list, and our task will query it as input
        self.keys = {"turnLeft": 0, "turnRight": 0,
                     "accel": 0, "fire": 0}

        #~ self.accept("escape", sys.exit)  # Escape quits
        self.accept("escape", on_exit)  # Escape quits
        # Other keys events set the appropriate value in our key dictionary
        self.accept("arrow_left",     self.setKey, ["turnLeft", 1])
        self.accept("arrow_left-up",  self.setKey, ["turnLeft", 0])
        self.accept("arrow_right",    self.setKey, ["turnRight", 1])
        self.accept("arrow_right-up", self.setKey, ["turnRight", 0])
        self.accept("arrow_up",       self.setKey, ["accel", 1])
        self.accept("arrow_up-up",    self.setKey, ["accel", 0])
        self.accept("space",          self.setKey, ["fire", 1])

        # Now we create the task. taskMgr is the task manager that actually
        # calls the function each frame. The add method creates a new task.
        # The first argument is the function to be called, and the second
        # argument is the name for the task.  It returns a task object which
        # is passed to the function each frame.
        self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")

        # Stores the time at which the next bullet may be fired.
        self.nextBullet = 0.0

        # This list will stored fired bullets.
        self.bullets = []

        # Complete initialization by spawning the asteroids.
        self.spawnAsteroids()
Example #36
0
    def __init__(self, textboxes=({}), default_text_scale=.07, graph_objs={}):
        ShowBase.__init__(self)

        self.joys = self.devices.getDevices(InputDevice.DeviceClass.gamepad)
        #Attaches input devices to base
        for ind, joy in enumerate(self.joys):
            self.attachInputDevice(joy, prefix=str(ind))
        #Joystick reading variable
        self.joystick_readings = []

        #Add panda and background
        self.scene = self.loader.loadModel("models/environment")
        self.scene.reparentTo(self.render)
        self.scene.setScale(0.25, 0.25, 0.25)
        #Sets the scene position
        self.scene.setPos(-8, 48, 0)

        self.camera.setPos(-8, 48, -4)

        self.pandaActor = Actor("models/panda-model",
                                {"walk": "models/panda-walk4"})
        self.pandaActor.setScale(0.005, 0.005, 0.005)
        self.pandaActor.reparentTo(self.render)
        self.pandaLocation = [0, 0, 0]
        self.setPandaToLocation()
        #Lines to be rendered on the next frame
        self.lines = []
        self.lineNodes = []
        self.lineNodePaths = []
        #Text boxes which will be rendered every frame
        #Key is a node name, value is a dict with
        #arguments such as text, location, and scale
        #Hack to keep default argument immutable and prevent bugs
        if type(textboxes) == tuple:
            self.textboxes = textboxes[0]
        else:
            self.textboxes = textboxes
        self.textNodes = {}
        self.textNodePaths = {}
        self.default_text_scale = default_text_scale
        #Geometry drawing node
        self.geom_node = GeomNode("drawer")
        self.aspect2d.attach_new_node(self.geom_node)
        self.text_is_active = True
        #If the text toggle button has been up for more than one frame
        self.text_button_lifted = True
        #If changes that need to be made on text have taken place
        self.text_toggled = True
        #Loop the animation to the one loaded in the dictionary
        self.pandaActor.loop("walk")
        #Intantiates physics engine
        self.physics = physics.Swerve()
        self.taskMgr.add(self.updateJoysticks, "updateJoysticks")
        self.taskMgr.add(self.walkPandaToPhysics, "walkPandaToPhysics")
        self.taskMgr.add(self.update2dDisplay, "update2dDisplay")
        self.taskMgr.add(self.toggleText, "toggleText")
        #Creates a graph of y vectors
        self.graphs = graph_objs
        #Adds dummy value to graph to prevent crash
        self.graphs["y_graph"].update(0)
        self.graphs["vector_graph"].update(0, 0)
Example #37
0
# -*- coding: utf-8 -*-
"""
Mouse Picking

by fabius astelix @2010-01-25

Level: BEGINNER

Mouse picking is the mouse pointer interaction with elements of the screen. We'll see below a little sample to know how to make mouse picking using the panda3d collision system.

NOTE If you won't find here some line of code explained, probably you missed it in the previous steps - if you don't find there as well though, or still isn't clear for you, browse at http://www.panda3d.org/phpbb2/viewtopic.php?t=7918 and post your issue to the thread.
"""
from direct.showbase.DirectObject import DirectObject
from panda3d.core import CollisionHandlerEvent, CollisionNode, CollisionSphere, CollisionTraverser, BitMask32, CollisionRay
from direct.showbase.ShowBase import ShowBase
base=ShowBase()
# import direct.directbase.DirectStart
#** snippet support routines - off the tutorial part
import snipstuff

#=========================================================================
# Scenographic stuff
#=========================================================================

#** some scenographic stuff (text, light etc)
splash=snipstuff.splashCard()
snipstuff.info.append("Simple Mouse Picking")
snipstuff.info.append("a minimal sample to show a simple collision setup for picking an object with the mouse pointer")
snipstuff.info.append("move the mouse pointer over the smiley to see it change color and click LMB to see a reaction.\n")
snipstuff.info_show()
Example #38
0
from direct.showbase.DirectObject import DirectObject
from direct.gui.DirectGui import *
from direct.interval.IntervalGlobal import *
from panda3d.core import lookAt
from panda3d.core import GeomVertexFormat, GeomVertexData
from panda3d.core import Geom, GeomTriangles, GeomVertexWriter
from panda3d.core import Texture, GeomNode
from panda3d.core import PerspectiveLens
from panda3d.core import CardMaker
from panda3d.core import Light, Spotlight
from panda3d.core import TextNode
from panda3d.core import LVector3
import sys
import os

base = ShowBase()
base.disableMouse()
base.camera.setPos(0, -10, 0)

title = OnscreenText(text="Panda3D: Tutorial - Making a Cube Procedurally",
                     style=1, fg=(1, 1, 1, 1), pos=(-0.1, 0.1), scale=.07,
                     parent=base.a2dBottomRight, align=TextNode.ARight)
escapeEvent = OnscreenText(text="1: Set a Texture onto the Cube",
                           style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.08),
                           align=TextNode.ALeft, scale=.05,
                           parent=base.a2dTopLeft)
spaceEvent = OnscreenText(text="2: Toggle Light from the front On/Off",
                          style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.14),
                          align=TextNode.ALeft, scale=.05,
                          parent=base.a2dTopLeft)
upDownEvent = OnscreenText(text="3: Toggle Light from on top On/Off",
Example #39
0
 def run(self):
     # Start with first sso.
     self.goto_sso(0)
     # Call parent's run().
     ShowBase.run(self)
Example #40
0
    def __init__(self, workingdir):
        ShowBase.__init__(self)
        self.view_lens = p3d.MatrixLens()
        self.cam = p3d.NodePath(p3d.Camera('view'))
        self.cam.node().set_lens(self.view_lens)
        self.cam.node().set_active(True)
        self.cam.reparent_to(self.render)

        self.pipe = p3d.GraphicsPipeSelection.get_global_ptr().make_module_pipe('pandagl')

        self.bg = p3d.LVecBase4(0.0, 0.0, 0.0, 1.0)

        p3d.get_model_path().prepend_directory(workingdir)

        self.texture = p3d.Texture()
        self.win = None
        self.make_offscreen(1, 1)

        self.disableMouse()
        self.setFrameRateMeter(True)

        self.image_width = 1
        self.image_height = 1
        self.image_data = struct.pack('=BBB', 0, 0, 0)

        # Setup conversion logic
        self.converter = Converter()
        self.conversion_queue = queue.Queue()
        def conversion(task):
            while not self.conversion_queue.empty():
                data = self.conversion_queue.get()
                #print(data)
                if 'extras' in data and 'view' in data['extras']:
                    viewd = data['extras']['view']
                    if 'width' in viewd:
                        width = viewd['width']
                        height = viewd['height']
                        self.make_offscreen(width, height)
                    if 'projection_matrix' in viewd:
                        proj_mat = self.converter.load_matrix(viewd['projection_matrix'])
                        self.view_lens.set_user_mat(proj_mat)
                    if 'view_matrix' in viewd:
                        view_mat = self.converter.load_matrix(viewd['view_matrix'])

                        # Panda wants an OpenGL model matrix instead of an OpenGL view matrix
                        view_mat.invert_in_place()
                        self.view_lens.set_view_mat(view_mat)

                self.converter.update(data)
                bg = self.converter.background_color
                self.bg = p3d.LVector4(bg[0], bg[1], bg[2], 1)
                self.view_region.set_clear_color(self.bg)
                self.converter.active_scene.reparent_to(self.render)
                #self.render.ls()

            if self.texture.has_ram_image():
                #start = time.perf_counter()
                self.server.image_lock.acquire()
                self.image_width = self.texture.get_x_size()
                self.image_height = self.texture.get_y_size()
                self.image_data = memoryview(self.texture.get_ram_image_as("BGR"))
                self.server.image_lock.release()
                #print('Extern: Updated image data in {}ms'.format((time.perf_counter() - start) * 1000))
                #self.texture.write('tex.png')
            return task.cont

        self.taskMgr.add(conversion, 'Conversion')

        # Setup communication with Blender
        self.server = Server(self.handle_data, self.get_img)
        if USE_THREAD:
            self.server.start()
            def server_mon(task):
                if not self.server.is_alive():
                    print('Server thread has terminated, closing program')
                    self.server.destroy()
                    time.sleep(0.1)
                    sys.exit()
                return task.cont
            self.taskMgr.add(server_mon, 'Server Monitor')
        else:
            def server_task(task):
                self.server.run()
                return task.cont
            self.taskMgr.add(server_task, 'Server Communication')


        try:
            pman_conf = pman.get_config(workingdir)
        except pman.NoConfigError:
            pman_conf = None

        self.rendermanager = rendermanager.create_render_manager(self, pman_conf)
Example #41
0
from panda3d.core import *
from direct.gui.DirectGui import *
from direct.showbase.ShowBase import ShowBase
from noise import snoise2
import os
import random
from Block import *

loadPrcFile('config/general.prc')

if __debug__:
    loadPrcFile('config/dev.prc')

base = ShowBase()

octavesElev = 5
octavesRough = 2
octavesDetail = 1
freq = 16.0 * octavesElev

world = {}

verboseLogging = False
fancyRendering = False
wantNewGeneration = False
fillWorld = False
base.setFrameRateMeter(True)

paused = False

inventory = [
Example #42
0
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)
        self.stimtype = 'image_sequence'

        #session_start
        self.session_start_time = datetime.datetime.now()

        self.accept("escape", sys.exit, [0])
        self.accept('q', self.close)
        self.accept('Q', self.close)

        self.AUTO_REWARD = AUTO_REWARD
        # disable mouse control so that we can place the camera
        base.disableMouse()
        camera.setPosHpr(0, 0, 10, 0, -90, 0)
        mat = Mat4(camera.getMat())
        mat.invertInPlace()
        base.mouseInterfaceNode.setMat(mat)
        # base.enableMouse()

        props = WindowProperties()
        # props.setFullscreen(True)
        props.setCursorHidden(True)
        props.setMouseMode(WindowProperties.M_relative)
        base.win.requestProperties(props)
        base.setBackgroundColor(0, 0, 0)  # set the background color to black

        #set up the textures
        # we now get buffer thats going to hold the texture of our new scene
        altBuffer = self.win.makeTextureBuffer("hello", 1524, 1024)
        # altBuffer.getDisplayRegion(0).setDimensions(0.5,0.9,0.5,0.8)
        # altBuffer = base.win.makeDisplayRegion()
        # altBuffer.makeDisplayRegion(0,1,0,1)

        # now we have to setup a new scene graph to make this scene
        self.dr2 = base.win.makeDisplayRegion(0, 0.1, 0, 0.1)

        altRender = NodePath("new render")
        # this takes care of setting up ther camera properly
        self.altCam = self.makeCamera(altBuffer)
        self.dr2.setCamera(self.altCam)
        self.altCam.reparentTo(altRender)
        self.altCam.setPos(0, -10, 0)

        self.bufferViewer.setPosition("llcorner")
        # self.bufferViewer.position = (.1,.4,.1,.4)
        self.bufferViewer.setCardSize(1.0, 0.0)
        print(self.bufferViewer.position)

        self.imagesTexture = MovieTexture("image_sequence")
        # success = self.imagesTexture.read("models/natural_images.avi")
        success = self.imagesTexture.read("models/movie_5hz.mpg")
        self.imagesTexture.setPlayRate(1.0)
        self.imagesTexture.setLoopCount(10)
        # self.imageTexture =loader.loadTexture("models/NaturalImages/BSDs_8143.tiff")
        # self.imagesTexture.reparentTo(altRender)

        cm = CardMaker("stimwindow")
        cm.setFrame(-4, 4, -3, 3)
        # cm.setUvRange(self.imagesTexture)
        self.card = NodePath(cm.generate())
        self.card.reparentTo(altRender)
        if self.stimtype == 'image_sequence':
            self.card.setTexture(self.imagesTexture, 1)

        # self.imagesTexture.play()

        # self.bufferViewer.setPosition("lrcorner")
        # self.bufferViewer.setCardSize(1.0, 0.0)
        self.accept("v", self.bufferViewer.toggleEnable)
        self.accept("V", self.bufferViewer.toggleEnable)

        # Load the tunnel
        self.initTunnel()

        #initialize some things
        # for the tunnel construction:
        self.boundary_to_add_next_segment = -1 * TUNNEL_SEGMENT_LENGTH
        self.current_number_of_segments = 8
        #task flow booleans
        self.in_waiting_period = False
        self.stim_started = False
        self.looking_for_a_cue_zone = True
        self.in_reward_window = False
        self.show_stimulus = False
        #for task control
        self.interval = 0
        self.time_waiting_in_cue_zone = 0
        self.wait_time = 1.83
        self.stim_duration = 4.0  # in seconds
        self.max_stim_duration = 6.0  # in seconds
        self.stim_elapsed = 0.0  # in seconds
        self.last_position = base.camera.getZ()
        self.position_on_track = base.camera.getZ()
        #for reward control
        self.reward_window = 1.0  # in seconds
        self.reward_elapsed = 0.0
        # self.reward_volume = 0.008 # in mL. this is for the hardcoded 0.1 seconds of reward time
        self.reward_volume = 10  # in uL, for the stepper motor
        self.reward_time = 0.1  # in sec, based on volume. hard coded right now but should be modified by the (1) calibration and (2) optionally by the main loop for dynamic reward scheduling
        # self.lick_buffer = []

        #INITIALIZE NIDAQ
        self.nidevice = 'Dev2'
        self.encodervinchannel = 1
        self.encodervsigchannel = 0
        self.invertdo = False
        self.diport = 1
        self.lickline = 1
        self.doport = 0
        self.rewardline = 0
        self.rewardlines = [0]
        self._setupDAQ()
        self.do.WriteBit(1, 1)
        self.do.WriteBit(
            3, 1
        )  #set reward high, because the logic is flipped somehow. possibly by haphazard wiring of the circuit (12/24/2018 djd)
        self.previous_encoder_position = self.ai.data[0][
            self.encodervsigchannel]
        self.encoder_gain = -20

        #INITIALIZE LICK SENSOR
        self._lickSensorSetup()

        #INITIALIZE  output data
        self.lickData = []
        self.x = []
        self.t = []
        self.trialData = []
        self.rewardData = []

        #INITIALIZE KEY SENSOR, for backup inputs and other user controls
        self.keys = key.KeyStateHandler()
        self.accept('r', self._give_reward, [self.reward_volume])
        self.accept('l', self._toggle_reward)

        img_list = glob.glob('models/NaturalImages/*.tiff')[:10]
        print(img_list)
        self.imageTextures = [loader.loadTexture(img) for img in img_list]

        if AUTO_MODE:
            self.gameTask = taskMgr.add(self.autoLoop2, "autoLoop2")
            self.rewardTask = taskMgr.add(self.rewardControl, "reward")
            self.cue_zone = concatenate((self.cue_zone,arange(\
                self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH,\
                self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH-TUNNEL_SEGMENT_LENGTH-80,\
                -1)))
            self.auto_position_on_track = 0
            self.auto_restart = False
            self.auto_running = True
            self.contTunnel()
        else:
            # Now we create the task. taskMgr is the task manager that actually
            # calls the function each frame. The add method creates a new task.
            # The first argument is the function to be called, and the second
            # argument is the name for the task.  It returns a task object which
            # is passed to the function each frame.
            self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
            # self.stimulusTask = taskMgr.add(self.stimulusControl, "stimulus")
            self.lickTask = taskMgr.add(self.lickControl, "lick")
            self.rewardTask = taskMgr.add(self.rewardControl, "reward")
Example #43
0
    def __init__(self):
        # Configure the parallax mapping settings (these are just the defaults)
        loadPrcFileData(
            "", "parallax-mapping-samples 3\n"
            "parallax-mapping-scale 0.1")

        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)

        # Check video card capabilities.
        if not self.win.getGsg().getSupportsBasicShaders():
            addTitle("Bump Mapping: "
                     "Video driver reports that Cg shaders are not supported.")
            return

        # Post the instructions
        self.title = addTitle("Panda3D: Tutorial - Bump Mapping")
        self.inst1 = addInstructions(0.06, "Press ESC to exit")
        self.inst2 = addInstructions(0.12, "Move mouse to rotate camera")
        self.inst3 = addInstructions(0.18, "Left mouse button: Move forwards")
        self.inst4 = addInstructions(0.24,
                                     "Right mouse button: Move backwards")
        self.inst5 = addInstructions(0.30, "Enter: Turn bump maps Off")

        # Load the 'abstract room' model.  This is a model of an
        # empty room containing a pillar, a pyramid, and a bunch
        # of exaggeratedly bumpy textures.

        self.room = loader.loadModel("models/abstractroom")
        self.room.reparentTo(render)

        # Make the mouse invisible, turn off normal mouse controls
        self.disableMouse()
        props = WindowProperties()
        props.setCursorHidden(True)
        self.win.requestProperties(props)
        self.camLens.setFov(60)

        # Set the current viewing target
        self.focus = LVector3(55, -55, 20)
        self.heading = 180
        self.pitch = 0
        self.mousex = 0
        self.mousey = 0
        self.last = 0
        self.mousebtn = [0, 0, 0]

        # Start the camera control task:
        taskMgr.add(self.controlCamera, "camera-task")
        self.accept("escape", sys.exit, [0])
        self.accept("mouse1", self.setMouseBtn, [0, 1])
        self.accept("mouse1-up", self.setMouseBtn, [0, 0])
        self.accept("mouse2", self.setMouseBtn, [1, 1])
        self.accept("mouse2-up", self.setMouseBtn, [1, 0])
        self.accept("mouse3", self.setMouseBtn, [2, 1])
        self.accept("mouse3-up", self.setMouseBtn, [2, 0])
        self.accept("enter", self.toggleShader)
        self.accept("j", self.rotateLight, [-1])
        self.accept("k", self.rotateLight, [1])
        self.accept("arrow_left", self.rotateCam, [-1])
        self.accept("arrow_right", self.rotateCam, [1])

        # Add a light to the scene.
        self.lightpivot = render.attachNewNode("lightpivot")
        self.lightpivot.setPos(0, 0, 25)
        self.lightpivot.hprInterval(10, LPoint3(360, 0, 0)).loop()
        plight = PointLight('plight')
        plight.setColor((1, 1, 1, 1))
        plight.setAttenuation(LVector3(0.7, 0.05, 0))
        plnp = self.lightpivot.attachNewNode(plight)
        plnp.setPos(45, 0, 0)
        self.room.setLight(plnp)

        # Add an ambient light
        alight = AmbientLight('alight')
        alight.setColor((0.2, 0.2, 0.2, 1))
        alnp = render.attachNewNode(alight)
        self.room.setLight(alnp)

        # Create a sphere to denote the light
        sphere = loader.loadModel("models/icosphere")
        sphere.reparentTo(plnp)

        # Tell Panda that it should generate shaders performing per-pixel
        # lighting for the room.
        self.room.setShaderAuto()

        self.shaderenable = 1
Example #44
0
 def __init__(self):
     ShowBase.__init__(self)
     resize_window = ConfigVariableBool('viewer-resize-window', '#t')
     if resize_window.getValue():
         self.win_size = (800, 800)
     # Black background
     self.win.setClearColor((1, 1, 1, 1))
     # Set up lights.
     ablight = AmbientLight("ambientlight")
     ablight.setColor(Vec4(0.5, 0.5, 0.5, 1))
     ablightnode = self.render.attachNewNode(ablight)
     self.render.setLight(ablightnode)
     ptlight0 = PointLight("pointlight0")
     ptlight0.setColor(VBase4(1, 1, 1, 1))
     ptlightnode0 = self.render.attachNewNode(ptlight0)
     ptlightnode0.setPos(500, 0, 500)
     base.render.setLight(ptlightnode0)
     ptlight1 = PointLight("pointlight1")
     ptlight1.setColor(VBase4(1, 1, 1, 1))
     ptlightnode1 = base.render.attachNewNode(ptlight1)
     ptlightnode1.setPos(0, 500, 500)
     base.render.setLight(ptlightnode1)
     # Spotlight. Casts shadows.
     slight = Spotlight("slight")
     slight.setScene(self.render)
     slight.setShadowCaster(True, 2**11, 2**11)
     # Set shadow mask, so we can exclude objects from casting shadows
     self.shadow_mask = BitMask32.bit(2)
     slight.setCameraMask(self.shadow_mask)
     slight.setColor((1.2, 1.2, 1.2, 1.))
     slight.getLens().setFov(45)
     slight.getLens().setNearFar(1, 100)
     slnp = self.lights.attachNewNode(slight)
     slnp.setPos((6, 8, 20))
     slnp.lookAt(0, 0, 0)
     self.render.setLight(slnp)
     # Ambient light.
     alight = AmbientLight("alight")
     a = 0.75
     alight.setColor((a, a, a, 1.0))
     #alight.setColor((0.8, 0.8, 0.8, 1.0))
     alnp = self.lights.attachNewNode(alight)
     self.render.setLight(alnp)
     self.lights.reparentTo(self.render)
     # Set auto shading for shadows
     use_shaders = ConfigVariableBool('viewer-use-shaders', '#t')
     if use_shaders.getValue():
         self.render.setShaderAuto()
     # Set antialiasing on
     self.render.setAntialias(AntialiasAttrib.MAuto)
     # Camera
     self.camera_rot = self.render.attachNewNode("camera_rot")
     self.cameras = self.camera_rot.attachNewNode("cameras")
     self.cameras.setPos(14, 32, 9.)
     self.look_at = self.render.attachNewNode("look_at")
     self.look_at.setPos(Point3(2, 0, 1))
     self.cameras.lookAt(self.look_at)
     self.camera.reparentTo(self.cameras)
     # Adjust the camera's lens
     lens = PerspectiveLens()
     self.camLens = lens
     self.camLens.setNearFar(0.01, 1000.0)
     setlens = ConfigVariableBool('viewer-set-cam-lens', '#t')
     if setlens:
         self.cam.node().setLens(self.camLens)
     #
     # Initialize / set variables
     self.sso = None
     self.ssos = []
     self.cache = None
     self.scene = SSO("scene")
     self.scene.reparentTo(self.render)
     # Key callbacks.
     self.accept("shift-control-escape", self.exit)
     self.accept("escape", self.exit)
     self.accept("0", self.reset_sso)
     self.accept("arrow_left", self.prev)
     self.accept("arrow_right", self.next)
     self.accept("page_down", self.prev, [100])
     self.accept("page_up", self.next, [100])
     self.accept("f1", self.toggle_debug)
     self.accept("o", self.physics_once, extraArgs=[1. / 10])
     self.accept("i", self.physics_once, extraArgs=[1. / 10000])
     # Remove existing keyboard tasks.
     self.mandatory_events = ("window-event", "async_loader_0",
                              "render-texture-targets-changed",
                              "shift-control-escape")
     # Task list: name: (key, args)
     events = {
         "physics": ("p", ),
         "repel": ("t", ),
         "bump": ("f", ),
         "rotate": ("r", 20),
         "rotate90": ("h", ),
         "ss_task": ("s", ),
         "ssa_task": ("w", ),
         "bp": ("b", )
     }
     # Add events
     for key, val in events.iteritems():
         call = [key] + list(val[1:])
         self.accept(val[0], self.toggle_task, call)
     # These are the key events that we will never ignore
     self.permanent_events = self.getAllAccepting()
     # These are the key events that we will never ignore
     self.permanent_tasks = [
         task.getName() for task in self.taskMgr.getAllTasks()
     ]
     self.start_time = -1
     self.old_elapsed = 0
Example #45
0
    def __init__(self, env_name, trial_data, headless=False):
        self.manually_quit = True
        try:
            ShowBase.__init__(self,
                              windowType="none" if headless else "onscreen")
        except:
            self.trial_finished_callback()

        # Allows importing components from project folder
        sys.path.append(".")

        # Initial scene setup
        self.disableMouse()
        self.setBackgroundColor(0.15, 0.15, 0.15, 1)
        EComponent.panda_root_node = self.render.attach_new_node(
            PandaNode("Root"))
        EComponent.base = self

        # Attach a directional light to the camera
        if not headless:
            self.dir_light = DirectionalLight("cam_dir_light")
            dir_light_path = self.camera.attach_new_node(self.dir_light)
            EComponent.panda_root_node.setLight(dir_light_path)

        # Read the project config file
        config_path = Path("project.yaml")
        config = None
        if not config_path.exists():
            sys.stderr.write("Error: Could not find project.yaml.")
            return
        with open("project.yaml", "r") as file:
            config = yaml.load(file, Loader=yaml.FullLoader)

        # Add floor
        if not headless:
            self.floor_node = FloorNode(self)
            floor_path = self.render.attach_new_node(self.floor_node)
            floor_path.setTwoSided(True)
            floor_path.set_shader_input("object_id", 0)

        # Add camera controller
        if not headless:
            self.cam_controller = CameraController(self, self.render,
                                                   self.camera)

        # Set up physics system
        self.physics_world = BulletWorld()
        self.physics_world.setGravity(LVector3f(0, 0, -9.81))
        EComponent.physics_world = self.physics_world
        self.taskMgr.add(self.physics_task, "physics_task")

        # Load environment
        with open(env_name + ".json", "r") as file:
            scene_dict = json.load(file)
            self.root_node = GraphNode.dict_to_scene_graph(scene_dict,
                                                           use_gui=False)

            trial = Trial()
            trial.data = trial_data
            trial.trial_finished_callback = self.trial_finished_callback
            self.setup_node(self.root_node, trial)

        # Set up update task
        self.taskMgr.add(self.update_task, "update_task")
Example #46
0
 def __init__(self):
     ShowBase.__init__(self)
Example #47
0
    def __init__(self):
        ShowBase.__init__(self)

        properties = WindowProperties()
        properties.setSize(1000, 750)
        self.win.requestProperties(properties)
        base.setBackgroundColor(0.5,1,0.5)
        self.textObject = OnscreenText(text ='shape-boi', pos = (0.925,0.925), scale = 0.075)

        self.thread = threading.Thread(target=self.udpConnect)
        self.thread2 = threading.Thread(target=self.runColorTrack)
        self.connectButton = DirectButton(text=('Open Connection'),pos=(-0.3,0,-0.98), scale=0.090, command=self.openConnection, frameColor=(255,255,255,0.15))
        self.trackButton = DirectButton(text=('Color Track'),pos=(-1,0,-0.98), scale=0.090, command=self.thread2.start,frameColor=(255,255,255,0.15),state=0)
        self.connectButton.hide()
        self.trackButton.hide()
        self.scoreUI = OnscreenText(text = "0",
                                    pos = (-1.3, 0.825),
                                    mayChange = True,
                                    align = TextNode.ALeft)

        env = Environment("MorgansModels/mapTest2")
        #loader.loadModel("Models/Misc/environment")

        self.clientMsg = ''

        #render.setShaderAuto()
        #self.environment.setPos(0,54,-3)
        #self.environment.setH(90)
        #self.environment.setP(0)

        #self.environment.setScale(2)
        #self.environment.setZ(-10)


        self.tempActor = Actor("MorgansModels/shape-boi-grab-test-point_level2",
                                {"walk":"MorgansModels/shape-boi-grab-test-point_level2-ArmatureAction",
                                 "lift":"MorgansModels/shape-boi-grab-test-point_level2-IcosphereAction"})
        '''
        # test with more realistic character
        self.tempActor = Actor("MorgansModels/mainCharacter_walking",
                                {"walk":"MorgansModels/mainCharacter_walking-ArmatureAction",
                                 "lift":"MorgansModels/shape-boi-grab-test-point_level2-IcosphereAction"})
        '''
        self.tempActor.reparentTo(render)
        self.tempActor.setH(0)
        self.tempActor.setPos(0,54,-3)
        self.tempActor.setScale(0.5,0.5,0.5)
        self.tempActor.loop("walk")
        #player 1
        self.cTrav = CollisionTraverser()
        self.pusher = CollisionHandlerPusher()
        colliderNode = CollisionNode("player")
        # Add a collision-sphere centred on (0, 0, 0), and with a radius of 0.3
        colliderNode.addSolid(CollisionSphere(0,0,0, 0.8))
        collider = self.tempActor.attachNewNode(colliderNode)
        collider.show()
        base.pusher.addCollider(collider, self.tempActor)
        # The traverser wants a collider, and a handler
        # that responds to that collider's collisions
        base.cTrav.addCollider(collider, self.pusher)
        self.pusher.setHorizontal(True)
        #collider.setZ(-3)

        self.myFriends = []
        for i in range(4):
            self.tempActor2 = Actor("MorgansModels/shape-boi-grab-test",
                                    {"walk":"MorgansModels/shape-boi-grab-test-ArmatureAction"})
            self.tempActor2.reparentTo(render)
            self.tempActor2.setH(180)
            self.tempActor2.setPos(0,50+(i*2),-3)
            self.tempActor2.setScale(0.5,0.5,0.5)
            self.tempActor2.loop("walk")
            self.myFriends.append(self.tempActor2)
        print(self.myFriends)




        self.score = 0


        ambientLight = AmbientLight("ambient light")
        ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1))
        self.ambientLightNodePath = render.attachNewNode(ambientLight)
        render.setLight(self.ambientLightNodePath)

        # In the body of your code
        mainLight = DirectionalLight("main light")
        self.mainLightNodePath = render.attachNewNode(mainLight)
        # Turn it around by 45 degrees, and tilt it down by 45 degrees
        self.mainLightNodePath.setHpr(45, -45, 0)
        render.setLight(self.mainLightNodePath)
        #render.setShaderAuto()
        '''
        liftSpot = Spotlight('spotlight')
        liftSpot.setColor((0.75, 1, 1, 1))
        self.spotLightNodePath = render.attachNewNode(liftSpot)
        render.setLight(self.spotLightNodePath)
        self.spotLightNodePath.setPos(self.tempActor2.getX(), self.tempActor2.getY(), self.tempActor2.getZ()+ 5)
        self.spotLightNodePath.lookAt(self.tempActor2)
        render.setShaderAuto()
        '''



        self.keyMap = {
            "up" : False,
            "down" : False,
            "left" : False,
            "right" : False,
            "shoot" : False
            }
        self.accept("w", self.updateKeyMap, ["up", True])
        self.accept("w-up", self.updateKeyMap, ["up", False])
        self.accept("s", self.updateKeyMap, ["down", True])
        self.accept("s-up", self.updateKeyMap, ["down", False])
        self.accept("a", self.updateKeyMap, ["left", True])
        self.accept("a-up", self.updateKeyMap, ["left", False])
        self.accept("d", self.updateKeyMap, ["right", True])
        self.accept("d-up", self.updateKeyMap, ["right", False])
        self.accept("mouse1", self.updateKeyMap, ["shoot", True])
        self.accept("mouse1-up", self.updateKeyMap, ["shoot", False])
        self.updateTask = taskMgr.add(self.update, "update")
        self.updateTask2 = taskMgr.add(self.updateScore, "updateScore")
        self.trackUpdate = taskMgr.add(self.handleMessage, 'handleMessage')
        #self.updateTask3 = taskMgr.add(self.udpUpdate)




        env.wallColliders()



        '''
        # towers
        wallSolid = CollisionTube(-1, 37, -4, -1, 37, 3, 1)
        wallNode = CollisionNode("wall")
        wallNode.addSolid(wallSolid)
        wall = render.attachNewNode(wallNode)
        wall.setY(8.0)
        wall.show()


        wallSolid = CollisionTube(-4.5, 48, -4, -4.5, 48, 3, 1)
        wallNode = CollisionNode("wall")
        wallNode.addSolid(wallSolid)
        wall = render.attachNewNode(wallNode)
        wall.setY(8.0)
        wall.show()
        '''
        self.disableMouse()
        base.disableMouse()
        self.camera.setPos(self.tempActor.getPos()+ Vec3(0,6,4))
        #self.camera.setPos(0, 0, 50)
        # Tilt the camera down by setting its pitch.
        self.camera.setP(-12.5)

        self.friendRoomCam()

        self.startMenu()
Example #48
0
    def __init__(self):
        ShowBase.__init__(self)
        self.disableMouse()

        # Instrucciones en pantalla
        self.ralph_escape = addInstructions(.06, "[ESC]: Para Salir")
        self.ralph_run = addInstructions(.12, "[A]: Para Empezar Juego")

        # Variables globales para el control
        self.arrayGlobal = []
        self.sonidoGlobal = -1

        # Carga de imágenes
        self.Perro = OnscreenImage(image='src/images/Dog.png')
        self.Caballo = OnscreenImage(image='src/images/Horse.png')
        self.Leon = OnscreenImage(image='src/images/Lion.png')
        self.Gato = OnscreenImage(image='src/images/Cat.png')
        self.Elefante = OnscreenImage(image='src/images/Elephant.png')
        self.Oveja = OnscreenImage(image='src/images/Sheep.png')
        self.Correcto = OnscreenImage(image='src/images/correcto.png',
                                      pos=(100, 100, 100))
        self.Incorrecto = OnscreenImage(image='src/images/incorrecto.png',
                                        pos=(100, 100, 100))
        self.arrayRespuestas = [self.Correcto, self.Incorrecto]
        self.arrayImages = [
            self.Perro, self.Caballo, self.Leon, self.Gato, self.Elefante,
            self.Oveja
        ]

        # Carga de audio
        self.audioElefante = loader.loadSfx("src/sounds/Dog.mp3")
        self.audioPerro = loader.loadSfx("src/sounds/Dog.mp3")
        self.audioCaballo = loader.loadSfx("src/sounds/Horse.mp3")
        self.audioLeon = loader.loadSfx("src/sounds/Lion.mp3")
        self.audioGato = loader.loadSfx("src/sounds/Cat.mp3")
        self.audioOveja = loader.loadSfx("src/sounds/Sheep.mp3")
        self.arrayAudios = [
            self.audioPerro, self.audioCaballo, self.audioLeon, self.audioGato,
            self.audioElefante, self.audioOveja
        ]

        # Aprende a usar botones prro
        self.btn1 = DirectButton(text="1",
                                 scale=.1,
                                 command=self.verificaRespuesta,
                                 extraArgs=[0])
        self.btn2 = DirectButton(text="2",
                                 scale=.1,
                                 command=self.verificaRespuesta,
                                 extraArgs=[1])
        self.btn3 = DirectButton(text="3",
                                 scale=.1,
                                 command=self.verificaRespuesta,
                                 extraArgs=[2])
        self.btn4 = DirectButton(text="4",
                                 scale=.1,
                                 command=self.verificaRespuesta,
                                 extraArgs=[3])
        self.btn5 = DirectButton(text="5",
                                 scale=.1,
                                 command=self.verificaRespuesta,
                                 extraArgs=[4])
        self.btn6 = DirectButton(text="6",
                                 scale=.1,
                                 command=self.verificaRespuesta,
                                 extraArgs=[5])
        self.arrayBotones = [
            self.btn1, self.btn2, self.btn3, self.btn4, self.btn5, self.btn6
        ]

        # Primer evento para desaparecer all de pantalla
        self.limpiarPantalla(False)

        # Eventos con teclas
        self.accept("escape", sys.exit)
        self.accept("a", self.iniciaJuego)
Example #49
0
# definitions
cameras = []
activeCam = 0;

# toggleCam task
def toggleCam(task):
    global cameras,activeCam
    cameras[activeCam].node().getDisplayRegion(0).setActive(0)
    activeCam = (activeCam + 1)%len(cameras)
    cameras[activeCam].node().getDisplayRegion(0).setActive(1)
    return task.again


# Set framework up
framework = ShowBase()

# Load the environment model.
scene = loader.loadModel("models/environment")
# Reparent the model to render.
scene.reparentTo(render)
# Apply scale and position transforms on the model.
scene.setScale(0.25, 0.25, 0.25)
scene.setPos(-8, 42, 0)

pandaActor = Actor("panda", {"walk": "panda-walk"})
pandaActor.reparentTo(render)
pandaActor.loop("walk")

# Create the four lerp intervals needed for the panda to
# walk back and forth.
    def __init__(self):

        # Load settings
        load_prc_file_data(
            "", """
            win-size 10 10
            window-type offscreen
            win-title GI Bake
            textures-power-2 none
            gl-coordinate-system default
            sync-video #f
            support-stencil #f
            framebuffer-stencil #f
            framebuffer-multisample #f
            multisamples 0
            gl-cube-map-seamless #t
            gl-force-fbo-color #f
        """)

        ShowBase.__init__(self)
        Globals.load(self)
        Globals.resolution = LVecBase2i(1600, 900)
        sun_vector = Vec3(0.2, 0.5, 1.2).normalized()
        capture_resolution = 32
        sun_shadow_map_resolution = 2048
        num_probes = LVecBase3i(64)
        divisor = 128
        num_bakers = 8
        padding = 0.5

        for region in self.win.get_display_regions():
            region.set_active(False)

        print("Loading scene ...")
        # model = loader.load_model("resources/test-scene.bam")
        model = loader.load_model("scene/scene.bam")
        # model = loader.load_model("scene/LivingRoom.egg")
        model.reparent_to(render)
        model.flatten_strong()

        start_point, end_point = model.get_tight_bounds()
        start_point -= padding
        end_point += padding
        diameter = (start_point - end_point).length() * 0.5
        model_center = (start_point + end_point) * 0.5
        model_size = end_point - start_point

        print("Rendering sun shadow map ..")
        sun_shadow_cam = Camera("SunShadowCamera")
        sun_shadow_lens = OrthographicLens()
        sun_shadow_lens.set_film_size(diameter * 2, diameter * 2)
        sun_shadow_lens.set_near_far(0, 2 * diameter)
        sun_shadow_cam.set_lens(sun_shadow_lens)
        sun_shadow_cam_np = render.attach_new_node(sun_shadow_cam)
        sun_shadow_cam_np.set_pos(model_center + sun_vector * diameter)
        sun_shadow_cam_np.look_at(model_center)

        sun_shadow_target = RenderTarget()
        sun_shadow_target.size = sun_shadow_map_resolution
        sun_shadow_target.add_depth_attachment(bits=32)
        sun_shadow_target.prepare_render(sun_shadow_cam_np)

        self.render_frame()
        sun_shadow_target.active = False
        shadow_mvp = self.get_mvp(sun_shadow_cam_np)

        print("Computing first bounce ..")

        # Target to store all results
        max_probes = num_probes.x * num_probes.y * num_probes.z

        if max_probes % divisor != 0:
            print("WARNING: Bad divisor:", divisor, "for", max_probes)

        num_rows = (max_probes + divisor - 1) // divisor
        final_data = Texture("FinalProbeResult")
        final_data.setup_2d_texture(6 * divisor, num_rows, Texture.T_float,
                                    Texture.F_rgba16)
        final_data.set_clear_color(Vec4(1.0, 0.6, 0.2, 1.0))

        worker_handles = []

        store_shader = Shader.load(Shader.SL_GLSL,
                                   "resources/default.vert.glsl",
                                   "resources/copy_cubemap.frag.glsl")
        convolute_shader = Shader.load(Shader.SL_GLSL,
                                       "resources/default.vert.glsl",
                                       "resources/convolute.frag.glsl")

        for worked_id in range(num_bakers):
            probe_position = Vec3(0, 0, 4)
            capture_target = RenderTarget()
            capture_target.size = capture_resolution * 6, capture_resolution
            capture_target.add_depth_attachment(bits=16)
            capture_target.add_color_attachment(bits=16, alpha=True)
            capture_target.prepare_render(None)

            # Remove all unused display regions
            internal_buffer = capture_target.internal_buffer
            internal_buffer.remove_all_display_regions()
            internal_buffer.disable_clears()
            internal_buffer.get_overlay_display_region().disable_clears()

            # Setup the cubemap capture rig
            directions = (Vec3(1, 0, 0), Vec3(-1, 0, 0), Vec3(0, 1, 0),
                          Vec3(0, -1, 0), Vec3(0, 0, 1), Vec3(0, 0, -1))
            capture_regions = []
            capture_cams = []
            capture_rig = render.attach_new_node("CaptureRig")
            capture_rig.set_pos(probe_position)

            # Prepare the display regions
            for i in range(6):
                region = capture_target.internal_buffer.make_display_region(
                    i / 6, i / 6 + 1 / 6, 0, 1)
                region.set_sort(25 + i)
                region.set_active(True)
                region.disable_clears()

                # Set the correct clears
                region.set_clear_depth_active(True)
                region.set_clear_depth(1.0)
                region.set_clear_color_active(True)
                region.set_clear_color(Vec4(0.0, 0.0, 0.0, 0.0))

                lens = PerspectiveLens()
                lens.set_fov(90)
                lens.set_near_far(0.05, 2 * diameter)
                camera = Camera("CaptureCam-" + str(i), lens)
                camera_np = capture_rig.attach_new_node(camera)
                camera_np.look_at(camera_np, directions[i])
                region.set_camera(camera_np)
                capture_regions.append(region)
                capture_cams.append(camera_np)

            capture_cams[0].set_r(90)
            capture_cams[1].set_r(-90)
            capture_cams[3].set_r(180)
            capture_cams[5].set_r(180)

            destination_cubemap = Texture("TemporaryCubemap")
            destination_cubemap.setup_cube_map(capture_resolution,
                                               Texture.T_float,
                                               Texture.F_rgba16)

            # Target to convert the FBO to a cubemap
            target_store_cubemap = RenderTarget()
            target_store_cubemap.size = capture_resolution * 6, capture_resolution
            target_store_cubemap.prepare_buffer()
            target_store_cubemap.set_shader_inputs(
                SourceTex=capture_target.color_tex,
                DestTex=destination_cubemap)

            target_store_cubemap.shader = store_shader

            # Target to filter the data
            store_pta = PTALVecBase2i.empty_array(1)
            target_convolute = RenderTarget()
            target_convolute.size = 6, 1
            # target_convolute.add_color_attachment(bits=16)
            target_convolute.prepare_buffer()
            target_convolute.set_shader_inputs(SourceTex=destination_cubemap,
                                               DestTex=final_data,
                                               storeCoord=store_pta)
            target_convolute.shader = convolute_shader

            # Set initial shader
            shader = Shader.load(Shader.SL_GLSL,
                                 "resources/first-bounce.vert.glsl",
                                 "resources/first-bounce.frag.glsl")
            render.set_shader(shader)
            render.set_shader_inputs(ShadowMap=sun_shadow_target.depth_tex,
                                     shadowMVP=shadow_mvp,
                                     sunVector=sun_vector)

            worker_handles.append((capture_rig, store_pta))

        print("Preparing to render", max_probes, "probes ..")
        widgets = [
            Counter(), "  ",
            Bar(), "  ",
            Percentage(), "  ",
            ETA(), " ",
            Rate()
        ]
        progressbar = ProgressBar(widgets=widgets, maxval=max_probes).start()
        progressbar.update(0)

        work_queue = []

        for z_pos in range(num_probes.z):
            for y_pos in range(num_probes.y):
                for x_pos in range(num_probes.x):
                    index = x_pos + y_pos * num_probes.x + z_pos * num_probes.y * num_probes.x
                    #     print("Baking", index, "out of", max_probes)
                    offs_x = start_point.x + x_pos / (num_probes.x +
                                                      0.5) * model_size.x
                    offs_y = start_point.y + y_pos / (num_probes.y +
                                                      0.5) * model_size.y
                    offs_z = start_point.z + z_pos / (num_probes.z +
                                                      0.5) * model_size.z

                    store_x = index % divisor
                    store_y = index // divisor

                    work_queue.append(
                        (Vec3(offs_x, offs_y,
                              offs_z), LVecBase2i(store_x, store_y)))

        for i, (pos, store) in enumerate(work_queue):
            worker_handles[i % num_bakers][0].set_pos(pos)
            worker_handles[i % num_bakers][1][0] = store
            if i % num_bakers == num_bakers - 1:
                self.render_frame()
                progressbar.update(i)

        progressbar.finish()
        self.render_frame()

        print("Writing out data ..")
        self.graphicsEngine.extract_texture_data(final_data, self.win.gsg)
        final_data.write("raw-bake.png")

        print("Writing out configuration")
        with open("_bake_params.py", "w") as handle:
            handle.write("#Autogenerated\n")
            handle.write(
                "from panda3d.core import LPoint3f, LVecBase3i, LVector3f\n")
            handle.write("BAKE_MESH_START = " + str(start_point) + "\n")
            handle.write("BAKE_MESH_END = " + str(end_point) + "\n")
            handle.write("BAKE_MESH_PROBECOUNT = " + str(num_probes) + "\n")
            handle.write("BAKE_DIVISOR = " + str(divisor) + "\n")
            handle.write("BAKE_SUN_VECTOR = " + str(sun_vector) + "\n")

        with open("_bake_params.glsl", "w") as handle:
            handle.write("// Autogenerated\n")
            handle.write("#define LPoint3f vec3\n")
            handle.write("#define LVector3f vec3\n")
            handle.write("#define LVecBase3i ivec3\n")
            handle.write("const vec3 bake_mesh_start = " + str(start_point) +
                         ";\n")
            handle.write("const vec3 bake_mesh_end = " + str(end_point) +
                         ";\n")
            handle.write("const ivec3 bake_mesh_probecount = " +
                         str(num_probes) + ";\n")
            handle.write("const int bake_divisor = " + str(divisor) + ";\n")
            handle.write("const vec3 sun_vector = " + str(sun_vector) + ";\n")
Example #51
0
    def __init__(self):
        ShowBase.__init__(self)
        FSM.__init__(self, "mainStateMachine")

        # some basic enhancements
        # window background color
        self.setBackgroundColor(0, 0, 0)
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()
        # Enhance font readability
        DGG.getDefaultFont().setPixelsPerUnit(100)
        # hide the mouse cursor
        hide_cursor()

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if audio should be muted
        mute = ConfigVariableBool("audio-mute", False).getValue()
        if mute:
            self.disableAllAudio()
        else:
            self.enableAllAudio()

        base.sfxManagerList[0].setVolume(
            ConfigVariableDouble("audio-volume-sfx", 1.0).getValue())
        base.difficulty = ConfigVariableInt("difficulty", 0).getValue()

        def setFullscreen():
            """Helper function to set the window fullscreen
            with width and height set to the screens size"""
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set window properties
            # clear all properties not previously set
            base.win.clearRejectedProperties()
            # setup new window properties
            props = WindowProperties()
            # Fullscreen
            props.setFullscreen(True)
            # set the window size to the screen resolution
            props.setSize(w, h)
            # request the new properties
            base.win.requestProperties(props)

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            setFullscreen()
        elif base.appRunner:
            # When the application is started as appRunner instance, it
            # doesn't respect our loadPrcFiles configurations specific
            # to the window as the window is already created, hence we
            # need to manually set them here.
            for dec in range(mainConfig.getNumDeclarations()):
                # check if we have the fullscreen variable
                if mainConfig.getVariableName(dec) == "fullscreen":
                    setFullscreen()
        # automatically safe configuration at application exit
        base.exitFunc = self.__writeConfig

        # due to the delayed window resizing and switch to fullscreen
        # we wait some time until everything is set so we can savely
        # proceed with other setups like the menus
        if base.appRunner:
            # this behaviour only happens if run from p3d files and
            # hence the appRunner is enabled
            taskMgr.doMethodLater(0.5,
                                  self.postInit,
                                  "post initialization",
                                  extraArgs=[])
        else:
            self.postInit()
Example #52
0
import MySQLdb
import direct
from toontown.toonbase.ToontownModules import *
from direct.showbase.ShowBase import ShowBase
from toontown.toonbase import TTLocalizer

language = TTLocalizer.getLanguage()

showbase = ShowBase(fStartDirect=False, windowType='none')
config = getConfigShowbase()

from otp.uberdog.DBInterface import DBInterface
from toontown.coderedemption import TTCodeRedemptionConsts

username = ConfigVariableString("mysql-user").getValue()
password = ConfigVariableString("mysql-passwd").getValue()

if username == "" or password == "":
    print("Username or password not found, check your config.prc!")
    sys.exit(2)

db = MySQLdb.connect(host="localhost",
                     port=3306,
                     user=username,
                     passwd=password)

print("Connected to MySQL at localhost.")

cursor = db.cursor()

Example #53
0
class PandaController(object):

    DEFAULT_FULLSCREEN = False
    DEFAULT_WIDTH = 800
    DEFAULT_HEIGHT = 600
    DEFAULT_FPS = 60
    DEFAULT_FRAME_METER = False
    DEFAULT_MUSIC_VOLUME = .3
    DEFAULT_SOUND_VOLUME = .1
    DEFAULT_MAX_DELTA = 1. / 20.
    DEFAULT_SHADERS = True

    def __init__(self):
        super(PandaController, self).__init__()
        self._timer = Timer()
        self._timer.max_delta = self.DEFAULT_MAX_DELTA
        self._tasks = task.TaskGroup()
        self._tasks.add(self._panda_task)
        self._music = None
        self._mouse_task = None
        self._relative_mouse = False

    @property
    def timer(self):
        return self._timer

    @property
    def tasks(self):
        return self._tasks

    def start(self, title):
        cfg = GlobalConf().child('panda')

        self.set_defaults(cfg)
        self.base = ShowBase()
        self.base.disableMouse()
        self.audio = self.base.sfxManagerList[0]
        self.audio3d = Audio3DManager(self.audio, camera)
        self.audio3d.setListenerVelocityAuto()
        self.audio3d.setDropOffFactor(0.1)  # HACK

        self.create_properties(title)
        self.update_properties(cfg)
        self.listen_conf(cfg)

        loadPrcFileData("", "interpolate-frames 1")
        loadPrcFileData("", "support-threads #f")
        path = getModelPath()
        path.prependPath('./data')

        self.base.enableParticles()

    def loop(self):
        self._timer.reset()
        self._timer.loop(self._loop_fn)

    def _loop_fn(self, timer):
        task_count = 1  # _panda_task
        if self._relative_mouse:
            task_count += 1  # _mouse_task
        if self._tasks.count > task_count:
            return self._tasks.update(timer)
        return False

    def set_defaults(self, cfg):
        cfg.child('fps').default(self.DEFAULT_FPS)
        cfg.child('width').default(self.DEFAULT_WIDTH)
        cfg.child('height').default(self.DEFAULT_HEIGHT)
        cfg.child('fullscreen').default(self.DEFAULT_FULLSCREEN)
        cfg.child('frame-meter').default(self.DEFAULT_FRAME_METER)
        cfg.child('music-volume').default(self.DEFAULT_MUSIC_VOLUME)
        cfg.child('sound-volume').default(self.DEFAULT_SOUND_VOLUME)

    def listen_conf(self, cfg):
        cfg.on_conf_nudge += self.update_properties

        cfg.child('fps').on_conf_change += self.update_fps
        cfg.child('frame-meter').on_conf_change += self.update_frame_meter
        cfg.child('music-volume').on_conf_change += self.update_music_volume
        cfg.child('sound-volume').on_conf_change += self.update_sound_volume

        self.audio.setVolume(cfg.child('sound-volume').value)

    def create_properties(self, title):
        self._prop = WindowProperties()
        self._prop.setTitle(title)

    def relative_mouse(self):
        if not self._relative_mouse:
            self._prop.setCursorHidden(True)
            self._prop.setMouseMode(WindowProperties.MRelative)
            self.base.win.requestProperties(self._prop)
            self._mouse_task = self._tasks.add(MouseTask())
            self._mouse_task.on_mouse_move += lambda x, y: \
                messenger.send ('mouse-move', [(x, y)])
            self._relative_mouse = True

    def absolute_mouse(self):
        if self._relative_mouse:
            self._relative_mouse = False
            if self._mouse_task:
                self._mouse_task.kill()
            self._prop.setCursorHidden(False)
            self._prop.setMouseMode(WindowProperties.MAbsolute)
            self.base.win.requestProperties(self._prop)

    def has_shaders(self):
        return self.base.win.getGsg().getSupportsBasicShaders() == 0

    def update_properties(self, cfg):
        self._prop.setSize(cfg.child('width').value, cfg.child('height').value)
        self._prop.setFullscreen(cfg.child('fullscreen').value)
        self.base.win.requestProperties(self._prop)

        self._timer.fps = cfg.child('fps').value
        self.base.setFrameRateMeter(cfg.child('frame-meter').value)

    def update_frame_meter(self, cfg):
        self.base.setFrameRateMeter(cfg.value)

    def update_fps(self, cfg):
        self._timer.fps = cfg.value

    def update_music_volume(self, cfg):
        if self._music:
            self._music.setVolume(cfg.value)

    def update_sound_volume(self, cfg):
        if self.audio:
            self.audio.setVolume(cfg.value)

    def _panda_task(self, timer):
        taskMgr.step()
        return task.running

    def set_background_color(self, *color):
        base.setBackgroundColor(*color)

    def loop_music(self, file):
        if self._music:
            self._music.setLoop(False)
            self.tasks.add(
                task.sequence(
                    task.linear(self._music.setVolume, self._music.getVolume(),
                                0.0)))

        volume = GlobalConf().path('panda.music-volume').value
        self._music = loader.loadSfx(file)
        self._music.setLoop(True)
        self.tasks.add(
            task.sequence(
                task.linear(self._music.setVolume, 0.0, volume, init=True)))
        self._music.play()
Example #54
0
    def __init__(self):
        ShowBase.__init__(self)

        # The standard title text that's in every tutorial
        # Things to note:
        #-fg represents the forground color of the text in (r,g,b,a) format
        #-pos  represents the position of the text on the screen.
        #      The coordinate system is a x-y based wih 0,0 as the center of the
        #      screen
        #-align sets the alingment of the text relative to the pos argument.
        #      Default is center align.
        #-scale set the scale of the text
        #-mayChange argument lets us change the text later in the program.
        #       By default mayChange is set to 0. Trying to change text when
        #       mayChange is set to 0 will cause the program to crash.

        #self.title = OnscreenText(
        #    text="Virtue Ethics Simulation",
        #    parent=base.a2dBottomRight, align=TextNode.A_right,
        #    style=1, fg=(0, 0, 255, 1), bg=(255,0,0,1), pos=(-0.1, 0.1), scale=.07)

        self.skeyEventText = self.genLabelText(
            "[S]: Turn on select agent [OFF]", 1)
        self.genLabelText("[A/D]: Choose selected agent", 2)

        self.selectText1 = self.selectLabelText("", 1)
        self.selectText2 = self.selectLabelText("", 2)
        self.selectText3 = self.selectLabelText("", 3)
        self.selectText4 = self.selectLabelText("", 4)
        self.selectText5 = self.selectLabelText("", 5)
        self.selectText6 = self.selectLabelText("", 6)
        self.selectText7 = self.selectLabelText("", 7)
        self.selectText8 = self.selectLabelText("", 8)

        self.selectText9 = self.RuleTextA("", 6)
        self.selectText10 = self.RuleTextA("", 5)
        self.selectText11 = self.RuleTextA("", 4)
        self.selectText12 = self.RuleTextA("", 3)
        self.selectText13 = self.RuleTextA("", 2)
        self.selectText14 = self.RuleTextA("", 1)

        self.pursuitText = self.pursuitTextA("", 7, (1, 1, 1, 1))
        self.pursuitTextP = self.pursuitTextA("", 5, (255, 0, 0, 0.8))
        self.pursuitTextE = self.pursuitTextA("", 4, (0, 1, 0, 0.8))
        self.pursuitTextC = self.pursuitTextA("", 3, (0, 1, 1, 0.8))
        self.pursuitTextS = self.pursuitTextA("", 2, (1, 1, 0, 0.8))
        self.pursuitTextT = self.pursuitTextA("", 1, (1, 1, 1, 1))

        #self.RuleText = self.RuleTextA("Rules known:\nTesting", 1)

        #self.avoidText2 = self.avoidTextB("Second object being avoided\nTesting\nTesting\nTesting", 5)
        #self.avoidText3 = self.avoidTextC("Second object being avoided\nTesting\nTesting\nTesting", 5)

        # A dictionary of what keys are currently being pressed
        # The key events update this list, and our task will query it as input
        self.keys = {
            "s": 0,
            "a": 0,
            "d": 0,
            "up": 0,
            "down": 0,
            "left": 0,
            "right": 0
        }

        #The keys that will be accepted for input
        self.accept("escape", sys.exit)
        self.accept("s", self.setKey, ["s", 1])
        self.accept("a", self.setKey, ["a", 1])
        self.accept("d", self.setKey, ["d", 1])
        self.accept("arrow_up", self.setKey, ["up", 1])
        self.accept("arrow_down", self.setKey, ["down", 1])
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up-up", self.setKey, ["up", 0])
        self.accept("arrow_down-up", self.setKey, ["down", 0])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])

        #At the start the select screen is off
        self.selectScreen = False

        #Selected agent when the select screen is turned on
        self.selectAgent = 0

        #Camera control
        self.disableMouse()
        self.cameraDistance = 150
        self.cameraAdjust = 20
        #Isometric view
        self.camera.setPos(int(math.sqrt(3) * self.cameraDistance / 2), 0,
                           self.cameraDistance / 2)
        self.camera.lookAt(0, 0, 0)

        # Load the environment model.
        #self.scene = self.loader.loadModel("Level")
        # Reparent the model to render.
        #self.scene.reparentTo(self.render)
        # Apply scale and position transforms on the model.
        #self.scene.setScale(5, 5, 5)
        #self.scene.setPos(-8, 42, 0)

        # The various rules that can be cognitively learned
        self.rule1Text = "Eating 1 food is good for me."
        self.rule2Text = "Eating 2 food is very good for me."
        self.rule2aText = "Eating 2 food is bad for others."
        self.rule3Text = "Eating 3 food is bad for me."
        self.rule3aText = "Eating 3 food is bad for others."
        #self.rule3bText = "Eating 3 food is bad for me."

        #Create the moving agents and their data
        self.agentlist = []
        self.agentDataList = []
        self.agentArrowList = []
        self.agentArrowExpire = [
        ]  # To keep track of when the arrows should disappear above
        for i in range(NUMBER_AGENTS):
            self.agentlist.append(Actor("Ralph", {"walk": "Ralph-Walk"}))
            self.agentlist[i].reparentTo(self.render)
            self.agentlist[i].setScale(8, 8, 8)
            self.agentlist[i].setPos(random.randint(-SIM_AREA, SIM_AREA),
                                     random.randint(-SIM_AREA, SIM_AREA), 0)
            self.agentlist[i].loop("walk")
            # Create corresponding agent data object
            self.agentDataList.append(AgentData())
            # Create arrow object to indicate punishment
            self.agentArrowList.append(
                Actor("squarrow-model", {"anim": "squarrow-anim"}))
            self.agentArrowList[i].reparentTo(self.agentlist[i])
            self.agentArrowList[i].setScale(0.1, 0.1, 0.1)
            self.agentArrowList[i].setColor(1, 0, 0)
            self.agentArrowList[i].setPos(0, 0, 0)
            self.agentArrowList[i].loop("anim")
            self.agentArrowExpire.append(0.0)

        #Create food resource models
        self.foodlist = []
        self.foodDataList = []
        #self.mars_tex = loader.loadTexture("mars_1k_tex.jpg")
        for i in range(NUMBER_FOOD):
            self.foodlist.append(loader.loadModel("package"))
            #self.foodlist[i].setTexture(self.mars_tex, 1)
            self.foodlist[i].reparentTo(self.render)
            self.foodlist[i].setScale(0.03, 0.03, 0.03)
            self.foodlist[i].setPos(random.randint(-SIM_AREA, SIM_AREA),
                                    random.randint(-SIM_AREA, SIM_AREA), 0)
            #self.foodlist[i].setColor(0, 0, 1)
            # Create corresponding food data object
            self.foodDataList.append(FoodData())
            # Create instances depending on amount
            if (self.foodDataList[-1].amount > 1):
                for x in range(1, self.foodDataList[-1].amount):
                    duplicate = (loader.loadModel("package"))
                    #duplicate.setTexture(self.mars_tex, 1)
                    #if (self.foodDataList[-1].amount == 3):
                    #    self.foodlist[i].setColor(1, 1, 0)
                    #else:
                    #    self.foodlist[i].setColor(1, 0, 0)
                    duplicate.reparentTo(self.foodlist[i])
                    duplicate.setPos(0, 0, x * 55)  #put it above

        # Set AI
        #Creating AI World
        self.AIworld = AIWorld(render)

        # Give AI behaviors to each agent
        self.AIchar = []
        self.AIbehaviors = []
        for i in range(NUMBER_AGENTS):
            self.AIchar.append(
                AICharacter("wanderer" + str(i), self.agentlist[i], 10, 1, 5))
            self.AIworld.addAiChar(self.AIchar[i])
            self.AIbehaviors.append(self.AIchar[i].getAiBehaviors())
            #The basic behavior is wander
            self.AIbehaviors[i].wander(5, 0, WANDER_RADIUS, 0.3)

        #Stores the time for food regrowth, metabolism(losing health)
        self.nextfoodregrowth = 0.0
        self.nextMetabolize = 0.0

        #Call the main game loop
        taskMgr.add(self.GameLoop, "GameLoop")
Example #55
0
    def __init__(self):
        ShowBase.__init__(self)

        # Load the environment model.
        self.scene = self.loader.loadModel("models/environment")
        # Reparent the model to render.
        self.scene.reparentTo(self.render)
        # Apply scale and position transforms on the model.
        self.scene.setScale(0.25, 0.25, 0.25)
        self.scene.setPos(-8, 42, 0)

        # Add the spinCameraTask procedure to the task manager.
        self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")

        # Load and transform the panda actor.
        self.pandaActor = Actor("models/panda-model",
                                {"walk": "models/panda-walk4"})
        self.pandaActor.setScale(0.005, 0.005, 0.005)
        self.pandaActor.reparentTo(self.render)
        # Loop its animation.
        self.pandaActor.loop("walk")

        ambLight = AmbientLight('ambient')
        ambLight.setColor(Vec4(0.3, 0.2, 0.2, 1.0))
        ambNode = self.render.attachNewNode(ambLight)
        self.render.setLight(ambNode)

        dirLight = DirectionalLight('directional')
        dirLight.setColor(Vec4(0.3, 0.9, 0.3, 1.0))
        dirNode = self.render.attachNewNode(dirLight)
        dirNode.setHpr(60, 0, 90)
        self.render.setLight(dirNode)

        pntLight = PointLight('point')
        pntLight.setColor(Vec4(3.9, 3.9, 3.8, 1.0))
        pntNode = self.render.attachNewNode(pntLight)
        pntNode.setPos(0, 0, 15)
        self.pandaActor.setLight(pntNode)

        sptLight = Spotlight('spot')
        sptLens = PerspectiveLens()
        sptLight.setLens(sptLens)
        sptLight.setColor(Vec4(1.0, 0.4, 0.4, 1.0))
        sptLight.setShadowCaster(True)
        sptNode = self.render.attachNewNode(sptLight)
        sptNode.setPos(-10, -10, 20)
        sptNode.lookAt(self.pandaActor)
        self.render.setLight(sptNode)

        self.render.setShaderAuto()

        self.activeRamp = 0
        toggle = Func(self.toggleRamp)
        switcher = Sequence(toggle, Wait(3))
        switcher.loop()

        # Add a dummy node to the camera to hold the projection matrix
        self.proj_dummy = self.cam.attach_new_node("proj-dummy")

        # Set up a node in 2-D space to hold the drawn lines
        self.line_node = GeomNode("lines")
        self.line_path = self.render2d.attach_new_node(self.line_node)

        self.taskMgr.add(self.draw_box, "draw-box")

        #self.annotations = Annotations();
        self.annotations = {'count': 0, 'items': []}
        self.wroteAnnotations = False
Example #56
0
    def __init__(self):

        ShowBase.__init__(self)
        global number_player
        global sizeboard_entry
        global number_turn_entry

        self.keyMap = {
            "up": False,
            "a": False,
            "z": False,
        }

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

        self.font = loader.loadFont("Fonts/Roboto-Bold.ttf")

        self.titleMenu = DirectDialog(frameSize=(-1.5, 1.5, -1.5, 1.5),
                                      fadeScreen=0.4,
                                      relief=DGG.FLAT,
                                      frameTexture="UI/background.jpg")
        self.optionMenu = DirectDialog(frameSize=(-1.5, 1.5, -1.5, 1.5),
                                       fadeScreen=0.4,
                                       relief=DGG.FLAT,
                                       frameTexture="UI/background.jpg")
        self.scoreboardResult = DirectDialog(frameSize=(-1.5, 1.5, -1.5, 1.5),
                                             fadeScreen=0.4,
                                             relief=DGG.FLAT,
                                             frameTexture="UI/end.jpg")

        self.buttonImages = (
            loader.loadTexture("UI/button.png")
        )

        def addPlayer():
            global number_player
            if(number_player < 4):
                number_player += 1
                number_player_text.setText(
                    "Number of Player : " + str(number_player))

        def removePlayer():
            global number_player
            if(number_player > 1):
                number_player -= 1
                number_player_text.setText(
                    "Number of Player : " + str(number_player))

        title = DirectLabel(text="ChariotParty",
                            scale=0.1,
                            pos=(0, 0, 0),
                            parent=self.titleMenu,
                            relief=None,
                            text_font=self.font,
                            text_fg=(76, 178, 178, 1))

        btn = DirectButton(text="Start",
                           command=self.begin,
                           text_fg=(76, 178, 178, 1),
                           pos=(-0.3, 0, -0.2),
                           parent=self.titleMenu,
                           scale=0.07,
                           text_font=self.font,
                           clickSound=loader.loadSfx("Sounds/click.ogg"),
                           frameTexture=self.buttonImages,
                           frameSize=(-4, 4, -1, 1),
                           text_scale=0.75,
                           relief=DGG.FLAT,
                           text_pos=(0, -0.2))
        btn.setTransparency(True)

        btn = DirectButton(text="Quit",
                           command=self.quit,
                           text_fg=(76, 178, 178, 1),
                           pos=(0.3, 0, -0.2),
                           parent=self.titleMenu,
                           scale=0.07,
                           text_font=self.font,
                           clickSound=loader.loadSfx("Sounds/click.ogg"),
                           frameTexture=self.buttonImages,
                           frameSize=(-4, 4, -1, 1),
                           text_scale=0.75,
                           relief=DGG.FLAT,
                           text_pos=(0, -0.2))
        btn.setTransparency(True)

        btn = DirectButton(text="Start",
                           command=self.startGame,
                           text_fg=(76, 178, 178, 1),
                           pos=(0, 0, -0.2),
                           parent=self.optionMenu,
                           scale=0.07,
                           text_font=self.font,
                           clickSound=loader.loadSfx("Sounds/click.ogg"),
                           frameTexture=self.buttonImages,
                           frameSize=(-4, 4, -1, 1),
                           text_scale=0.75,
                           relief=DGG.FLAT,
                           text_pos=(0, -0.2))
        btn.setTransparency(True)

        btn = DirectButton(text="+",
                           command=addPlayer,
                           text_fg=(76, 178, 178, 1),
                           pos=(-0.1, 0, 0.41),
                           parent=self.optionMenu,
                           scale=0.07,
                           text_font=self.font,
                           clickSound=loader.loadSfx("Sounds/click.ogg"),
                           frameTexture=self.buttonImages,
                           frameSize=(-1, 1, -1,    1),
                           text_scale=0.75,
                           relief=DGG.FLAT,
                           text_pos=(0, -0.2))
        btn.setTransparency(True)

        btn = DirectButton(text="-",
                           command=removePlayer,
                           text_fg=(76, 178, 178, 1),
                           pos=(0.1, 0, 0.41),
                           parent=self.optionMenu,
                           scale=0.07,
                           text_font=self.font,
                           clickSound=loader.loadSfx("Sounds/click.ogg"),
                           frameTexture=self.buttonImages,
                           frameSize=(-1, 1, -1, 1),
                           text_scale=0.75,
                           relief=DGG.FLAT,
                           text_pos=(0, -0.2))
        btn.setTransparency(True)

        btn = DirectButton(text="Export",
                           command=self.exportResult,
                           text_fg=(76, 178, 178, 1),
                           pos=(-0.3, 0, -0.4),
                           parent=self.scoreboardResult,
                           scale=0.07,
                           text_font=self.font,
                           clickSound=loader.loadSfx("Sounds/click.ogg"),
                           frameTexture=self.buttonImages,
                           frameSize=(-4, 4, -1, 1),
                           text_scale=0.75,
                           relief=DGG.FLAT,
                           text_pos=(0, -0.2))
        btn.setTransparency(True)

        btn = DirectButton(text="Restart",
                           command=self.restartGame,
                           text_fg=(76, 178, 178, 1),
                           pos=(0.3, 0, -0.4),
                           parent=self.scoreboardResult,
                           scale=0.07,
                           text_font=self.font,
                           clickSound=loader.loadSfx("Sounds/click.ogg"),
                           frameTexture=self.buttonImages,
                           frameSize=(-4, 4, -1, 1),
                           text_scale=0.75,
                           relief=DGG.FLAT,
                           text_pos=(0, -0.2))
        btn.setTransparency(True)

        # add some text

        number_player_text = OnscreenText(text=f"Number of player : {number_player}", pos=(0, 0.50),
                                          scale=0.07, fg=(255, 250, 250, 1), align=TextNode.ACenter, mayChange=1, parent=self.optionMenu)

        number_turn_text = OnscreenText(text="Number of turn :", pos=(0, 0.30),
                                        scale=0.07, fg=(255, 250, 250, 1), align=TextNode.ACenter, mayChange=1, parent=self.optionMenu)

        size_board_text = OnscreenText(text="Board size :", pos=(0, 0.10),
                                       scale=0.07, fg=(255, 250, 250, 1), align=TextNode.ACenter, mayChange=1, parent=self.optionMenu)

        numberTurn = OnscreenText(text=number_turn_entry, pos=(1, 0.5),
                                  scale=0.07, fg=(255, 250, 250, 1), align=TextNode.ACenter, mayChange=1, parent=self.optionMenu)
        sizeBoard = OnscreenText(text=sizeboard_entry, pos=(1, 0),
                                 scale=0.07, fg=(255, 250, 250, 1), align=TextNode.ACenter, mayChange=1, parent=self.optionMenu)

        # callback function to set  text

        def setNumberTurn(textEntered):
            numberTurn.setText(textEntered)

        def setSizeBoard(textEntered):
            sizeBoard.setText(textEntered)

        # clear the text

        def clearTextSize():
            sizeboard_entry.enterText('')

        def clearTextTurn():
            number_turn_entry.enterText('')

        # add text entry
        sizeboard_entry = DirectEntry(text="", width=15, pos=(-0.35, 0, 0), scale=.05, command=setSizeBoard,
                                      initialText="", numLines=1, focus=1, focusInCommand=clearTextSize, clickSound=loader.loadSfx("Sounds/click.ogg"), parent=self.optionMenu,)
        number_turn_entry = DirectEntry(text="", scale=.05, width=15, pos=(-0.35, 0, 0.20), command=setNumberTurn,
                                        initialText="", numLines=1, focusInCommand=clearTextTurn, parent=self.optionMenu)

        self.optionMenu.hide()
        music = loader.loadMusic("Sounds/Musics/ambiance.ogg")
        square = loader.loadModel(
            "Models/cube.egg")

        # setPos(x,y,z) start x:right y:forward z:up
        self.camera.setPos(4, -25, 20)
        self.camera.setHpr(0, -30, 0)

        music.setLoop(True)
        music.play()
        self.scoreboardResult.hide()
        self.accept("w", self.updateKeyMap, ["up", True])
        self.accept("w-up", self.updateKeyMap, ["up", False])

        # Task manager to listen to keydown event
        updateTask = taskMgr.add(self.update, "update")
Example #57
0
    def __init__(self):
        ShowBase.__init__(self)
        self.disableMouse()
        self.accept('escape', sys.exit)
        self.accept('a', self.IncreaseMaskRadius)
        self.accept('s', self.DecreaseMaskRadius)
        self.accept('z', self.setGray)
        self.accept('x', self.setHigh)
        self.accept('c', self.setLow)
        self.accept('v', self.increase_brightness)
        self.accept('b', self.decrease_brightness)
        x = np.linspace(0, 2 * np.pi, 100)
        y = (np.sign(np.sin(x)) + 1) / 2 * 255

        self.tex = Texture("texture")
        self.tex.setMagfilter(Texture.FTLinear)

        self.tex.setup2dTexture(100, 1, Texture.TUnsignedByte,
                                Texture.FLuminance)
        memoryview(self.tex.modify_ram_image())[:] = y.astype(
            np.uint8).tobytes()
        ts0 = TextureStage("mapping texture stage0")
        ts0.setSort(0)

        cm = CardMaker('card')

        self.cardnode = self.render.attachNewNode(cm.generate())

        self.lens1 = PerspectiveLens()
        self.lens1.setNearFar(0.01, 100)
        self.lens1.setFov(90, 90)
        self.cam.node().setLens(self.lens1)

        self.cardnode.setPos(-0.5, 0.5, -0.5)

        self.cardnode.setTexture(ts0, self.tex)

        self.my_shader = Shader.make(Shader.SLGLSL, my_shader[0], my_shader[1])

        self.cardnode.setShader(self.my_shader)
        self.scale = 1
        self.cycles = 15
        self.gratings_brightness = 0.3
        self.mask_radius = 0.2
        # self.cardnode.hide()
        self.cardnode.setShaderInput(
            "x_scale", self.scale *
            1.56)  # this is the measured aspect ratio of the projector
        self.cardnode.setShaderInput("y_scale", self.scale)
        self.cardnode.setShaderInput("cycles", self.cycles)
        self.cardnode.setShaderInput("rot_angle", 0)
        self.cardnode.setShaderInput("rot_angle_increment", np.deg2rad(20))
        self.cardnode.setShaderInput("gratings_brightness",
                                     self.gratings_brightness)
        self.cardnode.setShaderInput("low_contrast", 0.2)
        self.cardnode.setShaderInput("high_contrast", 1)
        self.cardnode.setShaderInput("stimcode", 1)
        self.cardnode.setShaderInput("mask_radius", self.mask_radius)
        self.pulse = 0
        self.pulsetimer = 0
        self.cardnode.setShaderInput('pulse', self.pulse)

        self.setBackgroundColor(self.gratings_brightness,
                                self.gratings_brightness, 0)
        self.cardnode.setShaderInput('stimcode', 3)
        self.phase1 = 0
        self.phase2 = 0
        self.cardnode.setShaderInput('phase1', self.phase1)
        self.cardnode.setShaderInput('phase2', self.phase2)
Example #58
0
        '''
        self._notify = DirectNotify().newCategory("Input")
        self._notify.info("New Keyboard-Object created: %s" % (self))
        base.buttonThrowers[0].node().setButtonUpEvent("button-up")
        base.buttonThrowers[0].node().setButtonDownEvent("button")
        base.accept("button-up", self.setKey, [False])
        base.accept("button", self.setKey, [True])

        self.keys = {}

    # ---------------------------------------------------------

    def setKey(self, value, key):
        '''
        '''
        self.keys[key] = value
        #print [key, self.keys[key]]

    # ---------------------------------------------------------


if __name__ == "__main__":

    #from panda3d.core import *
    #from direct.showbase.ShowBase import ShowBase
    sb = ShowBase()

    k = KeyboardDevice()

    run()
Example #59
0
    def __init__(self):

        # initialize the Panda3D showbase
        self.showbase = showbase = ShowBase()

        # the root node of all DirectGui widgets needs to be pixel2d in order to work
        # with the automatic layout system
        self.gui_root = gui_root = showbase.pixel2d

        # initialize the GUI system
        self.gui = gui = GUI(showbase)

        # Build the GUI layout

        # add a horizontally expanding title bar
        title = "Panda3D: scrolled frame layout example"
        label = DirectLabel(parent=gui_root,
                            text=title,
                            frameSize=(0, 0, -20, 30),
                            text_scale=20,
                            borderWidth=(6, 6),
                            relief=DGG.SUNKEN)
        widget = Widget(label)
        borders = (10, 10, 20, 10)
        gui.sizer.add(widget, expand=True, borders=borders)

        # add a horizontally growable sizer that will be expanded horizontally
        self.frame_area_sizer = sizer = Sizer("horizontal")
        borders = (10, 10, 20, 10)
        gui.sizer.add(sizer, expand=True, borders=borders)

        # add a vertically growable subsizer to the previous sizer
        btn_sizer = Sizer("vertical")
        borders = (0, 20, 0, 0)
        sizer.add(btn_sizer, borders=borders)

        # add horizontally expanding buttons to the subsizer;
        # they will have the same width, determined by the initially largest button
        borders = (0, 0, 10, 0)
        text = "Add button to frame"
        button = DirectButton(parent=gui_root,
                              text=text,
                              text_scale=20,
                              borderWidth=(2, 2),
                              command=self.__add_button)
        widget = Widget(button)
        btn_sizer.add(widget, expand=True, borders=borders)
        text = "Add checkbutton to frame"
        button = DirectButton(parent=gui_root,
                              text=text,
                              text_scale=20,
                              borderWidth=(2, 2),
                              command=self.__add_checkbutton)
        widget = Widget(button)
        btn_sizer.add(widget, expand=True, borders=borders)
        text = "Add radiobuttons to frame"
        button = DirectButton(parent=gui_root,
                              text=text,
                              text_scale=20,
                              borderWidth=(2, 2),
                              command=self.__add_radiobuttons)
        widget = Widget(button)
        btn_sizer.add(widget, expand=True, borders=borders)
        text = "Add slider to frame"
        button = DirectButton(parent=gui_root,
                              text=text,
                              text_scale=20,
                              borderWidth=(2, 2),
                              command=self.__add_slider)
        widget = Widget(button)
        btn_sizer.add(widget, expand=True, borders=borders)
        text = "Add sub-layout to frame"
        button = DirectButton(parent=gui_root,
                              text=text,
                              text_scale=20,
                              borderWidth=(2, 2),
                              command=self.__add_layout)
        widget = Widget(button)
        btn_sizer.add(widget, expand=True)
        # add vertical space with a fixed size
        btn_sizer.add((0, 50))
        text = "Destroy frame"
        button = DirectButton(parent=gui_root,
                              text=text,
                              text_scale=25,
                              textMayChange=True,
                              borderWidth=(3, 3),
                              command=self.__toggle_frame)
        self.frame_toggle_button = widget = Widget(button)
        btn_sizer.add(widget, expand=True)

        # add some horizontally stretching space, so that widgets added after it
        # will be pushed to the right
        sizer.add((0, 0), proportion=1.)

        self.has_frame = False
        # add a frame resizable in both directions and taking up two thirds of
        # the available horizontal space (because of the ratio of the proportions
        # used for the frame and the stretching space that was previously added)
        self.__toggle_frame(update_layout=False)

        # add some vertically stretching space to the GUI, so that widgets added
        # after it will be pushed downwards
        gui.sizer.add((0, 0), proportion=1.)

        # add a non-resizing input field, centered horizontally
        field = DirectEntry(parent=gui_root, text_scale=20, focus=1)
        widget = Widget(field)
        gui.sizer.add(widget, alignment="center_h")

        # add another vertically stretching space with the same proportion, to keep
        # the input field centered vertically within the available vertical space
        gui.sizer.add((0, 0), proportion=1.)

        # add a horizontally expanding status bar
        status_text = "GUI ready and awaiting input"
        label = DirectLabel(parent=gui_root,
                            text=status_text,
                            text_pos=(20, -10),
                            textMayChange=1,
                            frameSize=(0, 0, -10, 10),
                            text_scale=20,
                            text_align=TextNode.A_left)
        widget = Widget(label)
        borders = (10, 10, 10, 20)
        gui.sizer.add(widget, expand=True, borders=borders)

        # let the GUI system create the layout
        gui.layout()

        # run the app
        showbase.run()
Example #60
0
#!/usr/bin/env python

import sys

from panda3d.core import Point3

from direct.showbase.ShowBase import ShowBase

s = ShowBase()
base.disable_mouse()
s.accept("escape", sys.exit)

model = base.loader.load_model("models/smiley")
model.reparent_to(base.render)
base.cam.set_pos(0, -20, 0)
base.cam.look_at(0, 0, 0)


def adjust_pos(task):
    if base.mouseWatcherNode.has_mouse():
        model_pos = model.get_pos(base.cam)
        frustum_pos = Point3()
        base.cam.node().get_lens().project(model_pos, frustum_pos)
        mouse_x = base.mouseWatcherNode.get_mouse_x()
        mouse_y = base.mouseWatcherNode.get_mouse_y()
        model_depth = frustum_pos[2]
        new_frustum_pos = Point3(mouse_x, mouse_y, model_depth)
        new_model_pos = Point3()
        base.cam.node().get_lens().extrude_depth(new_frustum_pos,
                                                 new_model_pos)
        model.set_pos(base.cam, new_model_pos)