def __init__(self): load_prc_file_data("", """ textures-power-2 none window-type offscreen win-size 100 100 gl-coordinate-system default notify-level-display error print-pipe-types #f """) ShowBase.__init__(self) dest_tex = Texture() dest_tex.setup_2d_texture(2048, 2048, Texture.T_unsigned_byte, Texture.F_rgba8) cshader = Shader.load_compute(Shader.SL_GLSL, "grain.compute.glsl") node = NodePath("") node.set_shader(cshader) node.set_shader_input("DestTex", dest_tex) attr = node.get_attrib(ShaderAttrib) self.graphicsEngine.dispatch_compute( (2048 // 16, 2048 // 16, 1), attr, self.win.get_gsg()) base.graphicsEngine.extract_texture_data(dest_tex, base.win.get_gsg()) # Convert to single channel img = PNMImage(2048, 2048, 1, 255) dest_tex.store(img) img.set_num_channels(1) tex = Texture() tex.load(img) tex.write("grain.txo.pz")
def __init__(self): # 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()
def __init__(self): self.cvMgr = ConfigVariableManager.getGlobalPtr() load_prc_file_data('', 'textures-power-2 none') super().__init__() blenderpanda.init(self) self.accept('escape', sys.exit) if logger.isEnabledFor(logging.DEBUG): self.accept('d', self.toggle_debug_tools) for scene in scenes.available_scenes: self.addScene(scene()) # - surfdog - self.addScene(Scene('surfdog', filename='surfdog', # - surfdog - scale=[5.0, 0.1, 5.0], # - surfdog - position=[-8, 22, -2] # - surfdog - )) # -cannon- self.addScene(Scene('cannon', filename='cannon', # -cannon- position=[0,22,0], # -cannon- hpr=[-45,0,0] # -cannon- )) self.load_registered_scenes() # setup Horizons self.horizon = 'skysphere' self.addHorizon(Background('skysphere', filename='skysphere_mk2.egg')) self.addHorizon(Background('skybox', filename='skybox_1024')) self.load_horizon(self.horizon) self.console = ConsoleWindow(self) # explicit first hide self.console.toggleConsole(hide=True) self.setControls() self.render.set_shader_auto() atexit.register(self.killRestServer)
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()
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 showbase(request): extra_prc = request.param if hasattr(request, 'param') else '' print(extra_prc) p3d.load_prc_file_data('', f'{PRC_BASE}\n{extra_prc}') showbase = ShowBase() yield showbase showbase.destroy()
def __init__(self): load_prc_file_data( "", """ textures-power-2 none window-type offscreen win-size 100 100 gl-coordinate-system default notify-level-display error print-pipe-types #f """) ShowBase.__init__(self) dest_tex = Texture() dest_tex.setup_2d_texture(2048, 2048, Texture.T_unsigned_byte, Texture.F_rgba8) cshader = Shader.load_compute(Shader.SL_GLSL, "grain.compute.glsl") node = NodePath("") node.set_shader(cshader) node.set_shader_input("DestTex", dest_tex) attr = node.get_attrib(ShaderAttrib) self.graphicsEngine.dispatch_compute((2048 // 16, 2048 // 16, 1), attr, self.win.get_gsg()) base.graphicsEngine.extract_texture_data(dest_tex, base.win.get_gsg()) # Convert to single channel img = PNMImage(2048, 2048, 1, 255) dest_tex.store(img) img.set_num_channels(1) tex = Texture() tex.load(img) tex.write("grain.txo.pz")
def __init__(self): # 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()
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 Data/GUI/icon.ico """) # Load render pipeline self.render_pipeline = RenderPipeline(self) self.render_pipeline.create() self.render_pipeline.create_default_skybox() # 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 __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()
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()
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 Data/GUI/icon.ico """) # Load render pipeline self.render_pipeline = RenderPipeline(self) self.render_pipeline.create() self.render_pipeline.create_default_skybox() # 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 showbase(): from direct.showbase.ShowBase import ShowBase p3d.load_prc_file_data( '', 'window-type offscreen\n' 'framebuffer-hardware false\n' ) return ShowBase()
def showbase(request): extra_prc = request.param from direct.showbase.ShowBase import ShowBase print(extra_prc) p3d.load_prc_file_data('', f'{PRC_BASE}\n{extra_prc}') showbase = ShowBase() yield showbase showbase.destroy()
def __init__(self): """ Load some configuration variables, it's important for this to happen before the ShowBase is initialized """ load_prc_file_data( "", """ sync-video #t ### add entries below if you are not running from an installation. #model-path /path/to/panda3d """) ShowBase.__init__(self) base.set_background_color(0.1, 0.1, 0.8, 1) base.set_frame_rate_meter(True) base.cam.set_pos(0, -20, 4) base.cam.look_at(0, 0, 0) # Light alight = AmbientLight('ambientLight') alight.set_color(LVector4(0.5, 0.5, 0.5, 1)) alightNP = render.attach_new_node(alight) dlight = DirectionalLight('directionalLight') dlight.set_direction(LVector3(1, 1, -1)) dlight.set_color(LVector4(0.7, 0.7, 0.7, 1)) dlightNP = render.attach_new_node(dlight) render.clear_light() render.set_light(alightNP) render.set_light(dlightNP) # Input self.accept('escape', self.do_exit) self.accept('r', self.do_reset) self.accept('f1', base.toggle_wireframe) self.accept('f2', base.toggle_texture) self.accept('f3', self.toggle_debug) self.accept('f5', self.do_screenshot) self.accept('space', self.do_jump) self.accept('c', self.do_crouch) inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('reverse', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def __init__(self): load_prc_file_data("", """ stm-max-chunk-count 1024 stm-max-views 20 """) self.world = None self.worldNP = None # Setup everything self.setupWorld() # Get the player CreatePlayer.CreatePlayer(self.world, self.worldNP)
def request_opengl_config(data): sync_video_value = int(settings.sync_video) data.append("sync-video %d" % sync_video_value) os.environ['__GL_SYNC_TO_VBLANK'] = str(sync_video_value) os.environ['vblank_mode'] = str(sync_video_value) if settings.use_gl_version is not None: data.append("gl-version %s" % settings.use_gl_version) settings.core_profile = True elif sys.platform == "darwin" and settings.use_core_profile_mac: data.append("gl-version 3 2") settings.core_profile = True if settings.use_srgb and settings.use_hardware_srgb: data.append("framebuffer-srgb true") if settings.use_inverse_z: data.append("gl-depth-zero-to-one true") if settings.force_power_of_two_textures: data.append("textures-power-2 down") else: data.append("textures-power-2 none") if settings.use_hardware_sprites: data.append("hardware-point-sprites #t") if settings.stereoscopic_framebuffer: data.append("framebuffer-stereo #t") elif settings.red_blue_stereo: data.append("red-blue-stereo #t") elif settings.side_by_side_stereo: data.append("side-by-side-stereo #t") if settings.stereo_swap_eyes: data.append("swap-eyes #t") data.append("gl-coordinate-system default") data.append("gl-check-errors #t") if settings.dump_panda_shaders: data.append("dump-generated-shaders #t") data.append("driver-generate-mipmaps #t") data.append("gl-immutable-texture-storage true") data.append("state-cache #f") render_scene_to_buffer = False if settings.use_srgb and not settings.use_hardware_srgb: render_scene_to_buffer = True if settings.use_hdr: render_scene_to_buffer = True if settings.use_inverse_z: render_scene_to_buffer = True if not render_scene_to_buffer and settings.multisamples > 0: settings.framebuffer_multisampling = True load_prc_file_data("", "framebuffer-multisample 1") load_prc_file_data("", "multisamples %d" % settings.multisamples)
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 __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 test_prc(): p3d.load_prc_file_data( '', 'event-map-item-jump space raw-y gamepad0-face_a\n') emapper = eventmapper.EventMapper(manage_gamepads=False) assert emapper.get_inputs_for_event('jump') == [ 'space', 'raw-y', 'gamepad0-face_a', ] assert emapper.get_labels_for_event('jump') == [ 'space', 'y', ]
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 __init__(self, Input16bitTif, Texture, HFilmSize, VFilmSize, FocalLenght, VUTProject, Directory, videoFile, VideoWidth, VideoHeight, StartSecond, BBXMin, BBYMin, BBXMax, BBYMax): # , cameraCoord): load_prc_file_data( "", """ textures-power-2 none gl-coordinate-system default window-title Video UAV Tracker 3D """) ShowBase.__init__(self) self.set_background_color(0.4, 0.4, 1) self.setFrameRateMeter(True) self.lens = PerspectiveLens() self.lens.setFilmSize(float(HFilmSize) / 1000, float(VFilmSize) / 1000) self.lens.setFocalLength(float(FocalLenght) / 1000) base.cam.node().setLens(self.lens) self.VRTBoundingBox = str(BBXMin) + ',' + str(BBYMin) + ':' + str( BBXMax) + ',' + str(BBYMax) self.SetupCommunication() self.ManageDEM(Input16bitTif) self.SetupTexture(Texture) self.SetupVisibleTerrain() self.SetupBulletTerrain() self.accept("f3", self.toggleWireframe) self.EraseTmpFiles() self.Directory = Directory self.SetupModel(VUTProject) self.VideoFile = videoFile self.VideoWidth = VideoWidth self.VideoHeight = VideoHeight self.StartSecond = StartSecond self.OutputDir = self.VideoFile.split('.')[0] + '_Mosaic/' self.Mosaic = False self.MosaicCounter = 0 self.taskMgr.setupTaskChain('MosaicChain', numThreads=1, tickClock=None, threadPriority=None, frameBudget=None, frameSync=None, timeslicePriority=None) self.SendReadySignal(str(Directory))
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 __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 configure_visualiser_flags(config: Configuration, args: argparse.Namespace) -> bool: if args.visualiser_flags is not None: integral_pair_re = re.compile("\s*\(\s*[0-9]+\s*,\s*[0-9]+\s*\)\s*") naked_integral_pair_re = re.compile("\s*[0-9]+\s*[0-9]+\s*") data = "" def use_display_resolution(): nonlocal data for m in get_monitors(): data += "win-size {} {}\n".format(m.width, m.height) break # only need to specify for first window for f in args.visualiser_flags: if f.strip().lower() == "windowed-fullscreen": use_display_resolution() data += "win-origin 0 0\n" data += "undecorated true\n" continue n, v = f.split("=") n = n.strip().lower() v = v.strip().lower() if v in ("true", "1", "yes"): data += "{} true\n".format(n) elif v in ("false", "0", "no"): data += "{} false\n".format(n) elif integral_pair_re.match(v) is not None: v = re.sub('{\s+}|\(|\)', '', v) v1, v2 = v.split(',') data += "{} {} {}\n".format(n, v1, v2) elif naked_integral_pair_re.match(v) is not None: v = v.strip() v = re.sub('\s+', ',', v) v1, v2 = v.split(',') data += "{} {} {}\n".format(n, v1, v2) else: data += "{} {}".format(n, v) if "fullscreen true" in data and "win-size" not in data: use_display_resolution() load_prc_file_data('', data) return True
def toggle_debug_tools(self): # TODO: change this to the reload funcs if self._dt_enabled: load_prc_file_data("", "want-directtools true") load_prc_file_data("", "want-tk true") self._dt_enabled = False else: load_prc_file_data("", "want-directtools false") load_prc_file_data("", "want-tk false") self._dt_enabled = True
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 app(): from direct.showbase.ShowBase import ShowBase import pman.shim from game import playerdata from game.monster import Monster p3d.load_prc_file_data( '', 'window-type none\n' 'framebuffer-hardware false\n' 'audio-music-active false\n' 'audio-sfx-active false\n') class DummyApp(ShowBase): def __init__(self): super().__init__(self) pman.shim.init(self) player = playerdata.PlayerData() self.blackboard = { 'player': player, } default_monster = Monster.make_new('player_monster', 'Default', 'mine') self.blackboard['player'].monsters = [default_monster] self.camera = p3d.NodePath('camera') class Pipeline: def __init__(self): self.exposure = 6 self.render_pipeline = Pipeline() self.ui = MagicMock() self.event_mapper = MagicMock() def change_state(self, next_state): pass def change_to_previous_state(self): pass def load_ui(self, uiname): pass return DummyApp()
def test_load_unload_page(): var = core.ConfigVariableInt("test-var", 1) assert var.value == 1 page = core.load_prc_file_data("test_load_unload_page", "test-var 2") assert page assert var.value == 2 assert core.unload_prc_file(page) assert var.value == 1
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 create_main_window(base): if _create_main_window(base): return #We could not open the window, try to fallback to a supported configuration if settings.stereoscopic_framebuffer: print("Failed to open a window, disabling stereoscopic framebuffer...") load_prc_file_data("", "framebuffer-stereo #f") settings.stereoscopic_framebuffer = False if _create_main_window(base): return if settings.framebuffer_multisampling: print("Failed to open a window, disabling multisampling...") load_prc_file_data("", "framebuffer-multisample #f") settings.disable_multisampling = True settings.framebuffer_multisampling = False if _create_main_window(base): return #Can't create window even without multisampling if settings.use_gl_version is not None: print( "Failed to open window with OpenGL Core; falling back to older OpenGL." ) load_prc_file_data("", "gl-version") if _create_main_window(base): return print("Could not open any window") sys.exit(1)
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
def __init__(self): self.world = None self.worldNP = render.attachNewNode('World') self.introaudio = Resources.introaudio self.intromusic = Resources.intromusic initsequence = Sequence(Func(self.introaudio.play), Func(self.intromusic.play)) initsequence.start() load_prc_file_data( "", """ stm-max-chunk-count 1024 stm-max-views 20 """) # Setup everything self.setupWorld() # Get the player self.userCharacter = CreatePlayer.CreatePlayer(self.world, self.worldNP) taskMgr.add(self.update, 'updateWorld')
def test_track_gui_items(): page = core.load_prc_file_data("", "track-gui-items true") try: item = DirectGuiWidget() id = item.guiId assert id in ShowBase.guiItems assert ShowBase.guiItems[id] == item item.destroy() assert id not in ShowBase.guiItems finally: core.unload_prc_file(page)
def startFramework(msg): """start base framework""" global app # Load your application's configuration load_prc_file_data("", "model-path " + dataDir) load_prc_file_data("", "win-size 1024 768") load_prc_file_data("", "show-frame-rate-meter #t") load_prc_file_data("", "sync-video #t") # load_prc_file_data("", "want-directtools #t") # load_prc_file_data("", "want-tk #t") # Setup your application app = ShowBase() props = WindowProperties() props.setTitle("p3opensteer: " + msg) app.win.requestProperties(props) #common callbacks # return app
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 __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()
""" Uses mitsuba to generate the environment brdf """ from __future__ import print_function import os import sys import math from panda3d.core import PNMImage, load_prc_file_data, Vec3 load_prc_file_data("", "notify-level error") load_prc_file_data("", "notify-level-pnmimage error") configs = { "normal": { "out_dir": "slices", "out_name": "env_brdf_{}.png", "template_suffix": "", "sequence": xrange(7), "samples": 32, }, "metallic": { "out_dir": "slices_metal", "out_name": "env_brdf.png", "template_suffix": "-metal", "sequence": [1], "samples": 32, },
""" Converts pipeline resources to TXO files to speed up loading. This is called during the setup. """ from __future__ import print_function import os from panda3d.core import Filename, Texture, load_prc_file_data load_prc_file_data("", "window-type none") load_prc_file_data("", "notify-level-pnmimage error") load_prc_file_data("", "textures-power-2 none") files_to_convert = [ "data/gui/loading_screen_bg.png", "rpplugins/bloom/resources/lens_dirt.png", "data/builtin_models/skybox/skybox.jpg" ] this_dir = os.path.realpath(os.path.dirname(__file__)) os.chdir(this_dir) pipeline_dir = "../" import direct.directbase.DirectStart for filename in files_to_convert: src_path = os.path.abspath(os.path.join(pipeline_dir, filename))
import os import sys from direct.showbase.ShowBase import ShowBase import panda3d.core as p3d import rendermanager p3d.load_prc_file_data( '', 'model-path {}\n'.format(os.path.join(os.path.dirname(__file__), 'assets')) + \ 'framebuffer-srgb true\n' ) class GameApp(ShowBase): def __init__(self): ShowBase.__init__(self) self.accept('escape', sys.exit) self.rendermanager = rendermanager.create_render_manager('basic', self) app = GameApp() app.run()
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()
try: import queue except ImportError: import Queue as queue from direct.showbase.ShowBase import ShowBase import panda3d.core as p3d import pman from converter import Converter import rendermanager p3d.load_prc_file_data('', 'window-type none\n' 'gl-debug #t\n' ) USE_THREAD = True class Server(threading.Thread): def __init__(self, data_handler, update_handler): threading.Thread.__init__(self) self.socket = socket.socket() self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.image_lock = threading.Lock() remaining_attempts = 3 while remaining_attempts: try:
import queue import struct import sys import time import threading from direct.showbase.ShowBase import ShowBase import panda3d.core as p3d sys.path.append(os.path.join(os.path.dirname(__file__), 'pman')) import pman #pylint:disable=wrong-import-position p3d.load_prc_file_data( '', 'window-type none\n' 'pstats-gpu-timing 1\n' ) class BlenderConnection: def __init__(self, conn_addr): self.connection = multiprocessing.connection.Client(conn_addr) print('connected to', conn_addr) self.update_queue = queue.Queue() self.image_queue = queue.Queue() self.running = True self._conn_thread = threading.Thread(target=self._handle_connection) self._conn_thread.start()
def __init__(self): # Load some configuration variables, its important for this to happen # before the ShowBase is initialized load_prc_file_data( "", """ textures-power-2 none window-title Panda3D Shader Terrain Demo """) # Initialize the showbase ShowBase.__init__(self) # Increase camera FOV aswell as the far plane self.camLens.set_fov(90) self.camLens.set_near_far(0.1, 50000) # Construct the terrain self.terrain_node = ShaderTerrainMesh() # Set a heightfield, the heightfield should be a 16-bit png and # have a quadratic size of a power of two. self.terrain_node.heightfield_filename = "heightfield.png" # Set the target triangle width. For a value of 10.0 for example, # the terrain will attempt to make every triangle 10 pixels wide on screen. self.terrain_node.target_triangle_width = 10.0 # Generate the terrain self.terrain_node.generate() # Attach the terrain to the main scene and set its scale self.terrain = self.render.attach_new_node(self.terrain_node) self.terrain.set_scale(1024, 1024, 100) self.terrain.set_pos(-512, -512, -70.0) # Set a shader on the terrain. The ShaderTerrainMesh only works with # an applied shader. You can use the shaders used here in your own shaders terrain_shader = Shader.load(Shader.SL_GLSL, "terrain.vert.glsl", "terrain.frag.glsl") self.terrain.set_shader(terrain_shader) self.terrain.set_shader_input("camera", self.camera) # Set some texture on the terrain grass_tex = self.loader.loadTexture("textures/grass.png") grass_tex.set_minfilter(SamplerState.FT_linear_mipmap_linear) grass_tex.set_anisotropic_degree(16) self.terrain.set_texture(grass_tex) # Load some skybox - you can safely ignore this code skybox = self.loader.loadModel("models/skybox.bam") skybox.reparent_to(self.render) skybox.set_scale(20000) skybox_texture = self.loader.loadTexture("textures/skybox.jpg") skybox_texture.set_minfilter(SamplerState.FT_linear) skybox_texture.set_magfilter(SamplerState.FT_linear) skybox_texture.set_wrap_u(SamplerState.WM_repeat) skybox_texture.set_wrap_v(SamplerState.WM_mirror) skybox_texture.set_anisotropic_degree(16) skybox.set_texture(skybox_texture) skybox_shader = Shader.load(Shader.SL_GLSL, "skybox.vert.glsl", "skybox.frag.glsl") skybox.set_shader(skybox_shader)
import sys os.chdir(os.path.dirname(os.path.abspath(__file__))) from direct.showbase.ShowBase import ShowBase import panda3d.core as p3d import blenderpanda from bamboo.inputmapper import InputMapper import gamestates p3d.load_prc_file_data( '', 'model-path {}\n'.format('assets') + \ 'textures-power-2 none\n' ) # Load config files p3d.load_prc_file('config/game.prc') if os.path.exists('config/user.prc'): print("Loading user.prc") p3d.load_prc_file('config/user.prc') else: print("Did not find a user config") class GameApp(ShowBase): def __init__(self):
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))
def __init__(self): # Load some configuration variables, its important for this to happen # before the ShowBase is initialized load_prc_file_data("", """ textures-power-2 none window-title Panda3D Shader Terrain Demo gl-coordinate-system default """) # Initialize the showbase ShowBase.__init__(self) # Increase camera FOV aswell as the far plane self.camLens.set_fov(90) self.camLens.set_near_far(0.1, 50000) # Construct the terrain self.terrain_node = ShaderTerrainMesh() # Set a heightfield, the heightfield should be a 16-bit png and # have a quadratic size of a power of two. self.terrain_node.heightfield_filename = "heightfield.png" # Set the target triangle width. For a value of 10.0 for example, # the terrain will attempt to make every triangle 10 pixels wide on screen. self.terrain_node.target_triangle_width = 10.0 # Generate the terrain self.terrain_node.generate() # Attach the terrain to the main scene and set its scale self.terrain = self.render.attach_new_node(self.terrain_node) self.terrain.set_scale(1024, 1024, 100) self.terrain.set_pos(-512, -512, -70.0) # Set a shader on the terrain. The ShaderTerrainMesh only works with # an applied shader. You can use the shaders used here in your own shaders terrain_shader = Shader.load(Shader.SL_GLSL, "terrain.vert.glsl", "terrain.frag.glsl") self.terrain.set_shader(terrain_shader) self.terrain.set_shader_input("camera", self.camera) # Set some texture on the terrain grass_tex = self.loader.loadTexture("textures/grass.png") grass_tex.set_minfilter(SamplerState.FT_linear_mipmap_linear) grass_tex.set_anisotropic_degree(16) self.terrain.set_texture(grass_tex) # Load some skybox - you can safely ignore this code skybox = self.loader.loadModel("models/skybox.bam") skybox.reparent_to(self.render) skybox.set_scale(20000) skybox_texture = self.loader.loadTexture("textures/skybox.jpg") skybox_texture.set_minfilter(SamplerState.FT_linear) skybox_texture.set_magfilter(SamplerState.FT_linear) skybox_texture.set_wrap_u(SamplerState.WM_repeat) skybox_texture.set_wrap_v(SamplerState.WM_mirror) skybox_texture.set_anisotropic_degree(16) skybox.set_texture(skybox_texture) skybox_shader = Shader.load(Shader.SL_GLSL, "skybox.vert.glsl", "skybox.frag.glsl") skybox.set_shader(skybox_shader)
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 __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 __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 __init__(self): # Load some configuration variables, its important for this to happen # before the ShowBase is initialized load_prc_file_data("", """ textures-power-2 none gl-coordinate-system default window-title Panda3D ShaderTerrainMesh Demo # As an optimization, set this to the maximum number of cameras # or lights that will be rendering the terrain at any given time. stm-max-views 8 # Further optimize the performance by reducing this to the max # number of chunks that will be visible at any given time. stm-max-chunk-count 2048 """) # Initialize the showbase ShowBase.__init__(self) # Increase camera FOV as well as the far plane self.camLens.set_fov(90) self.camLens.set_near_far(0.1, 50000) # Construct the terrain self.terrain_node = ShaderTerrainMesh() # Set a heightfield, the heightfield should be a 16-bit png and # have a quadratic size of a power of two. heightfield = self.loader.loadTexture("heightfield.png") heightfield.wrap_u = SamplerState.WM_clamp heightfield.wrap_v = SamplerState.WM_clamp self.terrain_node.heightfield = heightfield # Set the target triangle width. For a value of 10.0 for example, # the terrain will attempt to make every triangle 10 pixels wide on screen. self.terrain_node.target_triangle_width = 10.0 # Generate the terrain self.terrain_node.generate() # Attach the terrain to the main scene and set its scale. With no scale # set, the terrain ranges from (0, 0, 0) to (1, 1, 1) self.terrain = self.render.attach_new_node(self.terrain_node) self.terrain.set_scale(1024, 1024, 100) self.terrain.set_pos(-512, -512, -70.0) # Set a shader on the terrain. The ShaderTerrainMesh only works with # an applied shader. You can use the shaders used here in your own application terrain_shader = Shader.load(Shader.SL_GLSL, "terrain.vert.glsl", "terrain.frag.glsl") self.terrain.set_shader(terrain_shader) self.terrain.set_shader_input("camera", self.camera) # Shortcut to view the wireframe mesh self.accept("f3", self.toggleWireframe) # Set some texture on the terrain grass_tex = self.loader.loadTexture("textures/grass.png") grass_tex.set_minfilter(SamplerState.FT_linear_mipmap_linear) grass_tex.set_anisotropic_degree(16) self.terrain.set_texture(grass_tex) # Load a skybox - you can safely ignore this code skybox = self.loader.loadModel("models/skybox.bam") skybox.reparent_to(self.render) skybox.set_scale(20000) skybox_texture = self.loader.loadTexture("textures/skybox.jpg") skybox_texture.set_minfilter(SamplerState.FT_linear) skybox_texture.set_magfilter(SamplerState.FT_linear) skybox_texture.set_wrap_u(SamplerState.WM_repeat) skybox_texture.set_wrap_v(SamplerState.WM_mirror) skybox_texture.set_anisotropic_degree(16) skybox.set_texture(skybox_texture) skybox_shader = Shader.load(Shader.SL_GLSL, "skybox.vert.glsl", "skybox.frag.glsl") skybox.set_shader(skybox_shader)
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import print_function from panda3d.core import PNMImage, load_prc_file_data, Texture, NodePath from panda3d.core import Shader, ShaderAttrib import shutil import os load_prc_file_data("", "textures-power-2 none") # load_prc_file_data("", "window-type offscreen") load_prc_file_data("", "win-size 100 100") load_prc_file_data("", "notify-level-display error") import direct.directbase.DirectStart compute_shader = Shader.make_compute(Shader.SL_GLSL, """ #version 430 layout (local_size_x = 16, local_size_y = 16) in; uniform writeonly image2D DestTex; uniform samplerCube SourceCubemap; uniform int size; uniform int blurSize;
def __init__(self): self.settings = core.load_prc_file(core.Filename.expand_from("$MAIN_DIR/settings.prc")) ShowBase.__init__(self, windowType='none') # Try opening "gl-version 3 2" window props = core.WindowProperties.get_default() have_window = False try: self.open_default_window(props=props) have_window = True except Exception: pass if not have_window: print("Failed to open window with OpenGL 3.2; falling back to older OpenGL.") core.load_prc_file_data("", "gl-version") self.open_default_window(props=props) print("The window seemed to have opened this time around.") gsg = self.win.gsg gl_version = (gsg.driver_version_major, gsg.driver_version_minor) self.has_fixed_function = gl_version < (3, 0) or gsg.max_lights > 0 print("OpenGL version: {0}.{1} ({2})".format(*gl_version, 'compat' if self.has_fixed_function else 'core')) print("OpenGL renderer: {0}".format(gsg.driver_renderer)) self.accept('escape', sys.exit) self.accept('f12', self.screenshot) self.disable_mouse() self.camLens.set_far(50) # Load in background self.set_background_color((0.31, 0.42, 0.53)) if not self.win.get_fb_properties().srgb_color: print("Did not get an sRGB framebuffer. The game may appear too dark.") # Load fonts self.symbol_font = loader.load_font("font/FreeSerif.otf") self.symbol_font.set_pixels_per_unit(64) self.regular_font = loader.load_font("font/Quicksand-Regular.otf") self.regular_font.set_pixels_per_unit(64) self.title_font = loader.load_font("font/Quicksand-Light.otf") self.title_font.set_pixels_per_unit(128) self.icon_fonts = { 'solid': loader.load_font("font/font-awesome5-solid.otf"), 'regular': loader.load_font("font/font-awesome5-regular.otf"), } for font in self.icon_fonts.values(): font.set_pixels_per_unit(64) # Load sounds DGG.setDefaultClickSound(loader.load_sfx('sfx/menu-interact.wav')) DGG.setDefaultRolloverSound(loader.load_sfx('sfx/menu-focus.wav')) self.endtile_sound = loader.load_sfx('sfx/endtile.wav') self.move_sound = loader.load_sfx('sfx/die-move.wav') self.impassable_sound = loader.load_sfx('sfx/impassable.wav') self.button_sound = loader.load_sfx('sfx/button-press.wav') self.transport_sound = loader.load_sfx('sfx/transport-engage.wav') self.slide_sound = loader.load_sfx('sfx/ice-slide.wav') self.wind_sound = loader.load_sfx('sfx/wind.ogg') self.crack_sound = loader.load_sfx('sfx/tile-crack.wav') self.collapse_sound = loader.load_sfx('sfx/tile-collapse.wav') self.restart_sound = loader.load_sfx('sfx/menu-interact.wav') self.music = { 'menu': loader.load_music('music/theme.ogg'), 'one': loader.load_music('music/world1.ogg'), 'two': loader.load_music('music/world2.ogg'), 'three': loader.load_music('music/world3.ogg'), 'four': loader.load_music('music/world4.ogg'), 'five': loader.load_music('music/world5.ogg'), 'six': loader.load_music('music/world6.ogg'), } self.playing_music = None self.music_on = True self.blur_shader = core.Shader.load(core.Shader.SL_GLSL, "shader/blur.vert", "shader/blur.frag") self.blur_scale = core.PTA_float([1.0]) self.blurred_tex = None self.quality = None screen = ui.Screen("select quality") ui.Button(screen, 'sublime', pos=(0.0, 0), command=self.setup_game, extraArgs=[3]) ui.Button(screen, 'mediocre', pos=(0.0, -0.15), command=self.setup_game, extraArgs=[2]) ui.Button(screen, 'terrible', pos=(0.0, -0.3), command=self.setup_game, extraArgs=[1]) self.quality_screen = screen screen.show_now() self.game_setup = False self.have_save = False self.blurred = True self.accept('connect-device', self.on_connect_device) self.accept('disconnect-device', self.on_disconnect_device) self.gamepads = set() dev_mgr = core.InputDeviceManager.get_global_ptr() for device in dev_mgr.get_devices(core.InputDevice.DeviceClass.gamepad): self.on_connect_device(device) self.gamepad_lstick_angle = None self.win_input = self.win.get_input_device(0) self.task_mgr.add(self.process_input) sys.stdout.flush() sys.stderr.flush()
sys.path.insert(0, "../Builtin") # Load some builtin LUI classes. When lui is included in panda, this will be # from direct.lui.LUIButton import LUIButton from LUIButton import LUIButton from LUISkin import LUIDefaultSkin from LUIRegion import LUIRegion from LUIInputHandler import LUIInputHandler # Setup panda, nothing special here from panda3d.core import load_prc_file_data load_prc_file_data("", """ text-minfilter linear text-magfilter linear text-pixels-per-unit 32 sync-video #f textures-power-2 none show-frame-rate-meter #t win-size 700 600 window-title LUI Minimal Example """) from direct.showbase.ShowBase import ShowBase class Application(ShowBase): def __init__(self): ShowBase.__init__(self) # Construct a new LUIRegion region = LUIRegion.make("LUI", base.win)