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()
class Application(ShowBase): def __init__(self): # Setup window size and title load_prc_file_data("", """ # win-size 1600 900 window-title Render Pipeline - Projected Water 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" # Initialize the projected water self.water = ProjectedWater(WaterOptions) self.water.setup_water(pipeline=self.render_pipeline, water_level=-3.0) # 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()
class Demo(ShowBase): def __init__(self): from rpcore import RenderPipeline, PointLight from rpcore.util.movement_controller import MovementController self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) self.render_pipeline.daytime_mgr.time = '08:00' self.point_light = PointLight() self.point_light.set_color(1, 1, 0.9) self.point_light.set_energy(10) self.point_light.set_pos(0, 5, 2) self.point_light.set_radius(20) self.render_pipeline.add_light(self.point_light) self.ruby = Actor('ruby_mesh.gltf', {'idle': 'ruby_anim.egg'}) self.ruby.reparent_to(self.render) self.ruby.set_h(180) self.ruby.loop('idle') self.render_pipeline.set_effect(self.ruby, 'hardware_skinning.yaml', options={}, sort=25) sattrib = self.ruby.get_attrib(ShaderAttrib) sattrib = sattrib.set_flag(ShaderAttrib.F_hardware_skinning, True) self.ruby.set_attrib(sattrib) self.controller = MovementController(self) self.controller.set_initial_position_hpr( Vec3(0, 5, 1.75), # position Vec3(180, -10, 0)) # hpr self.controller.setup()
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 - 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()
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()
class Demo(ShowBase): def __init__(self): from rpcore import RenderPipeline, PointLight from rpcore.util.movement_controller import MovementController self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) self.render_pipeline.daytime_mgr.time = '08:00' self.point_light = PointLight() self.point_light.set_color(1, 1, 0.9) self.point_light.set_energy(10) self.point_light.set_pos(0, 5, 2) self.point_light.set_radius(20) self.render_pipeline.add_light(self.point_light) self.ruby = Actor('ruby.egg', {'idle': 'ruby_anim.egg'}) self.ruby.reparent_to(self.render) self.ruby.set_h(180) self.ruby.loop('idle') self.controller = MovementController(self) self.controller.set_initial_position_hpr( Vec3(0, 5, 1.75), # position Vec3(180, -10, 0)) # hpr self.controller.setup()
class Demo(ShowBase): def __init__(self): from rpcore import RenderPipeline, PointLight from rpcore.util.movement_controller import MovementController self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) self.render_pipeline.daytime_mgr.time = '08:00' self.point_light = PointLight() self.point_light.set_color(1, 1, 0.9) self.point_light.set_energy(10) self.point_light.set_pos(0, 5, 2) self.point_light.set_radius(20) self.render_pipeline.add_light(self.point_light) # load animations from EGG, because glTF animations aren't supported self.ruby_scene = self.loader.load_model('ruby.gltf') self.ruby = Actor(self.ruby_scene.find('+Character'), {'idle': 'ruby_anim.egg'}) self.ruby.reparent_to(self.render) self.ruby.set_h(180) self.ruby.loop('idle') self.controller = MovementController(self) self.controller.set_initial_position_hpr( Vec3(0, 5, 1.75), # position Vec3(180, -10, 0)) # hpr self.controller.setup()
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()
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")
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)
class RPPlugin: def __init__(self, app): self.app = app sys.path.insert(0, "./") sys.path.insert(0, "./RenderPipeline") from rpcore import RenderPipeline self.render_pipeline = RenderPipeline() self.render_pipeline.create(app) from rpcore.util.movement_controller import MovementController self.controller = MovementController(app) self.controller.setup()
class Application(ShowBase): def __init__(self): cwd = os.path.abspath(os.getcwd()) if cwd in sys.path: sys.path.remove(cwd) path = 'dist' for i in os.listdir(path): if i.endswith('.whl'): sys.path.insert(0, os.path.abspath(os.path.join(path, i))) from rpcore import RenderPipeline self.render_pipeline = RenderPipeline() self.render_pipeline.create(self)
class MyApp(ShowBase): def __init__(self): if not USE_RP: ShowBase.__init__(self) else: # Construct and create the pipeline self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) self.win.setClearColor(Vec4(0.5, 0.8, 0.8, 1)) self.disableMouse() if not USE_RP: self.render.setShaderAuto() self.loadingMessage = self.showLoadingMessage() self.world = World(self, USE_RP) self.acceptOnce('createWorld', self.createWorld) self.world.start('--gogogo' in sys.argv) def createWorld(self, task=None): self.loadingMessage.removeNode() self.doMethodLater(0.1, self.world.createWorld, 'create world') def showLoadingMessage(self): bigFont = self.loader.loadFont('Harting.ttf', pointSize=32).makeCopy() bigFont.setOutline(Vec4(0, 0, 0, 1), 1, 0) loadingMessage = self.render2d.attachNewNode('loading') OnscreenText('Loading...', fg=Vec4(0, 0, 0, .75), pos=(.01, -.01), font=bigFont, align=TextNode.A_center, parent=loadingMessage) OnscreenText('Loading...', fg=Vec4(1, 1, 1, 1), font=bigFont, align=TextNode.A_center, parent=loadingMessage) return loadingMessage
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)
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)
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)
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)
class TheGreatTTF(ShowBase): def __init__(self): # Construct and create the pipeline self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) self.render_pipeline.daytime_mgr.time = "19:17" # ShowBase.__init__(self) self.hexgrid = HexGrid(2, 2, self) ps = [None] def node_click(node): if ps[0] is not None: ps[0].deselect() node.select() ps[0] = node self.hexgrid.onclick(node_click)
class MainApp(ShowBase): def __init__(self): # game version game_version = 'version 0.1.3' # Setup window size and title load_prc_file_data("", """ win-size 1600 900 window-title Craft game {} """.format(game_version)) # ------ Begin of render pipeline code ------ self.render_pipeline = RenderPipeline() self.render_pipeline.create(self) # ------ End of render pipeline code, that is 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
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
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 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)
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)
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'
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)
class Application(ShowBase, object): ''' The default Application class which holds the code for Panda3D to run the game ''' def __init__(self, quality): # Set the model quality, (super-low, low or high) self.quality = quality print("[>] PoultryGeist:\t Setting Model Resolution to {}".format( self.quality.upper())) load_prc_file_data("", "win-size 1920 1080") # Run the standard Showbase init if running in super-low resolution mode # Do some stuff if the game is running at normal or high resolution if self.quality != 'super-low': # Construct and create the pipeline self.render_pipeline = RenderPipeline() self.render_pipeline.pre_showbase_init() super(Application, self).__init__() self.render_pipeline.create(self) # Enable anti-aliasing for the game render.setAntialias(AntialiasAttrib.MAuto) # Set the time pipeline lighting simulation time self.render_pipeline.daytime_mgr.time = "20:15" else: super(Application, self).__init__() # Enable the filter handler self.filters = CommonFilters(base.win, base.cam) self.filters.setAmbientOcclusion() # Enable particles and physics self.enableParticles() #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 """) # Set the window size self.width, self.height = (800, 600) # Initialise the movement controller self.controller = None # Turn off normal mouse controls self.disableMouse() # Hide the cursor self.props = WindowProperties() # self.props.setCursorHidden(True) # Lower the FOV to make the game more difficult self.win.requestProperties(self.props) self.camLens.setFov(60) # Reduces the distance of which the camera can render objects close to it self.camLens.setNear(0.1) # Store and empty renderTree for later use self.emptyRenderTree = deepcopy(self.render) # Register the buttons for movement # TODO remove this and overhaul the button handling self.w_button = KeyboardButton.ascii_key('w'.encode()) self.s_button = KeyboardButton.ascii_key('s'.encode()) self.l_button = KeyboardButton.ascii_key('l'.encode()) self.switch_button = KeyboardButton.ascii_key('p'.encode()) # Initialise the SceneManager self.sceneMgr = SceneManager(self) # Initialise the collision traverser self.collisionTraverser = CollisionTraverser('main_traverser') base.cTrav = self.collisionTraverser base.cTrav.showCollisions(self.render) # Add the sceneMgr events to run as a task taskMgr.add(self.sceneMgr.runSceneTasks, "scene-tasks") def loadSettings(self, options): ''' Iterate a dictionary of settings and apply them to the game ''' # Toggle the audio based on the options if options.get('audio', 'on') == 'off': base.disableAllAudio() windowProperties = WindowProperties() # Set the resolution if options.get('resolution') == '720p': windowProperties.setSize(1280, 720) # Set the app width and height variables self.width, self.height = (1280, 720) else: windowProperties.setSize(1920, 1080) # Set the app width and height variables self.width, self.height = (1920, 1080) # Apply the properties to the window base.win.requestProperties(windowProperties) load_prc_file_data('', 'win-size {} {}'.format(self.width, self.height)) 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)) def dumpTree(self): for a in self.render.getChildren(): print(a)
class Application(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 - 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()
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)
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
""" 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()
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)
class Application(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 - 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()
class GameControl(ShowBase): def __init__(self): load_prc_file_data("", "win-size 1600 900") load_prc_file_data("", "window-title :)") # Later maybe icon/sound # -------RENDER PIPELINE-------- pipeline_path = "../../" 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.create(self) # -------END OF PIPELINE ------- # time of day self.render_pipeline.daytime_mgr.time = 0.812 self.menu = Menu(self) self.level = Level(self) self.cube = Cube(self.level, "./models/player1.egg", 1) self.cube1 = Cube(self.level, "./models/player2.egg", 2) self.movement = Movement(self.cube, self.cube1) self.cube.setMovement(self.movement) self.cube1.setMovement(self.movement) 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): self.menu.hideMenu() self.level.loadLevel() self.cube.resetCube() self.cube.enableGameControl() self.cube1.resetCube() self.cube1.enableGameControl() base.accept("escape", self.pauseGame) def pauseGame(self): self.cube.disableGameControl() self.cube1.disableGameControl() self.menu.showMenu() self.menu.showResume() base.accept("escape", self.resumeGame) def resumeGame(self): self.menu.hideMenu() self.menu.hideResume() self.cube.enableGameControl() self.cube1.enableGameControl() base.accept("escape", self.pauseGame) def levelEnd(self): self.cube.disableGameControl() self.cube1.disableGameControl() self.menu.showMenu()
class Application(ShowBase): 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()
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, 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) 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 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.tr1) if (self.keyMap["cam-left"] != 0): base.camera.setX(base.camera, +100 * globalClock.getDt()) if (self.keyMap["cam-right"] != 0): base.camera.setX(base.camera, -100 * globalClock.getDt()) if (self.keyMap["backward"] != 0): self.gnode.removeNode() self.tr9 = create_triangle(100, 0, 0, 0, 100, 0, 0, 0, 100, (0, 1, 0, 1)) self.tr8 = create_triangle(0, 0, 0, 100, 200, 0, 200, 0, 200, (0, 1, 0, 1)) self.gnode = GeomNode('square') # gnode.addGeom(square1) # gnode.addGeom(square2) # gnode.addGeom(square3) self.gnode.addGeom(self.tr9) self.gnode.addGeom(self.tr8) # self.tr1.setPos(400,400, 0) self.render.attachNewNode(self.gnode) # startpos = self.gnode.getPos() return task.cont
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)
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))
class CIBase(ShowBase): notify = directNotify.newCategory("CIBase") DebugShaderQualities = False def __init__(self): self.bspLoader = Py_CL_BSPLoader() self.bspLoader.setGlobalPtr(self.bspLoader) if metadata.USE_RENDER_PIPELINE: from rpcore import RenderPipeline self.pipeline = RenderPipeline() self.pipeline.create(self) else: ShowBase.__init__(self) self.loader.destroy() self.loader = CogInvasionLoader(self) __builtin__.loader = self.loader self.graphicsEngine.setDefaultLoader(self.loader.loader) self.cam.node().getDisplayRegion(0).setClearDepthActive(1) from panda3d.core import RenderAttribRegistry from panda3d.core import ShaderAttrib, TransparencyAttrib from libpandabsp import BSPMaterialAttrib attribRegistry = RenderAttribRegistry.getGlobalPtr() attribRegistry.setSlotSort(BSPMaterialAttrib.getClassSlot(), 0) attribRegistry.setSlotSort(ShaderAttrib.getClassSlot(), 1) attribRegistry.setSlotSort(TransparencyAttrib.getClassSlot(), 2) gsg = self.win.getGsg() # Let's print out the Graphics information. self.notify.info( 'Graphics Information:\n\tVendor: {0}\n\tRenderer: {1}\n\tVersion: {2}\n\tSupports Cube Maps: {3}\n\tSupports 3D Textures: {4}\n\tSupports Compute Shaders: {5}' .format(gsg.getDriverVendor(), gsg.getDriverRenderer(), gsg.getDriverVersion(), str(gsg.getSupportsCubeMap()), str(gsg.getSupports3dTexture()), str(gsg.getSupportsComputeShaders()))) # Enable shader generation on all of the main scenes if gsg.getSupportsBasicShaders() and gsg.getSupportsGlsl(): render.setShaderAuto() render2d.setShaderAuto() render2dp.setShaderAuto() else: # I don't know how this could be possible self.notify.error("GLSL shaders unsupported by graphics driver.") return # Let's disable fog on Intel graphics if gsg.getDriverVendor() == "Intel": metadata.NO_FOG = 1 self.notify.info('Applied Intel-specific graphical fix.') self.win.disableClears() self.camNode.setCameraMask(CIGlobals.MainCameraBitmask) from direct.distributed.ClockDelta import globalClockDelta __builtin__.globalClockDelta = globalClockDelta # Any ComputeNodes should be parented to this node, not render. # We isolate ComputeNodes to avoid traversing the same ComputeNodes # when doing multi-pass rendering. self.computeRoot = NodePath('computeRoot') self.computeCam = self.makeCamera(base.win) self.computeCam.node().setCullBounds(OmniBoundingVolume()) self.computeCam.node().setFinal(True) self.computeCam.reparentTo(self.computeRoot) # Initialized in initStuff() self.shaderGenerator = None render.hide() self.camLens.setNearFar(0.5, 10000) self.physicsWorld = BulletWorld() # Panda units are in feet, so the gravity is 32 feet per second, # not 9.8 meters per second. self.physicsWorld.setGravity(Vec3(0, 0, -32.1740)) self.physicsWorld.setGroupCollisionFlag(7, 1, True) self.physicsWorld.setGroupCollisionFlag(7, 2, True) self.physicsWorld.setGroupCollisionFlag(7, 3, False) self.physicsWorld.setGroupCollisionFlag(7, 4, False) self.physicsWorld.setGroupCollisionFlag(7, 8, True) self.taskMgr.add(self.__physicsUpdate, "physicsUpdate", sort=30) debugNode = BulletDebugNode('Debug') self.debugNP = render.attachNewNode(debugNode) self.physicsWorld.setDebugNode(self.debugNP.node()) self.physicsDbgFlag = False self.setPhysicsDebug(self.config.GetBool('physics-debug', False)) #self.shadowCaster = ShadowCaster(Vec3(163, -67, 0)) #self.shadowCaster.enable() self.bspLoader.setGamma(2.2) self.bspLoader.setWin(self.win) self.bspLoader.setCamera(self.camera) self.bspLoader.setRender(self.render) self.bspLoader.setMaterialsFile("phase_14/etc/materials.txt") #self.bspLoader.setTextureContentsFile("phase_14/etc/texturecontents.txt") self.bspLoader.setWantVisibility(True) self.bspLoader.setVisualizeLeafs(False) self.bspLoader.setWantLightmaps(True) #self.bspLoader.setShadowCamPos(Point3(-15, 5, 40)) #self.bspLoader.setShadowResolution(60 * 2, 1024 * 1) self.bspLoader.setPhysicsWorld(self.physicsWorld) self.bspLevel = None self.materialData = {} self.skyBox = None self.skyBoxUtil = None #self.nmMgr = RNNavMeshManager.get_global_ptr() #self.nmMgr.set_root_node_path(self.render) #self.nmMgr.get_reference_node_path().reparentTo(self.render) #self.nmMgr.start_default_update() #self.nmMgr.get_reference_node_path_debug().reparentTo(self.render) self.navMeshNp = None # Setup 3d audio run before igLoop so 3d positioning doesn't lag behind base.audio3d = Audio3DManager(base.sfxManagerList[0], camera, render) base.audio3d.setDropOffFactor(0.15) base.audio3d.setDopplerFactor(0.15) # Setup collision handlers base.cTrav = CollisionTraverser() base.lifter = CollisionHandlerFloor() base.pusher = CollisionHandlerPusher() base.queue = CollisionHandlerQueue() base.lightingCfg = None self.cl_attackMgr = None #self.accept('/', self.projectShadows) # Let's setup the user input storage system uis = UserInputStorage() self.inputStore = uis self.userInputStorage = uis __builtin__.inputStore = uis __builtin__.userInputStorage = uis self.credits2d = self.render2d.attachNewNode(PGTop("credits2d")) self.credits2d.setScale(1.0 / self.getAspectRatio(), 1.0, 1.0) self.wakeWaterHeight = -30.0 self.bloomToggle = False self.hdrToggle = False self.fxaaToggle = CIGlobals.getSettingsMgr().getSetting( "aa").getValue() == "FXAA" self.aoToggle = False self.music = None self.currSongName = None render.show(CIGlobals.ShadowCameraBitmask) self.avatars = [] wrm = WaterReflectionManager() self.waterReflectionMgr = wrm __builtin__.waterReflectionMgr = wrm # Let's setup our margins base.marginManager = MarginManager() base.margins = aspect2d.attachNewNode( base.marginManager, DirectGuiGlobals.MIDGROUND_SORT_INDEX + 1) base.leftCells = [ base.marginManager.addCell(0.1, -0.6, base.a2dTopLeft), base.marginManager.addCell(0.1, -1.0, base.a2dTopLeft), base.marginManager.addCell(0.1, -1.4, base.a2dTopLeft) ] base.bottomCells = [ base.marginManager.addCell(0.4, 0.1, base.a2dBottomCenter), base.marginManager.addCell(-0.4, 0.1, base.a2dBottomCenter), base.marginManager.addCell(-1.0, 0.1, base.a2dBottomCenter), base.marginManager.addCell(1.0, 0.1, base.a2dBottomCenter) ] base.rightCells = [ base.marginManager.addCell(-0.1, -0.6, base.a2dTopRight), base.marginManager.addCell(-0.1, -1.0, base.a2dTopRight), base.marginManager.addCell(-0.1, -1.4, base.a2dTopRight) ] base.mouseWatcherNode.setEnterPattern('mouse-enter-%r') base.mouseWatcherNode.setLeavePattern('mouse-leave-%r') base.mouseWatcherNode.setButtonDownPattern('button-down-%r') base.mouseWatcherNode.setButtonUpPattern('button-up-%r') cbm = CullBinManager.getGlobalPtr() cbm.addBin('ground', CullBinManager.BTUnsorted, 18) # The portal uses the shadow bin by default, # but we still want to see it with real shadows. cbm.addBin('portal', CullBinManager.BTBackToFront, 19) if not metadata.USE_REAL_SHADOWS: cbm.addBin('shadow', CullBinManager.BTBackToFront, 19) else: cbm.addBin('shadow', CullBinManager.BTFixed, -100) cbm.addBin('gui-popup', CullBinManager.BTUnsorted, 60) cbm.addBin('gsg-popup', CullBinManager.BTFixed, 70) self.setBackgroundColor(CIGlobals.DefaultBackgroundColor) self.disableMouse() self.enableParticles() base.camLens.setNearFar(CIGlobals.DefaultCameraNear, CIGlobals.DefaultCameraFar) base.transitions = CITransitions(loader) base.transitions.IrisModelName = "phase_3/models/misc/iris.bam" base.transitions.FadeModelName = "phase_3/models/misc/fade.bam" self.accept(self.inputStore.TakeScreenshot, ScreenshotHandler.takeScreenshot) #self.accept('u', render.setShaderOff) #self.accept('i', render.setShaderOff, [1]) #self.accept('o', render.setShaderOff, [2]) # Disabled oobe culling #self.accept('o', self.oobeCull) #self.accept('c', self.reportCam) self.taskMgr.add(self.__updateShadersAndPostProcess, 'CIBase.updateShadersAndPostProcess', 47) self.taskMgr.add(self.__update3DAudio, 'CIBase.update3DAudio', 59) def windowEvent(self, win): ShowBase.windowEvent(self, win) if hasattr(self, 'filters'): self.filters.windowEvent() def __update3DAudio(self, task): self.audio3d.update() return task.cont def __updateShadersAndPostProcess(self, task): if self.shaderGenerator: self.shaderGenerator.update() if hasattr(self, 'filters'): self.filters.update() return task.cont def hideHood(self): base.cr.playGame.hood.loader.geom.hide() def reportCam(self): print self.camera print self.camera.getNetTransform() self.camera.setScale(render, 1) self.camera.setShear(render, 0) """ print 'TPM START' tpMgr = TextPropertiesManager.getGlobalPtr() print 'PROPERTIES GET' tpRed = TextProperties() tpRed.setTextColor(1, 0, 0, 1) tpSlant = TextProperties() tpSlant.setSlant(0.3) print 'RED AND SLANT GENERATED' tpMgr.setProperties('red', tpRed) print 'RED SET' try: tpMgr.setProperties('slant', tpSlant) except Exception: print 'AN EXCEPTION OCCURRED' print 'SLANT SET' print 'TPM END' """ def convertHammerAngles(self, angles): """ (pitch, yaw + 90, roll) -> (yaw, pitch, roll) """ temp = angles[0] angles[0] = angles[1] - 90 angles[1] = temp return angles def planPath(self, startPos, endPos): """Uses recast/detour to find a path from the generated nav mesh from the BSP file.""" if not self.navMeshNp: return [startPos, endPos] result = [] valueList = self.navMeshNp.node().path_find_follow(startPos, endPos) for i in xrange(valueList.get_num_values()): result.append(valueList.get_value(i)) return result def getBSPLevelLightEnvironmentData(self): # [has data, angles, color] data = [0, Vec3(0), Vec4(0)] if not self.bspLoader.hasActiveLevel(): return data for i in xrange(self.bspLoader.getNumEntities()): classname = self.bspLoader.getEntityValue(i, "classname") if classname == "light_environment": data[0] = 1 data[1] = self.convertHammerAngles( self.bspLoader.getEntityValueVector(i, "angles")) data[2] = self.bspLoader.getEntityValueColor(i, "_light") break return data def cleanupSkyBox(self): if self.skyBoxUtil: self.skyBoxUtil.stopSky() self.skyBoxUtil.cleanup() self.skyBoxUtil = None if self.skyBox: self.skyBox.removeNode() self.skyBox = None def cleanupBSPLevel(self): self.cleanupSkyBox() #self.cleanupNavMesh() if self.bspLevel: # Cleanup any physics meshes for the level. self.disableAndRemovePhysicsNodes(self.bspLevel) self.bspLevel.removeNode() self.bspLevel = None self.bspLoader.cleanup() base.materialData = {} #def cleanupNavMesh(self): # if self.navMeshNp: # self.navMeshNp.removeNode() # self.navMeshNp = None #def setupNavMesh(self, node): # self.cleanupNavMesh() # nmMgr = RNNavMeshManager.get_global_ptr() # self.navMeshNp = nmMgr.create_nav_mesh() # self.navMeshNp.node().set_owner_node_path(node) # self.navMeshNp.node().setup() # if 0: # self.navMeshNp.node().enable_debug_drawing(self.camera) # self.navMeshNp.node().toggle_debug_drawing(True) def setupRender(self): """ Creates the render scene graph, the primary scene graph for rendering 3-d geometry. """ ## This is the root of the 3-D scene graph. ## Make it a BSPRender node to automatically cull ## nodes against the BSP leafs if there is a loaded ## BSP level. self.render = NodePath(BSPRender('render', BSPLoader.getGlobalPtr())) self.render.setAttrib(RescaleNormalAttrib.makeDefault()) self.render.setTwoSided(0) self.backfaceCullingEnabled = 1 self.textureEnabled = 1 self.wireframeEnabled = 0 def loadSkyBox(self, skyType): if skyType != OutdoorLightingConfig.STNone: self.skyBox = loader.loadModel( OutdoorLightingConfig.SkyData[skyType][0]) self.skyBox.hide(CIGlobals.ShadowCameraBitmask) self.skyBox.reparentTo(camera) self.skyBox.setCompass() self.skyBox.setZ(-350) self.skyBoxUtil = SkyUtil() self.skyBoxUtil.startSky(self.skyBox) def loadBSPLevel(self, mapFile): self.cleanupBSPLevel() base.bspLoader.read(mapFile) base.bspLevel = base.bspLoader.getResult() base.bspLoader.doOptimizations() for prop in base.bspLevel.findAllMatches("**/+BSPProp"): base.createAndEnablePhysicsNodes(prop) #base.setupNavMesh(base.bspLevel.find("**/model-0")) try: skyType = self.cr.playGame.hood.olc.skyType except: skyType = 1 #self.bspLoader.getEntityValueInt(0, "skytype") if skyType != OutdoorLightingConfig.STNone: skyCubemap = loader.loadCubeMap( OutdoorLightingConfig.SkyData[skyType][2]) self.shaderGenerator.setIdentityCubemap(skyCubemap) CIGlobals.preRenderScene(render) def doNextFrame(self, func, extraArgs=[]): taskMgr.add(self.__doNextFrameTask, "doNextFrame" + str(id(func)), extraArgs=[func, extraArgs], appendTask=True, sort=100000) def __doNextFrameTask(self, func, extraArgs, task): func(*extraArgs) return task.done def loadSfxOnNode(self, sndFile, node): """ Loads up a spatialized sound and attaches it to the specified node. """ snd = self.audio3d.loadSfx(sndFile) self.audio3d.attachSoundToObject(snd, node) return snd def physicsReport(self): print "\nThere are {0} total rigid bodies:".format( base.physicsWorld.getNumRigidBodies()) for rb in base.physicsWorld.getRigidBodies(): print "\t", NodePath(rb) print "\n" def removeEverything(self): for task in self.taskMgr.getTasks(): if task.getName() not in ['dataLoop', 'igLoop']: task.remove() camera.reparentTo(render) for tex in render.findAllTextures(): tex.releaseAll() for tex in aspect2d.findAllTextures(): tex.releaseAll() for tex in render2d.findAllTextures(): tex.releaseAll() for tex in hidden.findAllTextures(): tex.releaseAll() for node in render.findAllMatches("**;+s"): node.removeNode() for node in aspect2d.findAllMatches("**;+s"): node.removeNode() for node in render2d.findAllMatches("**;+s"): node.removeNode() for node in hidden.findAllMatches("**;+s"): node.removeNode() TexturePool.garbageCollect() ModelPool.garbageCollect() RenderState.garbageCollect() RenderState.clearCache() RenderState.clearMungerCache() self.win.getGsg().getPreparedObjects().releaseAll() self.graphicsEngine.renderFrame() def doMemReport(self): MemoryUsage.showCurrentTypes() MemoryUsage.showCurrentAges() print MemoryUsage.getCurrentCppSize() print MemoryUsage.getExternalSize() print MemoryUsage.getTotalSize() def doPointers(self): print "---------------------------------------------------------------------" data = {} mup = MemoryUsagePointers() MemoryUsage.getPointers(mup) for i in xrange(mup.getNumPointers()): ptr = mup.getPythonPointer(i) if ptr.__class__.__name__ in data.keys(): data[ptr.__class__.__name__] += 1 else: data[ptr.__class__.__name__] = 1 print "NodeReferenceCount:", data["NodeReferenceCount"] print "CopyOnWriteObject:", data["CopyOnWriteObject"] print "---------------------------------------------------------------------" def hideMouseCursor(self): props = WindowProperties() props.setCursorHidden(True) self.win.requestProperties(props) def showMouseCursor(self): props = WindowProperties() props.setCursorHidden(False) self.win.requestProperties(props) def doCamShake(self, intensity=1.0, duration=0.5, loop=False): shake = ShakeCamera(intensity, duration) shake.start(loop) return shake def renderFrames(self): self.graphicsEngine.renderFrame() self.graphicsEngine.renderFrame() def prepareScene(self): render.prepareScene(self.win.getGsg()) def setPhysicsDebug(self, flag): self.physicsDbgFlag = flag debugNode = self.debugNP.node() if flag: debugNode.showWireframe(True) debugNode.showConstraints(True) debugNode.showBoundingBoxes(True) debugNode.showNormals(False) self.debugNP.show() else: debugNode.showWireframe(False) debugNode.showConstraints(False) debugNode.showBoundingBoxes(False) debugNode.showNormals(False) self.debugNP.hide() def stopMusic(self): if self.music: self.music.stop() self.music = None self.currSongName = None def playMusic(self, songName, looping=True, volume=1.0): if isinstance(songName, list): # A list of possible songs were passed in, pick a random one. songName = random.choice(songName) if songName == self.currSongName: # Don't replay the same song. return self.stopMusic() self.currSongName = songName song = MusicCache.findSong(songName) if not song: self.notify.warning( "Song `{0}` not found in cache.".format(songName)) return self.music = song self.music.setLoop(looping) self.music.setVolume(volume) self.music.play() def fadeOutMusic(self, time=1.0, music=None): if not music: music = self.music if not music: return self.fadeAudio(time, music, music.getVolume(), 0.0) def fadeAudio(self, time, audio, start, end): from direct.interval.IntervalGlobal import LerpFunc def __changeMusicVolume(vol): audio.setVolume(vol) LerpFunc(__changeMusicVolume, time, start, end).start() def enablePhysicsNodes(self, rootNode): PhysicsUtils.attachBulletNodes(rootNode) def disablePhysicsNodes(self, rootNode): PhysicsUtils.detachBulletNodes(rootNode) def createPhysicsNodes(self, rootNode): PhysicsUtils.makeBulletCollFromPandaColl(rootNode) def createAndEnablePhysicsNodes(self, rootNode): self.createPhysicsNodes(rootNode) self.enablePhysicsNodes(rootNode) def removePhysicsNodes(self, rootNode): PhysicsUtils.removeBulletNodes(rootNode) def disableAndRemovePhysicsNodes(self, rootNode): PhysicsUtils.detachAndRemoveBulletNodes(rootNode) def __physicsUpdate(self, task): dt = globalClock.getDt() if dt <= 0.016: self.physicsWorld.doPhysics(dt, metadata.PHYS_SUBSTEPS, 0.016) elif dt <= 0.033: self.physicsWorld.doPhysics(dt, metadata.PHYS_SUBSTEPS, 0.033) else: self.physicsWorld.doPhysics(dt, 0) return task.cont def projectShadows(self): #self.shadowCaster.projectShadows() pass def setBloom(self, flag): self.bloomToggle = flag #if not hasattr(self, 'filters'): # # Sanity check # return #if flag: # self.filters.setBloom(desat = 0, intensity = 0.4, mintrigger = 0.85, maxtrigger = 1.0, size = "large") #else: # self.filters.delBloom() def initStuff(self): # Precache water bar shader, prevents crash from running out of GPU registers loader.loadShader("phase_14/models/shaders/progress_bar.sha") self.bspLoader.setWantShadows(metadata.USE_REAL_SHADOWS) self.shaderGenerator = BSPShaderGenerator(self.win, self.win.getGsg(), self.camera, self.render) self.win.getGsg().setShaderGenerator(self.shaderGenerator) self.bspLoader.setShaderGenerator(self.shaderGenerator) vlg = VertexLitGenericSpec() # models ulg = UnlitGenericSpec() # ui elements, particles, etc lmg = LightmappedGenericSpec() # brushes, displacements unm = UnlitNoMatSpec() # when there's no material csm = CSMRenderSpec() # renders the shadow scene for CSM skb = SkyBoxSpec() # renders the skybox onto faces dcm = DecalModulateSpec() # blends decals self.shaderGenerator.addShader(vlg) self.shaderGenerator.addShader(ulg) self.shaderGenerator.addShader(unm) self.shaderGenerator.addShader(lmg) self.shaderGenerator.addShader(csm) self.shaderGenerator.addShader(skb) self.shaderGenerator.addShader(dcm) self.shaderGenerator.setShaderQuality( CIGlobals.getSettingsMgr().getSetting("shaderquality").getValue()) if metadata.USE_REAL_SHADOWS and self.config.GetBool( 'pssm-debug-cascades', False): from panda3d.core import CardMaker, Shader #, Camera, Trackball cm = CardMaker('cm') cm.setFrame(-1, 1, -1, 1) np = aspect2d.attachNewNode(cm.generate()) np.setScale(0.3) np.setPos(0, -0.7, -0.7) np.setShader( Shader.load(Shader.SLGLSL, "phase_14/models/shaders/debug_csm.vert.glsl", "phase_14/models/shaders/debug_csm.frag.glsl")) np.setShaderInput("cascadeSampler", self.shaderGenerator.getPssmArrayTexture()) #cam = Camera('csmDbgCam') #tb = Trackball('tb') #lens = PerspectiveLens() #cam.setLens(lens) #cam.reparentTo(render) #base.openWindow(useCamera = cam) #self.shadowCaster.turnOnShadows() self.waterReflectionMgr.load() self.filters = CIPostProcess() self.filters.startup(self.win) self.filters.addCamera(self.cam) self.filters.setup() self.hdr = HDR() self.setHDR(self.hdrToggle) self.setBloom(self.bloomToggle) self.setFXAA(self.fxaaToggle) self.setAmbientOcclusion(self.aoToggle) #self.filters.setDepthOfField(distance = 10.0, range = 175.0, near = 1.0, far = 1000.0 / (1000.0 - 1.0)) #from src.coginvasion.globals import BSPUtility #BSPUtility.applyUnlitOverride(render) # We define this here (naming it cl_ to avoid trying to use the old base.attackMgr) # in order to precache attacks. The ClientRepository will then take our self.cl_attackMgr # and use it as base.cr.attackMgr. from src.coginvasion.attack.AttackManager import AttackManager self.cl_attackMgr = AttackManager() if self.DebugShaderQualities: from libpandabsp import SHADERQUALITY_HIGH, SHADERQUALITY_MEDIUM, SHADERQUALITY_LOW self.accept('1', self.shaderGenerator.setShaderQuality, [SHADERQUALITY_LOW]) self.accept('2', self.shaderGenerator.setShaderQuality, [SHADERQUALITY_MEDIUM]) self.accept('3', self.shaderGenerator.setShaderQuality, [SHADERQUALITY_HIGH]) def makeCamera(self, win, sort=0, scene=None, displayRegion=(0, 1, 0, 1), stereo=None, aspectRatio=None, clearDepth=0, clearColor=None, lens=None, camName='cam', mask=None, useCamera=None): """ Makes a new 3-d camera associated with the indicated window, and creates a display region in the indicated subrectangle. If stereo is True, then a stereo camera is created, with a pair of DisplayRegions. If stereo is False, then a standard camera is created. If stereo is None or omitted, a stereo camera is created if the window says it can render in stereo. If useCamera is not None, it is a NodePath to be used as the camera to apply to the window, rather than creating a new camera. """ # self.camera is the parent node of all cameras: a node that # we can move around to move all cameras as a group. if self.camera == None: # We make it a ModelNode with the PTLocal flag, so that # a wayward flatten operations won't attempt to mangle the # camera. self.camera = self.render.attachNewNode(ModelNode('camera')) self.camera.node().setPreserveTransform(ModelNode.PTLocal) builtins.camera = self.camera self.mouse2cam.node().setNode(self.camera.node()) if useCamera: # Use the existing camera node. cam = useCamera camNode = useCamera.node() assert (isinstance(camNode, Camera)) lens = camNode.getLens() cam.reparentTo(self.camera) else: # Make a new Camera node. camNode = Camera(camName) if lens == None: lens = PerspectiveLens() if aspectRatio == None: aspectRatio = self.getAspectRatio(win) lens.setAspectRatio(aspectRatio) cam = self.camera.attachNewNode(camNode) if lens != None: camNode.setLens(lens) if scene != None: camNode.setScene(scene) if mask != None: if (isinstance(mask, int)): mask = BitMask32(mask) camNode.setCameraMask(mask) if self.cam == None: self.cam = cam self.camNode = camNode self.camLens = lens self.camList.append(cam) # Now, make a DisplayRegion for the camera. if stereo is not None: if stereo: dr = win.makeStereoDisplayRegion(*displayRegion) else: dr = win.makeMonoDisplayRegion(*displayRegion) else: dr = win.makeDisplayRegion(*displayRegion) dr.setSort(sort) dr.disableClears() # By default, we do not clear 3-d display regions (the entire # window will be cleared, which is normally sufficient). But # we will if clearDepth is specified. if clearDepth: dr.setClearDepthActive(1) if clearColor: dr.setClearColorActive(1) dr.setClearColor(clearColor) dr.setCamera(cam) return cam def makeCamera2d(self, win, sort=10, displayRegion=(0, 1, 0, 1), coords=(-1, 1, -1, 1), lens=None, cameraName=None): """ Makes a new camera2d associated with the indicated window, and assigns it to render the indicated subrectangle of render2d. """ dr = win.makeMonoDisplayRegion(*displayRegion) dr.setSort(sort) dr.disableClears() # Make any texture reloads on the gui come up immediately. dr.setIncompleteRender(False) left, right, bottom, top = coords # Now make a new Camera node. if (cameraName): cam2dNode = Camera('cam2d_' + cameraName) else: cam2dNode = Camera('cam2d') if lens == None: lens = OrthographicLens() lens.setFilmSize(right - left, top - bottom) lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5) lens.setNearFar(-1000, 1000) cam2dNode.setLens(lens) # self.camera2d is the analog of self.camera, although it's # not as clear how useful it is. if self.camera2d == None: self.camera2d = self.render2d.attachNewNode('camera2d') camera2d = self.camera2d.attachNewNode(cam2dNode) dr.setCamera(camera2d) if self.cam2d == None: self.cam2d = camera2d return camera2d def precacheStuff(self): from src.coginvasion.toon import ToonGlobals ToonGlobals.precacheToons() self.cl_attackMgr.precache() from src.coginvasion.gags.LocationSeeker import LocationSeeker LocationSeeker.precache() from src.coginvasion.gags.LocationGag import LocationGag LocationGag.precache() from src.coginvasion.hood.DistributedBuilding import DistributedBuilding DistributedBuilding.precache() from src.coginvasion.cog import SuitBank SuitBank.precacheSuits() def setAmbientOcclusion(self, toggle): self.aoToggle = toggle #if not hasattr(self, 'filters'): # # Sanity check # return #if toggle: # self.filters.setAmbientOcclusion() #else: # self.filters.delAmbientOcclusion() def setFXAA(self, toggle): self.fxaaToggle = toggle #if not hasattr(self, 'filters'): # # Sanity check # return #if toggle: # self.filters.setFXAA() #else: # self.filters.delFXAA() def setHDR(self, toggle): self.hdrToggle = toggle #if not hasattr(self, 'hdr'): # return if toggle: # Don't clamp lighting calculations with hdr. render.setAttrib(LightRampAttrib.makeIdentity()) #self.hdr.enable() else: render.setAttrib(LightRampAttrib.makeDefault()) #self.hdr.disable() def setCellsActive(self, cells, active): for cell in cells: cell.setActive(active) self.marginManager.reorganize() def setTimeOfDay(self, time): if self.metadata.USE_RENDER_PIPELINE: self.pipeline.daytime_mgr.time = time def doOldToontownRatio(self): ShowBase.adjustWindowAspectRatio(self, 4. / 3.) self.credits2d.setScale(1.0 / (4. / 3.), 1.0, 1.0) def doRegularRatio(self): ShowBase.adjustWindowAspectRatio(self, self.getAspectRatio()) def adjustWindowAspectRatio(self, aspectRatio): if (CIGlobals.getSettingsMgr() is None): ShowBase.adjustWindowAspectRatio(self, aspectRatio) self.credits2d.setScale(1.0 / aspectRatio, 1.0, 1.0) return if CIGlobals.getSettingsMgr().getSetting("maspr").getValue(): # Go ahead and maintain the aspect ratio if the user wants us to. ShowBase.adjustWindowAspectRatio(self, aspectRatio) self.credits2d.setScale(1.0 / aspectRatio, 1.0, 1.0) else: # The user wants us to keep a 4:3 ratio no matter what (old toontown feels). self.doOldToontownRatio() def muteMusic(self): self.musicManager.setVolume(0.0) def unMuteMusic(self): self.musicManager.setVolume( CIGlobals.SettingsMgr.getSetting("musvol").getValue()) def muteSfx(self): self.sfxManagerList[0].setVolume(0.0) def unMuteSfx(self): self.sfxManagerList[0].setVolume( CIGlobals.SettingsMgr.getSetting("sfxvol").getValue()) def localAvatarReachable(self): # This verifies that the localAvatar hasn't been deleted and isn't none. return hasattr(self, 'localAvatar') and self.localAvatar
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"])
class Application(ShowBase): 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) def reload(self): print("Reloading") self.render_pipeline.reload_shaders() for i in range(4): self.taskMgr.step() self.win.save_screenshot("scene-rp.png")
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 # 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 = self.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( self.render).get_mat() transform_mat = Mat4.convert_mat( CS_zup_right, CS_yup_right) * transform_mat self.camera.set_mat(transform_mat) else: print("WARNING: No camera found") self.camera.set_pos(0, -3.5, 0) self.camera.look_at(0, -2.5, 0) self.camLens.set_fov(64.0) self.scene_node = scene scene.reparent_to(self.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
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 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 - 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") def reset(self): self.day_time = 0.209 def set_time_direction(self, direction): self.time_direction = direction def update(self, task): """ Update method """ frame_time = globalClock.get_frame_time() # Make the lights glow for i, light in enumerate(self._lights): brightness = math.sin(0.4 * i + frame_time * 1.0) light.energy = max(0, self.half_energy / 2 + brightness * self.half_energy) return task.cont
class Application(ShowBase): 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) def reload(self): print("Reloading") self.render_pipeline.reload_shaders() for i in range(4): self.taskMgr.step() self.win.save_screenshot("scene-rp.png")
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 - 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") def reset(self): self.day_time = 0.209 def set_time_direction(self, direction): self.time_direction = direction def update(self, task): """ Update method """ frame_time = globalClock.get_frame_time() # Make the lights glow for i, light in enumerate(self._lights): brightness = math.sin(0.4 * i + frame_time * 1.0) light.energy = max( 0, self.half_energy / 2 + brightness * self.half_energy) return task.cont
""" 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()