Example #1
0
class Application(ShowBase):
    def __init__(self):
        # Setup window size and title
        load_prc_file_data("", """
            # win-size 1600 900
            window-title Render Pipeline - Plugin Showcase - AO
        """)

        # Construct the render pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
        self.render_pipeline.daytime_mgr.time = "19:17"
        # self.render_pipeline.daytime_mgr.time = "12:00"

        # Load the scene
        model = self.loader.load_model("scene/Scene.bam")
        model.reparent_to(self.render)
        self.render_pipeline.prepare_scene(model)

        # probe = self.render_pipeline.add_environment_probe()
        # probe.set_pos(0, 0, 4)
        # probe.set_scale(42, 42, 8)
        # probe.parallax_correction = True
        # probe.border_smoothness = 0.001

        # Initialize movement controller, this is a convenience class
        # to provide an improved camera control compared to Panda3Ds default
        # mouse controller.
        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(-17.2912578583, -13.290019989, 6.88211250305),
            Vec3(-39.7285499573, -14.6770210266, 0.0))
        self.controller.setup()
Example #2
0
class Application(ShowBase):
    def __init__(self):
        # Setup window size and title
        load_prc_file_data("", """
            # win-size 1600 900
            window-title Render Pipeline - Material Sample
        """)

        # Construct the render pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
        self.render_pipeline.daytime_mgr.time = "19:17"
        # self.render_pipeline.daytime_mgr.time = "12:00"

        # Load the scene
        model = self.loader.load_model("scene/TestScene.bam")
        model.reparent_to(self.render)

        self.render_pipeline.prepare_scene(model)

        # Enable parallax mapping on the floor
        # self.render_pipeline.set_effect(
        #     model.find("**/FloorPlane"),
        #     "effects/default.yaml", {"parallax_mapping": True}, 100)

        # Initialize movement controller, this is a convenience class
        # to provide an improved camera control compared to Panda3Ds default
        # mouse controller.
        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(-17.2912578583, -13.290019989, 6.88211250305),
            Vec3(-39.7285499573, -14.6770210266, 0.0))
        self.controller.setup()
Example #3
0
class MainApp(ShowBase):
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
            win-size 1600 900
            window-title Render Pipeline - Car Demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # This is a helper class for better camera movement - its not really
        # a rendering element, but it included for convenience
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        self.render_pipeline.daytime_mgr.time = "20:08"

        # Load the scene
        model = loader.loadModel("scene/scene.bam")
        # model = loader.loadModel("scene2/Scene.bam")

        model.reparent_to(render)
        self.render_pipeline.prepare_scene(model)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(
            Vec3(-7.5, -5.3, 1.8), Vec3(-5.9, -4.0, 1.6))
        self.controller.setup()

        base.accept("l", self.tour)

    def tour(self):
        """ Camera flythrough """
        mopath = (
            (Vec3(-10.8645000458, 9.76458263397, 2.13306283951), Vec3(-133.556228638, -4.23447799683, 0.0)),
            (Vec3(-10.6538448334, -5.98406457901, 1.68028640747), Vec3(-59.3999938965, -3.32706642151, 0.0)),
            (Vec3(9.58458328247, -5.63625621796, 2.63269257545), Vec3(58.7906494141, -9.40668964386, 0.0)),
            (Vec3(6.8135137558, 11.0153560638, 2.25509500504), Vec3(148.762527466, -6.41223621368, 0.0)),
            (Vec3(-9.07093334198, 3.65908527374, 1.42396306992), Vec3(245.362503052, -3.59927511215, 0.0)),
            (Vec3(-8.75390911102, -3.82727789879, 0.990055501461), Vec3(296.090484619, -0.604830980301, 0.0)),
        )
        self.controller.play_motion_path(mopath, 3.0)
Example #4
0
class MainBase(ShowBase):

    def __init__(self):

        load_prc_file_data("", "win-size {} {}".format(w, h))
        load_prc_file_data("", "window-type offscreen")

        self.rp = RenderPipeline(self)
        self.rp.load_settings(
            os.path.join(base_path, "pipeline.yaml"))
        self.rp.set_empty_loading_screen()
        self.rp.create()

        self.rp.daytime_mgr.time = 0.45

        model = loader.loadModel("preview.bam")
        model.reparent_to(render)
        model.set_two_sided(True)
        self.rp.prepare_scene(model)

        base.disable_mouse()
        base.camLens.set_fov(110)

        base.render2d.hide()
        base.pixel2d.hide()
        base.pixel2dp.hide()

        main_cam = model.find("**/Camera")
        if main_cam:
            transform_mat = main_cam.get_transform(render).get_mat()
            transform_mat = Mat4.convert_mat(CS_zup_right, CS_yup_right) * transform_mat
            base.camera.set_mat(transform_mat)
        else:
            print("WARNING: No camera found")
Example #5
0
    def __init__(self):
        """ Inits the showbase """

        # Load options
        load_prc_file_data("", """
        model-cache-dir
        fullscreen #f
        win-size 1920 1080
        window-title Render Pipeline by tobspr 
        icon-filename dataGUI/icon.ico
        """)

        # Load render pipeline
        self.render_pipeline = RenderPipeline(self)
        self.render_pipeline.create()


        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(-987.129, -2763.58, 211.47), Vec3(5.21728, 7.84863, 0))
        self.controller.setup()

        # Hotkeys
        self.accept("r", self._reload_shader)

        self.addTask(self.update, "update")
        self.scene_wireframe = False

        self._init_terrain()
        self._reload_shader()
Example #6
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
            win-size 1600 900
            window-title Render Pipeline - Material Sample
        """)

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "19:17"

        # Load the scene
        model = loader.load_model("scene/TestScene.bam")
        model.reparent_to(render)
        self.render_pipeline.prepare_scene(model)

        # Enable parallax mapping on the floor
        self.render_pipeline.set_effect(model.find("**/FloorPlane"),
            "effects/default.yaml", {"parallax_mapping": True}, 100)

        # Initialize movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(-17.2912578583, -13.290019989, 6.88211250305),
            Vec3(-39.7285499573, -14.6770210266, 0.0))
        self.controller.setup()
Example #7
0
class Application(ShowBase):

    def __init__(self):
        # Notice that you must not call ShowBase.__init__ (or super), the render
        # pipeline does that for you.

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes. In case you placed the render
        # pipeline in a subfolder of your project, you have to adjust this.
        sys.path.insert(0, "../../")
        sys.path.insert(0, "../../RenderPipeline")

        # Import render pipeline classes
        from rpcore import RenderPipeline, SpotLight

        # Construct and create the pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
Example #8
0
class Application(ShowBase):

    def __init__(self):
        # Notice that you must not call ShowBase.__init__ (or super), the
        # render pipeline does that for you. If this is unconvenient for you,
        # have a look at the other initialization possibilities.

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes. In case you placed the render
        # pipeline in a subfolder of your project, you have to adjust this.
        sys.path.insert(0, "../../")
        sys.path.insert(0, "../../RenderPipeline")

        # Import the main render pipeline class
        from rpcore import RenderPipeline

        # Construct and create the pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
    def __init__(self):

        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "win-size 1600 900")
        # load_prc_file_data("", "fullscreen #t")
        load_prc_file_data("", "window-title cuboid")
        load_prc_file_data("", "icon-filename res/icon.ico")

        # I found openal works better for me
        load_prc_file_data("", "audio-library-name p3openal_audio")

         # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        # Use the utility script to import the render pipeline classes
        from rpcore import RenderPipeline

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.mount()
        self.render_pipeline.load_settings("/$$rpconfig/pipeline.yaml")
        self.render_pipeline.settings["pipeline.display_debugger"] = False
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        # [Optional] use the default skybox, you can use your own skybox as well
        # self.render_pipeline.create_default_skybox()

        # ------ End of render pipeline code, thats it! ------


        # Set time of day
        self.render_pipeline.daytime_mgr.time = 0.812

        self.menu = Menu(self)
        self.level = Level(self)
        self.cube = Cube(self.level)
        self.camControl = CamControl(self.cube)
        self.gui = GUI(self)
        self.menu.showMenu()
        base.accept("i",self.camControl.zoomIn)
        base.accept("o",self.camControl.zoomOut)
Example #10
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
            win-size 1600 900
            window-title Render Pipeline - Shading Models Demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # This is a helper class for better camera movement - its not really
        # a rendering element, but it included for convenience
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = 0.769

        # Load the scene
        model = loader.loadModel("scene/TestScene.bam")
        model.reparent_to(render)

        self.render_pipeline.prepare_scene(model)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(
            Vec3(6.6, -18.8, 4.5), Vec3(4.7, -16.7, 3.4))
        self.controller.setup()

        base.accept("l", self.tour)
        base.accept("r", self.reload_shaders)
Example #11
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
            win-size 1600 900
            window-title Render Pipeline by tobspr
            stm-max-chunk-count 2048
            gl-coordinate-system default
            stm-max-views 20
            notify-level-linmath error
        """)

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "04:25"

        # Add some environment probe to provide better reflections
        probe = self.render_pipeline.add_environment_probe()
        probe.set_pos(0, 0, 600)
        probe.set_scale(8192 * 2, 8192 * 2, 1000)

        self.terrain_np = render.attach_new_node("terrain")

        heightfield = loader.loadTexture("resources/heightfield.png")

        for x in range(3):
            for y in range(3):
                terrain_node = ShaderTerrainMesh()
                terrain_node.heightfield = heightfield
                terrain_node.target_triangle_width = 6.0
                terrain_node.generate()

                terrain_n = self.terrain_np.attach_new_node(terrain_node)
                terrain_n.set_scale(8192, 8192, 600)
                terrain_n.set_pos(-4096 + (x - 1) * 8192, -4096 + (y - 1) * 8192, 0)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(-12568, -11736, 697), Vec3(-12328, -11357, 679))
        self.controller.setup()

        self.accept("r", self.reload_shaders)
        self.reload_shaders()
Example #12
0
class World(ShowBase):

    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
        win-size 1600 900
        window-title Render Pipeline - Roaming Ralph Demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "7:40"

        # Use a special effect for rendering the scene, this is because the
        # roaming ralph model has no normals or valid materials
        self.render_pipeline.set_effect(render, "scene-effect.yaml", {}, sort=250)

        self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0}
        self.speed = 1.0
        base.win.setClearColor(Vec4(0,0,0,1))

        # Post the instructions

        self.inst1 = addInstructions(0.95, "[ESC]  Quit")
        self.inst4 = addInstructions(0.90, "[W]  Run Ralph Forward")
        self.inst4 = addInstructions(0.85, "[S]  Run Ralph Backward")
        self.inst2 = addInstructions(0.80, "[A]  Rotate Ralph Left")
        self.inst3 = addInstructions(0.75, "[D]  Rotate Ralph Right")
        self.inst6 = addInstructions(0.70, "[Left Arrow]  Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[Right Arrow]  Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("resources/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)


        # Remove wall nodes
        self.environ.find("**/wall").remove_node()

        # Create the main character, Ralph
        self.ralph = Actor("resources/ralph",
                                 {"run":"resources/ralph-run",
                                  "walk":"resources/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(Vec3(-110.9, 29.4, 1.8))

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

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

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("a", self.setKey, ["left",1])
        self.accept("d", self.setKey, ["right",1])
        self.accept("w", self.setKey, ["forward",1])
        self.accept("s", self.setKey, ["backward",1])
        self.accept("arrow_left", self.setKey, ["cam-left",1])
        self.accept("arrow_right", self.setKey, ["cam-right",1])
        self.accept("a-up", self.setKey, ["left",0])
        self.accept("d-up", self.setKey, ["right",0])
        self.accept("w-up", self.setKey, ["forward",0])
        self.accept("s-up", self.setKey, ["backward",0])
        self.accept("arrow_left-up", self.setKey, ["cam-left",0])
        self.accept("arrow_right-up", self.setKey, ["cam-right",0])
        self.accept("=", self.adjustSpeed, [0.25])
        self.accept("+", self.adjustSpeed, [0.25])
        self.accept("-", self.adjustSpeed, [-0.25])

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

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX() + 10,self.ralph.getY() + 10, 2)
        base.camLens.setFov(80)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()

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

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0,0,1000)
        self.camGroundRay.setDirection(0,0,-1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

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

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

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

    #Records the state of the arrow keys
    def setKey(self, key, value):
        self.keyMap[key] = value

    # Adjust movement speed
    def adjustSpeed(self, delta):
        newSpeed = self.speed + delta
        if 0 <= newSpeed <= 3:
          self.speed = newSpeed

    # Accepts arrow keys to move either the player or the menu cursor,
    # Also deals with grid checking and collision detection
    def move(self, task):

        # If the camera-left key is pressed, move camera left.
        # If the camera-right key is pressed, move camera right.

        base.camera.lookAt(self.ralph)
        if (self.keyMap["cam-left"]!=0):
            base.camera.setX(base.camera, +20 * globalClock.getDt())
        if (self.keyMap["cam-right"]!=0):
            base.camera.setX(base.camera, -20 * globalClock.getDt())

        # save ralph's initial position so that we can restore it,
        # in case he falls off the map or runs into something.

        startpos = self.ralph.getPos()

        # If a move-key is pressed, move ralph in the specified direction.

        if (self.keyMap["left"]!=0):
            self.ralph.setH(self.ralph.getH() + 300 * globalClock.getDt())
        elif (self.keyMap["right"]!=0):
            self.ralph.setH(self.ralph.getH() - 300 * globalClock.getDt())
        if (self.keyMap["forward"]!=0):
            self.ralph.setY(self.ralph, -25 * self.speed * globalClock.getDt())
        elif (self.keyMap["backward"]!=0):
            self.ralph.setY(self.ralph, 25 * self.speed * globalClock.getDt())

        # If ralph is moving, loop the run animation.
        # If he is standing still, stop the animation.

        if (self.keyMap["forward"]!=0) or (self.keyMap["backward"]!=0) or \
           (self.keyMap["left"]!=0) or (self.keyMap["right"]!=0):
            if self.isMoving is False:
                self.ralph.loop("run")
                self.isMoving = True
        else:
            if self.isMoving:
                self.ralph.stop()
                self.ralph.pose("walk",5)
                self.isMoving = False

        # If the camera is too far from ralph, move it closer.
        # If the camera is too close to ralph, move it farther.

        camvec = self.ralph.getPos() - base.camera.getPos()
        camvec.setZ(0)
        camdist = camvec.length()
        camvec.normalize()
        if (camdist > 10.0):
            base.camera.setPos(base.camera.getPos() + camvec*(camdist-10))
            camdist = 10.0
        if (camdist < 5.0):
            base.camera.setPos(base.camera.getPos() - camvec*(5-camdist))
            camdist = 5.0

        # Now check for collisions.

        self.cTrav.traverse(render)

        # Adjust ralph's Z coordinate.  If ralph's ray hit terrain,
        # update his Z. If it hit anything else, or didn't hit anything, put
        # him back where he was last frame.

        entries = []
        for i in range(self.ralphGroundHandler.getNumEntries()):
            entry = self.ralphGroundHandler.getEntry(i)
            entries.append(entry)
        if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"):
            self.ralph.setZ(entries[0].getSurfacePoint(render).getZ())
        else:
            self.ralph.setPos(startpos)

        # Keep the camera at one foot above the terrain,
        # or two feet above ralph, whichever is greater.

        entries = []
        for i in range(self.camGroundHandler.getNumEntries()):
            entry = self.camGroundHandler.getEntry(i)
            entries.append(entry)
        if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"):
            base.camera.setZ(entries[0].getSurfacePoint(render).getZ()+1.0)
        if (base.camera.getZ() < self.ralph.getZ() + 2.0):
            base.camera.setZ(self.ralph.getZ() + 2.0)

        # The camera should look in ralph's direction,
        # but it should also try to stay horizontal, so look at
        # a floater which hovers above ralph's head.

        self.floater.setPos(self.ralph.getPos())
        self.floater.setZ(self.ralph.getZ() + 2.0)
        base.camera.lookAt(self.floater)

        return task.cont
Example #13
0
class Application(ShowBase):
    '''
	The default Application class which holds the code for
	Panda3D to run the game
	'''
    def __init__(self):
        #Modify the Panda3D config on-the-fly
        #In this case, edit the window title
        load_prc_file_data(
            "", """window-title PoultryGeist
								  threading-model /Draw
								  multisamples 2
								  framebuffer-multisample 1
							   """)

        # Construct and create the pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        self.width, self.height = (800, 600)
        render.setAntialias(AntialiasAttrib.MAuto)

        # Set the model quality, (low or high)
        self.quality = "low"
        print("[>] PoultryGeist:\t      Setting Model Resolution to {}".format(
            self.quality.upper()))

        # Set the time
        self.render_pipeline.daytime_mgr.time = "20:15"

        # Turn off normal mouse controls
        self.disableMouse()

        # Hide the cursor
        props = WindowProperties()
        props.setCursorHidden(True)
        props.setMouseMode(WindowProperties.M_relative)
        # Lower the FOV to make the game more difficult
        self.win.requestProperties(props)
        self.camLens.setFov(90)

        # Register the buttons for movement
        self.w_button = KeyboardButton.ascii_key('w'.encode())
        self.s_button = KeyboardButton.ascii_key('s'.encode())

        self.switch_button = KeyboardButton.ascii_key('p'.encode())

        # Initialise the SceneManager
        self.sceneMgr = SceneManager(self)

        # Add the sceneMgr events to run as a task
        taskMgr.add(self.sceneMgr.runSceneTasks, "scene-tasks")

    def move(self, forward, dir, elapsed):
        '''
		Move the camera forward or backwards
		For testing ONLY at the moment
		'''
        if forward:
            self.sceneMgr.focus += dir * elapsed * 30
        else:
            self.sceneMgr.focus -= dir * elapsed * 30
        # Set the position of the camera based on the direction
        self.camera.setPos(self.sceneMgr.focus - (dir * 5))
Example #14
0
class MainApp(ShowBase):

    """ Main Testing Showbase """

    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
        win-size 1600 900
        window-title Render Pipeline - Benchmark
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, PointLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # This is a helper class for better camera movement - its not really
        # a rendering element, but it included for convenience
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "17:41"

        self.camLens.set_fov(90)

        model = self.loader.load_model("scene/Scene.bam")
        model.reparent_to(self.render)

        model.flatten_strong()
        num_rows = 255

        img = PNMImage("scene/lights.png")

        for x in range(num_rows):
            for y in range(num_rows):
                light = PointLight()
                # light.direction = (0, 0, -1)
                # light.fov = 60
                # light.set_color_from_temperature(randint(2000, 20000))
                light.color = img.get_xel(x * 1, y * 1)
                light.energy = 5000 * (x / num_rows)
                light.pos = Vec3(-(x - num_rows // 2) / num_rows * 1000.0,
                                 (y - num_rows // 2) / num_rows * 1000.0, 2)
                light.radius = 4
                light.inner_radius = 0.5
                light.casts_shadows = False
                light.shadow_map_resolution = 256
                self.render_pipeline.add_light(light)

        self.render_pipeline.prepare_scene(model)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(0, 450, 200), Vec3(0))
        self.controller.setup()

        self.accept("l", self.benchmark)

    def benchmark(self):
        mopath = (
            (Vec3(0.0, 450.0, 200.0), Vec3(180.0, -23.9624938965, 0.0)),
            (Vec3(-190.848297119, 304.510772705, 90.5852050781), Vec3(209.767547607, -19.2802791595, 0.0)),
            (Vec3(-220.74269104, 10.6886262894, 38.7188148499), Vec3(278.595062256, -16.6669464111, -0.00123210949823)),
            (Vec3(-51.2080802917, -188.072463989, 50.2380104065), Vec3(364.747375488, -22.7647132874, 0.0)),
            (Vec3(211.633651733, -190.621276855, 216.169631958), Vec3(413.887451172, -40.1869468689, -0.000118153897347)),
            (Vec3(320.780090332, 303.404388428, 341.834014893), Vec3(495.000030518, -41.1669464111, 0.00174981483724)),
            (Vec3(125.150436401, 294.57989502, 218.834960938), Vec3(444.363800049, 3.80416536331, 0.0)),
            (Vec3(-355.501434326, 153.010559082, 68.0701370239), Vec3(611.234924316, -11.5491724014, 0.000359044410288)),
            (Vec3(-118.283355713, -115.640907288, 6.09887886047), Vec3(637.222473145, -8.82695007324, 0.0)),
            (Vec3(80.3096160889, 12.4637413025, 26.0630741119), Vec3(676.439758301, -24.3980617523, 0.0)),
            (Vec3(69.6195449829, 152.581176758, 14.8633785248), Vec3(881.898925781, -15.3602952957, 0.0)),
            (Vec3(-202.29776001, 109.818962097, 94.7222290039), Vec3(962.381530762, -27.7736206055, 0.00155594921671)),
            (Vec3(6.89826059341, -412.195037842, 221.591659546), Vec3(1080.42749023, -31.1491756439, 0.0)),
            (Vec3(362.657867432, -34.1290054321, 216.362884521), Vec3(1166.81677246, -35.0691833496, 0.0)),
            (Vec3(-0.339450836182, 452.040649414, 199.996627808), Vec3(180.0, -23.9624938965, 0.0)),
        )
        self.controller.play_motion_path(mopath, 3.0)
Example #15
0
    def __init__(self):
        # Setup window size and title
        load_prc_file_data("", """
        win-size 900 600
        window-title Render Pipeline - Lights demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # Import the movement controller, this is a convenience class
        # to provide an improved camera control compared to Panda3Ds default
        # mouse controller.
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "5:20"

        # Configuration variables
        self.half_energy = 5000
        self.lamp_fov = 70
        self.lamp_radius = 10

        # Load the scene
        model = self.loader.load_model("scene/Scene.bam")
        model.reparent_to(self.render)

        # Animate balls, this is for testing the motion blur
        blend_type = "noBlend"
        np = model.find("**/MBRotate")
        np.hprInterval(1.5, Vec3(360, 360, 0), Vec3(0, 0, 0), blendType=blend_type).loop()

        np = model.find("**/MBUpDown")
        np_pos = np.get_pos() - Vec3(0, 0, 2)
        Sequence(
            np.posInterval(0.15, np_pos + Vec3(0, 0, 6), np_pos, blendType=blend_type),
            np.posInterval(0.15, np_pos, np_pos + Vec3(0, 0, 6), blendType=blend_type)).loop()

        np = model.find("**/MBFrontBack")
        np_pos = np.get_pos() - Vec3(0, 0, 2)
        Sequence(
            np.posInterval(0.15, np_pos + Vec3(0, 6, 0), np_pos, blendType=blend_type),
            np.posInterval(0.15, np_pos, np_pos + Vec3(0, 6, 0), blendType=blend_type)).loop()

        np = model.find("**/MBScale")
        Sequence(
            np.scaleInterval(0.2, Vec3(1.5), Vec3(1), blendType=blend_type),
            np.scaleInterval(0.2, Vec3(1), Vec3(1.5), blendType=blend_type)).loop()

        # Generate temperature lamps
        # This shows how to procedurally create lamps. In this case, we
        # base the lights positions on empties created in blender.
        self._lights = []
        light_key = lambda light: int(light.get_name().split("LampLum")[-1])
        lumlamps = sorted(model.find_all_matches("**/LampLum*"), key=light_key)
        for lumlamp in lumlamps:
            lum = float(lumlamp.get_name()[len("LampLum"):])
            light = SpotLight()
            light.direction = (0, -1.5, -1)
            light.fov = self.lamp_fov
            light.set_color_from_temperature(lum * 1000.0)
            light.energy = self.half_energy
            light.pos = lumlamp.get_pos(self.render)
            light.radius = self.lamp_radius
            light.casts_shadows = False
            light.shadow_map_resolution = 256
            self.render_pipeline.add_light(light)

            # Put Pandas on the edges
            if lumlamp in lumlamps[0:2] + lumlamps[-2:]:
                panda = self.loader.load_model("panda")
                panda.reparent_to(self.render)
                panda_mat = Material("default")
                panda_mat.emission = 0
                panda.set_material(panda_mat)
                panda.set_pos(light.pos)
                panda.set_z(0.65)
                panda.set_h(180 + randint(-60, 60))
                panda.set_scale(0.2)
                panda.set_y(panda.get_y() - 3.0)

            self._lights.append(light)

        self.render_pipeline.prepare_scene(model)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(23.9, 42.5, 13.4), Vec3(23.8, 33.4, 10.8))
        self.controller.setup()

        self.addTask(self.update, "update")
    def __init__(self):
        sys.path.insert(0, "../../")
        load_prc_file_data("", "win-size 512 512")
        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "print-pipe-types #f")
        load_prc_file_data("", "notify-level-glgsg error")
        # load_prc_file_data("", "win-size 1024 1024")

        from rpcore import RenderPipeline, PointLight

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.config_dir = "config/"
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        sphere = self.loader.loadModel("res/sphere.bam")
        sphere.reparent_to(self.render)

        self.disableMouse()
        self.camLens.setFov(40)
        self.camLens.setNearFar(0.03, 2000.0)
        self.camera.set_pos(0, -3.5, 0)
        self.camera.look_at(0, -2.5, 0)

        self.render2d.hide()
        self.aspect2d.hide()

        light = PointLight()
        light.pos = 10, -10, 10
        light.radius = 1e20
        light.color = (1, 1, 1)
        light.inner_radius = 4.0
        light.energy = 3
        self.render_pipeline.add_light(light)

        light = PointLight()
        light.pos = -10, -10, 10
        light.radius = 1e20
        light.color = (1, 1, 1)
        light.inner_radius = 4.0
        light.energy = 3
        self.render_pipeline.add_light(light)

        for mat in sphere.find_all_materials():
            mat.roughness = material.roughness
            mat.base_color = Vec4(*(list(material.basecolor) + [1]))
            mat.refractive_index = material.ior

            mat.metallic = 1.0 if material.mat_type == "metallic" else 0.0

            if material.mat_type == "clearcoat":
                mat.emission = (2, 0, 0, 0)
                mat.metallic = 1.0
                mat.refractive_index = 1.51

            if material.mat_type == "foliage":
                mat.emission = (5, 0, 0, 0)
                mat.metallic = 0.0
                mat.refractive_index = 1.51

        for i in range(10):
            self.taskMgr.step()

        self.win.save_screenshot("scene-rp.png")

        self.accept("r", self.reload)
Example #17
0
    def __init__(self, rendering: bool):
        """
        Constructor

        :param rendering: boolean indicating whether to use RenderPipeline or default Panda3d as visualization-module.
        """
        super().__init__(self)
        self.dir = Filename.fromOsSpecific(
            pyrado.PANDA_ASSETS_DIR).getFullpath()

        # Initialize RenderPipeline
        if rendering:
            sys.path.insert(0, pyrado.RENDER_PIPELINE_DIR)
            from rpcore import RenderPipeline

            self.render_pipeline = RenderPipeline()
            self.render_pipeline.pre_showbase_init()
            self.render_pipeline.set_loading_screen_image(
                osp.join(self.dir, "logo.png"))
            self.render_pipeline.settings["pipeline.display_debugger"] = False
            self.render_pipeline.create(self)
            self.render_pipeline.daytime_mgr.time = "17:00"
        else:
            self.render_pipeline = None

        # Activate antialiasing
        self.render.setAntialias(AntialiasAttrib.MAuto)

        # Set window properties
        self.windowProperties = WindowProperties()
        self.windowProperties.setForeground(True)
        self.windowProperties.setTitle("Experiment")

        # Set background color
        self.setBackgroundColor(1, 1, 1)

        # Configuration of the lighting
        self.directionalLight1 = DirectionalLight("directionalLight")
        self.directionalLightNP1 = self.render.attachNewNode(
            self.directionalLight1)
        self.directionalLightNP1.setHpr(0, -8, 0)
        self.render.setLight(self.directionalLightNP1)

        self.directionalLight2 = DirectionalLight("directionalLight")
        self.directionalLightNP2 = self.render.attachNewNode(
            self.directionalLight2)
        self.directionalLightNP2.setHpr(180, -20, 0)
        self.render.setLight(self.directionalLightNP2)

        self.ambientLight = AmbientLight("ambientLight")
        self.ambientLightNP = self.render.attachNewNode(self.ambientLight)
        self.ambientLight.setColor((0.1, 0.1, 0.1, 1))
        self.render.setLight(self.ambientLightNP)

        # Create a text node displaying the physic parameters on the top left of the screen
        self.text = TextNode("parameters")
        self.textNodePath = aspect2d.attachNewNode(self.text)
        self.text.setTextColor(0, 0, 0, 1)  # black
        self.textNodePath.setScale(0.07)
        self.textNodePath.setPos(-1.9, 0, 0.9)

        # Configure trace
        self.trace = LineSegs()
        self.trace.setThickness(3)
        self.trace.setColor(0.8, 0.8, 0.8)  # light grey
        self.lines = self.render.attachNewNode("Lines")
        self.last_pos = None

        # Adds one instance of the update function to the task-manager, thus initializes the animation
        self.taskMgr.add(self.update, "update")
    def __init__(self):
        sys.path.insert(0, "../../")
        load_prc_file_data("", "win-size 512 512")
        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "print-pipe-types #f")
        load_prc_file_data("", "notify-level-glgsg error")
        # load_prc_file_data("", "win-size 1024 1024")

        from rpcore import RenderPipeline, PointLight

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.config_dir = "config/"
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        sphere = loader.loadModel("res/sphere.bam")
        sphere.reparent_to(render)

        self.disableMouse()
        self.camLens.setFov(40)
        self.camLens.setNearFar(0.03, 2000.0)
        self.camera.set_pos(0, -3.5, 0)
        self.camera.look_at(0, -2.5, 0)

        self.render2d.hide()
        self.aspect2d.hide()

        light = PointLight()
        light.pos = 10, -10, 10
        light.radius = 1e20
        light.color = (1, 1, 1)
        light.inner_radius = 4.0
        light.energy = 3
        self.render_pipeline.add_light(light)

        light = PointLight()
        light.pos = -10, -10, 10
        light.radius = 1e20
        light.color = (1, 1, 1)
        light.inner_radius = 4.0
        light.energy = 3
        self.render_pipeline.add_light(light)

        for mat in sphere.find_all_materials():
            mat.roughness = material.roughness
            mat.base_color = Vec4(*(list(material.basecolor) + [1]))
            mat.refractive_index = material.ior

            mat.metallic = 1.0 if material.mat_type == "metallic" else 0.0

            if material.mat_type == "clearcoat":
                mat.emission = (2, 0, 0, 0)
                mat.metallic = 1.0
                mat.refractive_index = 1.51

            if material.mat_type == "foliage":
                mat.emission = (5, 0, 0, 0)
                mat.metallic = 0.0
                mat.refractive_index = 1.51

        for i in range(10):
            self.taskMgr.step()

        self.win.save_screenshot("scene-rp.png")

        base.accept("r", self.reload)
"""

This is an alternative possibility of initializing the RenderPipeline, which
uses the (deprecated!) DirectStart interface. This should not be used anymore,
except for fast prototyping.

"""

import sys

# Insert the pipeline path to the system path, this is required to be
# able to import the pipeline classes. In case you placed the render
# pipeline in a subfolder of your project, you have to adjust this.
sys.path.insert(0, "../../")
sys.path.insert(0, "../../RenderPipeline")

# Import render pipeline classes
from rpcore import RenderPipeline

# Construct and create the pipeline
render_pipeline = RenderPipeline()
render_pipeline.pre_showbase_init()

# Import (deprecated!) DirectStart interface
import direct.directbase.DirectStart
render_pipeline.create(base)

base.run()
Example #20
0
class Application(ShowBase):
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
            win-size 1600 900
            window-title Render Pipeline by tobspr
            stm-max-chunk-count 2048
            gl-coordinate-system default
            stm-max-views 20
            notify-level-linmath error
        """)

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "04:25"

        # Add some environment probe to provide better reflections
        probe = self.render_pipeline.add_environment_probe()
        probe.set_pos(0, 0, 600)
        probe.set_scale(8192 * 2, 8192 * 2, 1000)

        self.terrain_np = render.attach_new_node("terrain")

        heightfield = loader.loadTexture("resources/heightfield.png")

        for x in range(3):
            for y in range(3):
                terrain_node = ShaderTerrainMesh()
                terrain_node.heightfield = heightfield
                terrain_node.target_triangle_width = 6.0
                terrain_node.generate()

                terrain_n = self.terrain_np.attach_new_node(terrain_node)
                terrain_n.set_scale(8192, 8192, 600)
                terrain_n.set_pos(-4096 + (x - 1) * 8192, -4096 + (y - 1) * 8192, 0)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(-12568, -11736, 697), Vec3(-12328, -11357, 679))
        self.controller.setup()

        self.accept("r", self.reload_shaders)
        self.reload_shaders()

    def reload_shaders(self):
        self.render_pipeline.reload_shaders()

        # Set the terrain effect
        self.render_pipeline.set_effect(self.terrain_np, "effects/terrain-effect.yaml", {}, 100)
        base.accept("l", self.tour)


    def tour(self):
        control_points = (
            (Vec3(2755.62084961, 6983.76708984, 506.219055176), Vec3(-179.09147644, 4.30751991272, 0.0)),
            (Vec3(3153.70068359, 5865.30859375, 560.780822754), Vec3(-225.239028931, 3.43641376495, 0.0)),
            (Vec3(2140.57080078, 5625.22753906, 598.345031738), Vec3(-196.022613525, 1.91196918488, 0.0)),
            (Vec3(2598.85961914, 3820.56958008, 627.692993164), Vec3(-272.410125732, 3.32752752304, 0.0)),
            (Vec3(1894.64526367, 3597.39257812, 647.455078125), Vec3(-198.227630615, 0.605303645134, 0.0)),
            (Vec3(1998.48425293, 1870.05358887, 639.38458252), Vec3(-121.682502747, 0.169744253159, 0.0)),
            (Vec3(3910.55297852, 2370.70922852, 518.356567383), Vec3(-130.42376709, 3.65418696404, -0.000583928485867)),
            (Vec3(4830.80761719, 1542.30749512, 501.019073486), Vec3(21.7212314606, 8.00974178314, 0.0)),
            (Vec3(4324.81982422, 2259.2409668, 713.095458984), Vec3(-19.1500263214, -1.68137300014, 0.0)),
            (Vec3(4584.38720703, 3417.75073242, 612.79510498), Vec3(-39.4675331116, -4.94804239273, 0.0)),
            (Vec3(4569.68261719, 4840.80908203, 540.924926758), Vec3(-83.4887771606, 4.08973407745, 0.0)),
            (Vec3(5061.6484375, 5490.93896484, 694.142578125), Vec3(-135.778717041, 0.605291008949, 0.0)),
            (Vec3(6273.03222656, 6343.10546875, 769.735290527), Vec3(-200.826278687, -1.35470712185, 0.0)),
            (Vec3(7355.02832031, 6314.39892578, 1164.65527344), Vec3(-262.645324707, -12.2435855865, 0.0)),
            (Vec3(6321.42431641, 4453.68310547, 898.895202637), Vec3(-322.574157715, -2.22581481934, 0.0)),
            (Vec3(4820.63916016, 4637.07128906, 793.165222168), Vec3(-330.291748047, 0.931967377663, 0.0)),
            (Vec3(2621.3125, 4790.99072266, 691.223144531), Vec3(-423.059020996, 3.10974740982, 0.0)),
            (Vec3(2166.64697266, 5683.75195312, 685.415039062), Vec3(-497.871612549, -1.57248008251, 0.0)),
            (Vec3(2426.64135742, 7216.48974609, 993.247558594), Vec3(-524.17388916, -6.69025611877, 0.0)),
            (Vec3(5014.83398438, 6712.60253906, 963.192810059), Vec3(-596.072387695, -3.31469583511, 0.00446693599224)),
            (Vec3(6107.69970703, 5460.03662109, 820.63104248), Vec3(-650.567199707, 1.04085958004, 0.0)),
        )
        self.controller.play_motion_path(control_points, 3.0)
Example #21
0
    def __init__(self):
        # Setup window size and title
        load_prc_file_data(
            "",
            """
            # win-size 1600 900
            window-title Render Pipeline - Instancing Example
        """,
        )

        # Construct the render pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
        self.render_pipeline.daytime_mgr.time = "19:17"
        # self.render_pipeline.daytime_mgr.time = "12:00"

        # Load the scene
        model = self.loader.load_model("scene/Scene.bam")
        model.reparent_to(self.render)

        # Find the prefab object, we are going to in instance this object
        # multiple times
        prefab = model.find("**/InstancedObjectPrefab")

        # Collect all instances
        matrices = []
        for elem in model.find_all_matches("**/PREFAB*"):
            matrices.append(elem.get_mat(self.render))
            elem.remove_node()

        print("Loaded", len(matrices), "instances!")

        # Allocate storage for the matrices, each matrix has 16 elements,
        # but because one pixel has four components, we need amount * 4 pixels.
        buffer_texture = Texture()
        buffer_texture.setup_buffer_texture(len(matrices) * 4, Texture.T_float, Texture.F_rgba32, GeomEnums.UH_static)

        float_size = len(struct.pack("f", 0.0))
        floats = []

        # Serialize matrices to floats
        ram_image = buffer_texture.modify_ram_image()

        for idx, mat in enumerate(matrices):
            for i in range(4):
                for j in range(4):
                    floats.append(mat.get_cell(i, j))

        # Write the floats to the texture
        data = struct.pack("f" * len(floats), *floats)
        ram_image.set_subdata(0, len(data), data)

        # Load the effect
        self.render_pipeline.set_effect(prefab, "effects/basic_instancing.yaml", {})

        prefab.set_shader_input("InstancingData", buffer_texture)
        prefab.set_instance_count(len(matrices))

        # We have do disable culling, so that all instances stay visible
        prefab.node().set_bounds(OmniBoundingVolume())
        prefab.node().set_final(True)

        # Initialize movement controller, this is a convenience class
        # to provide an improved camera control compared to Panda3Ds default
        # mouse controller.
        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(Vec3(-23.2, -32.5, 5.3), Vec3(-33.8, -8.3, 0.0))
        self.controller.setup()
Example #22
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
        win-size 1600 900
        window-title Render Pipeline - Roaming Ralph Demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "7:40"

        # Use a special effect for rendering the scene, this is because the
        # roaming ralph model has no normals or valid materials
        self.render_pipeline.set_effect(render, "scene-effect.yaml", {}, sort=250)

        self.keyMap = {"left":0, "right":0, "forward":0, "backward":0, "cam-left":0, "cam-right":0}
        self.speed = 1.0
        base.win.setClearColor(Vec4(0,0,0,1))

        # Post the instructions

        self.inst1 = addInstructions(0.95, "[ESC]  Quit")
        self.inst4 = addInstructions(0.90, "[W]  Run Ralph Forward")
        self.inst4 = addInstructions(0.85, "[S]  Run Ralph Backward")
        self.inst2 = addInstructions(0.80, "[A]  Rotate Ralph Left")
        self.inst3 = addInstructions(0.75, "[D]  Rotate Ralph Right")
        self.inst6 = addInstructions(0.70, "[Left Arrow]  Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[Right Arrow]  Rotate Camera Right")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("resources/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)


        # Remove wall nodes
        self.environ.find("**/wall").remove_node()

        # Create the main character, Ralph
        self.ralph = Actor("resources/ralph",
                                 {"run":"resources/ralph-run",
                                  "walk":"resources/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(Vec3(-110.9, 29.4, 1.8))

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

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

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("a", self.setKey, ["left",1])
        self.accept("d", self.setKey, ["right",1])
        self.accept("w", self.setKey, ["forward",1])
        self.accept("s", self.setKey, ["backward",1])
        self.accept("arrow_left", self.setKey, ["cam-left",1])
        self.accept("arrow_right", self.setKey, ["cam-right",1])
        self.accept("a-up", self.setKey, ["left",0])
        self.accept("d-up", self.setKey, ["right",0])
        self.accept("w-up", self.setKey, ["forward",0])
        self.accept("s-up", self.setKey, ["backward",0])
        self.accept("arrow_left-up", self.setKey, ["cam-left",0])
        self.accept("arrow_right-up", self.setKey, ["cam-right",0])
        self.accept("=", self.adjustSpeed, [0.25])
        self.accept("+", self.adjustSpeed, [0.25])
        self.accept("-", self.adjustSpeed, [-0.25])

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

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX() + 10,self.ralph.getY() + 10, 2)
        base.camLens.setFov(80)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()

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

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0,0,1000)
        self.camGroundRay.setDirection(0,0,-1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

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

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

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
Example #23
0
class Application(ShowBase):

    ICOMING_PORT = 62360

    def __init__(self):
        load_prc_file_data("", "win-size 512 512")
        # load_prc_file_data("", "window-type offscreen")
        load_prc_file_data("", "model-cache-dir")
        load_prc_file_data("", "model-cache-textures #f")
        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "alpha-bits 0")
        load_prc_file_data("", "print-pipe-types #f")

        # Construct render pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.config_dir = "config/"
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        self.setup_scene()

        # Disable model caching
        BamCache.get_global_ptr().cache_models = False

        self.update_queue = []
        self.start_listen()

        # Render initial frames
        for i in range(10):
            self.taskMgr.step()

        last_update = 0.0
        self.scene_node = None

        current_lights = []
        current_envprobes = []

        # Wait for updates
        while True:

            # Update once in a while
            curr_time = time.time()
            if curr_time > last_update + 1.0:
                last_update = curr_time
                self.taskMgr.step()

            if self.update_queue:
                if self.scene_node:
                    self.scene_node.remove_node()

                # Only take the latest packet
                payload = self.update_queue.pop(0)
                print("RENDERING:", payload)

                scene = loader.loadModel(Filename.from_os_specific(payload["scene"]))

                for light in scene.find_all_matches("**/+PointLight"):
                    light.remove_node()
                for light in scene.find_all_matches("**/+Spotlight"):
                    light.remove_node()

                # Find camera
                main_cam = scene.find("**/Camera")
                if main_cam:
                    transform_mat = main_cam.get_transform(render).get_mat()
                    transform_mat = Mat4.convert_mat(CS_zup_right, CS_yup_right) * transform_mat
                    base.camera.set_mat(transform_mat)
                else:
                    print("WARNING: No camera found")
                    base.camera.set_pos(0, -3.5, 0)
                    base.camera.look_at(0, -2.5, 0)

                base.camLens.set_fov(64.0)

                self.scene_node = scene
                scene.reparent_to(render)

                # Render scene
                for i in range(8):
                    self.taskMgr.step()

                dest_path = Filename.from_os_specific(payload["dest"])
                print("Saving screenshot to", dest_path)
                self.win.save_screenshot(dest_path)
                self.notify_about_finish(int(payload["pingback_port"]))

    def start_listen(self):
        """ Starts the listener thread """
        thread = Thread(target=self.listener_thread, args=(), name="ListenerThread")
        thread.setDaemon(True)
        thread.start()
        return thread

    def listener_thread(self):
        """ Thread which listens to incoming updates """
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        print("Listening on 127.0.0.1:" + str(self.ICOMING_PORT))
        try:
            sock.bind(("127.0.0.1", self.ICOMING_PORT))
            while True:
                data, addr = sock.recvfrom(8192)
                self.handle_data(data)
        except Exception as msg:
            print("Failed to bind to address! Reason:", msg)
        finally:
            sock.close()

    def handle_data(self, data):
        """ Handles a new update """
        # print("Got:", data)
        unpacked_data = pickle.loads(data)
        # print("Data = ", unpacked_data)
        self.update_queue.append(unpacked_data)

    def notify_about_finish(self, port):
        """ Notifies the caller that the result finished """
        print("Sending finish result to localhost:" + str(port))
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        try:
            sock.connect(("localhost", port))
        except Exception as msg:
            print("Could not send finish result: ", msg)
            return
        sock.sendall(b"done")
        print("Sent done flag.")
        sock.close()

    def setup_scene(self):
        """ Setups the basic scene geometry """
        self.disableMouse()
        self.render2d.hide()
        self.aspect2d.hide()

        light = PointLight()
        light.pos = 20.0, -0.85, -1.31
        light.radius = 100.0
        light.energy = 2500
        light.set_color_from_temperature(8000)
        # self.render_pipeline.add_light(light)

        light = PointLight()
        light.pos = -11.2, -13.84, -9.24
        light.radius = 1e20
        light.set_color_from_temperature(8000)
        light.energy = 2500
Example #24
0
class PandaVis(ShowBase):
    """Base class for all visualizations with panda3d"""
    def __init__(self, rendering: bool):
        """
        Constructor

        :param rendering: boolean indicating whether to use RenderPipeline or default Panda3d as visualization-module.
        """
        super().__init__(self)
        self.dir = Filename.fromOsSpecific(
            pyrado.PANDA_ASSETS_DIR).getFullpath()

        # Initialize RenderPipeline
        if rendering:
            sys.path.insert(0, pyrado.RENDER_PIPELINE_DIR)
            from rpcore import RenderPipeline

            self.render_pipeline = RenderPipeline()
            self.render_pipeline.pre_showbase_init()
            self.render_pipeline.set_loading_screen_image(
                osp.join(self.dir, "logo.png"))
            self.render_pipeline.settings["pipeline.display_debugger"] = False
            self.render_pipeline.create(self)
            self.render_pipeline.daytime_mgr.time = "17:00"
        else:
            self.render_pipeline = None

        # Activate antialiasing
        self.render.setAntialias(AntialiasAttrib.MAuto)

        # Set window properties
        self.windowProperties = WindowProperties()
        self.windowProperties.setForeground(True)
        self.windowProperties.setTitle("Experiment")

        # Set background color
        self.setBackgroundColor(1, 1, 1)

        # Configuration of the lighting
        self.directionalLight1 = DirectionalLight("directionalLight")
        self.directionalLightNP1 = self.render.attachNewNode(
            self.directionalLight1)
        self.directionalLightNP1.setHpr(0, -8, 0)
        self.render.setLight(self.directionalLightNP1)

        self.directionalLight2 = DirectionalLight("directionalLight")
        self.directionalLightNP2 = self.render.attachNewNode(
            self.directionalLight2)
        self.directionalLightNP2.setHpr(180, -20, 0)
        self.render.setLight(self.directionalLightNP2)

        self.ambientLight = AmbientLight("ambientLight")
        self.ambientLightNP = self.render.attachNewNode(self.ambientLight)
        self.ambientLight.setColor((0.1, 0.1, 0.1, 1))
        self.render.setLight(self.ambientLightNP)

        # Create a text node displaying the physic parameters on the top left of the screen
        self.text = TextNode("parameters")
        self.textNodePath = aspect2d.attachNewNode(self.text)
        self.text.setTextColor(0, 0, 0, 1)  # black
        self.textNodePath.setScale(0.07)
        self.textNodePath.setPos(-1.9, 0, 0.9)

        # Configure trace
        self.trace = LineSegs()
        self.trace.setThickness(3)
        self.trace.setColor(0.8, 0.8, 0.8)  # light grey
        self.lines = self.render.attachNewNode("Lines")
        self.last_pos = None

        # Adds one instance of the update function to the task-manager, thus initializes the animation
        self.taskMgr.add(self.update, "update")

    def update(self, task: Task):
        """
        Updates the visualization with every call.

        :param task: Needed by panda3d task manager.
        :return Task.cont: indicates that task should be called again next frame.
        """
        return Task.cont

    def reset(self):
        """
        Resets the the visualization to a certain state, so that in can be run again. Removes the trace.
        """
        self.lines.getChildren().detach()
        self.last_pos = None

    def draw_trace(self, point):
        """
        Draws a line from the last point to the current point

        :param point: Current position of pen. Needs 3 value vector.
        """
        # Check if trace initialized
        if self.last_pos:
            # Set starting point of new line
            self.trace.moveTo(self.last_pos)

        # Draw line to that point
        self.trace.drawTo(point)

        # Save last position of pen
        self.last_pos = point

        # Show drawing
        self.trace_np = NodePath(self.trace.create())
        self.trace_np.reparentTo(self.lines)
Example #25
0
class MainApp(ShowBase):

    def __init__(self):
        # Setup window size and title
        load_prc_file_data("", """
        win-size 900 600
        window-title Render Pipeline - Lights demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # Import the movement controller, this is a convenience class
        # to provide an improved camera control compared to Panda3Ds default
        # mouse controller.
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "5:20"

        # Configuration variables
        self.half_energy = 5000
        self.lamp_fov = 70
        self.lamp_radius = 10

        # Load the scene
        model = self.loader.load_model("scene/Scene.bam")
        model.reparent_to(self.render)

        # Animate balls, this is for testing the motion blur
        blend_type = "noBlend"
        np = model.find("**/MBRotate")
        np.hprInterval(1.5, Vec3(360, 360, 0), Vec3(0, 0, 0), blendType=blend_type).loop()

        np = model.find("**/MBUpDown")
        np_pos = np.get_pos() - Vec3(0, 0, 2)
        Sequence(
            np.posInterval(0.15, np_pos + Vec3(0, 0, 6), np_pos, blendType=blend_type),
            np.posInterval(0.15, np_pos, np_pos + Vec3(0, 0, 6), blendType=blend_type)).loop()

        np = model.find("**/MBFrontBack")
        np_pos = np.get_pos() - Vec3(0, 0, 2)
        Sequence(
            np.posInterval(0.15, np_pos + Vec3(0, 6, 0), np_pos, blendType=blend_type),
            np.posInterval(0.15, np_pos, np_pos + Vec3(0, 6, 0), blendType=blend_type)).loop()

        np = model.find("**/MBScale")
        Sequence(
            np.scaleInterval(0.2, Vec3(1.5), Vec3(1), blendType=blend_type),
            np.scaleInterval(0.2, Vec3(1), Vec3(1.5), blendType=blend_type)).loop()

        # Generate temperature lamps
        # This shows how to procedurally create lamps. In this case, we
        # base the lights positions on empties created in blender.
        self._lights = []
        light_key = lambda light: int(light.get_name().split("LampLum")[-1])
        lumlamps = sorted(model.find_all_matches("**/LampLum*"), key=light_key)
        for lumlamp in lumlamps:
            lum = float(lumlamp.get_name()[len("LampLum"):])
            light = SpotLight()
            light.direction = (0, -1.5, -1)
            light.fov = self.lamp_fov
            light.set_color_from_temperature(lum * 1000.0)
            light.energy = self.half_energy
            light.pos = lumlamp.get_pos(self.render)
            light.radius = self.lamp_radius
            light.casts_shadows = False
            light.shadow_map_resolution = 256
            self.render_pipeline.add_light(light)

            # Put Pandas on the edges
            if lumlamp in lumlamps[0:2] + lumlamps[-2:]:
                panda = self.loader.load_model("panda")
                panda.reparent_to(self.render)
                panda_mat = Material("default")
                panda_mat.emission = 0
                panda.set_material(panda_mat)
                panda.set_pos(light.pos)
                panda.set_z(0.65)
                panda.set_h(180 + randint(-60, 60))
                panda.set_scale(0.2)
                panda.set_y(panda.get_y() - 3.0)

            self._lights.append(light)

        self.render_pipeline.prepare_scene(model)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(23.9, 42.5, 13.4), Vec3(23.8, 33.4, 10.8))
        self.controller.setup()

        self.addTask(self.update, "update")

    def update(self, task):
        """ Update method """
        frame_time = self.taskMgr.globalClock.get_frame_time()

        # Make the lights glow
        for i, light in enumerate(self._lights):
            brightness = math.sin(0.4 * i + frame_time)
            light.energy = max(0, self.half_energy / 2.0 + brightness * self.half_energy)
        return task.cont
Example #26
0
class App(ShowBase):

    def __init__(self):
        """ Inits the showbase """

        # Load options
        load_prc_file_data("", """
        model-cache-dir
        fullscreen #f
        win-size 1920 1080
        window-title Render Pipeline by tobspr 
        icon-filename dataGUI/icon.ico
        """)

        # Load render pipeline
        self.render_pipeline = RenderPipeline(self)
        self.render_pipeline.create()


        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position_hpr(
            Vec3(-987.129, -2763.58, 211.47), Vec3(5.21728, 7.84863, 0))
        self.controller.setup()

        # Hotkeys
        self.accept("r", self._reload_shader)

        self.addTask(self.update, "update")
        self.scene_wireframe = False

        self._init_terrain()
        self._reload_shader()

    def update(self, task):
        """ Main update task """
        self.terrain.update()
        self.terrain_shadow.update()
        return task.cont

    def _reload_shader(self):
        """ Reloads all terrain shaders """
        self.render_pipeline.reload_shaders()

        self.render_pipeline.set_effect(self.terrain.get_node(), "effects/terrain.yaml", {
            "render_gbuffer": True,
            "render_shadows": False,

        })

        self.render_pipeline.set_effect(self.terrain_shadow.get_node(), "effects/terrain_shadow.yaml", {
            "render_gbuffer": False,
            "render_shadows": True,
        }, 5000)


    def _init_terrain(self):
        """ Inits the terrain """

        layout = "Layout0"
        hmap = "data/terrain/" + layout + "/heightmap.png"

        bounds_file = "data/terrain/" + layout + "bounds.bin"

        if not isfile(bounds_file):
            print("Generating terrain bounds ..")
            TerrainMeshRenderer.generate_bounds(hmap, "data/Terrain/" + layout + "bounds.bin")

        terrainOffset = Vec3(-4096, -4096, 70.0)
        terrainScale = Vec3(1.0, 1.0, 700.0)

        self.terrain = TerrainMeshRenderer()
        self.terrain.set_heightfield_size(8192)
        self.terrain.set_culling_enabled(False)
        self.terrain.load_chunk_mesh("core/resources/Chunk32.bam")
        self.terrain.set_focus(base.cam, base.camLens)
        self.terrain.load_bounds(bounds_file)
        self.terrain.set_target_triangle_width(7.0)

        self.terrain.set_pos(terrainOffset)
        self.terrain.set_scale(terrainScale)

        self.terrain.create()

        node = self.terrain.get_node()
        node.reparentTo(render)

        self.terrain_shadow = TerrainMeshRenderer()
        self.terrain_shadow.set_heightfield_size(8192)
        self.terrain_shadow.load_chunk_mesh("core/resources/Chunk32.bam")
        self.terrain_shadow.set_focus(base.cam, base.camLens)
        self.terrain_shadow.set_target_triangle_width(7.0)
        self.terrain_shadow.load_bounds(bounds_file)
        self.terrain_shadow.set_pos(terrainOffset)
        self.terrain_shadow.set_scale(terrainScale)
        self.terrain_shadow.set_culling_enabled(False)
        self.terrain_shadow.create()

        nodeShadow = self.terrain_shadow.get_node()
        nodeShadow.reparentTo(render)

        hmap = loader.loadTexture("data/terrain/" + layout + "/heightmap.png")
        hmap.set_wrap_u(Texture.WM_clamp)
        hmap.set_wrap_v(Texture.WM_clamp)
        hmap.set_format(Texture.F_r16)
        node.set_shader_input("heightmap", hmap)
        nodeShadow.set_shader_input("heightmap", hmap)

        fmap = loader.loadTexture("data/terrain/" + layout + "/flowmap.png")
        fmap.set_wrap_u(Texture.WMClamp)
        fmap.set_wrap_v(Texture.WMClamp)
        node.set_shader_input("flowmap", fmap)

        for material in ['rock', 'grass', 'gravel', 'snow', 'moss']:
            for i in xrange(2):
                tex = loader.loadTexture("data/terrain/Materials/" + material + "_" + str(i+1) + ".png")
                tex.set_wrap_u(Texture.WM_repeat)
                tex.set_wrap_v(Texture.WM_repeat)
                tex.set_format(Texture.F_srgb_alpha)
                tex.set_minfilter(Texture.FT_linear_mipmap_linear)
                tex.set_magfilter(Texture.FT_linear)
                tex.set_anisotropic_degree(16)
                node.set_shader_input(material + ("Diffuse" if i == 0 else "Normal"), tex)
Example #27
0
    def __init__(self):
        
        self.renderPipeline = True
        
        if(self.renderPipeline is True):
            # Notice that you must not call ShowBase.__init__ (or super), the render
            # pipeline does that for you.
    
            # Insert the pipeline path to the system path, this is required to be
            # able to import the pipeline classes. In case you placed the render
            # pipeline in a subfolder of your project, you have to adjust this.
           
            sys.path.insert(0, "Game/render_pipeline")
            #sys.path.insert(0, "../../RenderPipeline")
            
            # Import render pipeline classes
            from rpcore import RenderPipeline, SpotLight
    
            # Construct and create the pipeline
            self.render_pipeline = RenderPipeline()
            self.render_pipeline.create(self)
    
            # Done! You can start setting up your application stuff as regular now.
        else:
            ShowBase.__init__(self)
        

                    
        
        #Debug stuff
        self.debug = True
        if(self.debug is True):
            base.setFrameRateMeter(True)
            render.analyze()
            
        #Disable modifiers Shift+Something/Alt+Something/Ctrl+Something
        base.mouseWatcherNode.set_modifier_buttons(ModifierButtons())
        base.buttonThrowers[0].node().set_modifier_buttons(ModifierButtons())
        

        #Create bullet world
        self.bWorld = bWorld('Game/models/maps/debug.egg')
                    
        #Add task to process physics
        taskMgr.add(self.update, 'updateWorld')

        
        #Set up the player
        self.bController = kCharacterController(self.bWorld.world, self.bWorld.worldNP, 1.75, 1.3, 0, 0.4)
        self.bController.setPos(render, Point3(0, 0, 10))        
        
        self.player = Player(self.bController,"Game/models/player/swifter",.1)
        
        self.keyboardSetup(self.player)
        
        # Create a camera to follow the player.
        #base.oobe()  

        # Attach the camera to the bullet controller's capsule node path 
        camera = Camera(self.bController)
        

        # Accept the Esc key to quit the game.
    
        self.accept("escape", sys.exit)   
Example #28
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
        win-size 1600 900
        window-title Render Pipeline - Material blending example
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # This is a helper class for better camera movement - its not really
        # a rendering element, but it included for convenience
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "6:43"

        # Load the scene
        model = loader.loadModel("scene/Scene.bam")
        model.reparent_to(render)

        # Set the material blending effect on the terrain
        terrain = model.find("**/Terrain")
        self.render_pipeline.set_effect(terrain, "effects/material_blend4.yaml", {
                "parallax_mapping": False, # Not supported
                "alpha_testing": False,
                "normal_mapping": False, # The effect does its own normal mapping
            }, 100)

        # Configure the effect
        terrain.set_shader_input("detail_scale_factor", 4.0)

        # Detailmap blending factors.
        # Blending is calculated as  (detailmap + <add>) ^ <pow>
        # The base map has no blending since it is used as a filling material
        # and blending the base map would cause spots with no material at all.
        terrain.set_shader_input("material_0_pow", 10.0)
        terrain.set_shader_input("material_0_add",  0.5)
        terrain.set_shader_input("material_1_pow", 10.0)
        terrain.set_shader_input("material_1_add",  0.5)
        terrain.set_shader_input("material_2_pow", 10.0)
        terrain.set_shader_input("material_2_add",  0.5)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(-15.2, -9.0, 11.8), Vec3(-12.3, -7.0, 9.7))
        self.controller.setup()
Example #29
0
    def __init__(self):

        # Notice that you must not call ShowBase.__init__ (or super), the
        # render pipeline does that for you. If this is unconvenient for you,
        # have a look at the other initialization possibilities.

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes. In case you placed the render
        # pipeline in a subfolder of your project, you have to adjust this.
        sys.path.insert(0, "../../")
        sys.path.insert(0, "../../RenderPipeline")

        # Import the main render pipeline class
        from rpcore import RenderPipeline, SpotLight
        world = BulletWorld()
        # Construct and create the pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)
        from rpcore.util.movement_controller import MovementController
        self.render_pipeline.daytime_mgr.time = 0.769
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(6.6, -18.8, 4.5),
                                             Vec3(4.7, -16.7, 3.4))
        self.controller.setup()

        # Done! You can start setting up your application stuff as regular now.
        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        self.speed = 1.0
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        #
        # vertex_format = GeomVertexFormat.get_v3n3()
        # vertex_data = GeomVertexData("triangle_data", vertex_format, Geom.UH_static)
        #
        # pos_writer = GeomVertexWriter(vertex_data,"vertex")
        # normal_writer = GeomVertexWriter(vertex_data,"normal")
        # normal = Vec3(0., -1., 0.)
        #
        # pos_writer.add_data3(-1., 0., -1.)
        # pos_writer.add_data3(1., 0., -1.)
        # pos_writer.add_data3(0., 0., 1.)
        #
        # for _ in range(3):
        #     normal_writer.add_data3(normal)
        #
        # prim = GeomTriangles(Geom.UH_static)
        # prim.add_vertices(0, 1, 2)
        #
        # geom = Geom(vertex_data)
        # geom.add_primitive(prim)
        # node = GeomNode("my_triangle")
        # node.add_geom(geom)
        # triangle = NodePath(node)
        # triangle.reparent_to(some_other_nodepath)
        # square1 = create_colored_rect(0, 0, 200, 200)
        # square2 = create_colored_rect(350, 100, 200, 200, (0, 0, 1, 1))
        # square3 = create_colored_rect(-640, -360, 200, 200, (0, 1, 0, 1))
        self.tr1 = create_triangle(0, 0, 0, 0, 200, 0, 0, 0, 200, (0, 1, 0, 1))
        self.tr2 = create_triangle(-500, 0, 0, -300, 200, 0, -300, 0, 200,
                                   (0, 1, 0, 1))
        radius = 60
        height = 40
        shape1 = BulletCylinderShape(radius, height, ZUp)
        shape2 = BulletCylinderShape(Vec3(radius, 0, 0.5 * height), ZUp)
        self.gnode = GeomNode('square')
        # gnode.addGeom(square1)
        # gnode.addGeom(square2)
        # gnode.addGeom(square3)
        height = 1.75
        radius = 0.4
        shape = BulletCapsuleShape(radius, height - 2 * radius, ZUp)
        self.gnode.addGeom(self.tr1)
        self.gnode.addGeom(self.tr2)
        playerNode = BulletCharacterControllerNode(shape, 0.4, 'Player')
        playerNP = self.render.attachNewNode(playerNode)
        playerNP.setPos(0, 0, 14)
        playerNP.setH(45)
        playerNP.setCollideMask(BitMask32.allOn())

        world.attachCharacter(playerNP.node())
        # self.tr1.setPos(400,400, 0)
        # self.render.attachNewNode(self.gnode)

        gnode2 = GeomNode('square2')
        textured_rect = create_textured_rect(-320, 0, 200, 280)
        gnode2.addGeom(textured_rect)

        texture = self.loader.loadTexture("assets/playte.png")
        ship = self.render.attachNewNode(gnode2)
        ship.setTransparency(TransparencyAttrib.MAlpha)
        ship.setTexture(texture)

        # self.ralph = Actor(tr1)

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

        self.accept("escape", sys.exit)
        self.accept("a", self.setKey, ["left", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("p", self.setKey, ["backward", 1])
        self.accept("arrow_left", self.setKey, ["cam-left", 1])
        self.accept("arrow_right", self.setKey, ["cam-right", 1])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("s-up", self.setKey, ["backward", 0])
        self.accept("arrow_left-up", self.setKey, ["cam-left", 0])
        self.accept("arrow_right-up", self.setKey, ["cam-right", 0])
        self.accept("=", self.adjustSpeed, [0.25])
        self.accept("+", self.adjustSpeed, [0.25])
        self.accept("-", self.adjustSpeed, [-0.25])

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

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(5, 5, 0)
        base.camLens.setFov(80)
class GameControl(ShowBase):
    """
    controlling the game itself, menu, editors level selection... it's sorta a fake-fsm.
    did i mention i dont like fsm's and prefer totaly whicked logic instead?
    """
    def __init__(self):

        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "win-size 1600 900")
        # load_prc_file_data("", "fullscreen #t")
        load_prc_file_data("", "window-title cuboid")
        load_prc_file_data("", "icon-filename res/icon.ico")

        # I found openal works better for me
        load_prc_file_data("", "audio-library-name p3openal_audio")

         # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        # Use the utility script to import the render pipeline classes
        from rpcore import RenderPipeline

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.mount()
        self.render_pipeline.load_settings("/$$rpconfig/pipeline.yaml")
        self.render_pipeline.settings["pipeline.display_debugger"] = False
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        # [Optional] use the default skybox, you can use your own skybox as well
        # self.render_pipeline.create_default_skybox()

        # ------ End of render pipeline code, thats it! ------


        # Set time of day
        self.render_pipeline.daytime_mgr.time = 0.812

        self.menu = Menu(self)
        self.level = Level(self)
        self.cube = Cube(self.level)
        self.camControl = CamControl(self.cube)
        self.gui = GUI(self)
        self.menu.showMenu()
        base.accept("i",self.camControl.zoomIn)
        base.accept("o",self.camControl.zoomOut)

    def startGame(self,level=0):
        #debug purpose only: to directly play a certian lvl number
        from sys import argv
        if len(argv) >1:
            level = int(argv[1])

        self.menu.hideMenu()
        self.level.loadLevel(level)
        self.cube.resetCube()
        self.cube.resetStats()
        self.cube.enableGameControl()
        base.accept("escape", self.pauseGame)

    def pauseGame(self):
        self.cube.disableGameControl()
        self.menu.showMenu()
        self.menu.showResume()
        #base.accept("escape", self.resumeGame )

    def resumeGame(self):
        self.menu.hideMenu()
        self.menu.hideResume()
        self.cube.enableGameControl()
        base.accept("escape", self.pauseGame)

    def levelEnd(self):
        self.cube.disableGameControl()
        self.menu.showMenu()
class GameControl(ShowBase):
    """
    controlling the game itself, menu, editors level selection... it's sorta a fake-fsm.
    did i mention i dont like fsm's and prefer totaly whicked logic instead?
    """
    def __init__(self):

        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "win-size 1600 900")
        # load_prc_file_data("", "fullscreen #t")
        load_prc_file_data("", "window-title cuboid")
        load_prc_file_data("", "icon-filename res/icon.ico")

        # I found openal works better for me
        load_prc_file_data("", "audio-library-name p3openal_audio")

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        # Use the utility script to import the render pipeline classes
        from rpcore import RenderPipeline

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.mount()
        self.render_pipeline.load_settings("/$$rpconfig/pipeline.yaml")
        self.render_pipeline.settings["pipeline.display_debugger"] = False
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        # [Optional] use the default skybox, you can use your own skybox as well
        # self.render_pipeline.create_default_skybox()

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = 0.812

        self.menu = Menu(self)
        self.level = Level(self)
        self.cube = Cube(self.level)
        self.camControl = CamControl(self.cube)
        self.gui = GUI(self)
        self.menu.showMenu()
        base.accept("i", self.camControl.zoomIn)
        base.accept("o", self.camControl.zoomOut)

    def startGame(self, level=0):
        #debug purpose only: to directly play a certian lvl number
        from sys import argv
        if len(argv) > 1:
            level = int(argv[1])

        self.menu.hideMenu()
        self.level.loadLevel(level)
        self.cube.resetCube()
        self.cube.resetStats()
        self.cube.enableGameControl()
        base.accept("escape", self.pauseGame)

    def pauseGame(self):
        self.cube.disableGameControl()
        self.menu.showMenu()
        self.menu.showResume()
        #base.accept("escape", self.resumeGame )

    def resumeGame(self):
        self.menu.hideMenu()
        self.menu.hideResume()
        self.cube.enableGameControl()
        base.accept("escape", self.pauseGame)

    def levelEnd(self):
        self.cube.disableGameControl()
        self.menu.showMenu()
    def loadPipeline(self):
        self._pipelineEngine = RenderPipeline()
        self._pipelineEngine.create(self)

        # set the time of day for the daytime cycle
        self._pipelineEngine.daytime_mgr.time = '1:00'
class ToonBase(OTPBase.OTPBase):
    notify = DirectNotifyGlobal.directNotify.newCategory('ToonBase')

    def __init__(self):
        OTPBase.OTPBase.__init__(self)
        self.disableShowbaseMouse()
        self.addCullBins()
        base.debugRunningMultiplier /= OTPGlobals.ToonSpeedFactor
        self.toonChatSounds = self.config.GetBool('toon-chat-sounds', 1)
        self.placeBeforeObjects = config.GetBool('place-before-objects', 1)
        self.endlessQuietZone = False
        self.wantDynamicShadows = 0
        self.exitErrorCode = 0
        camera.setPosHpr(0, 0, 0, 0, 0, 0)
        self.camLens.setMinFov(settings['fieldofview'] / (4. / 3.))
        self.camLens.setNearFar(ToontownGlobals.DefaultCameraNear,
                                ToontownGlobals.DefaultCameraFar)
        self.cam2d.node().setCameraMask(BitMask32.bit(1))
        self.musicManager.setVolume(settings.get("musicVol"))

        for sfm in self.sfxManagerList:
            sfm.setVolume(settings.get("sfxVol"))
        self.sfxActive = settings.get("sfxVol") > 0.0
        self.setBackgroundColor(ToontownGlobals.DefaultBackgroundColor)
        tpm = TextPropertiesManager.getGlobalPtr()
        candidateActive = TextProperties()
        candidateActive.setTextColor(0, 0, 1, 1)
        tpm.setProperties('candidate_active', candidateActive)
        candidateInactive = TextProperties()
        candidateInactive.setTextColor(0.3, 0.3, 0.7, 1)
        tpm.setProperties('candidate_inactive', candidateInactive)
        self.transitions.IrisModelName = 'phase_3/models/misc/iris'
        self.transitions.FadeModelName = 'phase_3/models/misc/fade'
        self.snapshotSfx = base.loadSfx('phase_4/audio/sfx/Photo_shutter.ogg')
        self.flashTrack = None
        self.exitFunc = self.userExit
        if __builtins__.has_key('launcher') and launcher:
            launcher.setPandaErrorCode(11)
        globalClock.setMaxDt(0.2)
        if self.config.GetBool('want-particles', 1) == 1:
            self.notify.debug('Enabling particles')
            self.enableParticles()

        # OS X Specific Actions
        if platform == "darwin":
            self.acceptOnce(ToontownGlobals.QuitGameHotKeyOSX, self.exitOSX)
            self.accept(ToontownGlobals.QuitGameHotKeyRepeatOSX, self.exitOSX)
            self.acceptOnce(ToontownGlobals.HideGameHotKeyOSX, self.hideGame)
            self.accept(ToontownGlobals.HideGameHotKeyRepeatOSX, self.hideGame)
            self.acceptOnce(ToontownGlobals.MinimizeGameHotKeyOSX,
                            self.minimizeGame)
            self.accept(ToontownGlobals.MinimizeGameHotKeyRepeatOSX,
                        self.minimizeGame)

        self.accept('f3', self.toggleGui)
        self.accept('panda3d-render-error', self.panda3dRenderError)
        oldLoader = self.loader
        self.loader = ToontownLoader.ToontownLoader(self)
        __builtins__['loader'] = self.loader

        self.asyncLoader = ToontownAsyncLoader.ToontownAsyncLoader(self)
        __builtins__['asyncloader'] = self.asyncLoader

        oldLoader.destroy()
        self.accept('PandaPaused', self.disableAllAudio)
        self.accept('PandaRestarted', self.enableAllAudio)
        self.friendMode = self.config.GetBool('switchboard-friends', 0)
        self.wantPets = self.config.GetBool('want-pets', 1)
        self.wantBingo = self.config.GetBool('want-fish-bingo', 1)
        self.wantKarts = self.config.GetBool('want-karts', 1)
        self.wantNewSpecies = self.config.GetBool('want-new-species', 0)
        self.inactivityTimeout = self.config.GetFloat(
            'inactivity-timeout', ToontownGlobals.KeyboardTimeout)
        if self.inactivityTimeout:
            self.notify.debug('Enabling Panda timeout: %s' %
                              self.inactivityTimeout)
            self.mouseWatcherNode.setInactivityTimeout(self.inactivityTimeout)
        self.mouseWatcherNode.setEnterPattern('mouse-enter-%r')
        self.mouseWatcherNode.setLeavePattern('mouse-leave-%r')
        self.mouseWatcherNode.setButtonDownPattern('button-down-%r')
        self.mouseWatcherNode.setButtonUpPattern('button-up-%r')
        self.randomMinigameAbort = self.config.GetBool('random-minigame-abort',
                                                       0)
        self.randomMinigameDisconnect = self.config.GetBool(
            'random-minigame-disconnect', 0)
        self.randomMinigameNetworkPlugPull = self.config.GetBool(
            'random-minigame-netplugpull', 0)
        self.autoPlayAgain = self.config.GetBool('auto-play-again', 0)
        self.skipMinigameReward = self.config.GetBool('skip-minigame-reward',
                                                      0)
        self.wantMinigameDifficulty = self.config.GetBool(
            'want-minigame-difficulty', 0)
        self.minigameDifficulty = self.config.GetFloat('minigame-difficulty',
                                                       -1.0)
        if self.minigameDifficulty == -1.0:
            del self.minigameDifficulty
        self.minigameSafezoneId = self.config.GetInt('minigame-safezone-id',
                                                     -1)
        if self.minigameSafezoneId == -1:
            del self.minigameSafezoneId
        cogdoGameSafezoneId = self.config.GetInt('cogdo-game-safezone-id', -1)
        cogdoGameDifficulty = self.config.GetFloat('cogdo-game-difficulty', -1)
        if cogdoGameDifficulty != -1:
            self.cogdoGameDifficulty = cogdoGameDifficulty
        if cogdoGameSafezoneId != -1:
            self.cogdoGameSafezoneId = cogdoGameSafezoneId
        ToontownBattleGlobals.SkipMovie = self.config.GetBool(
            'skip-battle-movies', 0)
        self.creditCardUpFront = self.config.GetInt('credit-card-up-front', -1)
        if self.creditCardUpFront == -1:
            del self.creditCardUpFront
        else:
            self.creditCardUpFront = self.creditCardUpFront != 0
        self.housingEnabled = self.config.GetBool('want-housing', 1)
        self.cannonsEnabled = self.config.GetBool('estate-cannons', 0)
        self.fireworksEnabled = self.config.GetBool('estate-fireworks', 0)
        self.dayNightEnabled = self.config.GetBool('estate-day-night', 0)
        self.cloudPlatformsEnabled = self.config.GetBool('estate-clouds', 0)
        self.greySpacing = self.config.GetBool('allow-greyspacing', 0)
        self.goonsEnabled = self.config.GetBool('estate-goon', 0)
        self.restrictTrialers = self.config.GetBool('restrict-trialers', 1)
        self.roamingTrialers = self.config.GetBool('roaming-trialers', 1)
        self.slowQuietZone = self.config.GetBool('slow-quiet-zone', 0)
        self.slowQuietZoneDelay = self.config.GetFloat('slow-quiet-zone-delay',
                                                       5)
        self.killInterestResponse = self.config.GetBool(
            'kill-interest-response', 0)
        tpMgr = TextPropertiesManager.getGlobalPtr()
        WLDisplay = TextProperties()
        WLDisplay.setSlant(0.3)
        WLEnter = TextProperties()
        WLEnter.setTextColor(1.0, 0.0, 0.0, 1)
        tpMgr.setProperties('WLDisplay', WLDisplay)
        tpMgr.setProperties('WLEnter', WLEnter)
        textShadow = TextProperties()
        textShadow.setShadow(.01)
        textShadow.setTextColor(0.8, 0.4, 0.0, 1)
        tpMgr.setProperties('textShadow', textShadow)
        del tpMgr
        self.lastScreenShotTime = globalClock.getRealTime()
        self.accept('InputState-forward', self.__walking)
        self.canScreenShot = 1
        self.glitchCount = 0
        self.walking = 0
        self.oldX = max(1, base.win.getXSize())
        self.oldY = max(1, base.win.getYSize())
        self.aspectRatio = float(self.oldX) / self.oldY
        self.localAvatarStyle = None

        self.wantCustomControls = settings.get('want-Custom-Controls', False)

        self.MOVE_UP = 'arrow_up'
        self.MOVE_DOWN = 'arrow_down'
        self.MOVE_LEFT = 'arrow_left'
        self.MOVE_RIGHT = 'arrow_right'
        self.JUMP = 'control'
        self.ACTION_BUTTON = 'delete'
        self.SCREENSHOT_KEY = 'f9'
        keymap = settings.get('keymap', {})
        if self.wantCustomControls:
            self.MOVE_UP = keymap.get('MOVE_UP', self.MOVE_UP)
            self.MOVE_DOWN = keymap.get('MOVE_DOWN', self.MOVE_DOWN)
            self.MOVE_LEFT = keymap.get('MOVE_LEFT', self.MOVE_LEFT)
            self.MOVE_RIGHT = keymap.get('MOVE_RIGHT', self.MOVE_RIGHT)
            self.JUMP = keymap.get('JUMP', self.JUMP)
            self.ACTION_BUTTON = keymap.get('ACTION_BUTTON',
                                            self.ACTION_BUTTON)
            self.SCREENSHOT_KEY = keymap.get('SCREENSHOT_KEY',
                                             self.SCREENSHOT_KEY)
            ToontownGlobals.OptionsPageHotkey = keymap.get(
                'OPTIONS-PAGE', ToontownGlobals.OptionsPageHotkey)

        self.CHAT_HOTKEY = keymap.get('CHAT_HOTKEY', 'r')

        self.accept(
            self.SCREENSHOT_KEY, self.takeScreenShot
        )  # TODO: Make the game ignore this and then re-accept it on a new key if it is rebinded

        self.Widescreen = settings.get('Widescreen', 0)

        self.currentScale = settings.get('texture-scale', 1.0)
        self.setTextureScale()
        self.setRatio()

        self.showDisclaimer = settings.get(
            'show-disclaimer', True
        )  # Show this the first time the user starts the game, it is set in the settings to False once they pick a toon

        self.lodMaxRange = 750
        self.lodMinRange = 5
        self.lodDelayFactor = 0.4

        # enable this feature, if you have render pipeline installed
        if config.GetBool('want-pipeline-renderer', False):
            from rpcore import RenderPipeline, SpotLight
            self.loadPipeline()

    def loadPipeline(self):
        self._pipelineEngine = RenderPipeline()
        self._pipelineEngine.create(self)

        # set the time of day for the daytime cycle
        self._pipelineEngine.daytime_mgr.time = '1:00'

    def updateAspectRatio(self):
        fadeSequence = Sequence(Func(base.transitions.fadeOut, .2), Wait(.2),
                                Func(self.setRatio),
                                Func(base.transitions.fadeIn, .2)).start()

    def setRatio(self):  # Set the aspect ratio
        print(GraphicsOptions.AspectRatios[self.Widescreen])
        base.setAspectRatio(GraphicsOptions.AspectRatios[self.Widescreen])

    def setTextureScale(self):  # Set the global texture scale (TODO)
        scale = settings.get('texture-scale')

    def openMainWindow(self, *args, **kw):
        result = OTPBase.OTPBase.openMainWindow(self, *args, **kw)
        self.setCursorAndIcon()
        return result

    def windowEvent(self, win):
        OTPBase.OTPBase.windowEvent(self, win)
        if not config.GetInt('keep-aspect-ratio', 0):
            return
        x = max(1, win.getXSize())
        y = max(1, win.getYSize())
        maxX = base.pipe.getDisplayWidth()
        maxY = base.pipe.getDisplayHeight()
        cwp = win.getProperties()
        originX = 0
        originY = 0
        if cwp.hasOrigin():
            originX = cwp.getXOrigin()
            originY = cwp.getYOrigin()
            if originX > maxX:
                originX = originX - maxX
            if originY > maxY:
                oringY = originY - maxY
        maxX -= originX
        maxY -= originY
        if math.fabs(x - self.oldX) > math.fabs(y - self.oldY):
            newY = x / self.aspectRatio
            newX = x
            if newY > maxY:
                newY = maxY
                newX = self.aspectRatio * maxY
        else:
            newX = self.aspectRatio * y
            newY = y
            if newX > maxX:
                newX = maxX
                newY = maxX / self.aspectRatio
        wp = WindowProperties()
        wp.setSize(newX, newY)
        base.win.requestProperties(wp)
        base.cam.node().getLens().setFilmSize(newX, newY)
        self.oldX = newX
        self.oldY = newY

    def setCursorAndIcon(self):
        tempdir = tempfile.mkdtemp()
        atexit.register(shutil.rmtree, tempdir)
        vfs = VirtualFileSystem.getGlobalPtr()

        searchPath = DSearchPath()
        searchPath.appendDirectory(Filename('/phase_3/etc'))

        for filename in ['toonmono.cur', 'icon.ico']:
            p3filename = Filename(filename)
            found = vfs.resolveFilename(p3filename, searchPath)
            if not found:
                return  # Can't do anything past this point.

            with open(os.path.join(tempdir, filename), 'wb') as f:
                f.write(vfs.readFile(p3filename, False))

        wp = WindowProperties()
        wp.setCursorFilename(
            Filename.fromOsSpecific(os.path.join(tempdir, 'toonmono.cur')))
        wp.setIconFilename(
            Filename.fromOsSpecific(os.path.join(tempdir, 'icon.ico')))
        self.win.requestProperties(wp)

    def addCullBins(self):
        cbm = CullBinManager.getGlobalPtr()
        cbm.addBin('ground', CullBinManager.BTUnsorted, 18)
        cbm.addBin('shadow', CullBinManager.BTBackToFront, 19)
        cbm.addBin('gui-popup', CullBinManager.BTFixed, 60)

    def disableShowbaseMouse(self):
        self.useDrive()
        self.disableMouse()
        if self.mouseInterface: self.mouseInterface.detachNode()
        if self.mouse2cam: self.mouse2cam.detachNode()

    def __walking(self, pressed):
        self.walking = pressed

    def toggleGui(self):
        if aspect2d.isHidden():
            aspect2d.show()
        else:
            aspect2d.hide()

    def takeScreenShot(self):
        if not os.path.exists(TTLocalizer.ScreenshotPath):
            os.mkdir(TTLocalizer.ScreenshotPath)
            self.notify.info('Made new directory to save screenshots.')
        namePrefix = TTLocalizer.ScreenshotPath + launcher.logPrefix + 'screenshot'
        timedif = globalClock.getRealTime() - self.lastScreenShotTime
        if self.glitchCount > 10 and self.walking:
            return
        if timedif < 1.0 and self.walking:
            self.glitchCount += 1
            return
        if not hasattr(self, 'localAvatar'):
            self.screenshot(namePrefix=namePrefix)
            self.lastScreenShotTime = globalClock.getRealTime()
            return
        if self.flashTrack and self.flashTrack.isPlaying():
            self.flashTrack.finish()
        self.transitions.noFade()
        coordOnScreen = self.config.GetBool('screenshot-coords', 0)
        self.localAvatar.stopThisFrame = 1
        ctext = self.localAvatar.getAvPosStr()
        self.screenshotStr = ''
        messenger.send('takingScreenshot')
        if coordOnScreen:
            coordTextLabel = DirectLabel(pos=(-0.81, 0.001, -0.87),
                                         text=ctext,
                                         text_scale=0.05,
                                         text_fg=VBase4(1.0, 1.0, 1.0, 1.0),
                                         text_bg=(0, 0, 0, 0),
                                         text_shadow=(0, 0, 0, 1),
                                         relief=None)
            coordTextLabel.setBin('gui-popup', 0)
            strTextLabel = None
            if len(self.screenshotStr):
                strTextLabel = DirectLabel(pos=(0.0, 0.001, 0.9),
                                           text=self.screenshotStr,
                                           text_scale=0.05,
                                           text_fg=VBase4(1.0, 1.0, 1.0, 1.0),
                                           text_bg=(0, 0, 0, 0),
                                           text_shadow=(0, 0, 0, 1),
                                           relief=None)
                strTextLabel.setBin('gui-popup', 0)
        self.graphicsEngine.renderFrame()
        self.screenshot(namePrefix=namePrefix,
                        imageComment=ctext + ' ' + self.screenshotStr)
        self.lastScreenShotTime = globalClock.getRealTime()
        self.transitions.setFadeColor(1, 1, 1)
        self.flashTrack = Sequence(
            Func(base.playSfx, self.snapshotSfx),
            Func(self.transitions.fadeOut, 0.15), Wait(0.2),
            Func(self.transitions.fadeIn, 0.8), Wait(1.0),
            Func(self.transitions.setFadeColor, 0, 0, 0))
        self.flashTrack.start()
        if coordOnScreen:
            if strTextLabel is not None:
                strTextLabel.destroy()
            coordTextLabel.destroy()
        return

    def addScreenshotString(self, str):
        if len(self.screenshotStr):
            self.screenshotStr += '\n'
        self.screenshotStr += str

    def initNametagGlobals(self):
        arrow = loader.loadModel('phase_3/models/props/arrow')
        card = loader.loadModel('phase_3/models/props/panel')
        speech3d = ChatBalloon(
            loader.loadModel('phase_3/models/props/chatbox'))
        thought3d = ChatBalloon(
            loader.loadModel('phase_3/models/props/chatbox_thought_cutout'))
        speech2d = ChatBalloon(
            loader.loadModel('phase_3/models/props/chatbox_noarrow'))
        chatButtonGui = loader.loadModel('phase_3/models/gui/chat_button_gui')
        NametagGlobals.setCamera(self.cam)
        NametagGlobals.setArrowModel(arrow)
        NametagGlobals.setNametagCard(card, VBase4(-0.5, 0.5, -0.5, 0.5))
        if self.mouseWatcherNode:
            NametagGlobals.setMouseWatcher(self.mouseWatcherNode)
        NametagGlobals.setSpeechBalloon3d(speech3d)
        NametagGlobals.setThoughtBalloon3d(thought3d)
        NametagGlobals.setSpeechBalloon2d(speech2d)
        NametagGlobals.setThoughtBalloon2d(thought3d)
        NametagGlobals.setPageButton(PGButton.SReady,
                                     chatButtonGui.find('**/Horiz_Arrow_UP'))
        NametagGlobals.setPageButton(PGButton.SDepressed,
                                     chatButtonGui.find('**/Horiz_Arrow_DN'))
        NametagGlobals.setPageButton(
            PGButton.SRollover, chatButtonGui.find('**/Horiz_Arrow_Rllvr'))
        NametagGlobals.setQuitButton(PGButton.SReady,
                                     chatButtonGui.find('**/CloseBtn_UP'))
        NametagGlobals.setQuitButton(PGButton.SDepressed,
                                     chatButtonGui.find('**/CloseBtn_DN'))
        NametagGlobals.setQuitButton(PGButton.SRollover,
                                     chatButtonGui.find('**/CloseBtn_Rllvr'))
        rolloverSound = DirectGuiGlobals.getDefaultRolloverSound()
        if rolloverSound:
            NametagGlobals.setRolloverSound(rolloverSound)
        clickSound = DirectGuiGlobals.getDefaultClickSound()
        if clickSound:
            NametagGlobals.setClickSound(clickSound)
        NametagGlobals.setToon(self.cam)

        self.marginManager = MarginManager()
        self.margins = self.aspect2d.attachNewNode(
            self.marginManager, DirectGuiGlobals.MIDGROUND_SORT_INDEX + 1)
        mm = self.marginManager

        # TODO: Dynamicaly add more and reposition cells
        padding = 0.0225

        # Order: Top to bottom
        self.leftCells = [
            mm.addGridCell(0.2 + padding, -0.45,
                           base.a2dTopLeft),  # Above boarding groups
            mm.addGridCell(0.2 + padding, -0.9, base.a2dTopLeft),  # 1
            mm.addGridCell(0.2 + padding, -1.35,
                           base.a2dTopLeft)  # Below Boarding Groups
        ]

        # Order: Left to right
        self.bottomCells = [
            mm.addGridCell(
                -0.87, 0.2 + padding,
                base.a2dBottomCenter),  # To the right of the laff meter
            mm.addGridCell(-0.43, 0.2 + padding, base.a2dBottomCenter),  # 1
            mm.addGridCell(0.01, 0.2 + padding, base.a2dBottomCenter),  # 2
            mm.addGridCell(0.45, 0.2 + padding, base.a2dBottomCenter),  # 3
            mm.addGridCell(
                0.89, 0.2 + padding,
                base.a2dBottomCenter)  # To the left of the shtiker book
        ]

        # Order: Bottom to top
        self.rightCells = [
            mm.addGridCell(-0.2 - padding, -1.35,
                           base.a2dTopRight),  # Above the street map
            mm.addGridCell(-0.2 - padding, -0.9,
                           base.a2dTopRight),  # Below the friends list
            mm.addGridCell(-0.2 - padding, -0.45,
                           base.a2dTopRight)  # Behind the friends list
        ]

    def hideFriendMargins(self):
        middleCell = self.rightCells[1]
        topCell = self.rightCells[2]

        self.setCellsAvailable([middleCell, topCell], False)

    def showFriendMargins(self):
        middleCell = self.rightCells[1]
        topCell = self.rightCells[2]

        self.setCellsAvailable([middleCell, topCell], True)

    def setCellsAvailable(self, cell_list, available):
        for cell in cell_list:
            self.marginManager.setCellAvailable(cell, available)

    def cleanupDownloadWatcher(self):
        self.downloadWatcher.cleanup()
        self.downloadWatcher = None
        return

    def startShow(self, cr, launcherServer=None):
        self.cr = cr
        base.graphicsEngine.renderFrame()
        self.downloadWatcher = ToontownDownloadWatcher.ToontownDownloadWatcher(
            TTLocalizer.LauncherPhaseNames)
        if launcher.isDownloadComplete():
            self.cleanupDownloadWatcher()
        else:
            self.acceptOnce('launcherAllPhasesComplete',
                            self.cleanupDownloadWatcher)
        gameServer = config.GetString('game-server', '')
        if gameServer:
            self.notify.info('Using game-server from Configrc: %s ' %
                             gameServer)
        elif launcherServer:
            gameServer = launcherServer
            self.notify.info('Using gameServer from launcher: %s ' %
                             gameServer)
        else:
            gameServer = 'gs1.projectaltis.com'
        serverPort = config.GetInt('server-port', 7198)
        serverList = []
        for name in gameServer.split(';'):
            url = URLSpec(name, 1)
            url.setScheme('s')
            if not url.hasPort():
                url.setPort(serverPort)
            serverList.append(url)

        if len(serverList) == 1:
            failover = config.GetString('server-failover', '')
            serverURL = serverList[0]
            for arg in failover.split():
                try:
                    port = int(arg)
                    url = URLSpec(serverURL)
                    url.setPort(port)
                except:
                    url = URLSpec(arg, 1)

                if url != serverURL:
                    serverList.append(url)

        cr.loginFSM.request('connect', [serverList])
        self.ttAccess = ToontownAccess.ToontownAccess()
        self.ttAccess.initModuleInfo()

        if config.GetBool('want-speedhack-fix', False):
            # Start checking for speedhacks.
            self.lastSpeedhackCheck = time.time()
            self.trueClock = TrueClock.getGlobalPtr()
            self.lastTrueClockTime = self.trueClock.getLongTime()
            taskMgr.add(self.__speedhackCheckTick, 'speedhack-tick')

    def __speedhackCheckTick(self, task):
        # Check if the time elapsed is less than interval-1 (1 second extra
        # just in case)
        elapsed = time.time() - self.lastSpeedhackCheck

        tc_elapsed = self.trueClock.getLongTime() - self.lastTrueClockTime
        if tc_elapsed > elapsed + 1:
            # They responded too fast. This indicates that the TrueClock is running faster
            # than normal, and possibly means they sped the process up.
            self.__killSpeedHacker()
            return task.done
        # Clean! Lets wait until the next iteration...
        self.lastSpeedhackCheck = time.time()
        self.lastTrueClockTime = self.trueClock.getLongTime()
        return task.cont

    def __killSpeedHacker(self):
        # go f**k yo' self and yo' cheat engine, f**k'r.
        self.cr.bootedIndex = 128
        self.cr.bootedText = 'SERVER CONNECTION FAILURE. CLIENT HAS EXCEEDED RATE-LIMIT.'
        self.cr.stopReaderPollTask()
        self.cr.lostConnection()

    def removeGlitchMessage(self):
        self.ignore('InputState-forward')
        print 'ignoring InputState-forward'

    def exitShow(self, errorCode=None):
        self.notify.info('Exiting Toontown: errorCode = %s' % errorCode)
        if errorCode:
            launcher.setPandaErrorCode(errorCode)
        else:
            launcher.setPandaErrorCode(0)
        sys.exit()

    def setExitErrorCode(self, code):
        self.exitErrorCode = code
        if os.name == 'nt':
            exitCode2exitPage = {
                OTPLauncherGlobals.ExitEnableChat: 'chat',
                OTPLauncherGlobals.ExitSetParentPassword: '******',
                OTPLauncherGlobals.ExitPurchase: 'purchase'
            }
            if code in exitCode2exitPage:
                launcher.setRegistry('EXIT_PAGE', exitCode2exitPage[code])

    def getExitErrorCode(self):
        return self.exitErrorCode

    def userExit(self):
        try:
            self.localAvatar.d_setAnimState('TeleportOut', 1)
        except:
            pass

        if hasattr(self, 'ttAccess'):
            self.ttAccess.delete()
        if self.cr.timeManager:
            self.cr.timeManager.setDisconnectReason(
                ToontownGlobals.DisconnectCloseWindow)
        base.cr._userLoggingOut = False
        try:
            localAvatar
        except:
            pass
        else:
            messenger.send('clientLogout')
            self.cr.dumpAllSubShardObjects()

        self.cr.loginFSM.request('shutdown')
        self.notify.warning('Could not request shutdown; exiting anyway.')
        self.ignore(ToontownGlobals.QuitGameHotKeyOSX)
        self.ignore(ToontownGlobals.QuitGameHotKeyRepeatOSX)
        self.ignore(ToontownGlobals.HideGameHotKeyOSX)
        self.ignore(ToontownGlobals.HideGameHotKeyRepeatOSX)
        self.ignore(ToontownGlobals.MinimizeGameHotKeyOSX)
        self.ignore(ToontownGlobals.MinimizeGameHotKeyRepeatOSX)
        self.exitShow()

    def panda3dRenderError(self):
        launcher.setPandaErrorCode(14)
        if self.cr.timeManager:
            self.cr.timeManager.setDisconnectReason(
                ToontownGlobals.DisconnectGraphicsError)
        self.cr.sendDisconnect()
        sys.exit()

    def getShardPopLimits(self):
        return (config.GetInt('shard-low-pop', ToontownGlobals.LOW_POP),
                config.GetInt('shard-mid-pop', ToontownGlobals.MID_POP),
                config.GetInt('shard-high-pop', ToontownGlobals.HIGH_POP))

    def playMusic(self, music, looping=0, interrupt=1, volume=None, time=0.0):
        OTPBase.OTPBase.playMusic(self, music, looping, interrupt, volume,
                                  time)

    # OS X Specific Actions
    def exitOSX(self):
        self.confirm = TTDialog.TTGlobalDialog(
            doneEvent='confirmDone',
            message=TTLocalizer.OptionsPageExitConfirm,
            style=TTDialog.TwoChoice)
        self.confirm.show()
        self.accept('confirmDone', self.handleConfirm)

    def handleConfirm(self):
        status = self.confirm.doneStatus
        self.ignore('confirmDone')
        self.confirm.cleanup()
        del self.confirm
        if status == 'ok':
            self.userExit()

    def hideGame(self):
        # Hacky, I know, but it works
        hideCommand = """osascript -e 'tell application "System Events"
                                            set frontProcess to first process whose frontmost is true
                                            set visible of frontProcess to false
                                       end tell'"""
        os.system(hideCommand)

    def minimizeGame(self):
        wp = WindowProperties()
        wp.setMinimized(True)
        base.win.requestProperties(wp)

    def reloadControls(self):
        keymap = settings.get('keymap', {})
        self.CHAT_HOTKEY = keymap.get('CHAT_HOTKEY', 'r')
        if self.wantCustomControls:
            self.MOVE_UP = keymap.get('MOVE_UP', self.MOVE_UP)
            self.MOVE_DOWN = keymap.get('MOVE_DOWN', self.MOVE_DOWN)
            self.MOVE_LEFT = keymap.get('MOVE_LEFT', self.MOVE_LEFT)
            self.MOVE_RIGHT = keymap.get('MOVE_RIGHT', self.MOVE_RIGHT)
            self.JUMP = keymap.get('JUMP', self.JUMP)
            self.ACTION_BUTTON = keymap.get('ACTION_BUTTON',
                                            self.ACTION_BUTTON)
            ToontownGlobals.OptionsPageHotkey = keymap.get(
                'OPTIONS-PAGE', ToontownGlobals.OptionsPageHotkey)
        else:
            self.MOVE_UP = 'arrow_up'
            self.MOVE_DOWN = 'arrow_down'
            self.MOVE_LEFT = 'arrow_left'
            self.MOVE_RIGHT = 'arrow_right'
            self.JUMP = 'control'
            self.ACTION_BUTTON = 'delete'
Example #34
0
    def __init__(self):
        load_prc_file_data("", "win-size 512 512")
        # load_prc_file_data("", "window-type offscreen")
        load_prc_file_data("", "model-cache-dir")
        load_prc_file_data("", "model-cache-textures #f")
        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "alpha-bits 0")
        load_prc_file_data("", "print-pipe-types #f")

        # Construct render pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.config_dir = "config/"
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        self.setup_scene()

        # Disable model caching
        BamCache.get_global_ptr().cache_models = False

        self.update_queue = []
        self.start_listen()

        # Render initial frames
        for i in range(10):
            self.taskMgr.step()

        last_update = 0.0
        self.scene_node = None

        current_lights = []
        current_envprobes = []

        # Wait for updates
        while True:

            # Update once in a while
            curr_time = time.time()
            if curr_time > last_update + 1.0:
                last_update = curr_time
                self.taskMgr.step()

            if self.update_queue:
                if self.scene_node:
                    self.scene_node.remove_node()

                # Only take the latest packet
                payload = self.update_queue.pop(0)
                print("RENDERING:", payload)

                scene = loader.loadModel(Filename.from_os_specific(payload["scene"]))

                for light in scene.find_all_matches("**/+PointLight"):
                    light.remove_node()
                for light in scene.find_all_matches("**/+Spotlight"):
                    light.remove_node()

                # Find camera
                main_cam = scene.find("**/Camera")
                if main_cam:
                    transform_mat = main_cam.get_transform(render).get_mat()
                    transform_mat = Mat4.convert_mat(CS_zup_right, CS_yup_right) * transform_mat
                    base.camera.set_mat(transform_mat)
                else:
                    print("WARNING: No camera found")
                    base.camera.set_pos(0, -3.5, 0)
                    base.camera.look_at(0, -2.5, 0)

                base.camLens.set_fov(64.0)

                self.scene_node = scene
                scene.reparent_to(render)

                # Render scene
                for i in range(8):
                    self.taskMgr.step()

                dest_path = Filename.from_os_specific(payload["dest"])
                print("Saving screenshot to", dest_path)
                self.win.save_screenshot(dest_path)
                self.notify_about_finish(int(payload["pingback_port"]))
Example #35
0
"""

This is an alternative possibility of initializing the RenderPipeline, which enables
you to construct the show base object yourself.

"""

import sys
from direct.showbase.ShowBase import ShowBase

# Insert the pipeline path to the system path, this is required to be
# able to import the pipeline classes. In case you placed the render
# pipeline in a subfolder of your project, you have to adjust this.
sys.path.insert(0, "../../RenderPipeline")
sys.path.insert(0, "../../")

# Import render pipeline classes
from rpcore import RenderPipeline, SpotLight

# Construct and create the pipeline
render_pipeline = RenderPipeline()
render_pipeline.pre_showbase_init()
base = ShowBase()
render_pipeline.create(base)

base.run()
Example #36
0
class StickFightGame(ShowBase):
    def __init__(self):
        
        self.renderPipeline = True
        
        if(self.renderPipeline is True):
            # Notice that you must not call ShowBase.__init__ (or super), the render
            # pipeline does that for you.
    
            # Insert the pipeline path to the system path, this is required to be
            # able to import the pipeline classes. In case you placed the render
            # pipeline in a subfolder of your project, you have to adjust this.
           
            sys.path.insert(0, "Game/render_pipeline")
            #sys.path.insert(0, "../../RenderPipeline")
            
            # Import render pipeline classes
            from rpcore import RenderPipeline, SpotLight
    
            # Construct and create the pipeline
            self.render_pipeline = RenderPipeline()
            self.render_pipeline.create(self)
    
            # Done! You can start setting up your application stuff as regular now.
        else:
            ShowBase.__init__(self)
        

                    
        
        #Debug stuff
        self.debug = True
        if(self.debug is True):
            base.setFrameRateMeter(True)
            render.analyze()
            
        #Disable modifiers Shift+Something/Alt+Something/Ctrl+Something
        base.mouseWatcherNode.set_modifier_buttons(ModifierButtons())
        base.buttonThrowers[0].node().set_modifier_buttons(ModifierButtons())
        

        #Create bullet world
        self.bWorld = bWorld('Game/models/maps/debug.egg')
                    
        #Add task to process physics
        taskMgr.add(self.update, 'updateWorld')

        
        #Set up the player
        self.bController = kCharacterController(self.bWorld.world, self.bWorld.worldNP, 1.75, 1.3, 0, 0.4)
        self.bController.setPos(render, Point3(0, 0, 10))        
        
        self.player = Player(self.bController,"Game/models/player/swifter",.1)
        
        self.keyboardSetup(self.player)
        
        # Create a camera to follow the player.
        #base.oobe()  

        # Attach the camera to the bullet controller's capsule node path 
        camera = Camera(self.bController)
        

        # Accept the Esc key to quit the game.
    
        self.accept("escape", sys.exit)   
          
        
        

    #For processing physic updates

    def update(self, task):
        dt = globalClock.getDt()
        
        
        """Might be needed later in bulletController"""
        #Get the characters old position, comes from the bullet Char controller
        #oldCharPos = self.bController.getPos(render)
      
        #Runs the update function in the bullet Char controller
        #It will apply physics and movement and check states
        self.bController.update() # WIP
        
        """Might be needed later in bulletController"""
        #newCharPos = self.bController.getPos(render)
        #delta = newCharPos - oldCharPos
        
        self.bWorld.world.doPhysics(dt, 4, 1./120.)
    
        return task.cont        
          
    def keyboardSetup(self,player):
        #Turn of shift/ctl/alt modifiers

        #setup keyboard inputs
        self.accept("escape", sys.exit)
        
        #movement
        self.accept("a", player.setMove, ["left","strafe_left"])
        self.accept("a-up", player.setMove, ["stop","strafe_left"])
        self.accept("d", player.setMove, ["right","strafe_right"])
        self.accept("d-up", player.setMove, ["stop","strafe_right"])
        self.accept("w", player.setMove, ["forward","forward"])
        self.accept("w-up", player.setMove, ["stop","forward"])
        self.accept("s", player.setMove, ["back","back"])
        self.accept("s-up", player.setMove, ["stop","back"])
    
        #modifyers / jumping
        self.accept("lcontrol", player.setMove, [True,"crouch"])
        self.accept("lcontrol-up", player.setMove, [False,"crouch"])
        self.accept("lshift", player.setMove, [True,"sprint"])
        self.accept("lshift-up", player.setMove, [False,"sprint"])
        self.accept("space", player.setMove, [True,"jump"])
        self.accept("space-up", player.setMove, [False,"jump"])
        
        #Set up mouse controls
        
        self.accept("mouse1", player.setMove, [True,"punch"])
        self.accept("mouse1-up", player.setMove, [False,"punch"])
        self.accept("mouse2", player.setMove, [True,"kick"])
        self.accept("mouse2-up", player.setMove, [False,"kick"])        
Example #37
0
class Application(ShowBase):

    ICOMING_PORT = 62360

    def __init__(self):
        load_prc_file_data("", "win-size 512 512")
        load_prc_file_data("", "window-type offscreen")
        load_prc_file_data("", "model-cache-dir")
        load_prc_file_data("", "model-cache-textures #f")
        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "alpha-bits 0")
        load_prc_file_data("", "print-pipe-types #f")

        # Construct render pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.config_dir = "config/"
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        self.setup_scene()

        # Disable model caching
        BamCache.get_global_ptr().cache_models = False

        self.update_queue = []
        self.start_listen()

        # Render initial frames
        for i in range(10):
            self.taskMgr.step()

        last_update = 0.0
        self.scene_node = None

        current_lights = []
        current_envprobes = []

        # Wait for updates
        while True:

            # Update once in a while
            curr_time = time.time()
            if curr_time > last_update + 1.0:
                last_update = curr_time
                self.taskMgr.step()

            if self.update_queue:
                if self.scene_node:
                    self.scene_node.remove_node()

                # Only take the latest packet
                payload = self.update_queue.pop(0)
                print("RENDERING:", payload)

                scene = loader.loadModel(
                    Filename.from_os_specific(payload["scene"]))

                for light in scene.find_all_matches("**/+PointLight"):
                    light.remove_node()
                for light in scene.find_all_matches("**/+Spotlight"):
                    light.remove_node()

                # Find camera
                main_cam = scene.find("**/Camera")
                if main_cam:
                    transform_mat = main_cam.get_transform(render).get_mat()
                    transform_mat = Mat4.convert_mat(
                        CS_zup_right, CS_yup_right) * transform_mat
                    base.camera.set_mat(transform_mat)
                else:
                    print("WARNING: No camera found")
                    base.camera.set_pos(0, -3.5, 0)
                    base.camera.look_at(0, -2.5, 0)

                base.camLens.set_fov(64.0)

                self.scene_node = scene
                scene.reparent_to(render)

                # Render scene
                for i in range(8):
                    self.taskMgr.step()

                dest_path = Filename.from_os_specific(payload["dest"])
                print("Saving screenshot to", dest_path)
                self.win.save_screenshot(dest_path)
                self.notify_about_finish(int(payload["pingback_port"]))

    def start_listen(self):
        """ Starts the listener thread """
        thread = Thread(target=self.listener_thread,
                        args=(),
                        name="ListenerThread")
        thread.setDaemon(True)
        thread.start()
        return thread

    def listener_thread(self):
        """ Thread which listens to incoming updates """
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        print("Listening on 127.0.0.1:" + str(self.ICOMING_PORT))
        try:
            sock.bind(("127.0.0.1", self.ICOMING_PORT))
            while True:
                data, addr = sock.recvfrom(8192)
                self.handle_data(data)
        except Exception as msg:
            print("Failed to bind to address! Reason:", msg)
        finally:
            sock.close()

    def handle_data(self, data):
        """ Handles a new update """
        # print("Got:", data)
        unpacked_data = pickle.loads(data)
        # print("Data = ", unpacked_data)
        self.update_queue.append(unpacked_data)

    def notify_about_finish(self, port):
        """ Notifies the caller that the result finished """
        print("Sending finish result to localhost:" + str(port))
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        try:
            sock.connect(("localhost", port))
        except Exception as msg:
            print("Could not send finish result: ", msg)
            return
        sock.sendall(b"done")
        print("Sent done flag.")
        sock.close()

    def setup_scene(self):
        """ Setups the basic scene geometry """
        self.disableMouse()
        self.render2d.hide()
        self.aspect2d.hide()

        light = PointLight()
        light.pos = 20.0, -0.85, -1.31
        light.radius = 100.0
        light.energy = 2500
        light.set_color_from_temperature(8000)
        # self.render_pipeline.add_light(light)

        light = PointLight()
        light.pos = -11.2, -13.84, -9.24
        light.radius = 1e20
        light.set_color_from_temperature(8000)
        light.energy = 2500
Example #38
0
class MainApp(ShowBase):
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
            win-size 1600 900
            window-title Render Pipeline - Shading Models Demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # This is a helper class for better camera movement - its not really
        # a rendering element, but it included for convenience
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = 0.769

        # Load the scene
        model = loader.loadModel("scene/TestScene.bam")
        model.reparent_to(render)

        self.render_pipeline.prepare_scene(model)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(
            Vec3(6.6, -18.8, 4.5), Vec3(4.7, -16.7, 3.4))
        self.controller.setup()

        base.accept("l", self.tour)
        base.accept("r", self.reload_shaders)

    def reload_shaders(self):
        self.render_pipeline.reload_shaders()
        self.render_pipeline.prepare_scene(render)

    def tour(self):
        mopath = (
            (Vec3(3.97601628304, -15.5422525406, 1.73230814934), Vec3(49.2462043762, -11.7619161606, 0.0)),
            (Vec3(4.37102460861, -6.52981519699, 2.84148645401), Vec3(138.54864502, -15.7908058167, 0.0)),
            (Vec3(-5.88968038559, -13.9816446304, 2.44033527374), Vec3(302.348571777, -13.2863616943, 0.0)),
            (Vec3(5.23844909668, -18.1897411346, 4.54698801041), Vec3(402.91229248, -14.7019147873, 0.0)),
            (Vec3(-7.27328443527, -0.466051012278, 3.30696845055), Vec3(607.032165527, -19.6019115448, 0.0)),
            (Vec3(5.33415555954, 1.92750489712, 2.53945565224), Vec3(484.103546143, -11.9796953201, 0.0)),
            (Vec3(-0.283608138561, -6.86583900452, 1.43702816963), Vec3(354.63848877, -4.79302883148, 0.0)),
            (Vec3(-11.7576808929, 7.0855755806, 3.40899515152), Vec3(272.73840332, -12.959692955, 0.0)),
            (Vec3(7.75462722778, 13.220041275, 3.97876667976), Vec3(126.342140198, -19.4930171967, 0.0)),
            (Vec3(-2.10827493668, 4.78230571747, 1.27567899227), Vec3(-40.1353683472, -5.77301359177, 0.0)),
            (Vec3(8.67115211487, 16.9084873199, 3.72598099709), Vec3(89.5658569336, -10.9996757507, 0.0)),
            (Vec3(-8.1254825592, 26.6411190033, 3.21335697174), Vec3(268.092102051, -12.1974525452, 0.0)),
            (Vec3(7.89382314682, 45.8911399841, 4.47727441788), Vec3(498.199554443, -11.3263425827, 0.0)),
            (Vec3(-2.33054184914, 43.8977775574, 1.86498868465), Vec3(551.198242188, 13.6092195511, 0.0)),
            (Vec3(4.80335664749, 36.9664497375, 6.16300296783), Vec3(810.128417969, -10.6730031967, 0.0)),
            (Vec3(45.0654678345, 7.54712438583, 22.2645874023), Vec3(808.238586426, -17.5330123901, 0.0)),
            (Vec3(5.99377584457, -12.3760728836, 4.53536558151), Vec3(806.978820801, -2.39745855331, 0.0)),
            (Vec3(6.05853939056, -1.72227275372, 4.53848743439), Vec3(809.65637207, -2.39745855331, 0.0)),
            (Vec3(4.81568479538, 8.28769683838, 4.48393821716), Vec3(809.65637207, -2.39745855331, 0.0)),
            (Vec3(5.82831144333, 17.5230751038, 4.52401590347), Vec3(809.65637207, -2.39745855331, 0.0)),
            (Vec3(4.09594917297, 26.7909412384, 4.44915866852), Vec3(809.65637207, -2.39745855331, 0.0)),
            (Vec3(4.39108037949, 37.2143096924, 5.16932630539), Vec3(809.65637207, -2.39745855331, 0.0)),
        )
        self.controller.play_motion_path(mopath, 2.3)
Example #39
0
    def __init__(self):
        load_prc_file_data("", "win-size 512 512")
        load_prc_file_data("", "window-type offscreen")
        load_prc_file_data("", "model-cache-dir")
        load_prc_file_data("", "model-cache-textures #f")
        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "alpha-bits 0")
        load_prc_file_data("", "print-pipe-types #f")

        # Construct render pipeline
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.config_dir = "config/"
        self.render_pipeline.set_empty_loading_screen()
        self.render_pipeline.create(self)

        self.setup_scene()

        # Disable model caching
        BamCache.get_global_ptr().cache_models = False

        self.update_queue = []
        self.start_listen()

        # Render initial frames
        for i in range(10):
            self.taskMgr.step()

        last_update = 0.0
        self.scene_node = None

        current_lights = []
        current_envprobes = []

        # Wait for updates
        while True:

            # Update once in a while
            curr_time = time.time()
            if curr_time > last_update + 1.0:
                last_update = curr_time
                self.taskMgr.step()

            if self.update_queue:
                if self.scene_node:
                    self.scene_node.remove_node()

                # Only take the latest packet
                payload = self.update_queue.pop(0)
                print("RENDERING:", payload)

                scene = loader.loadModel(
                    Filename.from_os_specific(payload["scene"]))

                for light in scene.find_all_matches("**/+PointLight"):
                    light.remove_node()
                for light in scene.find_all_matches("**/+Spotlight"):
                    light.remove_node()

                # Find camera
                main_cam = scene.find("**/Camera")
                if main_cam:
                    transform_mat = main_cam.get_transform(render).get_mat()
                    transform_mat = Mat4.convert_mat(
                        CS_zup_right, CS_yup_right) * transform_mat
                    base.camera.set_mat(transform_mat)
                else:
                    print("WARNING: No camera found")
                    base.camera.set_pos(0, -3.5, 0)
                    base.camera.look_at(0, -2.5, 0)

                base.camLens.set_fov(64.0)

                self.scene_node = scene
                scene.reparent_to(render)

                # Render scene
                for i in range(8):
                    self.taskMgr.step()

                dest_path = Filename.from_os_specific(payload["dest"])
                print("Saving screenshot to", dest_path)
                self.win.save_screenshot(dest_path)
                self.notify_about_finish(int(payload["pingback_port"]))
Example #40
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
        win-size 1600 900
        window-title Render Pipeline - Lights demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # This is a helper class for better camera movement - its not really
        # a rendering element, but it included for convenience
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "4:50"

        self.half_energy = 5000
        self.lamp_fov = 70
        self.lamp_radius = 10
        # Load the scene
        model = loader.loadModel("scene/Scene.bam")
        model.reparent_to(render)

        # Animate balls, this is for testing the motion blur
        blend_type = "noBlend"

        np = model.find("**/MBRotate")
        np.hprInterval(1.5, Vec3(360, 360, 0), Vec3(0, 0, 0), blendType=blend_type).loop()

        np = model.find("**/MBUpDown")
        np_pos = np.get_pos() - Vec3(0, 0, 2)
        Sequence(
            np.posInterval(0.15, np_pos + Vec3(0, 0, 6), np_pos, blendType=blend_type),
            np.posInterval(0.15, np_pos, np_pos + Vec3(0, 0, 6), blendType=blend_type)).loop()

        np = model.find("**/MBFrontBack")
        np_pos = np.get_pos() - Vec3(0, 0, 2)
        Sequence(
            np.posInterval(0.15, np_pos + Vec3(0, 6, 0), np_pos, blendType=blend_type),
            np.posInterval(0.15, np_pos, np_pos + Vec3(0, 6, 0), blendType=blend_type)).loop()

        np = model.find("**/MBScale")
        Sequence(
            np.scaleInterval(0.2, Vec3(1.5), Vec3(1), blendType=blend_type),
            np.scaleInterval(0.2, Vec3(1), Vec3(1.5), blendType=blend_type)).loop()


        # Generate temperature lamps
        # This shows how to procedurally create lamps. In this case, we
        # base the lights positions on empties created in blender.
        self._lights = []
        light_key = lambda light: int(light.get_name().split("LampLum")[-1])
        lumlamps = sorted(model.find_all_matches("**/LampLum*"), key=light_key)
        for lumlamp in lumlamps:
            lum = float(lumlamp.get_name()[len("LampLum"):])
            light = SpotLight()
            light.direction = (0, -1.5, -1)
            light.fov = self.lamp_fov
            light.set_color_from_temperature(lum * 1000.0)
            light.energy = self.half_energy
            light.pos = lumlamp.get_pos(self.render)
            light.radius = self.lamp_radius
            light.casts_shadows = False
            light.shadow_map_resolution = 256
            self.render_pipeline.add_light(light)

            # Put Pandas on the edges
            if lumlamp in lumlamps[0:2] + lumlamps[-2:]:
                panda = loader.loadModel("panda")
                panda.reparent_to(render)
                panda_mat = Material("default")
                panda_mat.emission = 0
                panda.set_material(panda_mat)
                panda.set_pos(light.pos)
                panda.set_z(0.65)
                panda.set_h(180 + randint(-60, 60))
                panda.set_scale(0.2)
                panda.set_y(panda.get_y() - 3.0)

            self._lights.append(light)

        self.render_pipeline.prepare_scene(model)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(23.9, 42.5, 13.4), Vec3(23.8, 33.4, 10.8))
        self.controller.setup()

        self.day_time = 0.3
        self.time_direction = 0

        # Keys to modify the time, disabled in the demo
        self.accept("k", self.reset)
        self.accept("p", self.set_time_direction, [1,])
        self.accept("p-up", self.set_time_direction, [0,])
        self.accept("i", self.set_time_direction, [-1,])
        self.accept("i-up", self.set_time_direction, [0,])

        self.addTask(self.update, "update")
Example #41
0
                            window-title {}
                            textures-power-2 none
                            framebuffer-multisample 1
                            multisamples 16
                            """.format(appName))

from direct.showbase.ShowBase import ShowBase
from direct.gui.DirectGui import *
import sys
sys.path.append(r"C:\Users\avise\Desktop\Games\RenderPipeline-master")

USE_RENDER_PIPELINE = True

if USE_RENDER_PIPELINE:
    from rpcore import RenderPipeline, SpotLight
    rp = RenderPipeline()

    models = {
        "terrain": "models/terrain.bam",
        "player": "models/jet/jet2.bam",
    }

else:
    models = {
        "terrain": "models/terrain_non_render_pipeline.egg",
        "player": "models/jet/jet2_non_render_pipeline.egg",
    }


class GameBase(ShowBase):
    def __init__(self, autoSetup=True, debug=False):
Example #42
0
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data("", """
        win-size 1600 900
        window-title Render Pipeline - Benchmark
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, PointLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # This is a helper class for better camera movement - its not really
        # a rendering element, but it included for convenience
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        # Set time of day
        self.render_pipeline.daytime_mgr.time = "17:41"

        self.camLens.set_fov(90)

        model = self.loader.load_model("scene/Scene.bam")
        model.reparent_to(self.render)

        model.flatten_strong()
        num_rows = 255

        img = PNMImage("scene/lights.png")

        for x in range(num_rows):
            for y in range(num_rows):
                light = PointLight()
                # light.direction = (0, 0, -1)
                # light.fov = 60
                # light.set_color_from_temperature(randint(2000, 20000))
                light.color = img.get_xel(x * 1, y * 1)
                light.energy = 5000 * (x / num_rows)
                light.pos = Vec3(-(x - num_rows // 2) / num_rows * 1000.0,
                                 (y - num_rows // 2) / num_rows * 1000.0, 2)
                light.radius = 4
                light.inner_radius = 0.5
                light.casts_shadows = False
                light.shadow_map_resolution = 256
                self.render_pipeline.add_light(light)

        self.render_pipeline.prepare_scene(model)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(0, 450, 200), Vec3(0))
        self.controller.setup()

        self.accept("l", self.benchmark)
Example #43
0
class MainApp(ShowBase):
    def __init__(self):

        # Setup window size, title and so on
        load_prc_file_data(
            "", """
            win-size 1600 900
            window-title Render Pipeline - Car Demo
        """)

        # ------ Begin of render pipeline code ------

        # Insert the pipeline path to the system path, this is required to be
        # able to import the pipeline classes
        pipeline_path = "../../"

        # Just a special case for my development setup, so I don't accidentally
        # commit a wrong path. You can remove this in your own programs.
        if not os.path.isfile(os.path.join(pipeline_path, "setup.py")):
            pipeline_path = "../../RenderPipeline/"

        sys.path.insert(0, pipeline_path)

        from rpcore import RenderPipeline, SpotLight
        self.render_pipeline = RenderPipeline()
        self.render_pipeline.create(self)

        # This is a helper class for better camera movement - its not really
        # a rendering element, but it included for convenience
        from rpcore.util.movement_controller import MovementController

        # ------ End of render pipeline code, thats it! ------

        self.render_pipeline.daytime_mgr.time = "20:08"

        # Load the scene
        model = loader.loadModel("scene/scene.bam")
        # model = loader.loadModel("scene2/Scene.bam")

        model.reparent_to(render)
        self.render_pipeline.prepare_scene(model)

        # Init movement controller
        self.controller = MovementController(self)
        self.controller.set_initial_position(Vec3(-7.5, -5.3, 1.8),
                                             Vec3(-5.9, -4.0, 1.6))
        self.controller.setup()

        base.accept("l", self.tour)

    def tour(self):
        """ Camera flythrough """
        mopath = (
            (Vec3(-10.8645000458, 9.76458263397,
                  2.13306283951), Vec3(-133.556228638, -4.23447799683, 0.0)),
            (Vec3(-10.6538448334, -5.98406457901,
                  1.68028640747), Vec3(-59.3999938965, -3.32706642151, 0.0)),
            (Vec3(9.58458328247, -5.63625621796,
                  2.63269257545), Vec3(58.7906494141, -9.40668964386, 0.0)),
            (Vec3(6.8135137558, 11.0153560638,
                  2.25509500504), Vec3(148.762527466, -6.41223621368, 0.0)),
            (Vec3(-9.07093334198, 3.65908527374,
                  1.42396306992), Vec3(245.362503052, -3.59927511215, 0.0)),
            (Vec3(-8.75390911102, -3.82727789879,
                  0.990055501461), Vec3(296.090484619, -0.604830980301, 0.0)),
        )
        self.controller.play_motion_path(mopath, 3.0)